<?php
/**
 * Agentic Square - Premium Admin Control Center: Global Asset Registry Inventory Matrix
 * Path: admin/all-items.php
 */

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

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

/**
 * ASYNCHRONOUS DATA PROVIDER INTERFACE
 * Intercepts real-time AJAX search and pagination requests to return dynamic HTML rows & navigation arrays.
 */
if (isset($_GET['action']) && $_GET['action'] === 'fetch_live_inventory') {
    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;

    $params = [];
    $whereQuery = " WHERE 1=1 ";

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

    try {
        // 1. Compute aggregate row tracking data totals
        $countQuery = "
            SELECT COUNT(i.id) 
            FROM items i 
            LEFT JOIN sellers s ON i.seller_id = s.id
            LEFT JOIN categories c ON i.category_id = c.id
            " . $whereQuery;
            
        $stmtCount  = $pdo->prepare($countQuery);
        $stmtCount->execute($params);
        $totalRecords = (int)$stmtCount->fetchColumn();
        $totalPages   = ceil($totalRecords / $limit);

        // 2. Fetch targeted localized rows matrix
        // FIXED: Joined sellers 's' table on i.seller_id = s.id to pull seller_name correctly
        $dataQuery = "
            SELECT
                i.id,
                i.item_name,
                i.item_slug,
                i.feature_image,
                i.amount AS price,
                c.category_name,
                s.seller_name AS author_name,
                (
                    SELECT COUNT(*)
                    FROM orders o
                    WHERE o.item_id = i.id AND o.payment_status = 'Paid'
                ) AS total_sold,
                (
                    SELECT COUNT(*)
                    FROM reviews r
                    WHERE r.item_id = i.id
                ) AS total_reviews,
                (
                    SELECT ROUND(AVG(r.rating), 2)
                    FROM reviews r
                    WHERE r.item_id = i.id
                ) AS average_rating
            FROM items i
            LEFT JOIN sellers s ON i.seller_id = s.id
            LEFT JOIN categories c ON i.category_id = c.id
            " . $whereQuery . "
            ORDER BY i.id DESC
            LIMIT $limit OFFSET $offset
        ";

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

        $htmlOutput = '';

        if (empty($inventoryItems)) {
            $htmlOutput .= '
            <tr>
                <td colspan="8" class="text-center py-12 text-nftTextGray text-xs font-medium font-mono">
                    <i class="fa-solid fa-magnifying-glass text-3xl block text-slate-800 mb-2"></i>
                    No administrative inventory records match search parameter queries.
                </td>
            </tr>';
        } else {
            $sl = $offset + 1;
            foreach ($inventoryItems as $item) {
                $imagePath = !empty($item['feature_image']) ? '../' . $item['feature_image'] : '../assets/img/placeholder.png';
                $itemUrl = item_url($item);
                $averageRating = number_format((float)($item['average_rating'] ?? 0), 2);
                $totalReviews = number_format((int)($item['total_reviews'] ?? 0));
                
                $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="flex items-center gap-3">
                            <div class="w-10 h-10 rounded-lg bg-slate-950 border border-slate-800 overflow-hidden flex-shrink-0 relative shadow-md">
                                <img src="' . htmlspecialchars($imagePath) . '" alt="Asset" class="w-full h-full object-cover" onerror="this.src=\'../assets/img/placeholder.png\';">
                            </div>
                            <a href="' . htmlspecialchars($itemUrl) . '" target="_blank" rel="noopener" class="truncate max-w-xs font-bold text-white group-hover:text-nftAccentCyan transition-colors block" title="' . htmlspecialchars($item['item_name']) . '">
                                ' . htmlspecialchars($item['item_name']) . '
                            </a>
                        </div>
                    </td>
                    <td class="px-6 py-4 text-slate-400 font-medium">' . htmlspecialchars($item['category_name'] ?? 'General') . '</td>
                    <td class="px-6 py-4 text-nftTextGray font-medium">' . htmlspecialchars($item['author_name'] ?? 'System/Admin') . '</td>
                    <td class="px-6 py-4 font-extrabold font-mono text-white">' . htmlspecialchars(format_currency($item['price']), ENT_QUOTES, 'UTF-8') . '</td>
                    <td class="px-6 py-4 font-mono text-slate-400 font-bold">' . number_format($item['total_sold']) . '</td>
                    <td class="px-6 py-4 font-mono text-amber-400 font-bold">
                        <span>' . $averageRating . '</span>
                        <span class="text-slate-600 font-sans">(' . $totalReviews . ')</span>
                    </td>
                    <td class="px-6 py-4 text-right">
                        <a href="edit-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 text-[10px] text-slate-500 group-hover/btn:text-nftAccentCyan"></i> Update
                        </a>
                    </td>
                </tr>';
            }
        }

        // Advanced Logic: << 5 6 7 ... 58 >> Pagination Builder
        $paginationOutput = '';
        if ($totalPages > 1) {
            // First Page / Skip Backward Control (<<)
            if ($page > 1) {
                $paginationOutput .= '<button type="button" onclick="changeInventoryPage(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; // Determines visible buffer neighboring tabs block
            
            // Build sliding pagination frames tracking indexes
            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="changeInventoryPage(' . $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; // Advance loop pointer past empty data block
                } 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; // Advance loop pointer directly to final item marker
                }
            }

            // Final Page / Skip Forward Control (>>)
            if ($page < $totalPages) {
                $paginationOutput .= '<button type="button" onclick="changeInventoryPage(' . $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' => 'Showing ' . count($inventoryItems) . ' entries of ' . number_format($totalRecords) . ' global catalog units'
        ]);
        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]">Database Error Encountered: ' . htmlspecialchars($e->getMessage()) . '</td></tr>',
            'pagination_controls' => '',
            'metrics_info' => 'Database Query Exception'
        ]);
        exit;
    }
}

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

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

    <?php include_once __DIR__ . '/admin-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-nftAccentPurple uppercase block mb-1">// SYSTEM CONTROL CATALOG INDEX</span>
                    <h1 class="text-3xl font-extrabold tracking-tight text-white">Global Asset Inventory</h1>
                    <p class="text-sm text-nftTextGray mt-1">Review operational performance metrics, track licensing sales values, and manage item definitions across the ledger platform.</p>
                </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">Platform Market Inventory 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="adminInventorySearch" 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 by asset, category, slug, or author handles...">
                    </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">Item Name</th>
                                <th class="px-6 py-4">Category</th>
                                <th class="px-6 py-4">Seller</th>
                                <th class="px-6 py-4">Price</th>
                                <th class="px-6 py-4">Total Sold</th>
                                <th class="px-6 py-4">Avg Review</th>
                                <th class="px-6 py-4 text-right">Update</th>
                            </tr>
                        </thead>
                        <tbody id="inventoryTableTarget" 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 records pipeline framework indices...
                                </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="inventoryMetricsDisplay" class="text-[11px] text-nftTextGray font-mono font-medium">Loading catalog indexes...</span>
                    <div id="inventoryPaginationControls" class="flex items-center space-x-1.5 select-none">
                        </div>
                </div>
            </div>

        </div>
    </main>

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

        // Auto initialization routine mapping listeners across structural DOM stages
        if (document.readyState === "complete" || document.readyState === "interactive") {
            setTimeout(dispatchLiveQueryFetch, 1);
        } else {
            document.addEventListener("DOMContentLoaded", dispatchLiveQueryFetch);
        }

        function triggerLiveSearchEngine() {
            clearTimeout(searchTimeoutTracker);
            searchTimeoutTracker = setTimeout(() => {
                currentActiveInventoryPage = 1; // Always reset map pointer back to base index frame on filter query updates
                dispatchLiveQueryFetch();
            }, 250);
        }

        function changeInventoryPage(pageTargetNodeIndex) {
            currentActiveInventoryPage = pageTargetNodeIndex;
            dispatchLiveQueryFetch();
        }

        function dispatchLiveQueryFetch() {
            const queryInputString = encodeURIComponent(document.getElementById('adminInventorySearch').value);
            // Points to its own file processing action stream
            const apiEndPointTarget = `all-items.php?action=fetch_live_inventory&search=${queryInputString}&page=${currentActiveInventoryPage}`;

            const uiRowBodyContainer = document.getElementById('inventoryTableTarget');
            const uiPaginationRowGroup = document.getElementById('inventoryPaginationControls');
            const uiMetricsTextNodeContainer = document.getElementById('inventoryMetricsDisplay');

            if (!uiRowBodyContainer) return;

            fetch(apiEndPointTarget, {
                    method: 'GET',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json'
                    }
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP network response configuration exception code: ${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;
                    } else {
                        throw new Error("Invalid response structural signature schema returned from stream engine.");
                    }
                })
                .catch(runtimeFaultExceptionContext => {
                    console.error("Administrative Dynamic Framework Sync Interruption Trace:", runtimeFaultExceptionContext);
                    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>
                            System Interface Stream Connection Synchronization Timeout Interruption Exception Fault.<br>
                            <span class="text-slate-500 text-[10px] mt-1 block font-sans">Details: ${runtimeFaultExceptionContext.message}. See developer console network trace context logs.</span>
                        </td>
                    </tr>`;
                });
        }
    </script>
</body>
</html>
