<?php
// dashboard_admin.php - Global Admin Controls Panel & Moderation Console
require_once 'db_connect.php';

// Enforce Admin only access
if (!isLoggedIn()) {
    header("Location: login.php?redirect=dashboard_admin.php&error=" . urlencode("Please log in."));
    exit();
}

$user = getLoggedInUser();
if ($user['role'] !== 'admin') {
    header("Location: index.php?error=" . urlencode("Unauthorized access. Admin privileges required."));
    exit();
}

$action = $_GET['action'] ?? '';

// Handle Admin POST Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // ACTION: TOGGLE BAN STATUS
    if ($action === 'toggle_ban') {
        $userId = intval($_POST['user_id'] ?? 0);
        if ($userId > 0 && $userId !== intval($user['id'])) {
            $stmt = $pdo->prepare("SELECT role, is_banned FROM users WHERE id = ?");
            $stmt->execute([$userId]);
            $target = $stmt->fetch();

            if ($target && $target['role'] !== 'admin') {
                $newBan = $target['is_banned'] ? 0 : 1;
                $update = $pdo->prepare("UPDATE users SET is_banned = ? WHERE id = ?");
                $update->execute([$newBan, $userId]);
                header("Location: dashboard_admin.php?success=" . urlencode("User ban status updated."));
                exit();
            }
        }
        header("Location: dashboard_admin.php?error=" . urlencode("Action failed."));
        exit();
    }

    // ACTION: CHANGE USER ROLE (RBAC)
    if ($action === 'change_role') {
        $userId   = intval($_POST['user_id'] ?? 0);
        $newRole  = $_POST['new_role'] ?? '';
        $allowedRoles = ['admin', 'seller', 'buyer'];

        if ($userId > 0 && $userId !== intval($user['id']) && in_array($newRole, $allowedRoles)) {
            $stmt = $pdo->prepare("SELECT role FROM users WHERE id = ?");
            $stmt->execute([$userId]);
            $target = $stmt->fetch();

            if ($target) {
                $update = $pdo->prepare("UPDATE users SET role = ? WHERE id = ?");
                $update->execute([$newRole, $userId]);
                header("Location: dashboard_admin.php?success=" . urlencode("User role changed to '{$newRole}' successfully."));
                exit();
            }
        }
        header("Location: dashboard_admin.php?error=" . urlencode("Failed to change user role."));
        exit();
    }

    // ACTION: DELETE USER
    if ($action === 'delete_user') {
        $userId = intval($_POST['user_id'] ?? 0);
        if ($userId > 0 && $userId !== intval($user['id'])) {
            $stmt = $pdo->prepare("SELECT role FROM users WHERE id = ?");
            $stmt->execute([$userId]);
            $target = $stmt->fetch();

            if ($target && $target['role'] !== 'admin') {
                $delete = $pdo->prepare("DELETE FROM users WHERE id = ?");
                $delete->execute([$userId]);
                header("Location: dashboard_admin.php?success=" . urlencode("User account deleted."));
                exit();
            }
        }
        header("Location: dashboard_admin.php?error=" . urlencode("Failed to delete user."));
        exit();
    }

    // ACTION: MODERATE PRODUCT
    if ($action === 'moderate_product') {
        $prodId = intval($_POST['product_id'] ?? 0);
        $status = $_POST['status'] ?? 'approved';

        if ($prodId > 0 && in_array($status, ['approved', 'pending', 'rejected'])) {
            $update = $pdo->prepare("UPDATE products SET status = ? WHERE id = ?");
            $update->execute([$status, $prodId]);
            header("Location: dashboard_admin.php?success=" . urlencode("Product status updated to {$status}."));
            exit();
        }
        header("Location: dashboard_admin.php?error=" . urlencode("Failed to moderate product."));
        exit();
    }

    // ACTION: DELETE PRODUCT LISTING
    if ($action === 'delete_product') {
        $prodId = intval($_POST['product_id'] ?? 0);
        if ($prodId > 0) {
            $delete = $pdo->prepare("DELETE FROM products WHERE id = ?");
            $delete->execute([$prodId]);
            header("Location: dashboard_admin.php?success=" . urlencode("Product listing deleted from platform."));
            exit();
        }
        header("Location: dashboard_admin.php");
        exit();
    }

    // ACTION: DISMISS REPORT
    if ($action === 'dismiss_report') {
        $reportId = intval($_POST['report_id'] ?? 0);
        if ($reportId > 0) {
            $update = $pdo->prepare("UPDATE product_reports SET status = 'dismissed' WHERE id = ?");
            $update->execute([$reportId]);
            header("Location: dashboard_admin.php?success=" . urlencode("Report dismissed."));
            exit();
        }
    }

    // ACTION: UPDATE ORDER STATUS
    if ($action === 'update_order') {
        $orderId = intval($_POST['order_id'] ?? 0);
        $status = $_POST['status'] ?? 'Pending';

        if ($orderId > 0 && in_array($status, ['Pending', 'Shipped', 'Delivered', 'Cancelled'])) {
            try {
                $pdo->beginTransaction();

                $stmt = $pdo->prepare("SELECT status FROM orders WHERE id = ?");
                $stmt->execute([$orderId]);
                $ord = $stmt->fetch();

                if ($ord) {
                    if ($status === 'Cancelled' && $ord['status'] !== 'Cancelled') {
                        $itemsStmt = $pdo->prepare("SELECT * FROM order_items WHERE order_id = ?");
                        $itemsStmt->execute([$orderId]);
                        $items = $itemsStmt->fetchAll();

                        $restoreStock = $pdo->prepare("UPDATE products SET stock = stock + ? WHERE id = ?");
                        foreach ($items as $it) {
                            if ($it['product_id'] !== null) {
                                $restoreStock->execute([$it['quantity'], $it['product_id']]);
                            }
                        }
                    }

                    $update = $pdo->prepare("UPDATE orders SET status = ? WHERE id = ?");
                    $update->execute([$status, $orderId]);
                }

                $pdo->commit();
                header("Location: dashboard_admin.php?success=" . urlencode("Order status updated to {$status}."));
                exit();
            } catch (Exception $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                header("Location: dashboard_admin.php?error=" . urlencode($e->getMessage()));
                exit();
            }
        }
        header("Location: dashboard_admin.php");
        exit();
    }
}

// 1. Gather stats
$salesStmt = $pdo->query("SELECT SUM(total_amount) as total FROM orders WHERE status != 'Cancelled'");
$totalRevenue = $salesStmt->fetch()['total'] ?? 0.00;

$usersCountStmt = $pdo->query("SELECT COUNT(*) as count FROM users");
$totalUsers = $usersCountStmt->fetch()['count'];

$prodCountStmt = $pdo->query("SELECT COUNT(*) as count FROM products WHERE status = 'approved' AND stock > 0");
$activeCatalog = $prodCountStmt->fetch()['count'];

$pendingCountStmt = $pdo->query("SELECT COUNT(*) as count FROM products WHERE status = 'pending'");
$pendingProductsCount = $pendingCountStmt->fetch()['count'];

$orderCountStmt = $pdo->query("SELECT COUNT(*) as count FROM orders");
$totalOrders = $orderCountStmt->fetch()['count'];

// 2. Fetch Users list
$usersStmt = $pdo->prepare("SELECT id, username, email, role, is_banned, created_at FROM users WHERE id != ? ORDER BY created_at DESC");
$usersStmt->execute([$user['id']]);
$allUsers = $usersStmt->fetchAll();

// 3. Fetch Products list
$prodsStmt = $pdo->query("SELECT p.*, u.username as seller_name FROM products p JOIN users u ON p.seller_id = u.id ORDER BY (p.status = 'pending') DESC, p.created_at DESC");
$allProducts = $prodsStmt->fetchAll();

// 4. Fetch Reports list
$reportsStmt = $pdo->query("
    SELECT r.*, p.title as product_title, p.seller_id, u.username as reporter_name, s.username as seller_name
    FROM product_reports r
    JOIN products p ON r.product_id = p.id
    LEFT JOIN users u ON r.user_id = u.id
    JOIN users s ON p.seller_id = s.id
    ORDER BY (r.status = 'pending') DESC, r.created_at DESC
");
$allReports = $reportsStmt ? $reportsStmt->fetchAll() : [];

// 5. Fetch Orders list
$ordersStmt = $pdo->query("SELECT o.*, u.username as buyer_name FROM orders o JOIN users u ON o.buyer_id = u.id ORDER BY o.created_at DESC");
$allOrders = $ordersStmt->fetchAll();

renderHeader(__('admin_page_title'));
?>

<div class="mb-10">
    <h1 class="text-3xl font-extrabold text-gray-900 tracking-tight"><?php echo __('admin_heading'); ?></h1>
    <p class="text-sm text-gray-500 mt-1"><?php echo __('admin_subheading'); ?></p>
</div>

<!-- Stats Counter Grid -->
<div class="grid grid-cols-2 lg:grid-cols-5 gap-4 mb-10">
    <div class="bg-white p-5 rounded-2xl border border-gray-100 shadow-sm">
        <span class="text-[10px] font-bold text-gray-400 uppercase tracking-wider block"><?php echo __('admin_stat_sales'); ?></span>
        <span class="text-xl sm:text-2xl font-black text-rose-600 mt-1 block">$<?php echo number_format($totalRevenue, 2); ?></span>
    </div>
    <div class="bg-white p-5 rounded-2xl border border-gray-100 shadow-sm">
        <span class="text-[10px] font-bold text-gray-400 uppercase tracking-wider block"><?php echo __('admin_stat_users'); ?></span>
        <span class="text-xl sm:text-2xl font-black text-gray-900 mt-1 block"><?php echo $totalUsers; ?></span>
    </div>
    <div class="bg-white p-5 rounded-2xl border border-gray-100 shadow-sm">
        <span class="text-[10px] font-bold text-gray-400 uppercase tracking-wider block"><?php echo __('admin_stat_catalog'); ?></span>
        <span class="text-xl sm:text-2xl font-black text-emerald-600 mt-1 block"><?php echo $activeCatalog; ?></span>
    </div>
    <div class="bg-white p-5 rounded-2xl border border-gray-100 shadow-sm">
        <span class="text-[10px] font-bold text-gray-400 uppercase tracking-wider block"><?php echo __('admin_stat_pending'); ?></span>
        <span class="text-xl sm:text-2xl font-black text-amber-500 mt-1 block"><?php echo $pendingProductsCount; ?></span>
    </div>
    <div class="bg-white p-5 rounded-2xl border border-gray-100 shadow-sm">
        <span class="text-[10px] font-bold text-gray-400 uppercase tracking-wider block"><?php echo __('admin_stat_orders'); ?></span>
        <span class="text-xl sm:text-2xl font-black text-gray-900 mt-1 block"><?php echo $totalOrders; ?></span>
    </div>
</div>

<div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
    
    <!-- Left: Navigation tab menu -->
    <nav class="lg:col-span-3 bg-white p-4 rounded-2xl border border-gray-100 shadow-sm space-y-1.5 h-fit">
        <button onclick="switchAdminTab('users-panel')" id="btn-users-panel" class="w-full text-left px-4 py-2.5 rounded-xl font-bold text-sm text-orange-600 bg-orange-50 transition-all flex items-center justify-between">
            <span class="flex items-center gap-2">
                <svg class="w-4 h-4 text-orange-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"/></svg>
                <?php echo __('admin_tab_users'); ?>
            </span>
        </button>
        <button onclick="switchAdminTab('products-panel')" id="btn-products-panel" class="w-full text-left px-4 py-2.5 rounded-xl font-semibold text-sm text-gray-500 hover:text-gray-900 transition-all flex items-center justify-between">
            <span class="flex items-center gap-2">
                <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 11V7a4 4 0 00-8 0v4M5 11h14l1 12H4L5 11z"/></svg>
                <?php echo __('admin_tab_catalog'); ?>
            </span>
            <?php if ($pendingProductsCount > 0): ?>
                <span class="px-2 py-0.5 text-[10px] font-black bg-amber-500 text-white rounded-full"><?php echo $pendingProductsCount; ?></span>
            <?php endif; ?>
        </button>
        <button onclick="switchAdminTab('reports-panel')" id="btn-reports-panel" class="w-full text-left px-4 py-2.5 rounded-xl font-semibold text-sm text-gray-500 hover:text-gray-900 transition-all flex items-center justify-between">
            <span class="flex items-center gap-2">
                <svg class="w-4 h-4 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
                <?php echo __('admin_tab_reports'); ?>
            </span>
            <?php if (count($allReports) > 0): ?>
                <span class="px-2 py-0.5 text-[10px] font-black bg-red-500 text-white rounded-full"><?php echo count($allReports); ?></span>
            <?php endif; ?>
        </button>
        <button onclick="switchAdminTab('orders-panel')" id="btn-orders-panel" class="w-full text-left px-4 py-2.5 rounded-xl font-semibold text-sm text-gray-500 hover:text-gray-900 transition-all flex items-center justify-between">
            <span class="flex items-center gap-2">
                <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"/></svg>
                <?php echo __('admin_tab_orders'); ?>
            </span>
        </button>
    </nav>

    <!-- Right: panel grids -->
    <div class="lg:col-span-9 space-y-6">
        
        <!-- Tab 1: User Management -->
        <section id="users-panel" class="bg-white p-6 rounded-3xl border border-gray-100 shadow-sm space-y-6">
            <h2 class="text-xl font-bold text-gray-900 pb-3 border-b border-gray-100"><?php echo __('admin_users_title'); ?></h2>
            <div class="overflow-x-auto">
                <table class="w-full text-left text-sm text-gray-500 divide-y divide-gray-100">
                    <thead>
                        <tr class="text-xs text-gray-400 font-bold uppercase tracking-wider">
                            <th class="pb-3"><?php echo __('admin_th_username'); ?></th>
                            <th class="pb-3"><?php echo __('admin_th_email'); ?></th>
                            <th class="pb-3"><?php echo __('admin_th_role'); ?></th>
                            <th class="pb-3"><?php echo __('admin_th_change_role'); ?></th>
                            <th class="pb-3"><?php echo __('admin_th_created'); ?></th>
                            <th class="pb-3 text-right"><?php echo __('admin_th_actions'); ?></th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100 text-xs sm:text-sm">
                        <?php foreach ($allUsers as $u): ?>
                            <tr class="hover:bg-slate-50/50">
                                <td class="py-4 font-bold text-gray-900"><?php echo sanitize($u['username']); ?></td>
                                <td class="py-4"><?php echo sanitize($u['email']); ?></td>
                                <td class="py-4">
                                    <?php
                                    if ($u['role'] === 'admin') {
                                        $roleColor = 'text-red-600 bg-red-50 border-red-100';
                                    } elseif ($u['role'] === 'seller') {
                                        $roleColor = 'text-blue-600 bg-blue-50 border-blue-100';
                                    } else {
                                        $roleColor = 'text-emerald-600 bg-emerald-50 border-emerald-100';
                                    }
                                    ?>
                                    <span class="px-2.5 py-1 rounded-full text-[10px] font-black uppercase tracking-wider border <?php echo $roleColor; ?>">
                                        <?php echo strtoupper($u['role']); ?>
                                    </span>
                                </td>
                                <td class="py-4">
                                    <form action="dashboard_admin.php?action=change_role" method="POST" class="inline-flex">
                                        <input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">
                                        <select name="new_role" onchange="this.form.submit()" class="text-xs p-1 bg-gray-50 border border-gray-200 rounded-lg font-bold">
                                            <option value="buyer" <?php echo $u['role'] === 'buyer' ? 'selected' : ''; ?>>Buyer</option>
                                            <option value="seller" <?php echo $u['role'] === 'seller' ? 'selected' : ''; ?>>Seller</option>
                                            <option value="admin" <?php echo $u['role'] === 'admin' ? 'selected' : ''; ?>>Admin</option>
                                        </select>
                                    </form>
                                </td>
                                <td class="py-4 text-xs text-gray-400"><?php echo date('Y-m-d', strtotime($u['created_at'])); ?></td>
                                <td class="py-4 text-right space-x-2">
                                    <form action="dashboard_admin.php?action=toggle_ban" method="POST" class="inline">
                                        <input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">
                                        <?php if ($u['is_banned']): ?>
                                            <button type="submit" class="px-3 py-1 bg-emerald-50 text-emerald-600 hover:bg-emerald-100 font-bold rounded-lg text-xs transition-colors">
                                                <?php echo __('admin_btn_unban'); ?>
                                            </button>
                                        <?php else: ?>
                                            <button type="submit" class="px-3 py-1 bg-amber-50 text-amber-600 hover:bg-amber-100 font-bold rounded-lg text-xs transition-colors">
                                                <?php echo __('admin_btn_ban'); ?>
                                            </button>
                                        <?php endif; ?>
                                    </form>

                                    <form action="dashboard_admin.php?action=delete_user" method="POST" class="inline" onsubmit="return confirm('Permanently delete this user account?')">
                                        <input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">
                                        <button type="submit" class="px-3 py-1 bg-red-50 text-red-600 hover:bg-red-100 font-bold rounded-lg text-xs transition-colors">
                                            <?php echo __('admin_btn_delete'); ?>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </section>

        <!-- Tab 2: Catalog Moderation -->
        <section id="products-panel" class="hidden bg-white p-6 rounded-3xl border border-gray-100 shadow-sm space-y-6">
            <h2 class="text-xl font-bold text-gray-900 pb-3 border-b border-gray-100"><?php echo __('admin_catalog_title'); ?></h2>
            <div class="overflow-x-auto">
                <table class="w-full text-left text-sm text-gray-500 divide-y divide-gray-100">
                    <thead>
                        <tr class="text-xs text-gray-400 font-bold uppercase tracking-wider">
                            <th class="pb-3"><?php echo __('admin_th_product'); ?></th>
                            <th class="pb-3"><?php echo __('admin_th_seller'); ?></th>
                            <th class="pb-3"><?php echo __('admin_th_price'); ?></th>
                            <th class="pb-3"><?php echo __('admin_th_stock'); ?></th>
                            <th class="pb-3"><?php echo __('admin_th_status'); ?></th>
                            <th class="pb-3 text-right"><?php echo __('admin_th_actions'); ?></th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100 text-xs sm:text-sm">
                        <?php foreach ($allProducts as $p): 
                            $img = getProductImgUrl($p['id'], $p['images']);
                        ?>
                            <tr class="hover:bg-slate-50/50 <?php echo $p['status'] === 'pending' ? 'bg-amber-50/30' : ''; ?>">
                                <td class="py-4 font-bold text-gray-900 flex items-center gap-3">
                                    <img src="<?php echo $img; ?>" class="w-10 h-10 rounded-lg object-cover border flex-shrink-0" onerror="this.onerror=null; this.src='https://images.unsplash.com/photo-1526170375885-4d8ecf77b99f?w=100';">
                                    <div>
                                        <span class="block truncate max-w-xs font-bold"><?php echo sanitize($p['title']); ?></span>
                                        <span class="text-[10px] text-gray-400 uppercase font-semibold"><?php echo sanitize($p['category']); ?></span>
                                    </div>
                                </td>
                                <td class="py-4 text-xs font-bold text-gray-700"><?php echo sanitize($p['seller_name']); ?></td>
                                <td class="py-4 font-bold text-rose-600">$<?php echo number_format($p['price'], 2); ?></td>
                                <td class="py-4"><?php echo $p['stock']; ?></td>
                                <td class="py-4">
                                    <?php if ($p['status'] === 'approved'): ?>
                                        <span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-100 text-emerald-800 uppercase"><?php echo __('sell_status_approved'); ?></span>
                                    <?php elseif ($p['status'] === 'pending'): ?>
                                        <span class="px-2 py-0.5 rounded text-[10px] font-bold bg-amber-100 text-amber-800 uppercase"><?php echo __('sell_status_pending'); ?></span>
                                    <?php else: ?>
                                        <span class="px-2 py-0.5 rounded text-[10px] font-bold bg-red-100 text-red-800 uppercase"><?php echo __('sell_status_rejected'); ?></span>
                                    <?php endif; ?>
                                </td>
                                <td class="py-4 text-right space-x-2">
                                    <form action="dashboard_admin.php?action=moderate_product" method="POST" class="inline">
                                        <input type="hidden" name="product_id" value="<?php echo $p['id']; ?>">
                                        <?php if ($p['status'] !== 'approved'): ?>
                                            <button type="submit" name="status" value="approved" class="px-3 py-1 bg-emerald-500 hover:bg-emerald-600 text-white font-bold rounded-lg text-xs transition-colors shadow-sm">
                                                <?php echo __('admin_btn_approve'); ?>
                                            </button>
                                        <?php endif; ?>
                                        <?php if ($p['status'] !== 'rejected'): ?>
                                            <button type="submit" name="status" value="rejected" class="px-3 py-1 bg-amber-50 text-amber-700 hover:bg-amber-100 font-bold rounded-lg text-xs transition-colors">
                                                <?php echo __('admin_btn_reject'); ?>
                                            </button>
                                        <?php endif; ?>
                                    </form>

                                    <form action="dashboard_admin.php?action=delete_product" method="POST" class="inline" onsubmit="return confirm('Permanently remove product listing?')">
                                        <input type="hidden" name="product_id" value="<?php echo $p['id']; ?>">
                                        <button type="submit" class="px-3 py-1 bg-red-50 text-red-600 hover:bg-red-100 font-bold rounded-lg text-xs transition-colors">
                                            <?php echo __('admin_btn_delete'); ?>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </section>

        <!-- Tab 3: Product Safety Reports -->
        <section id="reports-panel" class="hidden bg-white p-6 rounded-3xl border border-gray-100 shadow-sm space-y-6">
            <h2 class="text-xl font-bold text-gray-900 pb-3 border-b border-gray-100"><?php echo __('admin_reports_title'); ?></h2>
            
            <?php if (empty($allReports)): ?>
                <p class="text-xs text-gray-400 text-center py-10"><?php echo __('admin_no_reports'); ?></p>
            <?php else: ?>
                <div class="overflow-x-auto">
                    <table class="w-full text-left text-sm text-gray-500 divide-y divide-gray-100">
                        <thead>
                            <tr class="text-xs text-gray-400 font-bold uppercase tracking-wider">
                                <th class="pb-3"><?php echo __('admin_th_rep_product'); ?></th>
                                <th class="pb-3"><?php echo __('admin_th_seller'); ?></th>
                                <th class="pb-3"><?php echo __('admin_th_rep_reason'); ?></th>
                                <th class="pb-3"><?php echo __('admin_th_rep_details'); ?></th>
                                <th class="pb-3"><?php echo __('admin_th_reporter'); ?></th>
                                <th class="pb-3 text-right"><?php echo __('admin_th_actions'); ?></th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 text-xs sm:text-sm">
                            <?php foreach ($allReports as $rep): ?>
                                <tr class="hover:bg-slate-50/50 <?php echo $rep['status'] === 'pending' ? 'bg-red-50/30' : ''; ?>">
                                    <td class="py-4 font-bold text-gray-900 max-w-xs truncate"><?php echo sanitize($rep['product_title']); ?></td>
                                    <td class="py-4 text-xs font-bold text-gray-700"><?php echo sanitize($rep['seller_name']); ?></td>
                                    <td class="py-4"><span class="px-2 py-0.5 bg-red-100 text-red-700 font-bold rounded text-[10px]"><?php echo sanitize($rep['reason']); ?></span></td>
                                    <td class="py-4 text-xs text-gray-500 max-w-xs truncate"><?php echo sanitize($rep['details'] ?: '-'); ?></td>
                                    <td class="py-4 text-xs text-gray-400"><?php echo sanitize($rep['reporter_name'] ?: 'Guest/Buyer'); ?></td>
                                    <td class="py-4 text-right space-x-2">
                                        <form action="dashboard_admin.php?action=delete_product" method="POST" class="inline" onsubmit="return confirm('Delete reported product listing from platform?')">
                                            <input type="hidden" name="product_id" value="<?php echo $rep['product_id']; ?>">
                                            <button type="submit" class="px-3 py-1 bg-red-600 hover:bg-red-700 text-white font-bold rounded-lg text-xs shadow-sm transition-colors">
                                                <?php echo __('admin_btn_delete_prod'); ?>
                                            </button>
                                        </form>

                                        <form action="dashboard_admin.php?action=dismiss_report" method="POST" class="inline">
                                            <input type="hidden" name="report_id" value="<?php echo $rep['id']; ?>">
                                            <button type="submit" class="px-3 py-1 bg-gray-100 hover:bg-gray-200 text-gray-600 font-bold rounded-lg text-xs transition-colors">
                                                <?php echo __('admin_btn_dismiss'); ?>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </section>

        <!-- Tab 4: Platform Orders -->
        <section id="orders-panel" class="hidden bg-white p-6 rounded-3xl border border-gray-100 shadow-sm space-y-6">
            <h2 class="text-xl font-bold text-gray-900 pb-3 border-b border-gray-100"><?php echo __('admin_orders_title'); ?></h2>
            <div class="overflow-x-auto">
                <table class="w-full text-left text-sm text-gray-500 divide-y divide-gray-100">
                    <thead>
                        <tr class="text-xs text-gray-400 font-bold uppercase tracking-wider">
                            <th class="pb-3"><?php echo __('admin_th_order_id'); ?></th>
                            <th class="pb-3"><?php echo __('admin_th_buyer'); ?></th>
                            <th class="pb-3"><?php echo __('admin_th_amount'); ?></th>
                            <th class="pb-3"><?php echo __('admin_th_payment'); ?></th>
                            <th class="pb-3"><?php echo __('admin_th_fulfillment'); ?></th>
                            <th class="pb-3 text-right"><?php echo __('admin_th_actions'); ?></th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100 text-xs sm:text-sm">
                        <?php foreach ($allOrders as $o): ?>
                            <tr class="hover:bg-slate-50/50">
                                <td class="py-4 font-bold text-gray-900">TV-<?php echo $o['id']; ?></td>
                                <td class="py-4"><?php echo sanitize($o['buyer_name']); ?></td>
                                <td class="py-4 font-bold text-rose-600">$<?php echo number_format($o['total_amount'], 2); ?></td>
                                <td class="py-4 text-xs font-semibold"><?php echo sanitize($o['payment_method']); ?></td>
                                <td class="py-4">
                                    <span class="px-2.5 py-1 rounded-full text-[10px] font-black uppercase tracking-wider bg-orange-50 text-orange-600 border border-orange-100">
                                        <?php echo sanitize($o['status']); ?>
                                    </span>
                                </td>
                                <td class="py-4 text-right">
                                    <form action="dashboard_admin.php?action=update_order" method="POST" class="inline-flex gap-2">
                                        <input type="hidden" name="order_id" value="<?php echo $o['id']; ?>">
                                        <select name="status" class="text-xs p-1 bg-gray-50 border border-gray-200 rounded-lg font-bold">
                                            <option value="Pending" <?php echo $o['status'] === 'Pending' ? 'selected' : ''; ?>>Pending</option>
                                            <option value="Shipped" <?php echo $o['status'] === 'Shipped' ? 'selected' : ''; ?>>Shipped</option>
                                            <option value="Delivered" <?php echo $o['status'] === 'Delivered' ? 'selected' : ''; ?>>Delivered</option>
                                            <option value="Cancelled" <?php echo $o['status'] === 'Cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                                        </select>
                                        <button type="submit" class="px-2.5 py-1 bg-gray-900 text-white font-bold rounded-lg text-xs hover:bg-gray-800 transition-colors"><?php echo __('admin_btn_save'); ?></button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </section>

    </div>

</div>

<script>
    function switchAdminTab(panelId) {
        const panels = ['users-panel', 'products-panel', 'reports-panel', 'orders-panel'];
        panels.forEach(p => {
            const el = document.getElementById(p);
            if (el) {
                if (p === panelId) el.classList.remove('hidden');
                else el.classList.add('hidden');
            }
        });

        const btnIds = {
            'users-panel': 'btn-users-panel',
            'products-panel': 'btn-products-panel',
            'reports-panel': 'btn-reports-panel',
            'orders-panel': 'btn-orders-panel'
        };

        Object.entries(btnIds).forEach(([pId, btnId]) => {
            const btn = document.getElementById(btnId);
            if (btn) {
                if (pId === panelId) {
                    btn.className = "w-full text-left px-4 py-2.5 rounded-xl font-bold text-sm text-orange-600 bg-orange-50 transition-all flex items-center justify-between";
                } else {
                    btn.className = "w-full text-left px-4 py-2.5 rounded-xl font-semibold text-sm text-gray-500 hover:text-gray-900 transition-all flex items-center justify-between";
                }
            }
        });
    }
</script>

<?php
renderFooter();
?>
