<?php
/**
 * Agentic Square - Seller Support Tickets Inbox (With Real-Time Controls)
 * Path: seller/support-tickets.php
 */
require_once __DIR__ . '/../config/config.php';

// SECURITY GATE: Only allow logged-in users with the 'seller' role
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'seller') {
    header('Location: ../login.php');
    exit;
}

// Fetch all ticket nodes linked to items owned by this specific seller
$query = "SELECT st.*, o.item_name, u.full_name as client_name 
          FROM support_tickets st 
          JOIN orders o ON st.order_id = o.id 
          JOIN users u ON st.user_id = u.id 
          WHERE o.seller_id = ? 
          ORDER BY st.created_at DESC";

$stmt = $pdo->prepare($query);
$stmt->execute([$_SESSION['user_id']]);
$tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);

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-6xl mx-auto space-y-6">
            
            <div>
                <span class="text-xs font-bold tracking-widest text-nftAccentCyan uppercase block mb-1">// Vendor Resolution Module</span>
                <h1 class="text-3xl font-extrabold tracking-tight text-white">Support Ticket Inbox</h1>
            </div>

            <div class="glass-card bg-slate-950/40 p-4 rounded-2xl border border-slate-800/80 grid grid-cols-1 sm:grid-cols-3 gap-4 items-center">
                <div class="relative">
                    <input type="text" id="tableSearch" placeholder="Search client, item, subject..." class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl pl-4 pr-10 py-2.5 text-xs text-white focus:outline-none transition-all">
                    <div class="absolute right-3 top-3 text-slate-600 pointer-events-none">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
                    </div>
                </div>

                <div>
                    <select id="statusFilter" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none transition-all">
                        <option value="ALL">All Ticket Statuses</option>
                        <option value="Pending">Pending</option>
                        <option value="Solved">Solved</option>
                    </select>
                </div>

                <div>
                    <select id="priorityFilter" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none transition-all">
                        <option value="ALL">All Urgency Levels</option>
                        <option value="Low">Low Priority</option>
                        <option value="High">High Priority</option>
                    </select>
                </div>
            </div>

            <div class="glass-card bg-slate-950/20 rounded-2xl border border-slate-800/80 overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse" id="ticketsTable">
                        <thead>
                            <tr class="border-b border-slate-900 bg-slate-950/40 text-xs font-bold uppercase text-nftTextGray tracking-wider">
                                <th class="p-4 sm:p-5">Client Name</th>
                                <th class="p-4 sm:p-5">Associated Item</th>
                                <th class="p-4 sm:p-5">Inquiry Subject</th>
                                <th class="p-4 sm:p-5">Urgency</th>
                                <th class="p-4 sm:p-5">Status</th>
                                <th class="p-4 sm:p-5 text-right">Action Matrix</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-900/60 text-sm">
                            <?php if (empty($tickets)): ?>
                                <tr id="noDataRow">
                                    <td colspan="6" class="p-8 text-center text-nftTextGray font-mono text-xs">
                                        No support tickets have been opened under your tracking matrix profile.
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($tickets as $t): ?>
                                    <tr class="ticket-row hover:bg-slate-900/20 transition-all" 
                                        data-status="<?= htmlspecialchars($t['ticket_status']) ?>" 
                                        data-priority="<?= htmlspecialchars($t['priority'] ?? 'Low') ?>">
                                        <td class="p-4 sm:p-5 font-semibold text-white search-target"><?= htmlspecialchars($t['client_name']) ?></td>
                                        <td class="p-4 sm:p-5 text-slate-300 search-target"><?= htmlspecialchars($t['item_name']) ?></td>
                                        <td class="p-4 sm:p-5 text-slate-400 max-w-xs truncate search-target"><?= htmlspecialchars($t['subject']) ?></td>
                                        <td class="p-4 sm:p-5">
                                            <span class="px-2.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider <?= ($t['priority'] ?? 'Low') === 'High' ? 'bg-rose-500/10 text-rose-400 border border-rose-500/20' : 'bg-slate-800 text-slate-400' ?>">
                                                <?= htmlspecialchars($t['priority'] ?? 'Low') ?>
                                            </span>
                                        </td>
                                        <td class="p-4 sm:p-5">
                                            <span class="px-2.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider <?= $t['ticket_status'] === 'Solved' ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-amber-500/10 text-amber-400 border border-amber-500/20' ?>">
                                                <?= htmlspecialchars($t['ticket_status']) ?>
                                            </span>
                                        </td>
                                        <td class="p-4 sm:p-5 text-right">
                                            <a href="ticket-details.php?id=<?= $t['id'] ?>" class="text-xs font-bold uppercase tracking-widest text-nftAccentCyan hover:text-white transition-all">
                                                Interact &rarr;
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                <tr id="noResultsRow" class="hidden">
                                    <td colspan="6" class="p-8 text-center text-nftTextGray font-mono text-xs">
                                        No structural pipeline vectors match your custom filter rules.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <div class="p-4 sm:p-5 bg-slate-950/40 border-t border-slate-900 flex flex-col sm:flex-row items-center justify-between gap-4 text-xs font-mono text-nftTextGray">
                    <div id="paginationMetrics">Showing 0 to 0 of 0 logs</div>
                    <div class="flex items-center gap-2 select-none" id="paginationControls">
                        </div>
                </div>
            </div>
        </div>
    </main>

    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const tableRows = Array.from(document.querySelectorAll(".ticket-row"));
            const searchInput = document.getElementById("tableSearch");
            const statusFilter = document.getElementById("statusFilter");
            const priorityFilter = document.getElementById("priorityFilter");
            const noResultsRow = document.getElementById("noResultsRow");
            const paginationMetrics = document.getElementById("paginationMetrics");
            const paginationControls = document.getElementById("paginationControls");

            const CONFIG = { rowsPerPage: 10, maxVisiblePages: 4 };
            let currentActivePage = 1;
            let currentlyFilteredRows = [...tableRows];

            function filterAndPaginateTable() {
                const searchString = searchInput.value.toLowerCase().trim();
                const activeStatus = statusFilter.value;
                const activePriority = priorityFilter.value;

                // 1. Run multi-vector verification criteria filter against original structural data set
                currentlyFilteredRows = tableRows.filter(row => {
                    const matchesStatus = (activeStatus === "ALL" || row.getAttribute("data-status") === activeStatus);
                    const matchesPriority = (activePriority === "ALL" || row.getAttribute("data-priority") === activePriority);
                    
                    let matchesSearch = true;
                    if (searchString !== "") {
                        const cellTargets = Array.from(row.querySelectorAll(".search-target"));
                        matchesSearch = cellTargets.some(cell => cell.textContent.toLowerCase().includes(searchString));
                    }
                    return matchesStatus && matchesPriority && matchesSearch;
                });

                // 2. Adjust boundary variables to match realigned collection length limits
                const totalMatchingLogs = currentlyFilteredRows.length;
                const totalPagesCalculated = Math.ceil(totalMatchingLogs / CONFIG.rowsPerPage) || 1;

                if (currentActivePage > totalPagesCalculated) {
                    currentActivePage = totalPagesCalculated;
                }

                // 3. Hide all primary data frames before displaying pagination ranges
                tableRows.forEach(row => row.classList.add("hidden"));

                const startOffsetIndex = (currentActivePage - 1) * CONFIG.rowsPerPage;
                const endOffsetIndex = Math.min(startOffsetIndex + CONFIG.rowsPerPage, totalMatchingLogs);

                if (totalMatchingLogs === 0) {
                    if(noResultsRow) noResultsRow.classList.remove("hidden");
                    paginationMetrics.textContent = "Showing 0 to 0 of 0 entries";
                } else {
                    if(noResultsRow) noResultsRow.classList.add("hidden");
                    paginationMetrics.textContent = `Showing ${startOffsetIndex + 1} to ${endOffsetIndex} of ${totalMatchingLogs} tracking entries`;
                    
                    // Reveal the matching subset allocated to the active page
                    for (let i = startOffsetIndex; i < endOffsetIndex; i++) {
                        currentlyFilteredRows[i].classList.remove("hidden");
                    }
                }

                renderDynamicPaginationControls(totalPagesCalculated);
            }

            function renderDynamicPaginationControls(totalPages) {
                paginationControls.innerHTML = "";
                if (totalPages <= 1 && currentlyFilteredRows.length === 0) return;

                // Helper factory component function for layout button objects
                function createButton(label, targetPage, isButtonActive = false, isButtonDisabled = false) {
                    const btn = document.createElement("button");
                    btn.className = "px-3 py-1.5 rounded-lg border font-bold uppercase text-[10px] tracking-wider transition-all ";
                    btn.textContent = label;

                    if (isButtonDisabled) {
                        btn.className += "border-slate-900 bg-slate-950/20 text-slate-700 cursor-not-allowed";
                        btn.disabled = true;
                    } else if (isButtonActive) {
                        btn.className += "border-nftAccentCyan/30 bg-nftAccentCyan text-black";
                    } else {
                        btn.className += "border-slate-800 bg-slate-950/60 text-slate-300 hover:border-slate-700 hover:text-white";
                        btn.addEventListener("click", () => {
                            currentActivePage = targetPage;
                            filterAndPaginateTable();
                        });
                    }
                    return btn;
                }

                // Render Left Arrow Control Boundary Anchor
                paginationControls.appendChild(createButton("Prev", currentActivePage - 1, false, currentActivePage === 1));

                // Formulate shifting numerical pagination array layout map bounds
                let startPageWindow = Math.max(1, currentActivePage - Math.floor(CONFIG.maxVisiblePages / 2));
                let endPageWindow = startPageWindow + CONFIG.maxVisiblePages - 1;

                if (endPageWindow > totalPages) {
                    endPageWindow = totalPages;
                    startPageWindow = Math.max(1, endPageWindow - CONFIG.maxVisiblePages + 1);
                }

                for (let pageNum = startPageWindow; pageNum <= endPageWindow; pageNum++) {
                    paginationControls.appendChild(createButton(pageNum, pageNum, pageNum === currentActivePage));
                }

                // Inject structural ellipsis break map markers if total length spans beyond window
                if (endPageWindow < totalPages) {
                    const ellipsisElement = document.createElement("span");
                    ellipsisElement.className = "px-1.5 text-slate-600 font-bold select-none";
                    ellipsisElement.textContent = "...";
                    paginationControls.appendChild(ellipsisElement);
                }

                // Render Right Arrow Control Boundary Anchor
                paginationControls.appendChild(createButton("Next", currentActivePage + 1, false, currentActivePage === totalPages));
            }

            // Bind Event Listeners for real-time responsiveness
            searchInput.addEventListener("input", () => { currentActivePage = 1; filterAndPaginateTable(); });
            statusFilter.addEventListener("change", () => { currentActivePage = 1; filterAndPaginateTable(); });
            priorityFilter.addEventListener("change", () => { currentActivePage = 1; filterAndPaginateTable(); });

            // Initialize on component mount
            filterAndPaginateTable();
        });
    </script>
</body>
</html>