<?php
// category_dashboard.php
// Expected variables from parent: $conn, $where, $params, $types, $total_count, $active_label

// 1. Total Submissions: Use $total_count

// 2. Distinct Organizations
$org_sql = "SELECT COUNT(DISTINCT org_name) as org_count FROM submissions WHERE $where";
$stmt = $conn->prepare($org_sql);
if (!empty($types)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$dash_orgs = $stmt->get_result()->fetch_assoc()['org_count'];

// 3. Active Counties & map data
$county_sql = "SELECT county FROM submissions WHERE $where";
$stmt = $conn->prepare($county_sql);
if (!empty($types)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$county_res = $stmt->get_result();

$county_counts = [];
while ($row = $county_res->fetch_assoc()) {
    $c_str = $row['county'];
    if ($c_str && $c_str !== 'N/A') {
        $c_arr = explode(',', $c_str);
        foreach ($c_arr as $c) {
            $c = trim($c);
            if ($c && $c !== 'N/A') {
                $county_counts[$c] = ($county_counts[$c] ?? 0) + 1;
            }
        }
    }
}
$dash_counties_total = count($county_counts);

arsort($county_counts);
$top_counties = array_slice($county_counts, 0, 5, true);

// 4. Top Rated Submissions
$top_sql = "SELECT s.id, s.title, coalesce(r.avg_rating, 0) as rating 
            FROM submissions s 
            LEFT JOIN (SELECT item_id, AVG(rating) as avg_rating FROM ratings WHERE item_type='submission' GROUP BY item_id) r ON s.id = r.item_id
            WHERE $where
            ORDER BY rating DESC LIMIT 3";
$stmt = $conn->prepare($top_sql);
if (!empty($types)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$dash_top_rated = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// 5. Total Views
$view_sql = "SELECT SUM(IFNULL(view_count, 0)) as total_views FROM submissions WHERE $where";
$stmt = $conn->prepare($view_sql);
if (!empty($types)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$dash_total_views = $stmt->get_result()->fetch_assoc()['total_views'];

// 6. Top Viewed Submissions
$viewed_sql = "SELECT id, title, coalesce(view_count, 0) as views FROM submissions WHERE $where ORDER BY views DESC LIMIT 3";
$stmt = $conn->prepare($viewed_sql);
if (!empty($types)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$dash_top_viewed = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// 7. Recent Submissions 
$recent_sql = "SELECT s.id, s.title, s.org_name, s.created_at, coalesce(r.avg_rating, 0) as rating 
               FROM submissions s 
               LEFT JOIN (SELECT item_id, AVG(rating) as avg_rating FROM ratings WHERE item_type='submission' GROUP BY item_id) r ON s.id = r.item_id
               WHERE $where ORDER BY s.created_at DESC LIMIT 5";
$stmt = $conn->prepare($recent_sql);
if (!empty($types)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$dash_recent_subs = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// 8. Top Organizations
$org_agg_sql = "SELECT org_name, COUNT(*) as submission_count FROM submissions WHERE $where AND org_name IS NOT NULL AND org_name != '' GROUP BY org_name ORDER BY submission_count DESC LIMIT 10";
$stmt = $conn->prepare($org_agg_sql);
if (!empty($types)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$dash_top_orgs = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$dash_max_org_count = !empty($dash_top_orgs) ? (int) $dash_top_orgs[0]['submission_count'] : 1;

// 9. Monthly Submission Trend (last 12 months)
$trend_sql = "SELECT DATE_FORMAT(created_at, '%Y-%m') as m, COUNT(*) as c FROM submissions WHERE $where AND created_at >= DATE_SUB(NOW(), INTERVAL 12 MONTH) GROUP BY m ORDER BY m";
$stmt = $conn->prepare($trend_sql);
if (!empty($types)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$trend_res = $stmt->get_result();
$dash_trend_labels = [];
$dash_trend_values = [];
while ($trow = $trend_res->fetch_assoc()) {
    $dash_trend_labels[] = date("M 'y", strtotime($trow['m'] . '-01'));
    $dash_trend_values[] = (int) $trow['c'];
}

// 10. Sector Distribution
$sec_sql = "SELECT org_sector, role FROM submissions WHERE $where";
$stmt = $conn->prepare($sec_sql);
if (!empty($types)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$sec_res = $stmt->get_result();
$dash_sector_counts = [];
while ($srow = $sec_res->fetch_assoc()) {
    $sector = 'Other';
    if (!empty($srow['org_sector'])) {
        $sd = json_decode($srow['org_sector'], true);
        if (!empty($sd['sector'])) {
            $sector = $sd['sector'];
        }
    } elseif (!empty($srow['role'])) {
        $sector = $srow['role'];
    }
    $dash_sector_counts[$sector] = ($dash_sector_counts[$sector] ?? 0) + 1;
}
arsort($dash_sector_counts);

// Note: Top Rated is already fetched as $dash_top_rated, Most Viewed as $dash_top_viewed
?>

<style>
    .dash-glass {
        background: rgba(255, 255, 255, 0.07);
        backdrop-filter: blur(16px);
        -webkit-backdrop-filter: blur(16px);
        border: 1px solid rgba(255, 255, 255, 0.15);
    }

    .dash-glass-light {
        background: rgba(255, 255, 255, 0.12);
        backdrop-filter: blur(12px);
        -webkit-backdrop-filter: blur(12px);
        border: 1px solid rgba(255, 255, 255, 0.2);
    }

    .dash-glass-card {
        background: rgba(255, 255, 255, 0.09);
        backdrop-filter: blur(14px);
        -webkit-backdrop-filter: blur(14px);
        border: 1px solid rgba(255, 255, 255, 0.18);
        transition: all 0.25s ease;
    }

    .dash-glass-card:hover {
        background: rgba(255, 255, 255, 0.16);
        border-color: rgba(255, 255, 255, 0.35);
        transform: translateY(-2px);
        box-shadow: 0 12px 32px rgba(0, 0, 0, 0.25);
    }
</style>
<div class="relative w-full"
    style="background: linear-gradient(135deg, #012a4a 0%, #013a5e 40%, #01497c 70%, #023e6e 100%); padding: 2.5rem 0;">
    <!-- decorative blobs -->
    <div
        style="position:absolute;top:-60px;right:-60px;width:320px;height:320px;background:rgba(33,158,188,0.18);border-radius:50%;filter:blur(60px);pointer-events:none;">
    </div>
    <div
        style="position:absolute;bottom:-40px;left:-40px;width:240px;height:240px;background:rgba(212,175,55,0.12);border-radius:50%;filter:blur(50px);pointer-events:none;">
    </div>
    <div class="max-w-7xl mx-auto px-4">
        <div class="flex flex-col md:flex-row items-center justify-between mb-8">
            <div>
                <p class="text-[11px] font-bold uppercase tracking-widest text-blue-300 mb-1"><i
                        class="fa-solid fa-chart-pie mr-1"></i> Sub-Category Dashboard</p>
                <h3 class="font-display font-bold text-2xl text-white">
                    <?php echo $active_label ? htmlspecialchars($active_label) . ' Dashboard' : 'Category Overview'; ?>
                </h3>
                <p class="text-blue-200/70 text-sm mt-1">Key metrics and geographical reach for these submissions.</p>
            </div>
        </div>

        <!-- Top Row: Top KPIs -->
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
            <div class="dash-glass-card rounded-xl p-5 flex items-center justify-between">
                <div>
                    <p class="text-[11px] font-bold text-blue-200/70 uppercase tracking-widest mb-1">Total Submissions
                    </p>
                    <p class="text-3xl font-bold text-white"><?php echo number_format($total_count); ?></p>
                </div>
                <div class="w-12 h-12 rounded-full flex items-center justify-center text-xl shrink-0"
                    style="background:rgba(99,179,237,0.2);color:#63B3ED;">
                    <i class="fa-solid fa-file-lines"></i>
                </div>
            </div>

            <div class="dash-glass-card rounded-xl p-5 flex items-center justify-between">
                <div>
                    <p class="text-[11px] font-bold text-blue-200/70 uppercase tracking-widest mb-1">Organizations</p>
                    <p class="text-3xl font-bold text-white"><?php echo number_format($dash_orgs); ?></p>
                </div>
                <div class="w-12 h-12 rounded-full flex items-center justify-center text-xl shrink-0"
                    style="background:rgba(72,187,120,0.2);color:#68D391;">
                    <i class="fa-solid fa-building"></i>
                </div>
            </div>

            <div class="dash-glass-card rounded-xl p-5 flex items-center justify-between">
                <div>
                    <p class="text-[11px] font-bold text-blue-200/70 uppercase tracking-widest mb-1">Active Counties</p>
                    <p class="text-3xl font-bold text-white"><?php echo number_format($dash_counties_total); ?></p>
                </div>
                <div class="w-12 h-12 rounded-full flex items-center justify-center text-xl shrink-0"
                    style="background:rgba(246,173,85,0.2);color:#F6AD55;">
                    <i class="fa-solid fa-map-location-dot"></i>
                </div>
            </div>

            <div class="dash-glass-card rounded-xl p-5 flex items-center justify-between">
                <div>
                    <p class="text-[11px] font-bold text-blue-200/70 uppercase tracking-widest mb-1">Total Views</p>
                    <p class="text-3xl font-bold text-white"><?php echo number_format($dash_total_views); ?></p>
                </div>
                <div class="w-12 h-12 rounded-full flex items-center justify-center text-xl shrink-0"
                    style="background:rgba(183,148,246,0.2);color:#B794F4;">
                    <i class="fa-solid fa-eye"></i>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">

            <!-- Left Column: Top Viewed Submissions -->
            <div class="flex flex-col">
                <h4 class="text-[11px] font-bold text-blue-200/70 uppercase tracking-widest mb-3">Most Viewed</h4>
                <div class="dash-glass rounded-xl p-4 flex-1">
                    <?php if (empty($dash_top_viewed)): ?>
                        <div class="h-full flex items-center justify-center text-blue-200/50 text-sm p-8 text-center">
                            No submissions yet
                        </div>
                    <?php else: ?>
                        <div class="flex flex-col gap-3">
                            <?php foreach ($dash_top_viewed as $idx => $tv): ?>
                                <a href="view_submission.php?id=<?php echo $tv['id']; ?>"
                                    class="group block dash-glass-light rounded-lg p-3">
                                    <div class="flex items-start gap-3">
                                        <div class="w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm shrink-0"
                                            style="background:rgba(183,148,246,0.25);color:#B794F4;">
                                            #<?php echo $idx + 1; ?>
                                        </div>
                                        <div>
                                            <h5
                                                class="text-sm font-bold text-white group-hover:text-blue-300 transition-colors line-clamp-2 leading-tight">
                                                <?php echo htmlspecialchars($tv['title']); ?>
                                            </h5>
                                            <div class="flex items-center gap-1 mt-1 text-xs text-blue-200/60">
                                                <i class="fa-solid fa-eye"></i>
                                                <span class="font-bold"><?php echo number_format($tv['views']); ?></span>
                                            </div>
                                        </div>
                                    </div>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Middle Column: Monthly Trend (small) -->
            <div class="flex flex-col md:col-span-2">
                <h4 class="text-[11px] font-bold text-blue-200/70 uppercase tracking-widest mb-3"><i
                        class="fa-solid fa-chart-line mr-1"></i> Monthly Submission Trend</h4>
                <div class="dash-glass rounded-xl p-4 flex-1 relative" style="min-height:250px;max-height:300px;">
                    <canvas id="dashTrendChart" style="width:100%;height:100%;"></canvas>
                </div>
            </div>

            <!-- Right Column: Top Rated Submissions -->
            <div class="flex flex-col">
                <h4 class="text-[11px] font-bold text-blue-200/70 uppercase tracking-widest mb-3">Top Rated Submissions
                </h4>
                <div class="dash-glass rounded-xl p-4 flex-1">
                    <?php if (empty($dash_top_rated)): ?>
                        <div class="h-full flex items-center justify-center text-blue-200/50 text-sm p-8 text-center">
                            No rated submissions yet
                        </div>
                    <?php else: ?>
                        <div class="flex flex-col gap-3">
                            <?php foreach ($dash_top_rated as $idx => $tr): ?>
                                <a href="view_submission.php?id=<?php echo $tr['id']; ?>"
                                    class="group block dash-glass-light rounded-lg p-3">
                                    <div class="flex items-start gap-3">
                                        <div class="w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm shrink-0"
                                            style="background:rgba(246,173,85,0.2);color:#F6AD55;">
                                            #<?php echo $idx + 1; ?>
                                        </div>
                                        <div>
                                            <h5
                                                class="text-sm font-bold text-white group-hover:text-blue-300 transition-colors line-clamp-2 leading-tight">
                                                <?php echo htmlspecialchars($tr['title']); ?>
                                            </h5>
                                            <div class="flex items-center gap-1 mt-1 text-xs" style="color:#F6AD55;">
                                                <i class="fa-solid fa-star"></i>
                                                <span
                                                    class="font-bold text-white/70"><?php echo number_format($tr['rating'], 1); ?></span>
                                            </div>
                                        </div>
                                    </div>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

        </div>

        <!-- Row 2: Map + Top Orgs -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8 mt-8">
            <!-- Geographic Reach Map (prominent) -->
            <div class="lg:col-span-2 bg-white/10 backdrop-blur rounded-xl p-5 border border-white/10">
                <h3 class="text-white font-bold text-sm mb-4"><i
                        class="fa-solid fa-map-location-dot mr-2 text-[#D4AF37]"></i>Geographic Reach</h3>
                <div class="relative" style="min-height:300px;max-height:380px;">
                    <?php if (empty($top_counties)): ?>
                        <div class="absolute inset-0 flex items-center justify-center text-blue-200/50 text-sm">
                            No county data available
                        </div>
                    <?php else: ?>
                        <div id="categoryMapDiv" class="w-full" style="height:340px;"></div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Top 10 Organisations Leaderboard -->
            <div class="bg-white/10 backdrop-blur rounded-xl p-5 border border-white/10 flex flex-col">
                <h3 class="text-white font-bold text-sm mb-4"><i class="fa-solid fa-trophy mr-2 text-[#D4AF37]"></i>Top
                    Organisations</h3>
                <div class="flex-1 overflow-y-auto pr-2 custom-scrollbar space-y-3">
                    <?php if (empty($dash_top_orgs)): ?>
                        <div class="text-blue-200/50 text-xs italic">No items found.</div>
                    <?php else: ?>
                        <?php foreach ($dash_top_orgs as $idx => $t_org):
                            $pct = ($t_org['submission_count'] / $dash_max_org_count) * 100;
                            ?>
                            <a href="?<?php echo !empty($_GET['sub']) ? 'sub=' . urlencode($_GET['sub']) . '&' : ''; ?>org=<?php echo urlencode($t_org['org_name']); ?>#submissions"
                                class="group relative block hover:no-underline">
                                <div class="flex justify-between text-xs mb-1">
                                    <span class="text-white font-bold truncate pr-3 group-hover:text-blue-300 transition-colors"
                                        title="<?php echo htmlspecialchars($t_org['org_name']); ?>">
                                        <?php echo ($idx + 1) . '. ' . htmlspecialchars($t_org['org_name']); ?>
                                    </span>
                                    <span
                                        class="text-blue-300 font-bold"><?php echo number_format($t_org['submission_count']); ?></span>
                                </div>
                                <div class="w-full bg-white/5 rounded-full h-1.5 overflow-hidden">
                                    <div class="bg-gradient-to-r from-blue-400 to-teal-400 h-1.5 rounded-full transition-all group-hover:from-blue-300 group-hover:to-teal-300"
                                        style="width: <?php echo $pct; ?>%"></div>
                                </div>
                            </a>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Row 3: Sector Distribution + Recent -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
            <div class="lg:col-span-1 bg-white/10 backdrop-blur rounded-xl p-5 border border-white/10">
                <h3 class="text-white font-bold text-sm mb-4"><i
                        class="fa-solid fa-building mr-2 text-[#D4AF37]"></i>Sector Distribution</h3>
                <div class="relative" style="height:220px;">
                    <canvas id="dashSectorChart"></canvas>
                </div>
            </div>

            <!-- Latest Uploads -->
            <div class="lg:col-span-2 bg-white/10 backdrop-blur rounded-xl p-5 border border-white/10 flex flex-col">
                <h3 class="text-white font-bold text-sm mb-4"><i
                        class="fa-solid fa-clock mr-2 text-[#D4AF37]"></i>Latest Uploads</h3>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <?php if (empty($dash_recent_subs)): ?>
                        <div class="col-span-1 sm:col-span-2 text-blue-200/50 text-xs italic">No recent submissions found.
                        </div>
                    <?php else: ?>
                        <?php foreach (array_slice($dash_recent_subs, 0, 4) as $rec_sub): ?>
                            <a href="view_submission.php?id=<?php echo $rec_sub['id']; ?>"
                                class="group bg-white/5 rounded-lg p-3 hover:bg-white/10 transition-colors border border-white/5 flex gap-3">
                                <div
                                    class="w-10 h-10 rounded bg-blue-500/20 text-blue-300 flex items-center justify-center shrink-0">
                                    <i class="fa-solid fa-file-lines"></i>
                                </div>
                                <div class="min-w-0 flex-1">
                                    <h4
                                        class="text-white font-bold text-xs truncate group-hover:text-blue-300 transition-colors">
                                        <?php echo htmlspecialchars($rec_sub['title']); ?>
                                    </h4>
                                    <p class="text-[10px] text-blue-200/60 truncate mt-1"><i
                                            class="fa-regular fa-building mr-1"></i><?php echo htmlspecialchars($rec_sub['org_name']); ?>
                                    </p>
                                    <p class="text-[9px] text-white/40 mt-1">
                                        <?php echo date('d M Y', strtotime($rec_sub['created_at'])); ?>
                                    </p>
                                </div>
                            </a>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Smart Filters Panel -->
        <div class="bg-white/10 backdrop-blur border border-white/20 rounded-2xl overflow-hidden mt-8">
            <div class="p-4 px-6 flex items-center justify-between cursor-pointer hover:bg-white/5 transition-colors"
                onclick="document.getElementById('dash-filters-content').classList.toggle('hidden'); document.getElementById('dash-filters-icon').classList.toggle('rotate-180');">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-full bg-blue-500/20 text-blue-300 flex items-center justify-center">
                        <i class="fa-solid fa-filter"></i>
                    </div>
                    <div>
                        <h3 class="text-white font-bold text-lg">Smart Filters</h3>
                        <p class="text-blue-200 text-xs">Refine the dashboard data to your specific needs</p>
                    </div>
                </div>
                <div>
                    <i id="dash-filters-icon"
                        class="fa-solid fa-chevron-down text-white/50 transition-transform duration-300 <?php echo (!empty($_GET['q']) || !empty($_GET['county']) || !empty($_GET['sector'])) ? 'rotate-180' : ''; ?>"></i>
                </div>
            </div>

            <div id="dash-filters-content"
                class="<?php echo (!empty($_GET['q']) || !empty($_GET['county']) || !empty($_GET['sector'])) ? '' : 'hidden'; ?>">
                <div class="p-6 pt-0 border-t border-white/10 mt-2">
                    <form method="GET" action="" class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
                        <!-- preserve needed parameters -->
                        <?php if (!empty($_GET['sub'])): ?>
                            <input type="hidden" name="sub" value="<?php echo htmlspecialchars($_GET['sub']); ?>">
                        <?php endif; ?>

                        <div>
                            <label class="block text-blue-200 text-xs font-bold mb-2 tracking-wide uppercase">Search
                                Keyword</label>
                            <div class="relative">
                                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <i class="fa-solid fa-search text-white/40"></i>
                                </div>
                                <input type="text" name="q" value="<?php echo htmlspecialchars($_GET['q'] ?? ''); ?>"
                                    placeholder="Search submissions..."
                                    class="w-full bg-white/5 border border-white/20 rounded-lg py-2.5 pl-10 pr-4 text-white placeholder-white/40 focus:outline-none focus:border-blue-400 focus:ring-1 focus:ring-blue-400 transition-colors">
                            </div>
                        </div>

                        <div>
                            <label
                                class="block text-blue-200 text-xs font-bold mb-2 tracking-wide uppercase">County</label>
                            <select name="county"
                                class="w-full bg-[#1a2b4c] border border-white/20 rounded-lg py-2.5 px-4 text-white focus:outline-none focus:border-blue-400 focus:ring-1 focus:ring-blue-400 transition-colors appearance-none"
                                style="color-scheme: dark;">
                                <option value="">All Counties</option>
                                <?php
                                $all_counties = ["National", "Baringo", "Bomet", "Bungoma", "Busia", "Elgeyo-Marakwet", "Embu", "Garissa", "Homa Bay", "Isiolo", "Kajiado", "Kakamega", "Kericho", "Kiambu", "Kilifi", "Kirinyaga", "Kisii", "Kisumu", "Kitui", "Kwale", "Laikipia", "Lamu", "Machakos", "Makueni", "Mandera", "Marsabit", "Meru", "Migori", "Mombasa", "Murang'a", "Nairobi", "Nakuru", "Nandi", "Narok", "Nyamira", "Nyandarua", "Nyeri", "Samburu", "Siaya", "Taita-Taveta", "Tana River", "Tharaka-Nithi", "Trans Nzoia", "Turkana", "Uasin Gishu", "Vihiga", "Wajir", "West Pokot"];
                                foreach ($all_counties as $c) {
                                    $selected = (strcasecmp($_GET['county'] ?? '', $c) === 0) ? 'selected' : '';
                                    echo "<option value=\"$c\" $selected>$c</option>";
                                }
                                ?>
                            </select>
                        </div>

                        <div>
                            <label class="block text-blue-200 text-xs font-bold mb-2 tracking-wide uppercase">Sector /
                                Role</label>
                            <select name="sector"
                                class="w-full bg-[#1a2b4c] border border-white/20 rounded-lg py-2.5 px-4 text-white focus:outline-none focus:border-blue-400 focus:ring-1 focus:ring-blue-400 transition-colors appearance-none"
                                style="color-scheme: dark;">
                                <option value="">All Sectors</option>
                                <?php $gsec = $_GET['sector'] ?? ''; ?>
                                <option value="State Actor" <?php echo ($gsec == 'State Actor') ? 'selected' : ''; ?>>
                                    State Actor</option>
                                <option value="Non-State Actor" <?php echo ($gsec == 'Non-State Actor') ? 'selected' : ''; ?>>Non-State Actor</option>
                                <option value="Private Sector" <?php echo ($gsec == 'Private Sector') ? 'selected' : ''; ?>>Private Sector</option>
                                <option value="Academia" <?php echo ($gsec == 'Academia') ? 'selected' : ''; ?>>Academia
                                </option>
                                <option value="Media" <?php echo ($gsec == 'Media') ? 'selected' : ''; ?>>Media</option>
                                <option value="Citizen" <?php echo ($gsec == 'Citizen') ? 'selected' : ''; ?>>Citizen
                                </option>
                            </select>
                        </div>

                        <div class="flex gap-2">
                            <button type="submit"
                                class="flex-1 bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white font-bold py-2.5 px-4 rounded-lg shadow-lg hover:shadow-xl transition-all flex justify-center items-center gap-2">
                                <i class="fa-solid fa-check"></i> Apply
                            </button>
                            <?php if (!empty($_GET['q']) || !empty($_GET['county']) || !empty($_GET['sector'])): ?>
                                <a href="?<?php echo !empty($_GET['sub']) ? 'sub=' . htmlspecialchars($_GET['sub']) : ''; ?>"
                                    class="bg-white/10 hover:bg-white/20 text-white py-2.5 px-4 rounded-lg transition-colors flex justify-center items-center"
                                    title="Clear Filters">
                                    <i class="fa-solid fa-xmark"></i>
                                </a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </div>
        </div>

    </div>
</div>

<?php
// Active filter pill banner – shown at bottom of dashboard, above submissions grid
$dash_active_filters = [];
if (!empty($_GET['org']))
    $dash_active_filters[] = ['label' => 'Organisation: ' . htmlspecialchars($_GET['org']), 'param' => 'org'];
if (!empty($_GET['county']))
    $dash_active_filters[] = ['label' => 'County: ' . htmlspecialchars($_GET['county']), 'param' => 'county'];
if (!empty($_GET['sector']))
    $dash_active_filters[] = ['label' => 'Sector: ' . htmlspecialchars($_GET['sector']), 'param' => 'sector'];
if (!empty($_GET['q']))
    $dash_active_filters[] = ['label' => 'Search: "' . htmlspecialchars($_GET['q']) . '"', 'param' => 'q'];
$_dash_base_url = '?' . (!empty($_GET['sub']) ? 'sub=' . urlencode($_GET['sub']) : '');
?>
<div id="submissions"
    style="background:linear-gradient(135deg,#012a4a 0%,#013a5e 40%,#01497c 70%,#023e6e 100%); padding: 1.5rem 0 0 0;">
    <div class="max-w-7xl mx-auto px-4 pb-4">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
            <div>
                <p class="text-[10px] font-bold uppercase tracking-widest text-blue-300 mb-0.5">
                    <i class="fa-solid fa-list mr-1"></i> Results
                </p>
                <h3 class="font-display font-bold text-lg text-white">
                    <?php if (!empty($dash_active_filters)): ?>
                        Filtered Submissions
                    <?php else: ?>
                        <?php echo $active_label ? htmlspecialchars($active_label) . ' Submissions' : 'All Submissions'; ?>
                    <?php endif; ?>
                    <span class="ml-2 text-sm font-normal text-blue-200/60"><?php echo number_format($total_count); ?>
                        found</span>
                </h3>
            </div>
            <?php if (!empty($dash_active_filters)): ?>
                <a href="<?php echo htmlspecialchars($_dash_base_url); ?>#top"
                    class="inline-flex items-center gap-1.5 px-4 py-2 bg-white/10 hover:bg-white/20 text-white text-xs font-bold rounded-full border border-white/20 transition-colors shrink-0">
                    <i class="fa-solid fa-rotate-left"></i> Clear All &amp; Back to Top
                </a>
            <?php endif; ?>
        </div>

        <?php if (!empty($dash_active_filters)): ?>
            <div class="flex flex-wrap items-center gap-2 mt-3">
                <?php foreach ($dash_active_filters as $af): ?>
                    <?php
                    $clear_p = $_GET;
                    unset($clear_p[$af['param']]);
                    $clear_u = '?' . http_build_query($clear_p) . '#submissions';
                    ?>
                    <span
                        class="inline-flex items-center gap-1.5 px-3 py-1 bg-blue-600/80 text-white text-xs font-bold rounded-full border border-blue-400/30">
                        <?php echo $af['label']; ?>
                        <a href="<?php echo htmlspecialchars($clear_u); ?>" class="hover:text-blue-200 transition-colors"
                            title="Remove filter">
                            <i class="fa-solid fa-xmark"></i>
                        </a>
                    </span>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>



<?php if (!empty($top_counties)): ?>
    <!-- Scripts for AmCharts -->
    <script src="https://cdn.amcharts.com/lib/4/core.js"></script>
    <script src="https://cdn.amcharts.com/lib/4/maps.js"></script>
    <script src="https://cdn.amcharts.com/lib/4/geodata/kenyaLow.js"></script>
    <script src="https://cdn.amcharts.com/lib/4/themes/animated.js"></script>

    <script>
        window.SaniMapConfig = {
            containerId: "categoryMapDiv",
            countyData: <?php echo json_encode($top_counties); ?>,
            hash: "submissions"
        };
    </script>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    window.SaniChartConfig = {
        hash: "submissions",
        maintainAspectRatio: false,
        trend: {
            id: 'dashTrendChart',
            labels: <?php echo json_encode($dash_trend_labels); ?>,
            values: <?php echo json_encode($dash_trend_values); ?>
        },
        sector: {
            id: 'dashSectorChart',
            labels: <?php echo json_encode(array_keys($dash_sector_counts)); ?>,
            values: <?php echo json_encode(array_values($dash_sector_counts)); ?>
        }
    };
</script>
<script src="assets/js/dashboard-charts.js"></script>
<script src="assets/js/filter-scroll.js"></script>