<?php
/**
 * Agentic Square - Premium Admin Control Center: Global Sales Ledger Registry
 * Path: admin/all-orders.php
 */

require_once __DIR__ . '/../config/config.php';
ensure_transaction_fee_schema();

// 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, status sorting, and pagination requests.
 */
if (isset($_GET['action']) && $_GET['action'] === 'fetch_live_orders') {
    if (ob_get_length()) ob_end_clean();
    header('Content-Type: application/json; charset=utf-8');

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

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

    // Search query parameter matching filter layer logic
    if (!empty($search)) {
        $whereQuery .= " AND (o.item_name LIKE ? OR o.customer_name LIKE ? OR o.customer_email LIKE ? OR s.seller_name LIKE ?)";
        $searchParam = "%{$search}%";
        array_push($params, $searchParam, $searchParam, $searchParam, $searchParam);
    }

    // Dropdown payment status tracking filter
    if (!empty($statusFilter)) {
        $whereQuery .= " AND o.payment_status = ? ";
        array_push($params, $statusFilter);
    }

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

        // 2. Fetch targeted localized rows matrix matching user definitions
        $dataQuery = "
            SELECT
                o.id AS order_id,
                o.item_id,
                o.item_name,
                i.item_slug,
	                o.customer_name,
	                o.customer_email,
	                o.price AS amount,
	                o.transaction_fee_rate,
	                o.transaction_fee_amount,
	                o.total_amount,
	                o.payment_status,
	                s.seller_name
	            FROM orders o
	            LEFT JOIN items i ON o.item_id = i.id
	            LEFT JOIN sellers s ON o.seller_id = s.user_id
            " . $whereQuery . "
            ORDER BY o.id DESC
            LIMIT $limit OFFSET $offset
        ";

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

        $htmlOutput = '';

        if (empty($ordersItems)) {
            $htmlOutput .= '
            <tr>
	                <td colspan="11" class="text-center py-12 text-nftTextGray text-xs font-medium font-mono">
                    <i class="fa-solid fa-file-invoice-dollar text-3xl block text-slate-800 mb-2"></i>
                    No ledger transactions match search parameter queries.
                </td>
            </tr>';
        } else {
            $sl = $offset + 1;
            foreach ($ordersItems as $order) {
                $itemName = htmlspecialchars($order['item_name']);
                $itemTitle = htmlspecialchars($order['item_name']);
                $itemNameDisplay = $itemName;

                if (!empty($order['item_slug']) && !empty($order['item_id'])) {
                    $itemUrl = item_url([
                        'id' => (int)$order['item_id'],
                        'item_slug' => (string)$order['item_slug'],
                    ]);
                    $itemNameDisplay = '<a href="' . htmlspecialchars($itemUrl) . '" target="_blank" rel="noopener" class="block truncate hover:text-nftAccentCyan transition-colors">' . $itemName . '</a>';
                }

                // Payment Badge UI Matrix Rendering
                $statusStr = $order['payment_status'] ?? 'Pending';
                if ($statusStr === 'Paid') {
                    $badgeClass = 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400';
                } elseif ($statusStr === 'Pending') {
                    $badgeClass = 'bg-amber-500/10 border-amber-500/20 text-amber-400';
                } else {
                    $badgeClass = 'bg-rose-500/10 border-rose-500/20 text-rose-400';
                }

                $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 font-bold text-white group-hover:text-nftAccentCyan transition-colors max-w-xs truncate" title="' . $itemTitle . '">
                        ' . $itemNameDisplay . '
                    </td>
                    <td class="px-6 py-4 text-slate-300 font-medium">' . htmlspecialchars($order['customer_name']) . '</td>
                    <td class="px-6 py-4 text-slate-400 font-mono text-[11px]">' . htmlspecialchars($order['customer_email']) . '</td>
	                    <td class="px-6 py-4 font-extrabold font-mono text-white">' . htmlspecialchars(format_currency($order['amount']), ENT_QUOTES, 'UTF-8') . '</td>
	                    <td class="px-6 py-4 font-mono text-amber-300">' . number_format((float)($order['transaction_fee_rate'] ?? 0), 2) . '%</td>
	                    <td class="px-6 py-4 font-mono text-amber-300">' . htmlspecialchars(format_currency((float)($order['transaction_fee_amount'] ?? 0)), ENT_QUOTES, 'UTF-8') . '</td>
	                    <td class="px-6 py-4 font-extrabold font-mono text-emerald-400">' . htmlspecialchars(format_currency(!empty($order['total_amount']) ? (float)$order['total_amount'] : (float)$order['amount']), ENT_QUOTES, 'UTF-8') . '</td>
	                    <td class="px-6 py-4 text-nftTextGray font-medium">' . htmlspecialchars($order['seller_name'] ?? 'Core System Platform') . '</td>
                    <td class="px-6 py-4">
                        <span class="' . $badgeClass . ' border px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider inline-flex items-center gap-1">
                            ' . htmlspecialchars($statusStr) . '
                        </span>
                    </td>
                    <td class="px-6 py-4 text-right">
                        <a href="update-order.php?id=' . $order['order_id'] . '" class="inline-flex items-center justify-center bg-slate-900 hover:bg-slate-800 border border-slate-800 text-nftAccentPurple 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-nftAccentPurple"></i> Update
                        </a>
                    </td>
                </tr>';
            }
        }

        // Advanced Logic: << 5 6 7 ... 58 >> Pagination Builder
        $paginationOutput = '';
        if ($totalPages > 1) {
            if ($page > 1) {
                $paginationOutput .= '<button type="button" onclick="changeOrdersPage(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="changeOrdersPage(' . $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="changeOrdersPage(' . $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($ordersItems) . ' entries of ' . number_format($totalRecords) . ' system order mappings'
        ]);
        exit;
    } catch (Exception $e) {
        echo json_encode([
	            'table_rows' => '<tr><td colspan="11" 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-nftAccentCyan uppercase block mb-1">// TRANSACTION ARCHIVE PIPELINE</span>
                    <h1 class="text-3xl font-extrabold tracking-tight text-white">Global Sales Settlement Ledger</h1>
                    <p class="text-sm text-nftTextGray mt-1">Audit customer details, confirm license fulfillment states, and manually intercept or update order records globally.</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-stretch 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">Financial Settlement Matrix Registry</h4>
                    </div>

                    <div class="flex flex-col sm:flex-row gap-3 items-stretch w-full md:w-auto">
                        <select id="adminOrderStatusFilter" onchange="triggerLiveSearchEngine()" class="bg-slate-950/80 text-white font-medium text-xs px-4 py-3 rounded-xl border border-slate-900 focus:outline-none focus:border-nftAccentCyan transition-colors cursor-pointer min-w-[140px]">
                            <option value="">All Statuses</option>
                            <option value="Paid">Paid</option>
                            <option value="Pending">Pending</option>
                            <option value="Failed">Failed</option>
                        </select>

                        <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="adminOrdersSearch" 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, client name, email, or author...">
                        </div>
                    </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 Asset</th>
                                <th class="px-6 py-4">Client Name</th>
                                <th class="px-6 py-4">Client Email</th>
	                                <th class="px-6 py-4">Price</th>
	                                <th class="px-6 py-4">Fee %</th>
	                                <th class="px-6 py-4">Fee Amount</th>
	                                <th class="px-6 py-4">Total</th>
	                                <th class="px-6 py-4">Seller Name</th>
                                <th class="px-6 py-4">Payment Status</th>
                                <th class="px-6 py-4 text-right">Action</th>
                            </tr>
                        </thead>
                        <tbody id="ordersTableTarget" class="divide-y divide-slate-900/50 text-xs text-slate-300 font-medium">
                            <tr>
	                                <td colspan="11" class="text-center py-10 font-mono text-nftTextGray text-[11px]">
                                    Synchronizing ledger data mapping structures...
                                </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="ordersMetricsDisplay" class="text-[11px] text-nftTextGray font-mono font-medium">Loading ledger indexes...</span>
                    <div id="ordersPaginationControls" class="flex items-center space-x-1.5 select-none"></div>
                </div>
            </div>

        </div>
    </main>

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

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

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

        function changeOrdersPage(pageTargetNodeIndex) {
            currentActiveOrdersPage = pageTargetNodeIndex;
            dispatchLiveQueryFetch();
        }

        function dispatchLiveQueryFetch() {
            const queryInputString = encodeURIComponent(document.getElementById('adminOrdersSearch').value);
            const statusFilterValue = encodeURIComponent(document.getElementById('adminOrderStatusFilter').value);
            
            const apiEndPointTarget = `all-orders.php?action=fetch_live_orders&search=${queryInputString}&status_filter=${statusFilterValue}&page=${currentActiveOrdersPage}`;

            const uiRowBodyContainer = document.getElementById('ordersTableTarget');
            const uiPaginationRowGroup = document.getElementById('ordersPaginationControls');
            const uiMetricsTextNodeContainer = document.getElementById('ordersMetricsDisplay');

            if (!uiRowBodyContainer) return;

            fetch(apiEndPointTarget, {
                    method: 'GET',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json'
                    }
                })
                .then(response => {
                    if (!response.ok) throw new Error(`HTTP transaction status fault check: ${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("Ledger Stream Processing Error Context Trace:", err);
                    uiRowBodyContainer.innerHTML = `
                    <tr>
                        <td colspan="11" 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>
                            Pipeline Sync Timeout Interruption Exception Fault.<br>
                            <span class="text-slate-500 text-[10px] mt-1 block font-sans">Details: ${err.message}. Check browser network streams.</span>
                        </td>
                    </tr>`;
                });
        }
    </script>
</body>
</html>
