<?php
require_once '../config/db.php';
require_once '../config/auth.php';
require_once '../config/functions.php';
requireAdmin();

$page_title = 'Analytics Dashboard';

// Summary stats
$total_lost     = $conn->query("SELECT COUNT(*) c FROM lost_items")->fetch_assoc()['c'];
$total_found    = $conn->query("SELECT COUNT(*) c FROM found_items")->fetch_assoc()['c'];
$total_returned = $conn->query("SELECT COUNT(*) c FROM lost_items WHERE status='returned'")->fetch_assoc()['c'];
$total_matches  = $conn->query("SELECT COUNT(*) c FROM matches WHERE match_status='approved'")->fetch_assoc()['c'];
$total_users    = $conn->query("SELECT COUNT(*) c FROM users WHERE role='user'")->fetch_assoc()['c'];
$return_rate    = $total_lost > 0 ? round(($total_returned / $total_lost) * 100, 1) : 0;

// Monthly trends (current year)
$months_label = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
$ml = array_fill(1,12,0);
$mf = array_fill(1,12,0);
$r = $conn->query("SELECT MONTH(created_at) m, COUNT(*) c FROM lost_items WHERE YEAR(created_at)=YEAR(NOW()) GROUP BY m");
while($row=$r->fetch_assoc()) $ml[$row['m']] = (int)$row['c'];
$r = $conn->query("SELECT MONTH(created_at) m, COUNT(*) c FROM found_items WHERE YEAR(created_at)=YEAR(NOW()) GROUP BY m");
while($row=$r->fetch_assoc()) $mf[$row['m']] = (int)$row['c'];

// Trends comparison (this month vs last month)
$current_month = date('m');
$last_month = date('m', strtotime('-1 month'));
$current_year = date('Y');
$lost_this_month = $conn->query("SELECT COUNT(*) c FROM lost_items WHERE MONTH(created_at)='$current_month' AND YEAR(created_at)='$current_year'")->fetch_assoc()['c'];
$lost_last_month = $conn->query("SELECT COUNT(*) c FROM lost_items WHERE MONTH(created_at)='$last_month' AND YEAR(created_at)='$current_year'")->fetch_assoc()['c'];
$lost_trend = $lost_last_month > 0 ? round((($lost_this_month - $lost_last_month) / $lost_last_month) * 100, 1) : 0;
$found_this_month = $conn->query("SELECT COUNT(*) c FROM found_items WHERE MONTH(created_at)='$current_month' AND YEAR(created_at)='$current_year'")->fetch_assoc()['c'];
$found_last_month = $conn->query("SELECT COUNT(*) c FROM found_items WHERE MONTH(created_at)='$last_month' AND YEAR(created_at)='$current_year'")->fetch_assoc()['c'];
$found_trend = $found_last_month > 0 ? round((($found_this_month - $found_last_month) / $found_last_month) * 100, 1) : 0;
$matched_this_month = $conn->query("SELECT COUNT(*) c FROM matches WHERE MONTH(created_at)='$current_month' AND YEAR(created_at)='$current_year' AND match_status='approved'")->fetch_assoc()['c'];
$matched_last_month = $conn->query("SELECT COUNT(*) c FROM matches WHERE MONTH(created_at)='$last_month' AND YEAR(created_at)='$current_year' AND match_status='approved'")->fetch_assoc()['c'];
$matched_trend = $matched_last_month > 0 ? round((($matched_this_month - $matched_last_month) / $matched_last_month) * 100, 1) : 0;

// Category stats
$cat_lost_res  = $conn->query("SELECT category, COUNT(*) c FROM lost_items  WHERE category!='' GROUP BY category ORDER BY c DESC LIMIT 7");
$cat_found_res = $conn->query("SELECT category, COUNT(*) c FROM found_items WHERE category!='' GROUP BY category ORDER BY c DESC LIMIT 7");
$cat_lost_labels=[]; $cat_lost_data=[];
while($r=$cat_lost_res->fetch_assoc())  { $cat_lost_labels[]=$r['category']; $cat_lost_data[]=$r['c']; }
$cat_found_labels=[]; $cat_found_data=[];
while($r=$cat_found_res->fetch_assoc()) { $cat_found_labels[]=$r['category']; $cat_found_data[]=$r['c']; }

// Status breakdown
$s_pending  = $conn->query("SELECT COUNT(*) c FROM lost_items WHERE status='pending'")->fetch_assoc()['c'];
$s_matched  = $conn->query("SELECT COUNT(*) c FROM lost_items WHERE status='matched'")->fetch_assoc()['c'];
$s_returned = $conn->query("SELECT COUNT(*) c FROM lost_items WHERE status='returned'")->fetch_assoc()['c'];
$s_closed   = $conn->query("SELECT COUNT(*) c FROM lost_items WHERE status='closed'")->fetch_assoc()['c'];

// Gender stats - admin-entered gender for walk-ins, auto-detected for user posts
$g_year  = isset($_GET['g_year'])  ? (int)$_GET['g_year']  : (int)date('Y');
$g_month = isset($_GET['g_month']) ? (int)$_GET['g_month'] : 0;
$g_where = "WHERE f.surrenderer_gender IS NOT NULL AND YEAR(f.created_at)=$g_year";
if ($g_month > 0) $g_where .= " AND MONTH(f.created_at)=$g_month";
$gender_stats = $conn->query("SELECT f.surrenderer_gender as gender, COUNT(f.id) as returned_count FROM found_items f $g_where GROUP BY f.surrenderer_gender ORDER BY f.surrenderer_gender");
$gender_rows=[]; while($g=$gender_stats->fetch_assoc()) $gender_rows[]=$g;
$g_labels=[]; $g_returned=[];
foreach($gender_rows as $g){ $g_labels[]=ucfirst($g['gender']); $g_returned[]=(int)$g['returned_count']; }

// Top locations
$top_lost_loc  = $conn->query("SELECT location, COUNT(*) c FROM lost_items  WHERE location!='' GROUP BY location ORDER BY c DESC LIMIT 6");
$top_found_loc = $conn->query("SELECT location, COUNT(*) c FROM found_items WHERE location!='' GROUP BY location ORDER BY c DESC LIMIT 6");
$ll=[]; $ld=[]; while($r=$top_lost_loc->fetch_assoc())  { $ll[]=$r['location']; $ld[]=$r['c']; }
$fl=[]; $fd=[]; while($r=$top_found_loc->fetch_assoc()) { $fl[]=$r['location']; $fd[]=$r['c']; }

// Weekly trend (last 7 days)
$weekly=[]; $weekly_labels=[];
for($i=6;$i>=0;$i--){
    $date = date('Y-m-d', strtotime("-$i days"));
    $weekly_labels[] = date('D', strtotime($date));
    $wl = $conn->query("SELECT COUNT(*) c FROM lost_items  WHERE DATE(created_at)='$date'")->fetch_assoc()['c'];
    $wf = $conn->query("SELECT COUNT(*) c FROM found_items WHERE DATE(created_at)='$date'")->fetch_assoc()['c'];
    $weekly[] = ['lost'=>(int)$wl,'found'=>(int)$wf];
}
$weekly_lost  = array_column($weekly,'lost');
$weekly_found = array_column($weekly,'found');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $page_title ?> - RELINK Admin</title>
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/style.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
/* ═════════════════════════════════════════════════════════ */
/* 🎨 ANALYTICS DASHBOARD - ENHANCED STYLES */
/* ═════════════════════════════════════════════════════════ */

/* Main layout improvements */
.page-content { padding: 24px 28px; background: var(--bg-primary); }

/* STAT CARDS - Enhanced */
.analytics-stat-row {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 18px;
    margin-bottom: 32px;
    animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}

.a-stat {
    background: var(--white);
    border-radius: 14px;
    padding: 24px 20px;
    border: 1px solid var(--border);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    display: flex;
    flex-direction: column;
    gap: 8px;
    position: relative;
    overflow: hidden;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    cursor: default;
}

.a-stat:hover {
    transform: translateY(-6px);
    box-shadow: 0 12px 24px rgba(0, 0, 0, 0.08);
    border-color: currentColor;
}

.a-stat::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 5px;
    border-radius: 14px 14px 0 0;
    animation: gradientShift 3s ease-in-out infinite;
}

.a-stat::after {
    content: '';
    position: absolute;
    bottom: -30px; right: -30px;
    width: 100px; height: 100px;
    border-radius: 50%;
    opacity: 0.04;
    transition: all 0.3s ease;
}

.a-stat:hover::after { bottom: -20px; right: -20px; opacity: 0.08; }

.a-stat.blue::before   { background: linear-gradient(90deg, #3b82f6, #0ea5e9); }
.a-stat.blue::after    { background: #3b82f6; }
.a-stat.green::before  { background: linear-gradient(90deg, #10b981, #14b8a6); }
.a-stat.green::after   { background: #10b981; }
.a-stat.yellow::before { background: linear-gradient(90deg, #f59e0b, #fbbf24); }
.a-stat.yellow::after  { background: #f59e0b; }
.a-stat.purple::before { background: linear-gradient(90deg, #8b5cf6, #a855f7); }
.a-stat.purple::after  { background: #8b5cf6; }
.a-stat.lime::before   { background: linear-gradient(90deg, #4f9d1c, #65a30d); }
.a-stat.lime::after    { background: #4f9d1c; }

.a-stat .a-icon {
    font-size: 28px;
    margin-bottom: 4px;
    display: block;
}

.a-stat .a-val {
    font-size: 36px;
    font-weight: 900;
    color: var(--text);
    line-height: 1;
    letter-spacing: -1px;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    font-variant-numeric: tabular-nums;
}

.a-stat .a-lbl {
    font-size: 12px;
    color: var(--text-muted);
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.8px;
}

.a-stat .a-sub {
    font-size: 11px;
    color: var(--text-muted);
    margin-top: 2px;
}

.a-stat .a-trend {
    font-size: 11px;
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 4px;
    margin-top: 4px;
    height: 18px;
}

.a-trend.up { color: #10b981; }
.a-trend.down { color: #ef4444; }
.a-trend.neutral { color: var(--text-muted); }

/* QUICK INSIGHTS SECTION */
.insights-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-bottom: 28px;
    animation: fadeInUp 0.7s ease-out 0.1s both;
}

.insight-card {
    background: linear-gradient(135deg, var(--white), var(--bg-secondary));
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 18px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
    transition: all 0.3s ease;
}

.insight-card:hover {
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.06);
    transform: translateY(-3px);
}

.insight-card .insight-badge {
    display: inline-block;
    background: var(--primary-light);
    color: var(--primary);
    font-size: 10px;
    font-weight: 800;
    padding: 4px 10px;
    border-radius: 20px;
    margin-bottom: 8px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.insight-card .insight-title {
    font-size: 12px;
    color: var(--text-muted);
    text-transform: uppercase;
    letter-spacing: 0.6px;
    font-weight: 700;
    margin-bottom: 6px;
}

.insight-card .insight-value {
    font-size: 20px;
    font-weight: 900;
    color: var(--text);
    margin-bottom: 4px;
}

.insight-card .insight-desc {
    font-size: 11px;
    color: var(--text-muted);
    line-height: 1.4;
}

/* Chart cards */
.chart-card {
    background: var(--white);
    border-radius: 14px;
    border: 1px solid var(--border);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    transition: all 0.3s ease;
    animation: fadeInUp 0.6s ease-out forwards;
}

@for $i from 1 to 6 {
    .chart-card:nth-child(#{$i}) {
        animation-delay: #{$i * 0.08}s;
    }
}

.chart-card:hover {
    box-shadow: 0 12px 24px rgba(0, 0, 0, 0.08);
    transform: translateY(-3px);
}

.chart-card-header {
    padding: 20px 24px 16px;
    border-bottom: 1px solid var(--border);
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: linear-gradient(135deg, var(--white) 0%, var(--bg-secondary) 100%);
}

.chart-card-header h3 {
    font-size: 14px;
    font-weight: 800;
    color: var(--text);
    margin: 0;
    display: flex;
    align-items: center;
    gap: 8px;
}

.chart-card-header .subtitle {
    font-size: 12px;
    color: var(--text-muted);
    margin-top: 4px;
}

.chart-card-body {
    padding: 24px;
}

.chart-h-lg { height: 340px; position: relative; }
.chart-h-md { height: 280px; position: relative; }
.chart-h-sm { height: 220px; position: relative; }

/* Layout rows with animations */
.row-full  {
    margin-bottom: 24px;
    animation: fadeInUp 0.6s ease-out 0.15s both;
}
.row-3col  {
    display: grid;
    grid-template-columns: 2fr 1.2fr 1fr;
    gap: 24px;
    margin-bottom: 24px;
    animation: fadeInUp 0.6s ease-out 0.2s both;
}
.row-2col  {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    margin-bottom: 24px;
    animation: fadeInUp 0.6s ease-out forwards;
}

.row-2col:nth-of-type(3) { animation-delay: 0.25s; }
.row-2col:nth-of-type(4) { animation-delay: 0.3s; }

/* Location bars with enhanced styling */
.loc-item {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 14px;
    transition: all 0.2s ease;
    padding: 4px;
    border-radius: 6px;
}

.loc-item:hover {
    background: var(--bg-secondary);
}

.loc-label {
    font-size: 12px;
    font-weight: 700;
    color: var(--text);
    min-width: 130px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.loc-bar-wrap {
    flex: 1;
    background: var(--bg-secondary);
    border-radius: 20px;
    height: 12px;
    overflow: hidden;
    position: relative;
}

.loc-bar {
    height: 12px;
    border-radius: 20px;
    transition: width 1s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
}

.loc-bar::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(90deg, rgba(255,255,255,0), rgba(255,255,255,0.4));
    border-radius: 20px;
}

.loc-count {
    font-size: 12px;
    font-weight: 900;
    color: var(--text-muted);
    min-width: 32px;
    text-align: right;
}

/* Gender table */
.gender-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 16px;
}

.gender-table th {
    font-size: 11px;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: var(--text-muted);
    padding: 10px 10px;
    border-bottom: 2px solid var(--border);
    text-align: left;
}

.gender-table td {
    font-size: 13px;
    padding: 12px 10px;
    border-bottom: 1px solid var(--border);
    color: var(--text);
}

.gender-table tr:last-child td {
    border-bottom: none;
}

.gender-table td strong {
    font-weight: 800;
}

/* Status legend */
.status-legend {
    display: flex;
    flex-direction: column;
    gap: 12px;
    margin-top: 18px;
}

.status-leg-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 13px;
    color: var(--text);
    padding: 8px 0;
    transition: all 0.2s ease;
}

.status-leg-item:hover {
    transform: translateX(4px);
}

.status-leg-dot {
    width: 12px;
    height: 12px;
    border-radius: 3px;
    flex-shrink: 0;
}

.status-leg-label {
    display: flex;
    align-items: center;
    gap: 8px;
}

/* Year/Period badge */
.year-badge {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    font-size: 11px;
    font-weight: 800;
    padding: 6px 14px;
    border-radius: 20px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

/* Empty state */
.empty-state {
    color: var(--text-muted);
    font-size: 13px;
    text-align: center;
    padding: 40px 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
}

.empty-state::before {
    content: '';
    font-size: 32px;
    margin-bottom: 8px;
}

/* Dark mode support */
body.dark-mode .chart-card-header {
    background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
}

body.dark-mode .insight-card {
    background: linear-gradient(135deg, #0f172a, #1e293b);
}

body.dark-mode .loc-item:hover {
    background: #1e293b;
}

/* Responsive Design */
@media(max-width: 1400px) {
    .analytics-stat-row { grid-template-columns: repeat(4, 1fr); }
    .insights-grid { grid-template-columns: repeat(2, 1fr); }
    .row-3col { grid-template-columns: 1.5fr 1fr; }
    .row-3col > *:last-child { grid-column: span 2; }
}

@media(max-width: 1100px) {
    .analytics-stat-row { grid-template-columns: repeat(3, 1fr); }
    .row-3col { grid-template-columns: 1fr; }
    .row-3col > *:last-child { grid-column: span 1; }
}

@media(max-width: 768px) {
    .analytics-stat-row { grid-template-columns: repeat(2, 1fr); gap: 12px; }
    .insights-grid { grid-template-columns: 1fr; }
    .row-3col, .row-2col { grid-template-columns: 1fr; gap: 16px; }
    .chart-h-lg { height: 280px; }
    .chart-h-md { height: 240px; }
    .chart-h-sm { height: 200px; }
    .chart-card-body { padding: 16px; }
    .page-content { padding: 16px; }
}

@media(max-width: 480px) {
    .analytics-stat-row { grid-template-columns: 1fr; }
    .loc-label { min-width: 100px; }
    .a-val { font-size: 28px; }
    .chart-h-lg { height: 240px; }
}
</style>
</head>
<body>
<div class="layout">
    <?php include '../includes/admin_sidebar.php'; ?>
    <div class="main-content">
        <?php include '../includes/topbar.php'; ?>
        <div class="page-content">

            <!-- ── STAT CARDS WITH TRENDS ── -->
            <div class="analytics-stat-row">
                <div class="a-stat blue">
                    <span class="a-icon">🔍</span>
                    <span class="a-val counter" data-target="<?= $total_lost ?>">0</span>
                    <span class="a-lbl">Total Lost</span>
                    <span class="a-sub">Reports on record</span>
                    <span class="a-trend <?= $lost_trend >= 0 ? 'up' : 'down' ?>">
                        <?= $lost_trend >= 0 ? '↑' : '↓' ?> <?= abs($lost_trend) ?>% this month
                    </span>
                </div>
                <div class="a-stat green">
                    <span class="a-icon">📦</span>
                    <span class="a-val counter" data-target="<?= $total_found ?>">0</span>
                    <span class="a-lbl">Total Found</span>
                    <span class="a-sub">Reports on record</span>
                    <span class="a-trend <?= $found_trend >= 0 ? 'up' : 'down' ?>">
                        <?= $found_trend >= 0 ? '↑' : '↓' ?> <?= abs($found_trend) ?>% this month
                    </span>
                </div>
                <div class="a-stat yellow">
                    <span class="a-icon">✅</span>
                    <span class="a-val counter" data-target="<?= $total_returned ?>">0</span>
                    <span class="a-lbl">Returned</span>
                    <span class="a-sub">Successfully claimed</span>
                    <span class="a-trend neutral">
                        <?= $total_returned > 0 ? round(($total_returned/$total_lost)*100, 1) : 0 ?>% recovery rate
                    </span>
                </div>
                <div class="a-stat purple">
                    <span class="a-icon">🤝</span>
                    <span class="a-val counter" data-target="<?= $total_matches ?>">0</span>
                    <span class="a-lbl">Matches</span>
                    <span class="a-sub">Approved matches</span>
                    <span class="a-trend <?= $matched_trend >= 0 ? 'up' : 'down' ?>">
                        <?= $matched_trend >= 0 ? '↑' : '↓' ?> <?= abs($matched_trend) ?>% this month
                    </span>
                </div>
                <div class="a-stat lime">
                    <span class="a-icon">👥</span>
                    <span class="a-val counter" data-target="<?= $total_users ?>">0</span>
                    <span class="a-lbl">Users</span>
                    <span class="a-sub">Active members</span>
                    <span class="a-trend neutral">
                        Helping the community
                    </span>
                </div>
            </div>

            <!-- ── QUICK INSIGHTS ── -->
            <div class="insights-grid">
                <div class="insight-card">
                    <span class="insight-badge" style="background: #10b98133; color: #10b981;">📊 Key Metric</span>
                    <div class="insight-title">Success Rate</div>
                    <div class="insight-value"><?= $return_rate ?>%</div>
                    <div class="insight-desc">Of lost items were successfully returned to their owners</div>
                </div>

                <div class="insight-card">
                    <span class="insight-badge" style="background: #3b82f633; color: #3b82f6;">📈 This Month</span>
                    <div class="insight-title">New Reports</div>
                    <div class="insight-value"><?= ($lost_this_month + $found_this_month) ?></div>
                    <div class="insight-desc"><?= $lost_this_month ?> lost, <?= $found_this_month ?> found items reported</div>
                </div>

                <div class="insight-card">
                    <span class="insight-badge" style="background: #f59e0b33; color: #f59e0b;">🎯 Efficiency</span>
                    <div class="insight-title">Avg. Match Time</div>
                    <div class="insight-value">Fast</div>
                    <div class="insight-desc"><?= $total_matches ?> successful matches made so far</div>
                </div>
            </div>

            <!-- ── ROW 1: Full-width Monthly Trend ── -->
            <div class="row-full">
                <div class="chart-card">
                    <div class="chart-card-header">
                        <div>
                            <h3>📈 Monthly Trends</h3>
                            <div class="subtitle">Lost vs Found items per month</div>
                        </div>
                        <span class="year-badge"><?= date('Y') ?></span>
                    </div>
                    <div class="chart-card-body">
                        <div class="chart-h-lg"><canvas id="trendChart"></canvas></div>
                    </div>
                </div>
            </div>

            <!-- ── ROW 2: Weekly + Status Doughnut + Gender Pie ── -->
            <div class="row-3col">
                <div class="chart-card">
                    <div class="chart-card-header">
                        <div>
                            <h3>📅 Last 7 Days Activity</h3>
                            <div class="subtitle">Daily lost & found reports this week</div>
                        </div>
                    </div>
                    <div class="chart-card-body">
                        <div class="chart-h-md"><canvas id="weeklyChart"></canvas></div>
                    </div>
                </div>

                <div class="chart-card">
                    <div class="chart-card-header">
                        <div>
                            <h3>🔄 Item Status</h3>
                            <div class="subtitle">Lost items breakdown</div>
                        </div>
                    </div>
                    <div class="chart-card-body">
                        <div class="chart-h-sm"><canvas id="statusChart"></canvas></div>
                        <div class="status-legend">
                            <div class="status-leg-item">
                                <div class="status-leg-label"><div class="status-leg-dot" style="background:#fcd34d"></div> Pending</div>
                                <strong><?= $s_pending ?></strong>
                            </div>
                            <div class="status-leg-item">
                                <div class="status-leg-label"><div class="status-leg-dot" style="background:#93c5fd"></div> Matched</div>
                                <strong><?= $s_matched ?></strong>
                            </div>
                            <div class="status-leg-item">
                                <div class="status-leg-label"><div class="status-leg-dot" style="background:#6ee7b7"></div> Returned</div>
                                <strong><?= $s_returned ?></strong>
                            </div>
                            <div class="status-leg-item">
                                <div class="status-leg-label"><div class="status-leg-dot" style="background:#d1d5db"></div> Closed</div>
                                <strong><?= $s_closed ?></strong>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="chart-card">
                    <div class="chart-card-header">
                        <div>
                            <h3>👥 Demographics</h3>
                            <div class="subtitle">Gender of walk-in surrenderers</div>
                        </div>
                    </div>
                    <div class="chart-card-body">
                        <form method="GET" style="display:flex;gap:6px;margin-bottom:12px;flex-wrap:wrap">
                            <select name="g_year" class="form-control" style="width:90px;font-size:12px;padding:4px 8px">
                                <?php for($y=date('Y');$y>=date('Y')-4;$y--): ?>
                                <option value="<?= $y ?>" <?= $g_year==$y?'selected':'' ?>><?= $y ?></option>
                                <?php endfor; ?>
                            </select>
                            <select name="g_month" class="form-control" style="width:110px;font-size:12px;padding:4px 8px">
                                <option value="0" <?= $g_month==0?'selected':'' ?>>All Months</option>
                                <?php foreach(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] as $mi=>$mn): ?>
                                <option value="<?= $mi+1 ?>" <?= $g_month==$mi+1?'selected':'' ?>><?= $mn ?></option>
                                <?php endforeach; ?>
                            </select>
                            <button type="submit" class="btn btn-sm btn-primary">Filter</button>
                        </form>
                        <div class="chart-h-sm"><canvas id="genderChart"></canvas></div>
                        <table class="gender-table">
                            <thead><tr><th>Gender</th><th>Surrendered Items</th></tr></thead>
                            <tbody>
                            <?php if(empty($gender_rows)): ?>
                            <tr><td colspan="2" style="text-align:center;color:var(--text-muted);padding:16px">No data for selected period.</td></tr>
                            <?php endif; ?>
                            <?php foreach($gender_rows as $g): ?>
                            <tr>
                                <td><?= ucfirst($g['gender']) ?></td>
                                <td><strong><?= $g['returned_count'] ?></strong></td>
                            </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- ── ROW 3: Category Charts ── -->
            <div class="row-2col">
                <div class="chart-card">
                    <div class="chart-card-header">
                        <div>
                            <h3>📂 Lost Items by Category</h3>
                            <div class="subtitle">Top categories reported as lost</div>
                        </div>
                    </div>
                    <div class="chart-card-body">
                        <div class="chart-h-md"><canvas id="catLostChart"></canvas></div>
                    </div>
                </div>
                <div class="chart-card">
                    <div class="chart-card-header">
                        <div>
                            <h3>📂 Found Items by Category</h3>
                            <div class="subtitle">Top categories reported as found</div>
                        </div>
                    </div>
                    <div class="chart-card-body">
                        <div class="chart-h-md"><canvas id="catFoundChart"></canvas></div>
                    </div>
                </div>
            </div>

            <!-- ── ROW 4: Location Hotspots ── -->
            <div class="row-2col">
                <div class="chart-card">
                    <div class="chart-card-header">
                        <div>
                            <h3>📍 Lost Item Hotspots</h3>
                            <div class="subtitle">Locations where items are most frequently lost</div>
                        </div>
                    </div>
                    <div class="chart-card-body">
                        <?php
                        $max_l = max(array_merge($ld, [1]));
                        foreach($ll as $i => $loc):
                            $cnt = $ld[$i];
                        ?>
                        <div class="loc-item">
                            <span class="loc-label" title="<?= htmlspecialchars($loc) ?>">📍 <?= htmlspecialchars($loc) ?></span>
                            <div class="loc-bar-wrap">
                                <div class="loc-bar" style="width:<?= round(($cnt/$max_l)*100) ?>%;background:linear-gradient(90deg,#ef4444,#f87171)"></div>
                            </div>
                            <span class="loc-count"><?= $cnt ?></span>
                        </div>
                        <?php endforeach; ?>
                        <?php if(empty($ll)): ?>
                        <p style="color:var(--text-muted);font-size:13px;text-align:center;padding:20px 0">No location data yet.</p>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="chart-card">
                    <div class="chart-card-header">
                        <div>
                            <h3>📍 Found Item Hotspots</h3>
                            <div class="subtitle">Locations where items are most frequently found</div>
                        </div>
                    </div>
                    <div class="chart-card-body">
                        <?php
                        $max_f = max(array_merge($fd, [1]));
                        foreach($fl as $i => $loc):
                            $cnt = $fd[$i];
                        ?>
                        <div class="loc-item">
                            <span class="loc-label" title="<?= htmlspecialchars($loc) ?>">📍 <?= htmlspecialchars($loc) ?></span>
                            <div class="loc-bar-wrap">
                                <div class="loc-bar" style="width:<?= round(($cnt/$max_f)*100) ?>%;background:linear-gradient(90deg,#10b981,#34d399)"></div>
                            </div>
                            <span class="loc-count"><?= $cnt ?></span>
                        </div>
                        <?php endforeach; ?>
                        <?php if(empty($fl)): ?>
                        <p style="color:var(--text-muted);font-size:13px;text-align:center;padding:20px 0">No location data yet.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>

<script src="<?= BASE_URL ?>/assets/js/main.js"></script>
<script>
// ═════════════════════════════════════════════════════════════════════
// 🎯 ANIMATED COUNTER - Numbers count up when page loads
// ═════════════════════════════════════════════════════════════════════
function animateCounters() {
    const counters = document.querySelectorAll('.counter');
    const isVisible = (el) => {
        const rect = el.getBoundingClientRect();
        return rect.top <= window.innerHeight && rect.bottom >= 0;
    };

    const animate = (counter) => {
        const target = parseInt(counter.getAttribute('data-target'));
        const increment = target / 40; // 40 frames of animation
        let current = 0;

        const timer = setInterval(() => {
            current += increment;
            if (current >= target) {
                counter.textContent = target.toLocaleString();
                clearInterval(timer);
            } else {
                counter.textContent = Math.floor(current).toLocaleString();
            }
        }, 15);
    };

    counters.forEach(counter => {
        if (isVisible(counter) && !counter.classList.contains('animated')) {
            counter.classList.add('animated');
            animate(counter);
        }
    });
}

// Start animation when page loads
document.addEventListener('DOMContentLoaded', () => {
    setTimeout(animateCounters, 300);
});

// ═════════════════════════════════════════════════════════════════════
// 📊 CHART CONFIGURATION
// ═════════════════════════════════════════════════════════════════════
const isDark    = () => document.body.classList.contains('dark-mode');
const tickColor = () => isDark() ? '#94a3b8' : '#64748b';
const gridColor = () => isDark() ? 'rgba(255,255,255,.08)' : 'rgba(0,0,0,.05)';
const borderClr = () => isDark() ? '#1e293b' : '#ffffff';

const tooltip = {
    backgroundColor: isDark() ? '#0f172a' : '#1e293b',
    titleColor: '#f1f5f9',
    bodyColor: '#cbd5e1',
    borderColor: 'rgba(255,255,255,.12)',
    borderWidth: 2,
    padding: 12,
    cornerRadius: 12,
    displayColors: true,
    boxPadding: 6,
    titleFont: { size: 12, weight: '600' },
    bodyFont: { size: 11 }
};

function baseScales() {
    return {
        x: {
            grid: { display: false },
            ticks: { color: tickColor(), font: { size: 11, weight: '500' } },
            border: { display: false }
        },
        y: {
            beginAtZero: true,
            grid: { color: gridColor(), drawBorder: false },
            ticks: { color: tickColor(), font: { size: 11, weight: '500' }, precision: 0 },
            border: { display: false }
        }
    };
}

function hBarScales() {
    return {
        x: {
            beginAtZero: true,
            grid: { color: gridColor() },
            ticks: { color: tickColor(), font: { size: 11, weight: '500' }, precision: 0 },
            border: { display: false }
        },
        y: {
            grid: { display: false },
            ticks: { color: tickColor(), font: { size: 11, weight: '500' } },
            border: { display: false }
        }
    };
}

// Gradient helper
function makeGradient(ctx, color1, color2) {
    const g = ctx.createLinearGradient(0, 0, 0, 340);
    g.addColorStop(0, color1);
    g.addColorStop(1, color2);
    return g;
}

// ── Monthly Trend ──
const trendCtx = document.getElementById('trendChart').getContext('2d');
const trendChart = new Chart(trendCtx, {
    type: 'line',
    data: {
        labels: <?= json_encode($months_label) ?>,
        datasets: [
            {
                label: 'Lost Items',
                data: <?= json_encode(array_values($ml)) ?>,
                borderColor: '#ef4444',
                backgroundColor: makeGradient(trendCtx, 'rgba(239,68,68,.25)', 'rgba(239,68,68,.01)'),
                borderWidth: 3,
                pointBackgroundColor: '#ef4444',
                pointBorderColor: '#fff',
                pointBorderWidth: 2,
                pointRadius: 6,
                pointHoverRadius: 8,
                tension: 0.4,
                fill: true,
                segment: {
                    borderDash: ctx => ctx.p0DataIndex === ctx.p1DataIndex - 1 && <?= json_encode(array_values($ml)) ?>[ctx.p1DataIndex] === 0 ? [5, 5] : undefined
                }
            },
            {
                label: 'Found Items',
                data: <?= json_encode(array_values($mf)) ?>,
                borderColor: '#10b981',
                backgroundColor: makeGradient(trendCtx, 'rgba(16,185,129,.25)', 'rgba(16,185,129,.01)'),
                borderWidth: 3,
                pointBackgroundColor: '#10b981',
                pointBorderColor: '#fff',
                pointBorderWidth: 2,
                pointRadius: 6,
                pointHoverRadius: 8,
                tension: 0.4,
                fill: true
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        interaction: { mode: 'index', intersect: false },
        plugins: {
            legend: {
                position: 'top',
                labels: {
                    font: { size: 12, weight: '600' },
                    boxWidth: 14,
                    padding: 16,
                    color: tickColor(),
                    usePointStyle: true,
                    pointStyle: 'circle'
                }
            },
            tooltip: { ...tooltip }
        },
        scales: baseScales()
    }
});

// ── Weekly Activity ──
const weeklyChart = new Chart(document.getElementById('weeklyChart'), {
    type: 'bar',
    data: {
        labels: <?= json_encode($weekly_labels) ?>,
        datasets: [
            {
                label: 'Lost',
                data: <?= json_encode($weekly_lost) ?>,
                backgroundColor: 'rgba(239,68,68,.85)',
                borderRadius: 8,
                borderSkipped: false,
                borderColor: 'rgba(239,68,68,1)',
                borderWidth: 0
            },
            {
                label: 'Found',
                data: <?= json_encode($weekly_found) ?>,
                backgroundColor: 'rgba(16,185,129,.85)',
                borderRadius: 8,
                borderSkipped: false,
                borderColor: 'rgba(16,185,129,1)',
                borderWidth: 0
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        interaction: { mode: 'index', intersect: false },
        plugins: {
            legend: {
                position: 'top',
                labels: {
                    font: { size: 11, weight: '600' },
                    boxWidth: 12,
                    padding: 12,
                    color: tickColor(),
                    usePointStyle: true,
                    pointStyle: 'rectRounded'
                }
            },
            tooltip: { ...tooltip }
        },
        scales: baseScales()
    }
});

// ── Status Doughnut ──
const statusChart = new Chart(document.getElementById('statusChart'), {
    type: 'doughnut',
    data: {
        labels: ['🟨 Pending','🔵 Matched','🟢 Returned','⚫ Closed'],
        datasets: [{
            data: [<?= "$s_pending,$s_matched,$s_returned,$s_closed" ?>],
            backgroundColor: ['#fbbf24','#60a5fa','#34d399','#94a3b8'],
            borderWidth: 3,
            borderColor: borderClr(),
            hoverOffset: 12
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        cutout: '68%',
        plugins: {
            legend: {
                position: 'bottom',
                labels: {
                    font: { size: 10, weight: '600' },
                    padding: 12,
                    color: tickColor()
                }
            },
            tooltip: { ...tooltip }
        }
    }
});

// ── Gender Doughnut ──
const genderChart = new Chart(document.getElementById('genderChart'), {
    type: 'doughnut',
    data: {
        labels: <?= json_encode($g_labels) ?>,
        datasets: [{
            data: <?= json_encode($g_returned) ?>,
            backgroundColor: ['#60a5fa','#f472b6','#34d399','#fbbf24'],
            borderWidth: 3,
            borderColor: borderClr(),
            hoverOffset: 12
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        cutout: '62%',
        plugins: {
            legend: {
                position: 'bottom',
                labels: {
                    font: { size: 10, weight: '600' },
                    padding: 12,
                    color: tickColor(),
                    usePointStyle: true,
                    pointStyle: 'circle'
                }
            },
            tooltip: { ...tooltip }
        }
    }
});

// ── Lost Category ──
const catLostChart = new Chart(document.getElementById('catLostChart'), {
    type: 'bar',
    data: {
        labels: <?= json_encode($cat_lost_labels) ?>,
        datasets: [{
            label: 'Lost Items',
            data: <?= json_encode($cat_lost_data) ?>,
            backgroundColor: ['#ef4444','#f97316','#eab308','#10b981','#3b82f6','#8b5cf6','#ec4899'],
            borderRadius: 8,
            borderSkipped: false
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        indexAxis: 'y',
        plugins: {
            legend: { display: false },
            tooltip: { ...tooltip }
        },
        scales: hBarScales()
    }
});

// ── Found Category ──
const catFoundChart = new Chart(document.getElementById('catFoundChart'), {
    type: 'bar',
    data: {
        labels: <?= json_encode($cat_found_labels) ?>,
        datasets: [{
            label: 'Found Items',
            data: <?= json_encode($cat_found_data) ?>,
            backgroundColor: ['#10b981','#3b82f6','#8b5cf6','#eab308','#ef4444','#f97316','#ec4899'],
            borderRadius: 8,
            borderSkipped: false
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        indexAxis: 'y',
        plugins: {
            legend: { display: false },
            tooltip: { ...tooltip }
        },
        scales: hBarScales()
    }
});

// ── Live update on dark mode toggle ──
const allCharts = [trendChart, weeklyChart, statusChart, genderChart, catLostChart, catFoundChart];
const origToggle = window.toggleDarkMode;
window.toggleDarkMode = function () {
    origToggle();
    allCharts.forEach(chart => {
        if (chart.options.plugins?.legend?.labels) chart.options.plugins.legend.labels.color = tickColor();
        ['x','y'].forEach(axis => {
            if (chart.options.scales?.[axis]) {
                if (chart.options.scales[axis].ticks) chart.options.scales[axis].ticks.color = tickColor();
                if (chart.options.scales[axis].grid?.color !== undefined) chart.options.scales[axis].grid.color = gridColor();
            }
        });
        if (chart.config.type === 'doughnut') chart.data.datasets.forEach(ds => ds.borderColor = borderClr());
        chart.update();
    });
};
</script>
</body>
</html>
