<?php
session_start();
include '../config.php';
include 'auth_check.php';

// Generate CSRF token if not exists
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];

// CSRF verification helper
function verify_csrf_token()
{
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        http_response_code(403);
        die('Invalid security token. Please refresh the page and try again.');
    }
}

// Handle Content Status Updates (Barriers/Thematic content)
if (isset($_POST['action']) && isset($_POST['id'])) {
    verify_csrf_token();
    $action = $_POST['action'];
    $id = intval($_POST['id']);
    $new_status = ($action === 'approve') ? 'approved' : 'rejected';

    $update = $conn->prepare("UPDATE content SET status = ? WHERE id = ?");
    $update->bind_param("si", $new_status, $id);
    $update->execute();
    header("Location: submissions.php?cat_type=challenges_sector");
    exit;
}

// Handle Submission Status Updates
if (isset($_POST['sub_action']) && isset($_POST['sub_id'])) {
    verify_csrf_token();
    $action = $_POST['sub_action'];
    $id = intval($_POST['sub_id']);
    $new_status = ($action === 'approve') ? 'approved' : 'rejected';
    $is_verified = ($new_status === 'approved') ? 1 : 0;

    $update = $conn->prepare("UPDATE submissions SET status = ?, is_verified = ? WHERE id = ?");
    $update->bind_param("sii", $new_status, $is_verified, $id);
    $update->execute();

    // --- Send email notification to the submission author ---
    $notify_stmt = $conn->prepare("SELECT s.title, s.user_id, u.email, u.organization_name FROM submissions s JOIN users u ON s.user_id = u.id WHERE s.id = ?");
    $notify_stmt->bind_param("i", $id);
    $notify_stmt->execute();
    $notify_data = $notify_stmt->get_result()->fetch_assoc();
    $notify_stmt->close();

    if ($notify_data && !empty($notify_data['email'])) {
        require_once __DIR__ . '/../smtp_mailer.php';

        $author_name = !empty($notify_data['organization_name']) ? htmlspecialchars($notify_data['organization_name']) : 'User';
        $sub_title   = htmlspecialchars(html_entity_decode($notify_data['title'], ENT_QUOTES | ENT_HTML5));
        $status_label = ($new_status === 'approved') ? '✅ Approved' : '⚠️ Needs Changes';
        $status_color = ($new_status === 'approved') ? '#16a34a' : '#dc2626';
        $site_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'sanibook.ke');

        $email_body = "
        <div style='font-family:Inter,sans-serif;max-width:600px;margin:auto;'>
            <div style='background:#0f172a;padding:24px 32px;border-radius:12px 12px 0 0;'>
                <h2 style='color:#fff;margin:0;'>SaniBook Submission Update</h2>
            </div>
            <div style='padding:24px 32px;border:1px solid #e2e8f0;border-top:none;border-radius:0 0 12px 12px;'>
                <p>Hello {$author_name},</p>
                <p>Your submission <strong>\"{$sub_title}\"</strong> has been reviewed and its status has been updated:</p>
                <div style='text-align:center;margin:20px 0;'>
                    <span style='display:inline-block;padding:10px 24px;border-radius:8px;font-weight:700;font-size:16px;color:#fff;background:{$status_color};'>
                        {$status_label}
                    </span>
                </div>
                " . ($new_status === 'rejected' ? "<p style='color:#64748b;'>If changes are needed, you can edit and resubmit your data from your dashboard.</p>" : "<p style='color:#64748b;'>Your data is now publicly visible on SaniBook.</p>") . "
                <p><a href='{$site_url}/view_submission.php?id={$id}' style='display:inline-block;padding:10px 20px;background:#2563eb;color:#fff;text-decoration:none;border-radius:8px;font-weight:600;'>View Submission</a></p>
                <p style='color:#94a3b8;font-size:12px;margin-top:24px;'>— The SaniBook Team</p>
            </div>
        </div>";

        $mailer = new SmtpMailer();
        $mailer->send($notify_data['email'], "SaniBook: Your Submission \"{$sub_title}\" - {$status_label}", $email_body);
    }

    header("Location: submissions.php");
    exit;
}

// Handle Delete with Refund
if (isset($_POST['delete_id'])) {
    verify_csrf_token();
    $delete_id = intval($_POST['delete_id']);

    $chk = $conn->prepare("SELECT tokens_locked, user_id FROM submissions WHERE id = ?");
    $chk->bind_param("i", $delete_id);
    $chk->execute();
    $sub_data = $chk->get_result()->fetch_assoc();
    $chk->close();

    if ($sub_data) {
        $locked = floatval($sub_data['tokens_locked'] ?? 0);
        $del_user_id = intval($sub_data['user_id'] ?? 0);

        if ($locked > 0 && $del_user_id > 0) {
            $sub_stmt = $conn->prepare("SELECT id, tokens_remaining FROM user_subscriptions WHERE user_id = ? AND status = 'active' LIMIT 1");
            $sub_stmt->bind_param("i", $del_user_id);
            $sub_stmt->execute();
            $sub_info = $sub_stmt->get_result()->fetch_assoc();
            $sub_stmt->close();

            if ($sub_info) {
                $new_bal = floatval($sub_info['tokens_remaining']) + $locked;
                $ref_upd = $conn->prepare("UPDATE user_subscriptions SET tokens_remaining = ? WHERE id = ?");
                $ref_upd->bind_param("di", $new_bal, $sub_info['id']);
                $ref_upd->execute();
                $ref_upd->close();

                $ref_desc = "Refund: Submission #$delete_id deleted";
                $ref_log = $conn->prepare("INSERT INTO token_transactions (user_id, subscription_id, amount, transaction_type, description) VALUES (?, ?, ?, 'refund', ?)");
                $ref_log->bind_param("iids", $del_user_id, $sub_info['id'], $locked, $ref_desc);
                $ref_log->execute();
                $ref_log->close();
            }
        }
    }

    // Delete associated media files
    $media_stmt = $conn->prepare("SELECT id, file_path FROM media_uploads WHERE submission_id = ?");
    $media_stmt->bind_param("i", $delete_id);
    $media_stmt->execute();
    $media_res = $media_stmt->get_result();
    while ($m = $media_res->fetch_assoc()) {
        $full_path = SECURE_UPLOAD_PATH . $m['file_path'];
        if (file_exists($full_path)) {
            unlink($full_path);
        }
    }
    $media_stmt->close();
    $conn->query("DELETE FROM media_uploads WHERE submission_id = $delete_id");

    $conn->query("DELETE FROM submissions WHERE id = $delete_id");
    header("Location: submissions.php?msg=deleted");
    exit;
}

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Submissions - SaniBook Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
</head>

<body class="bg-slate-100 font-sans text-slate-900">

    <?php include 'navbar.php'; ?>

    <div class="max-w-7xl mx-auto p-6">

        <?php
        // Determine active filters
        $filter = isset($_GET['filter']) ? $_GET['filter'] : 'pending';
        $cat_type = isset($_GET['cat_type']) ? $_GET['cat_type'] : '';
        $sub_cat = isset($_GET['sub_cat']) ? $_GET['sub_cat'] : '';

        // Build base URL helper
        function admin_url($extra = [])
        {
            global $filter, $cat_type, $sub_cat;
            $params = array_merge(['filter' => $filter], $extra);
            if (!isset($extra['cat_type']) && $cat_type)
                $params['cat_type'] = $cat_type;
            if (!isset($extra['sub_cat']) && $sub_cat)
                $params['sub_cat'] = $sub_cat;
            $params = array_filter($params, fn($v) => $v !== '');
            return 'submissions.php?' . http_build_query($params);
        }

        // Known sub-categories
        $pillar_subs = ['Financing', 'Governance', 'Research & Learning', 'Coordination and Collaboration', 'Menstrual Health Management', 'Capacity Building'];

        $chain_subs = [];
        $sc_result = $conn->query("SELECT DISTINCT service_chains FROM submissions WHERE service_chains IS NOT NULL AND service_chains != '' AND service_chains != '[]'");
        if ($sc_result) {
            while ($sc_row = $sc_result->fetch_assoc()) {
                $decoded = json_decode($sc_row['service_chains'], true);
                if (is_array($decoded)) {
                    foreach ($decoded as $v) {
                        $chain_subs[$v] = true;
                    }
                }
            }
        }
        $chain_subs = array_keys($chain_subs);
        sort($chain_subs);

        $cat_subs = [];
        $cat_result = $conn->query("SELECT id, title FROM categories ORDER BY title ASC");
        if ($cat_result) {
            while ($cat_row = $cat_result->fetch_assoc()) {
                $cat_subs[] = $cat_row;
            }
        }

        // Count helpers
        $status_clause = '';
        if ($filter === 'pending')
            $status_clause = "AND status = 'pending'";
        elseif ($filter === 'approved')
            $status_clause = "AND status = 'approved'";
        elseif ($filter === 'rejected')
            $status_clause = "AND status = 'rejected'";

        $count_chain = $conn->query("SELECT COUNT(*) as c FROM submissions WHERE service_chains IS NOT NULL AND service_chains != '' AND service_chains != '[]' $status_clause")->fetch_assoc()['c'] ?? 0;
        $count_pillar = $conn->query("SELECT COUNT(*) as c FROM submissions WHERE enabling_pillars IS NOT NULL AND enabling_pillars != '' AND enabling_pillars != '[]' $status_clause")->fetch_assoc()['c'] ?? 0;
        $count_sector = $conn->query("SELECT COUNT(*) as c FROM content WHERE 1=1 $status_clause")->fetch_assoc()['c'] ?? 0;
        ?>

        <?php if (isset($_GET['msg']) && $_GET['msg'] == 'deleted'): ?>
            <div class="bg-green-100 text-green-700 p-4 rounded-lg mb-6 border border-green-200">
                <i class="fa-solid fa-check mr-1"></i> Submission deleted successfully.
            </div>
        <?php endif; ?>

        <div class="flex justify-between items-center mb-6">
            <h2 class="text-2xl font-bold text-slate-800">Content Moderation</h2>
        </div>


        <!-- Status Filter Pills -->
        <div class="flex items-center gap-2 mb-4">
            <a href="<?php echo admin_url(['filter' => 'pending', 'cat_type' => $cat_type, 'sub_cat' => $sub_cat]); ?>"
                class="px-4 py-2 rounded-lg text-sm font-bold border transition-colors <?php echo $filter === 'pending' ? 'bg-orange-500 text-white border-orange-500' : 'bg-orange-50 text-orange-700 border-orange-200 hover:bg-orange-100'; ?>">
                Pending</a>
            <a href="<?php echo admin_url(['filter' => 'approved', 'cat_type' => $cat_type, 'sub_cat' => $sub_cat]); ?>"
                class="px-4 py-2 rounded-lg text-sm font-bold border transition-colors <?php echo $filter === 'approved' ? 'bg-green-500 text-white border-green-500' : 'bg-green-50 text-green-700 border-green-200 hover:bg-green-100'; ?>">
                Approved</a>
            <a href="<?php echo admin_url(['filter' => 'rejected', 'cat_type' => $cat_type, 'sub_cat' => $sub_cat]); ?>"
                class="px-4 py-2 rounded-lg text-sm font-bold border transition-colors <?php echo $filter === 'rejected' ? 'bg-red-500 text-white border-red-500' : 'bg-red-50 text-red-700 border-red-200 hover:bg-red-100'; ?>">
                Rejected</a>
            <a href="<?php echo admin_url(['filter' => 'all', 'cat_type' => $cat_type, 'sub_cat' => $sub_cat]); ?>"
                class="px-4 py-2 rounded-lg text-sm font-bold border transition-colors <?php echo $filter === 'all' ? 'bg-slate-700 text-white border-slate-700' : 'bg-slate-100 text-slate-600 border-slate-300 hover:bg-slate-200'; ?>">
                All</a>

            <?php if ($cat_type === 'challenges_sector'): ?>
                <a href="content-form.php"
                    class="ml-auto px-4 py-2 rounded-lg bg-blue-600 text-white font-bold hover:bg-blue-700 shadow-sm transition-colors text-sm flex items-center">
                    <i class="fa-solid fa-plus mr-2"></i> Add Content
                </a>
            <?php endif; ?>
        </div>


        <!-- Category Type Cards -->
        <div class="grid grid-cols-4 gap-3 mb-4">
            <a href="<?php echo admin_url(['cat_type' => '', 'sub_cat' => '']); ?>"
                class="rounded-xl border-2 p-4 text-center transition-all hover:shadow-md <?php echo !$cat_type ? 'border-slate-700 bg-slate-700 text-white shadow-md' : 'border-slate-200 bg-white text-slate-600 hover:border-slate-300'; ?>">
                <i class="fa-solid fa-layer-group text-lg mb-1"></i>
                <div class="text-sm font-bold">All Types</div>
            </a>
            <a href="<?php echo admin_url(['cat_type' => 'service_chain', 'sub_cat' => '']); ?>"
                class="rounded-xl border-2 p-4 text-center transition-all hover:shadow-md <?php echo $cat_type === 'service_chain' ? 'border-blue-500 bg-blue-500 text-white shadow-md' : 'border-blue-200 bg-blue-50 text-blue-700 hover:border-blue-300'; ?>">
                <i class="fa-solid fa-link text-lg mb-1"></i>
                <div class="text-sm font-bold">Service Chain</div>
                <div
                    class="text-xs font-semibold mt-0.5 <?php echo $cat_type === 'service_chain' ? 'text-blue-100' : 'text-blue-400'; ?>">
                    <?php echo $count_chain; ?>
                </div>
            </a>
            <a href="<?php echo admin_url(['cat_type' => 'enabling_pillar', 'sub_cat' => '']); ?>"
                class="rounded-xl border-2 p-4 text-center transition-all hover:shadow-md <?php echo $cat_type === 'enabling_pillar' ? 'border-orange-500 bg-orange-500 text-white shadow-md' : 'border-orange-200 bg-orange-50 text-orange-700 hover:border-orange-300'; ?>">
                <i class="fa-solid fa-cubes text-lg mb-1"></i>
                <div class="text-sm font-bold">Enabling Pillars</div>
                <div
                    class="text-xs font-semibold mt-0.5 <?php echo $cat_type === 'enabling_pillar' ? 'text-orange-100' : 'text-orange-400'; ?>">
                    <?php echo $count_pillar; ?>
                </div>
            </a>
            <a href="<?php echo admin_url(['cat_type' => 'challenges_sector', 'sub_cat' => '']); ?>"
                class="rounded-xl border-2 p-4 text-center transition-all hover:shadow-md <?php echo $cat_type === 'challenges_sector' ? 'border-purple-500 bg-purple-500 text-white shadow-md' : 'border-purple-200 bg-purple-50 text-purple-700 hover:border-purple-300'; ?>">
                <i class="fa-solid fa-tag text-lg mb-1"></i>
                <div class="text-sm font-bold">Barriers</div>
                <div
                    class="text-xs font-semibold mt-0.5 <?php echo $cat_type === 'challenges_sector' ? 'text-purple-100' : 'text-purple-400'; ?>">
                    <?php echo $count_sector; ?>
                </div>
            </a>
        </div>

        <!-- Sub-Category Strip -->
        <?php if ($cat_type === 'service_chain' && !empty($chain_subs)): ?>
            <div class="flex flex-wrap items-center gap-2 mb-5 p-3 bg-blue-50 rounded-lg border border-blue-100">
                <span class="text-xs font-bold text-blue-500 mr-1">Sub-category:</span>
                <a href="<?php echo admin_url(['cat_type' => 'service_chain', 'sub_cat' => '']); ?>"
                    class="px-3 py-1 rounded-full text-xs font-bold transition-all <?php echo !$sub_cat ? 'bg-blue-600 text-white' : 'bg-white text-blue-600 border border-blue-200 hover:bg-blue-100'; ?>">
                    All Chains</a>
                <?php foreach ($chain_subs as $cs): ?>
                    <a href="<?php echo admin_url(['cat_type' => 'service_chain', 'sub_cat' => $cs]); ?>"
                        class="px-3 py-1 rounded-full text-xs font-bold transition-all <?php echo $sub_cat === $cs ? 'bg-blue-600 text-white' : 'bg-white text-blue-600 border border-blue-200 hover:bg-blue-100'; ?>">
                        <?php echo htmlspecialchars($cs); ?></a>
                <?php endforeach; ?>
            </div>
        <?php elseif ($cat_type === 'enabling_pillar'): ?>
            <div class="flex flex-wrap items-center gap-2 mb-5 p-3 bg-orange-50 rounded-lg border border-orange-100">
                <span class="text-xs font-bold text-orange-500 mr-1">Sub-category:</span>
                <a href="<?php echo admin_url(['cat_type' => 'enabling_pillar', 'sub_cat' => '']); ?>"
                    class="px-3 py-1 rounded-full text-xs font-bold transition-all <?php echo !$sub_cat ? 'bg-orange-600 text-white' : 'bg-white text-orange-600 border border-orange-200 hover:bg-orange-100'; ?>">
                    All Pillars</a>
                <?php foreach ($pillar_subs as $ps): ?>
                    <a href="<?php echo admin_url(['cat_type' => 'enabling_pillar', 'sub_cat' => $ps]); ?>"
                        class="px-3 py-1 rounded-full text-xs font-bold transition-all <?php echo $sub_cat === $ps ? 'bg-orange-600 text-white' : 'bg-white text-orange-600 border border-orange-200 hover:bg-orange-100'; ?>">
                        <?php echo htmlspecialchars($ps); ?></a>
                <?php endforeach; ?>
            </div>
        <?php elseif ($cat_type === 'challenges_sector' && !empty($cat_subs)): ?>
            <div class="flex flex-wrap items-center gap-2 mb-5 p-3 bg-purple-50 rounded-lg border border-purple-100">
                <span class="text-xs font-bold text-purple-500 mr-1">Sub-category:</span>
                <a href="<?php echo admin_url(['cat_type' => 'challenges_sector', 'sub_cat' => '']); ?>"
                    class="px-3 py-1 rounded-full text-xs font-bold transition-all <?php echo !$sub_cat ? 'bg-purple-600 text-white' : 'bg-white text-purple-600 border border-purple-200 hover:bg-purple-100'; ?>">
                    All Sectors</a>
                <?php foreach ($cat_subs as $csub): ?>
                    <a href="<?php echo admin_url(['cat_type' => 'challenges_sector', 'sub_cat' => $csub['id']]); ?>"
                        class="px-3 py-1 rounded-full text-xs font-bold transition-all <?php echo $sub_cat == $csub['id'] ? 'bg-purple-600 text-white' : 'bg-white text-purple-600 border border-purple-200 hover:bg-purple-100'; ?>">
                        <?php echo htmlspecialchars($csub['title']); ?></a>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php if ($cat_type !== 'challenges_sector'): ?>
            <!-- ==================== DATA SUBMISSIONS TAB ==================== -->
            <div class="bg-white rounded-xl shadow-sm overflow-hidden border border-slate-200">
                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse">
                        <thead class="bg-slate-50 text-slate-500 uppercase text-xs font-bold tracking-wider">
                            <tr>
                                <th class="p-4 border-b">ID</th>
                                <th class="p-4 border-b">Organization</th>
                                <th class="p-4 border-b w-1/3">Title</th>
                                <th class="p-4 border-b">Status</th>
                                <th class="p-4 border-b">Sections</th>
                                <th class="p-4 border-b">Submitted</th>
                                <th class="p-4 border-b text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100">
                            <?php
                            $sql = "SELECT id, org_name, title, status, service_chains, enabling_pillars, thematic_categories, category_id, created_at FROM submissions WHERE 1=1 ";
                            if ($filter === 'pending')
                                $sql .= "AND status = 'pending' ";
                            elseif ($filter === 'approved')
                                $sql .= "AND status = 'approved' ";
                            elseif ($filter === 'rejected')
                                $sql .= "AND status = 'rejected' ";

                            if ($cat_type === 'service_chain') {
                                $sql .= "AND service_chains IS NOT NULL AND service_chains != '' AND service_chains != '[]' ";
                                if ($sub_cat) {
                                    $escaped_sub = $conn->real_escape_string($sub_cat);
                                    $sql .= "AND service_chains LIKE '%\"" . $escaped_sub . "\"%' ";
                                }
                            } elseif ($cat_type === 'enabling_pillar') {
                                $sql .= "AND enabling_pillars IS NOT NULL AND enabling_pillars != '' AND enabling_pillars != '[]' ";
                                if ($sub_cat) {
                                    $escaped_sub = $conn->real_escape_string($sub_cat);
                                    $sql .= "AND enabling_pillars LIKE '%\"" . $escaped_sub . "\"%' ";
                                }
                            } elseif ($cat_type === 'challenges_sector') {
                                $sql .= "AND category_id IS NOT NULL AND category_id > 0 ";
                                if ($sub_cat) {
                                    $escaped_sub = intval($sub_cat);
                                    $sql .= "AND category_id = $escaped_sub ";
                                }
                            }

                            $sql .= "ORDER BY created_at DESC";
                            $result = $conn->query($sql);

                            if ($result && $result->num_rows > 0):
                                while ($row = $result->fetch_assoc()):
                                    $status = $row['status'] ?? 'pending';
                                    $status_class = match ($status) {
                                        'approved' => 'bg-green-100 text-green-700 border-green-200',
                                        'rejected' => 'bg-red-100 text-red-700 border-red-200',
                                        default => 'bg-orange-100 text-orange-700 border-orange-200'
                                    };
                                    ?>
                                    <tr class="hover:bg-slate-50 transition-colors">
                                        <td class="p-4 text-sm text-slate-400">#<?php echo $row['id']; ?></td>
                                        <td class="p-4 font-semibold text-slate-800">
                                            <?php echo htmlspecialchars($row['org_name']); ?>
                                        </td>
                                        <td class="p-4 text-sm text-slate-600">
                                            <?php echo $row['title'] ? htmlspecialchars($row['title']) : '<span class="italic text-slate-400">No Title</span>'; ?>
                                        </td>
                                        <td class="p-4">
                                            <span
                                                class="px-2 py-1 rounded-full text-[10px] font-bold uppercase border <?php echo $status_class; ?>">
                                                <?php echo $status; ?>
                                            </span>
                                        </td>
                                        <td class="p-4">
                                            <?php
                                            $chains = json_decode($row['service_chains'] ?? '[]', true) ?: [];
                                            $pillars = json_decode($row['enabling_pillars'] ?? '[]', true) ?: [];
                                            $thematic = json_decode($row['thematic_categories'] ?? '[]', true) ?: [];
                                            ?>
                                            <div class="flex flex-wrap gap-1 max-w-xs">
                                                <?php foreach ($chains as $c): ?>
                                                    <span
                                                        class="px-1.5 py-0.5 bg-blue-50 text-blue-600 border border-blue-200 text-[10px] font-bold rounded-full whitespace-nowrap"><?php echo htmlspecialchars($c); ?></span>
                                                <?php endforeach; ?>
                                                <?php foreach ($pillars as $p): ?>
                                                    <span
                                                        class="px-1.5 py-0.5 bg-orange-50 text-orange-600 border border-orange-200 text-[10px] font-bold rounded-full whitespace-nowrap"><?php echo htmlspecialchars($p); ?></span>
                                                <?php endforeach; ?>
                                                <?php foreach ($thematic as $t): ?>
                                                    <span
                                                        class="px-1.5 py-0.5 bg-purple-50 text-purple-600 border border-purple-200 text-[10px] font-bold rounded-full whitespace-nowrap"><?php echo htmlspecialchars($t); ?></span>
                                                <?php endforeach; ?>
                                                <?php if (empty($chains) && empty($pillars) && empty($thematic)): ?>
                                                    <span class="text-[10px] text-slate-400 italic">None</span>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td class="p-4 text-sm text-slate-500">
                                            <?php echo date('M d, Y', strtotime($row['created_at'])); ?>
                                        </td>
                                        <td class="p-4 text-right">
                                            <div class="flex justify-end gap-2">
                                                <a href="submission-view.php?id=<?php echo $row['id']; ?>"
                                                    class="p-2 bg-slate-50 text-slate-600 rounded hover:bg-slate-100 border border-slate-200"
                                                    title="View">
                                                    <i class="fa-solid fa-eye"></i>
                                                </a>
                                                <a href="submission-form.php?id=<?php echo $row['id']; ?>"
                                                    class="p-2 bg-blue-50 text-blue-600 rounded hover:bg-blue-100 border border-blue-200"
                                                    title="Review & Edit">
                                                    <i class="fa-solid fa-pen"></i>
                                                </a>
                                                <?php if ($status !== 'approved'): ?>
                                                    <form method="POST" action="<?php echo admin_url(); ?>" class="inline">
                                                        <input type="hidden" name="csrf_token"
                                                            value="<?php echo htmlspecialchars($csrf_token); ?>">
                                                        <input type="hidden" name="sub_id" value="<?php echo $row['id']; ?>">
                                                        <button type="submit" name="sub_action" value="approve"
                                                            class="p-2 bg-green-50 text-green-600 rounded hover:bg-green-100 border border-green-200"
                                                            title="Approve">
                                                            <i class="fa-solid fa-check"></i>
                                                        </button>
                                                    </form>
                                                <?php endif; ?>
                                                <?php if ($status !== 'rejected'): ?>
                                                    <form method="POST" action="<?php echo admin_url(); ?>" class="inline">
                                                        <input type="hidden" name="csrf_token"
                                                            value="<?php echo htmlspecialchars($csrf_token); ?>">
                                                        <input type="hidden" name="sub_id" value="<?php echo $row['id']; ?>">
                                                        <button type="submit" name="sub_action" value="reject"
                                                            class="p-2 bg-red-50 text-red-600 rounded hover:bg-red-100 border border-red-200"
                                                            title="Reject">
                                                            <i class="fa-solid fa-xmark"></i>
                                                        </button>
                                                    </form>
                                                <?php endif; ?>
                                                <form method="POST"
                                                    onsubmit="return confirm('Are you sure you want to delete this submission?');"
                                                    class="inline">
                                                    <input type="hidden" name="csrf_token"
                                                        value="<?php echo htmlspecialchars($csrf_token); ?>">
                                                    <input type="hidden" name="delete_id" value="<?php echo $row['id']; ?>">
                                                    <button type="submit"
                                                        class="p-2 bg-red-50 text-red-600 rounded hover:bg-red-100 border border-red-200"
                                                        title="Delete">
                                                        <i class="fa-solid fa-trash"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endwhile; else: ?>
                                <tr>
                                    <td colspan="7" class="p-8 text-center text-slate-400 italic bg-slate-50">
                                        No submissions found in this filter.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        <?php else: ?>
            <!-- ==================== BARRIERS (THEMATIC CONTENT) TAB ==================== -->
            <div class="bg-white rounded-xl shadow-sm overflow-hidden border border-slate-200">
                <table class="w-full text-left border-collapse">
                    <thead class="bg-slate-50 text-slate-500 uppercase text-xs font-bold tracking-wider">
                        <tr>
                            <th class="p-4 border-b">ID</th>
                            <th class="p-4 border-b">Type</th>
                            <th class="p-4 border-b w-1/3">Title</th>
                            <th class="p-4 border-b">Category</th>
                            <th class="p-4 border-b">Date</th>
                            <th class="p-4 border-b">Status</th>
                            <th class="p-4 border-b text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100">
                        <?php
                        $sql = "SELECT c.id, c.title, c.type, c.created_at, c.status, cat.title as cat_title 
                        FROM content c 
                        JOIN categories cat ON c.category_id = cat.id ";
                        $where_clauses = [];
                        if ($filter === 'pending')
                            $where_clauses[] = "c.status = 'pending'";
                        elseif ($filter === 'approved')
                            $where_clauses[] = "c.status = 'approved'";
                        elseif ($filter === 'rejected')
                            $where_clauses[] = "c.status = 'rejected'";

                        if ($sub_cat) {
                            $where_clauses[] = "c.category_id = " . intval($sub_cat);
                        }

                        if (!empty($where_clauses)) {
                            $sql .= "WHERE " . implode(" AND ", $where_clauses) . " ";
                        }
                        $sql .= "ORDER BY c.created_at DESC";

                        $result = $conn->query($sql);

                        if ($result && $result->num_rows > 0):
                            while ($row = $result->fetch_assoc()):
                                $status_class = match ($row['status']) {
                                    'approved' => 'bg-green-100 text-green-700',
                                    'rejected' => 'bg-red-100 text-red-700',
                                    default => 'bg-orange-100 text-orange-700'
                                };
                                ?>
                                <tr class="hover:bg-slate-50 transition-colors">
                                    <td class="p-4 text-sm text-slate-400">#<?php echo $row['id']; ?></td>
                                    <td class="p-4">
                                        <span
                                            class="px-2 py-1 rounded text-xs font-bold uppercase tracking-wide bg-slate-100 text-slate-600">
                                            <?php echo $row['type']; ?>
                                        </span>
                                    </td>
                                    <td class="p-4 font-semibold text-slate-800">
                                        <a href="../view_content.php?id=<?php echo $row['id']; ?>" target="_blank"
                                            class="hover:text-blue-600 hover:underline">
                                            <?php echo htmlspecialchars($row['title']); ?>
                                        </a>
                                    </td>
                                    <td class="p-4 text-sm text-slate-600"><?php echo $row['cat_title']; ?></td>
                                    <td class="p-4 text-sm text-slate-500">
                                        <?php echo date('M d, Y', strtotime($row['created_at'])); ?>
                                    </td>
                                    <td class="p-4">
                                        <span
                                            class="px-2 py-1 rounded-full text-xs font-bold uppercase <?php echo $status_class; ?>">
                                            <?php echo $row['status']; ?>
                                        </span>
                                    </td>
                                    <td class="p-4 text-right">
                                        <form method="POST" class="inline-flex gap-2">
                                            <input type="hidden" name="csrf_token"
                                                value="<?php echo htmlspecialchars($csrf_token); ?>">
                                            <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                                            <?php if ($row['status'] !== 'approved'): ?>
                                                <button type="submit" name="action" value="approve"
                                                    class="p-2 bg-green-50 text-green-600 rounded hover:bg-green-100 border border-green-200"
                                                    title="Approve">
                                                    <i class="fa-solid fa-check"></i>
                                                </button>
                                            <?php endif; ?>
                                            <?php if ($row['status'] !== 'rejected'): ?>
                                                <button type="submit" name="action" value="reject"
                                                    class="p-2 bg-red-50 text-red-600 rounded hover:bg-red-100 border border-red-200"
                                                    title="Reject">
                                                    <i class="fa-solid fa-xmark"></i>
                                                </button>
                                            <?php endif; ?>
                                        </form>
                                        <div class="inline-flex gap-2 items-center">
                                            <a href="../view_content.php?id=<?php echo $row['id']; ?>"
                                                class="p-2 bg-slate-50 text-slate-600 rounded hover:bg-slate-100 border border-slate-200 inline-block"
                                                title="View">
                                                <i class="fa-solid fa-eye"></i>
                                            </a>
                                            <a href="content-form.php?id=<?php echo $row['id']; ?>"
                                                class="p-2 bg-blue-50 text-blue-600 rounded hover:bg-blue-100 border border-blue-200 inline-block"
                                                title="Edit">
                                                <i class="fa-solid fa-pen"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endwhile; else: ?>
                            <tr>
                                <td colspan="7" class="p-8 text-center text-slate-400 italic bg-slate-50">
                                    No content found in this filter.
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>

    </div>

</body>

</html>
