<?php

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

// Dynamic relative path resolver 
if (!isset($pdo)) {
    $configPath = file_exists(__DIR__ . '/../config/config.php') ? __DIR__ . '/../config/config.php' : '../config/config.php';
    if (file_exists($configPath)) {
        require_once $configPath;
    } else {
        if (isset($_GET['action']) && $_GET['action'] === 'fetch_live_inventory') {
            header('Content-Type: application/json; charset=utf-8');
            echo json_encode(['table_rows' => '<tr><td colspan="8" class="text-center py-4 text-rose-400">Configuration runtime layer link failure.</td></tr>', 'pagination_controls' => '', 'metrics_info' => 'Error']);
            exit;
        }
    }
}

/**
 * ASYNCHRONOUS DATA PROVIDER INTERFACE
 * Intercepts real-time AJAX search and pagination requests to return dynamic HTML rows.
 */
if (isset($_GET['action']) && $_GET['action'] === 'fetch_live_inventory') {

    if (ob_get_length()) ob_end_clean();
    header('Content-Type: application/json; charset=utf-8');

    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
        echo json_encode([
            'table_rows' => '<tr><td colspan="8" class="text-center py-6 text-rose-400">Unauthorized session tracking clearance validation rejection.</td></tr>',
            'pagination_controls' => '',
            'metrics_info' => 'Access Denied'
        ]);
        exit;
    }

    $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)) {
        // RESOLUTION FIX: Swapped out non-existent username criteria fields for item name, item slug, or seller corporate handles
        $whereQuery .= " AND (i.item_name LIKE ? OR i.item_slug LIKE ? OR s.seller_name LIKE ?)";
        $searchParam = "%{$search}%";
        array_push($params, $searchParam, $searchParam, $searchParam);
    }

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

        // 2. Fetch targeted localized window offset rows mapping schema matrix arrays
        // RESOLUTION FIX: Exchanged 's.username' for 's.seller_name' to establish valid data joins matching your schema guidelines
        $dataQuery = "
SELECT
    i.*,
    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 ROUND(AVG(r.rating), 2)
        FROM reviews r
        WHERE r.item_id = i.id
    ) AS average_rating,

    (
        SELECT COUNT(*)
        FROM reviews r
        WHERE r.item_id = i.id
    ) AS total_reviews

FROM items i
LEFT JOIN sellers s
    ON i.seller_id = s.id

" . $whereQuery . "

ORDER BY i.id DESC
LIMIT $limit OFFSET $offset
";

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

        $htmlOutput = '';

        if (empty($inventoryItems)) {
            $htmlOutput .= '
            <tr>
                <td colspan="8" class="text-center py-12 text-nftTextGray text-xs font-medium">
                    <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';
                $statusStr = $item['status'] ?? 'active';
                $statusClass = ($statusStr === 'active') ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400' : 'bg-rose-500/10 border-rose-500/20 text-rose-400';

                $totalSold = number_format($item['total_sold'] ?? 0);
                $rating    = number_format((float)($item['average_rating'] ?? 0.00), 2);
                $reviews   = number_format((int)($item['total_reviews'] ?? 0));
                $itemUrl   = function_exists('item_url') ? item_url($item) : '../item-details.php?slug=' . rawurlencode((string)$item['item_slug']);

                $htmlOutput .= '
                <tr class="hover:bg-slate-900/20 transition-colors group">
                    <td class="py-4 pl-2 font-mono font-bold text-slate-500">' . $sl++ . '</td>
                    <td class="py-2">
                        <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 Visual Feature" class="w-full h-full object-cover" onerror="this.src=\'../assets/img/placeholder.png\';">
                        </div>
                    </td>
	                    <td class="py-4 font-bold text-white group-hover:text-nftAccentCyan transition-colors">
	                        <a href="' . htmlspecialchars($itemUrl) . '" target="_blank" rel="noopener" class="block truncate max-w-xs font-semibold hover:text-nftAccentCyan transition-colors" title="' . htmlspecialchars($item['item_name']) . '">
	                            ' . htmlspecialchars($item['item_name']) . '
	                        </a>
	                    </td>
                    <td class="py-4 text-nftTextGray font-medium">' . htmlspecialchars($item['author_name'] ?? 'System/Admin') . '</td>
                    <td class="py-4 font-extrabold font-mono text-emerald-400">' . htmlspecialchars(format_currency($item['amount']), ENT_QUOTES, 'UTF-8') . '</td>
                    
                    <td class="py-4 font-mono text-slate-400 text-[11px]">
                        <div class="space-y-0.5">
                            <div><span class="text-slate-600 font-sans">Sold:</span> ' . $totalSold . '</div>
                            <div class="flex items-center gap-1">
                                <span class="text-slate-600 font-sans">Rating:</span> <span class="text-amber-400 font-bold">' . $rating . '</span> 
                                <span class="text-slate-600 font-sans">(' . $reviews . ')</span>
                            </div>
                        </div>
                    </td>

                    <td class="py-4">
                        <span class="' . $statusClass . ' border px-2 py-0.5 rounded-md text-[9px] font-bold uppercase">' . htmlspecialchars($statusStr) . '</span>
                    </td>
                    <td class="py-4 text-right pr-2">
                        <div class="inline-flex gap-2">
                            <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-2.5 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> Manage
                            </a>
                        </div>
                    </td>
                </tr>';
            }
        }

        $paginationOutput = '';
        if ($totalPages > 1) {
            for ($i = 1; $i <= $totalPages; $i++) {
                $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-bold transition-all ' . $activeClass . '">' . $i . '</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;
    }
}
?>

<div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-6">

    <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-nftAccentPurple animate-ping"></div>
            <h4 class="font-bold text-base text-white tracking-wide">Global 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 names, slug tags, or author handles...">
        </div>
    </div>

    <div class="overflow-x-auto">
        <table class="w-full text-left text-sm border-collapse">
            <thead>
                <tr class="border-b border-slate-900 text-xs font-bold text-nftTextGray uppercase tracking-wider">
                    <th class="pb-3 pl-2 w-12">SL</th>
                    <th class="pb-3 w-20">Asset Visual</th>
                    <th class="pb-3">Product Asset Title</th>
                    <th class="pb-3 w-36">Author Account</th>
                    <th class="pb-3 w-32">License Price</th>
                    <th class="pb-3 w-40">Performance Tracking</th>
                    <th class="pb-3 w-24">Status</th>
                    <th class="pb-3 text-right pr-2 w-28">Actions</th>
                </tr>
            </thead>
            <tbody id="inventoryTableTarget" class="divide-y divide-slate-900/50 text-xs text-slate-300 font-medium">
            </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-medium">Loading inventory indexes...</span>
        <div id="inventoryPaginationControls" class="flex items-center space-x-1.5">
        </div>
    </div>
</div>

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

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

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

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

    function dispatchLiveQueryFetch() {
        const queryInputString = encodeURIComponent(document.getElementById('adminInventorySearch').value);
        const apiEndPointTarget = `all-items-table.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(payloadDataPayloadNode => {
                if (payloadDataPayloadNode && typeof payloadDataPayloadNode === 'object') {
                    uiRowBodyContainer.innerHTML = payloadDataPayloadNode.table_rows;
                    uiPaginationRowGroup.innerHTML = payloadDataPayloadNode.pagination_controls;
                    uiMetricsTextNodeContainer.textContent = payloadDataPayloadNode.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}. Check your browser developer console (F12) Network logs for precise server stack errors.</span>
            </td>
        </tr>`;
            });
    }
</script>
