<?php
/**
 * Agentic Square - Premium Admin Control Center: Global Seller Registry Matrix
 * Path: admin/all-sellers.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;
}

// FETCH SUMMARY METRICS FOR CARDS
$stats = $pdo->query("SELECT COUNT(id) as total_sellers, SUM(current_balance) as total_balance FROM sellers")->fetch(PDO::FETCH_ASSOC);

/**
 * ASYNCHRONOUS DATA PROVIDER INTERFACE
 */
if (isset($_GET['action']) && $_GET['action'] === 'fetch_live_sellers') {
    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 (s.seller_name LIKE ? OR s.email LIKE ? OR s.city LIKE ? OR s.country LIKE ?)";
        $searchParam = "%{$search}%";
        array_push($params, $searchParam, $searchParam, $searchParam, $searchParam);
    }

    try {
        $countQuery = "SELECT COUNT(s.id) FROM sellers s" . $whereQuery;
        $stmtCount  = $pdo->prepare($countQuery);
        $stmtCount->execute($params);
        $totalRecords = (int)$stmtCount->fetchColumn();
        $totalPages   = ceil($totalRecords / $limit);

        // orders.seller_id stores the seller user_id, while items.seller_id stores sellers.id.
        $dataQuery = "
            SELECT
                s.id AS seller_db_id,
                s.user_id,
                s.seller_slug,
                s.seller_name,
                s.email,
                s.profile_picture,
                s.current_balance,
                (
                    SELECT COUNT(*)
                    FROM items i
                    WHERE i.user_id = s.user_id OR i.seller_id = s.id
                ) AS total_items,
                (
                    SELECT COUNT(*)
                    FROM orders o
                    WHERE o.seller_id = s.user_id AND o.payment_status = 'Paid'
                ) AS total_sold,
                (
                    SELECT COALESCE(SUM(o.net_seller_income), 0)
                    FROM orders o
                    WHERE o.seller_id = s.user_id AND o.payment_status = 'Paid'
                ) AS total_earnings
            FROM sellers s
            $whereQuery
            ORDER BY s.id DESC
            LIMIT $limit OFFSET $offset
        ";

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

        $htmlOutput = '';
        if (empty($sellersCollection)) {
            $htmlOutput .= '<tr><td colspan="8" class="text-center py-12 text-nftTextGray text-xs font-medium font-mono">No marketplace merchant records match search parameter queries.</td></tr>';
        } else {
            $sl = $offset + 1;
            foreach ($sellersCollection as $seller) {
                $avatarPath = !empty($seller['profile_picture']) ? '../' . $seller['profile_picture'] : '../assets/img/vendor-placeholder.png';
                $sellerProfileUrl = seller_url($seller);
                $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-9 h-9 rounded-full bg-slate-950 border border-slate-800 overflow-hidden flex-shrink-0 shadow-md">
                                <img src="' . htmlspecialchars($avatarPath) . '" alt="Merchant Profile" class="w-full h-full object-cover" onerror="this.src=\'../assets/img/vendor-placeholder.png\';">
                            </div>
                            <a href="' . htmlspecialchars($sellerProfileUrl, ENT_QUOTES, 'UTF-8') . '" target="_blank" rel="noopener" class="font-bold text-white group-hover:text-nftAccentCyan transition-colors truncate max-w-[180px] block" title="' . htmlspecialchars($seller['seller_name']) . '">
                                ' . htmlspecialchars($seller['seller_name']) . '
                            </a>
                        </div>
                    </td>
                    <td class="px-6 py-4 text-slate-400 font-mono text-[11px]">' . htmlspecialchars($seller['email']) . '</td>
                    <td class="px-6 py-4 font-mono font-bold text-slate-300">' . number_format($seller['total_items']) . '</td>
                    <td class="px-6 py-4 font-mono font-bold text-emerald-500">' . number_format($seller['total_sold']) . '</td>
                    <td class="px-6 py-4 font-mono font-extrabold text-white">' . htmlspecialchars(format_currency($seller['current_balance']), ENT_QUOTES, 'UTF-8') . '</td>
                    <td class="px-6 py-4 font-mono font-extrabold text-nftAccentCyan">' . htmlspecialchars(format_currency($seller['total_earnings']), ENT_QUOTES, 'UTF-8') . '</td>
                    <td class="px-6 py-4 text-right">
                        <a href="update-seller.php?id=' . $seller['seller_db_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-user-gear text-[10px] text-slate-500 group-hover/btn:text-nftAccentCyan"></i> Update
                        </a>
                    </td>
                </tr>';
            }
        }

        // Pagination generation remains the same
        $paginationOutput = '';
        if ($totalPages > 1) {
            if ($page > 1) $paginationOutput .= '<button type="button" onclick="changeSellersPage(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="changeSellersPage(' . $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="changeSellersPage(' . $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($sellersCollection) . ' entries of ' . number_format($totalRecords) . ' active marketplace merchant accounts']);
        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: ' . 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-nftAccentCyan uppercase block mb-1">// MERCHANT MANAGEMENT SUB-SYSTEM</span>
                    <h1 class="text-3xl font-extrabold tracking-tight text-white">Global Vendor Directory</h1>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div class="glass-card p-6 rounded-2xl border border-slate-800 bg-slate-950/20">
                    <div class="text-xs uppercase font-bold tracking-widest text-slate-500 mb-1">Total Active Sellers</div>
                    <div class="text-3xl font-black text-white"><?= number_format($stats['total_sellers']) ?></div>
                </div>
                <div class="glass-card p-6 rounded-2xl border border-slate-800 bg-slate-950/20">
                    <div class="text-xs uppercase font-bold tracking-widest text-slate-500 mb-1">Available Sellers Balance</div>
                    <div class="text-3xl font-black text-emerald-400"><?= htmlspecialchars(format_currency($stats['total_balance'] ?? 0), ENT_QUOTES, 'UTF-8') ?></div>
                </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">Verified Merchant Matrix Ledger</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="adminSellersSearch" 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 merchant name, email, country...">
                    </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">Seller Profile</th><th class="px-6 py-4">Email Address</th><th class="px-6 py-4">Total Items</th><th class="px-6 py-4">Total Sold</th><th class="px-6 py-4">Current Balance</th><th class="px-6 py-4">Total Earnings</th><th class="px-6 py-4 text-right">Update</th>
                            </tr>
                        </thead>
                        <tbody id="sellersTableTarget" 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]">Compiling data...</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="sellersMetricsDisplay" class="text-[11px] text-nftTextGray font-mono font-medium"></span>
                    <div id="sellersPaginationControls" class="flex items-center space-x-1.5 select-none"></div>
                </div>
            </div>
        </div>
    </main>

    <script>
        let searchTimeoutTracker = null;
        let currentActiveSellersPage = 1;
        document.addEventListener("DOMContentLoaded", dispatchLiveQueryFetch);

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

        function changeSellersPage(pageTargetNodeIndex) {
            currentActiveSellersPage = pageTargetNodeIndex;
            dispatchLiveQueryFetch();
        }

        function dispatchLiveQueryFetch() {
            const queryInputString = encodeURIComponent(document.getElementById('adminSellersSearch').value);
            fetch(`all-sellers.php?action=fetch_live_sellers&search=${queryInputString}&page=${currentActiveSellersPage}`)
                .then(r => r.json())
                .then(d => {
                    document.getElementById('sellersTableTarget').innerHTML = d.table_rows;
                    document.getElementById('sellersPaginationControls').innerHTML = d.pagination_controls;
                    document.getElementById('sellersMetricsDisplay').textContent = d.metrics_info;
                });
        }
    </script>
</body>
</html>
