<?php
/**
 * Agentic Square - Premium Admin Control Center: Review Management
 * Path: admin/reviews.php
 */

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

// Security Guard
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

// Handle asynchronous data requests
if (isset($_GET['action']) && $_GET['action'] === 'fetch_reviews') {
    if (ob_get_length()) ob_end_clean();
    header('Content-Type: application/json; charset=utf-8');

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

    $params = [];
    $where = " WHERE 1=1 ";
    if (!empty($search)) {
        $where .= " AND (client_name LIKE ? OR seller_name LIKE ? OR item_name LIKE ?)";
        $searchParam = "%{$search}%";
        array_push($params, $searchParam, $searchParam, $searchParam);
    }

    try {
        // Fetch count for pagination
        $stmtCount = $pdo->prepare("SELECT COUNT(*) FROM reviews" . $where);
        $stmtCount->execute($params);
        $totalRecords = (int)$stmtCount->fetchColumn();
        $totalPages = ceil($totalRecords / $limit);

        // Fetch data
        $query = "SELECT * FROM reviews $where ORDER BY created_at DESC LIMIT $limit OFFSET $offset";
        $stmt = $pdo->prepare($query);
        $stmt->execute($params);
        $reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $html = '';
        $sl = $offset + 1;
        foreach ($reviews as $row) {
            $ratingStars = str_repeat('★', (int)$row['rating']) . str_repeat('☆', 5 - (int)$row['rating']);
            $html .= '<tr class="border-b border-slate-900/50 hover:bg-slate-900/20">
                <td class="px-6 py-4 font-mono text-slate-500">' . $sl++ . '</td>
                <td class="px-6 py-4 text-xs text-slate-400">' . date('Y-m-d', strtotime($row['created_at'])) . '</td>
                <td class="px-6 py-4 font-bold text-white">' . htmlspecialchars($row['client_name']) . '</td>
                <td class="px-6 py-4 text-slate-300">' . htmlspecialchars($row['seller_name']) . '</td>
                <td class="px-6 py-4 text-nftAccentCyan">' . htmlspecialchars($row['item_name']) . '</td>
                <td class="px-6 py-4 text-xs text-slate-400 max-w-[200px] truncate" title="' . htmlspecialchars($row['review_text']) . '">' . htmlspecialchars($row['review_text']) . '</td>
                <td class="px-6 py-4 text-amber-400 font-bold tracking-widest">' . $ratingStars . '</td>
            </tr>';
        }

        echo json_encode([
            'html' => $html ?: '<tr><td colspan="7" class="text-center py-10">No reviews found.</td></tr>',
            'pagination' => ($totalPages > 1) ? "Page $page of $totalPages" : ''
        ]);
        exit;
    } catch (Exception $e) {
        echo json_encode(['html' => '<tr><td colspan="7">Error: ' . $e->getMessage() . '</td></tr>']);
        exit;
    }
}

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

<body class="bg-nftDark text-white">
    <?php include_once __DIR__ . '/admin-sidebar.php'; ?>
    <main class="lg:ml-64 min-h-screen pt-10 px-8">
        <h1 class="text-2xl font-bold mb-6">// ITEM REVIEW LEDGER</h1>
        
        <div class="glass-card p-6 rounded-2xl border border-slate-800 bg-slate-950/20">
            <input type="text" id="revSearch" oninput="loadReviews()" class="w-full bg-slate-900 border border-slate-800 p-3 rounded-lg mb-6 text-sm" placeholder="Search by client, seller, or item...">
            
            <div class="overflow-x-auto">
                <table class="w-full text-left">
                    <thead>
                        <tr class="border-b border-slate-800 text-xs text-nftTextGray uppercase">
                            <th class="px-6 py-4">SL</th>
                            <th class="px-6 py-4">Date</th>
                            <th class="px-6 py-4">Client</th>
                            <th class="px-6 py-4">Seller</th>
                            <th class="px-6 py-4">Item</th>
                            <th class="px-6 py-4">Review</th>
                            <th class="px-6 py-4">Rating</th>
                        </tr>
                    </thead>
                    <tbody id="revTarget"><tr><td colspan="7" class="text-center py-10">Loading...</td></tr></tbody>
                </table>
            </div>
        </div>
    </main>

    <script>
        function loadReviews() {
            const s = document.getElementById('revSearch').value;
            fetch('reviews.php?action=fetch_reviews&search=' + encodeURIComponent(s))
                .then(r => r.json())
                .then(d => document.getElementById('revTarget').innerHTML = d.html);
        }
        document.addEventListener("DOMContentLoaded", loadReviews);
    </script>
</body>