<?php
/**
 * Agentic Square - Premium Seller Dashboard: Products Inventory Matrix
 * Path: seller/my-items.php
 */

require_once __DIR__ . '/../config/config.php';

// SECURITY ACCESS GUARD RULE: Verify session authentication context permissions
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

$user_id = (int)$_SESSION['user_id'];

// Resolve the internal seller data identity mapping pointer
$stmtSeller = $pdo->prepare("SELECT id FROM sellers WHERE user_id = ? LIMIT 1");
$stmtSeller->execute([$user_id]);
$currentSeller = $stmtSeller->fetch(PDO::FETCH_ASSOC);

if (!$currentSeller) {
    // Graceful exception if account is authenticated but lacks registered merchant rows
    die("System Access Fault: Your profile is not currently registered inside our marketplace vendors indexing ledger framework.");
}

$seller_id = (int)$currentSeller['id'];

/**
 * ASYNCHRONOUS DATA PROVIDER INTERFACE
 * Intercepts real-time AJAX search and page offset selections to safely return specialized rows.
 */
if (isset($_GET['action']) && $_GET['action'] === 'fetch_live_my_items') {
    if (ob_get_length()) ob_end_clean();
    header('Content-Type: application/json; charset=utf-8');

    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    $page   = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
    $limit  = 10;
    $offset = ($page - 1) * $limit;

    // Strict ownership mapping constraints enforced down across param vectors
    $params = [$user_id, $seller_id];
    $whereQuery = " WHERE i.user_id = ? AND i.seller_id = ? ";

    if (!empty($search)) {
        $whereQuery .= " AND (i.item_name LIKE ? OR i.item_slug LIKE ?)";
        $searchParam = "%{$search}%";
        array_push($params, $searchParam, $searchParam);
    }

    try {
        // 1. Compute aggregate count totals targeting exclusively this merchant's files array
        $countQuery = "SELECT COUNT(i.id) FROM items i " . $whereQuery;
        $stmtCount  = $pdo->prepare($countQuery);
        $stmtCount->execute($params);
        $totalRecords = (int)$stmtCount->fetchColumn();
        $totalPages   = ceil($totalRecords / $limit);

        // 2. Extract item properties containing unique product aggregate volume calculation sub-queries
        $dataQuery = "
	            SELECT
	                i.id,
	                i.item_name,
	                i.item_slug,
	                i.feature_image,
                i.amount,
                i.status,
                i.views,
                (
                    SELECT COUNT(*) 
                    FROM orders o 
                    WHERE o.item_id = i.id AND o.payment_status = 'Paid'
                ) AS total_sold
            FROM items i
            " . $whereQuery . "
            ORDER BY i.id DESC
            LIMIT $limit OFFSET $offset
        ";

        $stmtData = $pdo->prepare($dataQuery);
        $stmtData->execute($params);
        $myItemsCollection = $stmtData->fetchAll(PDO::FETCH_ASSOC);

        $htmlOutput = '';

        if (empty($myItemsCollection)) {
            $htmlOutput .= '
            <tr>
                <td colspan="7" class="text-center py-12 text-nftTextGray text-xs font-medium font-mono">
                    <i class="fa-solid fa-folder-open text-3xl block text-slate-800 mb-2"></i>
                    No catalog items match your search queries or repository entries.
                </td>
            </tr>';
        } else {
            $sl = $offset + 1;
	            foreach ($myItemsCollection as $item) {
	                $imagePath = !empty($item['feature_image']) ? '../' . $item['feature_image'] : '../assets/img/placeholder.png';
	                $itemDetailsUrl = item_url($item);
	                $statusStr = $item['status'] ?? 'active';
                
                $statusBadge = ($statusStr === 'active')
                    ? '<span class="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 px-2 py-0.5 rounded-md text-[9px] font-bold uppercase tracking-wider">Active</span>'
                    : '<span class="bg-rose-500/10 border border-rose-500/20 text-rose-400 px-2 py-0.5 rounded-md text-[9px] font-bold uppercase tracking-wider">' . htmlspecialchars($statusStr) . '</span>';

                $htmlOutput .= '
                <tr class="hover:bg-slate-900/20 transition-colors group border-b border-slate-900/40">
                    <td class="px-6 py-4 font-mono font-bold text-slate-500">' . $sl++ . '</td>
                    <td class="px-6 py-4">
                        <div class="w-12 h-10 rounded-lg bg-slate-950 border border-slate-900 overflow-hidden relative shadow-md">
                            <img src="' . htmlspecialchars($imagePath) . '" alt="Asset Feature Visual" class="w-full h-full object-cover" onerror="this.src=\'../assets/img/placeholder.png\';">
                        </div>
                    </td>
	                    <td class="px-6 py-4 font-bold text-white group-hover:text-nftAccentCyan transition-colors max-w-xs truncate" title="' . htmlspecialchars($item['item_name']) . '">
	                        <a href="' . htmlspecialchars($itemDetailsUrl, ENT_QUOTES, 'UTF-8') . '" target="_blank" rel="noopener" class="block truncate hover:text-nftAccentCyan transition-colors">
	                            ' . htmlspecialchars($item['item_name']) . '
	                        </a>
                    </td>
                    <td class="px-6 py-4 font-extrabold font-mono text-emerald-400">' . htmlspecialchars(format_currency($item['amount']), ENT_QUOTES, 'UTF-8') . '</td>
                    <td class="px-6 py-4 font-mono font-bold text-white">' . number_format($item['total_sold']) . ' Units</td>
                    <td class="px-6 py-4 font-mono font-bold text-nftAccentCyan">' . number_format($item['views'] ?? 0) . ' Views</td>
                    <td class="px-6 py-4">' . $statusBadge . '</td>
                    <td class="px-6 py-4 text-right">
                        <a href="update-item.php?id=' . $item['id'] . '" class="inline-flex items-center justify-center bg-slate-900 hover:bg-slate-800 border border-slate-800 text-nftAccentCyan px-3 py-1.5 rounded-lg text-[11px] font-bold transition-all gap-1.5 group/btn">
                            <i class="fa-solid fa-pen-to-square text-[10px] text-slate-500 group-hover/btn:text-nftAccentCyan"></i> Update
                        </a>
                    </td>
                </tr>';
            }
        }

        // Sliding buffer pagination control index frame builder
        $paginationOutput = '';
        if ($totalPages > 1) {
            if ($page > 1) {
                $paginationOutput .= '<button type="button" onclick="changeMyItemsPage(1)" class="px-2.5 h-8 rounded-lg text-xs font-mono font-bold transition-all bg-slate-900 border border-slate-800 text-slate-400 hover:text-white hover:border-slate-700">&lt;&lt;</button>';
            }

            $rangeWindow = 1;
            for ($i = 1; $i <= $totalPages; $i++) {
                if ($i == 1 || $i == $totalPages || ($i >= $page - $rangeWindow && $i <= $page + $rangeWindow)) {
                    $activeClass = ($i === $page) ? 'bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple text-white shadow-md' : 'bg-slate-900 border border-slate-800 text-slate-400 hover:text-white hover:border-slate-700';
                    $paginationOutput .= '<button type="button" onclick="changeMyItemsPage(' . $i . ')" class="w-8 h-8 rounded-lg text-xs font-mono font-bold transition-all ' . $activeClass . '">' . $i . '</button>';
                } elseif ($i == 2 && $page > ($rangeWindow + 2)) {
                    $paginationOutput .= '<span class="text-slate-600 px-1 text-xs font-mono">...</span>';
                    $i = $page - $rangeWindow - 1;
                } elseif ($i == $page + $rangeWindow + 1 && $page < ($totalPages - $rangeWindow - 1)) {
                    $paginationOutput .= '<span class="text-slate-600 px-1 text-xs font-mono">...</span>';
                    $i = $totalPages - 1;
                }
            }

            if ($page < $totalPages) {
                $paginationOutput .= '<button type="button" onclick="changeMyItemsPage(' . $totalPages . ')" class="px-2.5 h-8 rounded-lg text-xs font-mono font-bold transition-all bg-slate-900 border border-slate-800 text-slate-400 hover:text-white hover:border-slate-700">&gt;&gt;</button>';
            }
        }

        echo json_encode([
            'table_rows' => $htmlOutput,
            'pagination_controls' => $paginationOutput,
            'metrics_info' => 'Displaying ' . count($myItemsCollection) . ' items of ' . number_format($totalRecords) . ' total registered assets'
        ]);
        exit;
    } catch (Exception $e) {
        echo json_encode([
            'table_rows' => '<tr><td colspan="8" class="text-center py-4 text-rose-400 font-mono text-[11px]">Stream Exception Error Encountered: ' . htmlspecialchars($e->getMessage()) . '</td></tr>',
            'pagination_controls' => '',
            'metrics_info' => 'Internal Processing Error'
        ]);
        exit;
    }
}

require_once __DIR__ . '/../sections/header.php';
?>

<body class="bg-nftDark text-white antialiased overflow-x-hidden">

    <?php include_once __DIR__ . '/seller-sidebar.php'; ?>

    <main class="lg:ml-64 min-h-screen pt-24 lg:pt-10 pb-16 px-4 sm:px-6 lg:px-8">
        <div class="max-w-7xl mx-auto space-y-8">
            
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 border-b border-slate-900/60 pb-6">
                <div>
                    <span class="text-xs font-bold tracking-widest text-nftAccentCyan uppercase block mb-1">// MERCHANT INVENTORY COMMAND</span>
                    <h1 class="text-3xl font-extrabold tracking-tight text-white">My Product Blueprint Assets</h1>
                    <p class="text-sm text-nftTextGray mt-1">Review live catalog structures, observe settlement download conversions, and update code packages descriptions real-time.</p>
                </div>
                <div>
	                    <a href="<?php echo htmlspecialchars(app_url('seller/sell-item.php'), ENT_QUOTES, 'UTF-8'); ?>" class="inline-flex items-center justify-center bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple text-slate-950 font-black tracking-wide text-xs px-5 py-3 rounded-xl shadow-lg hover:opacity-90 transition-all gap-2">
                        <i class="fa-solid fa-cloud-arrow-up"></i> Upload New Product
                    </a>
                </div>
            </div>

            <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-6 bg-slate-950/20">
                <div class="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
                    <div class="flex items-center space-x-2.5">
                        <div class="w-2 h-2 rounded-full bg-nftAccentCyan animate-ping"></div>
                        <h4 class="font-bold text-base text-white tracking-wide">Live Architecture Repository Registry</h4>
                    </div>

                    <div class="relative w-full md:w-80">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3.5 pointer-events-none text-slate-500 text-xs">
                            <i class="fa-solid fa-magnifying-glass"></i>
                        </span>
                        <input type="text" id="sellerInventorySearch" oninput="triggerLiveSearchEngine()" class="w-full bg-slate-950/80 text-white placeholder-slate-500 font-medium text-xs px-4 py-3 pl-10 rounded-xl border border-slate-900 focus:outline-none focus:border-nftAccentCyan transition-colors shadow-inner" placeholder="Search my items by name, slugs...">
                    </div>
                </div>

                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse">
                        <thead>
                            <tr class="border-b border-slate-900 text-[11px] font-bold text-nftTextGray uppercase tracking-widest bg-slate-950/40">
                                <th class="px-6 py-4 w-12">SL</th>
                                <th class="px-6 py-4 w-20">Asset Image</th>
                                <th class="px-6 py-4">Product Asset Name</th>
                                <th class="px-6 py-4">License Price</th>
                                <th class="px-6 py-4">Total Sold</th>
                                <th class="px-6 py-4">Traffic Views</th>
                                <th class="px-6 py-4">Status</th>
                                <th class="px-6 py-4 text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody id="myItemsTableTarget" class="divide-y divide-slate-900/50 text-xs text-slate-300 font-medium">
                            <tr>
                                <td colspan="8" class="text-center py-10 font-mono text-nftTextGray text-[11px]">
                                    Synchronizing localized product array sequences...
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <div class="flex flex-col sm:flex-row items-center justify-between pt-4 border-t border-slate-900/60 gap-4">
                    <span id="myItemsMetricsDisplay" class="text-[11px] text-nftTextGray font-mono font-medium">Loading catalog indexes...</span>
                    <div id="myItemsPaginationControls" class="flex items-center space-x-1.5 select-none"></div>
                </div>
            </div>

        </div>
    </main>

    <script>
        let searchTimeoutTracker = null;
        let currentActiveItemsPage = 1;

        if (document.readyState === "complete" || document.readyState === "interactive") {
            setTimeout(dispatchLiveQueryFetch, 1);
        } else {
            document.addEventListener("DOMContentLoaded", dispatchLiveQueryFetch);
        }

        function triggerLiveSearchEngine() {
            clearTimeout(searchTimeoutTracker);
            searchTimeoutTracker = setTimeout(() => {
                currentActiveItemsPage = 1; 
                dispatchLiveQueryFetch();
            }, 250);
        }

        function changeMyItemsPage(pageTargetNodeIndex) {
            currentActiveItemsPage = pageTargetNodeIndex;
            dispatchLiveQueryFetch();
        }

        function dispatchLiveQueryFetch() {
            const queryInputString = encodeURIComponent(document.getElementById('sellerInventorySearch').value);
            const apiEndPointTarget = `my-items.php?action=fetch_live_my_items&search=${queryInputString}&page=${currentActiveItemsPage}`;

            const uiRowBodyContainer = document.getElementById('myItemsTableTarget');
            const uiPaginationRowGroup = document.getElementById('myItemsPaginationControls');
            const uiMetricsTextNodeContainer = document.getElementById('myItemsMetricsDisplay');

            if (!uiRowBodyContainer) return;

            fetch(apiEndPointTarget, {
                    method: 'GET',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json'
                    }
                })
                .then(response => {
                    if (!response.ok) throw new Error(`Network tracking interface fault: ${response.status}`);
                    return response.json();
                })
                .then(payloadDataNode => {
                    if (payloadDataNode && typeof payloadDataNode === 'object') {
                        uiRowBodyContainer.innerHTML = payloadDataNode.table_rows;
                        uiPaginationRowGroup.innerHTML = payloadDataNode.pagination_controls;
                        uiMetricsTextNodeContainer.textContent = payloadDataNode.metrics_info;
                    }
                })
                .catch(err => {
                    console.error("Seller File System Data Extraction Error Trace:", err);
                    uiRowBodyContainer.innerHTML = `
                    <tr>
                        <td colspan="8" class="text-center py-10 text-rose-400 font-mono text-[11px] bg-rose-950/10 rounded-xl border border-rose-900/20">
                            <i class="fa-solid fa-triangle-exclamation text-xl block mb-2 text-rose-500"></i>
                            Failed to synchronize item ledger tables asynchronously.<br>
                            <span class="text-slate-500 text-[10px] mt-1 block font-sans">Details: ${err.message}</span>
                        </td>
                    </tr>`;
                });
        }
    </script>
</body>
</html>
