<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

// Correct require order: config first (DB + helpers), then AI config
require_once 'config.php';
require_once 'ai_config.php';

$conn = getDBConnection();

// Role-based access control
$allowed_roles = ['admin', 'accountant', 'cashier', 'director', 'supervisor', 'headteacher'];

if (!in_array($_SESSION['role'], $allowed_roles)) {
    switch ($_SESSION['role']) {
        case 'tutor':
            header('Location: modules/reports/index.php');
            break;
        case 'registrar':
            header('Location: students.php');
            break;
        default:
            header('Location: index.php?error=access_denied');
            break;
    }
    exit;
}

// Get dashboard statistics
$totalStudents = 0;
$totalCollections = 0;
$totalExpenses = 0;
$pendingPayments = 0;

// Get total students
$result = $conn->query("SELECT COUNT(*) as count FROM students WHERE status = 'active'");
if ($result) {
    $row = $result->fetch_assoc();
    $totalStudents = $row['count'];
}

// Get total collections
$result = $conn->query("SELECT COALESCE(SUM(amount_paid), 0) as total FROM payments");
if ($result) {
    $row = $result->fetch_assoc();
    $totalCollections = $row['total'];
}

// Get total expenses
$result = $conn->query("SELECT COALESCE(SUM(amount), 0) as total FROM expenses");
if ($result) {
    $row = $result->fetch_assoc();
    $totalExpenses = $row['total'];
}

// Get pending payments count - FIXED QUERY
$result = $conn->query("SELECT COUNT(DISTINCT s.id) as count 
    FROM students s 
    LEFT JOIN payments p ON s.id = p.student_id 
    WHERE s.status = 'active' AND p.id IS NULL");
if ($result) {
    $row = $result->fetch_assoc();
    $pendingPayments = $row['count'];
}

// Get recent transactions
$recentPayments = [];
$result = $conn->query("SELECT p.*, s.first_name, s.last_name, fs.fee_type 
    FROM payments p 
    JOIN students s ON p.student_id = s.id 
    JOIN fee_structures fs ON p.fee_structure_id = fs.id 
    ORDER BY p.payment_date DESC LIMIT 10");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $recentPayments[] = $row;
    }
}

// Get monthly collections for chart - FIXED QUERY
$monthlyData = [];
$months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
for ($i = 1; $i <= 12; $i++) {
    $result = $conn->query("SELECT COALESCE(SUM(amount_paid), 0) as total FROM payments WHERE MONTH(payment_date) = $i AND YEAR(payment_date) = YEAR(CURDATE())");
    if ($result) {
        $row = $result->fetch_assoc();
        $monthlyData[] = $row['total'];
    } else {
        $monthlyData[] = 0;
    }
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - EduTrack PRO</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="wrapper">
        <!-- Sidebar -->
        <nav id="sidebar" class="sidebar">
            <?php
            if (!defined('EDUTRACK_MODULES')) require_once __DIR__ . '/module_definitions.php';
            echo buildSidebar('dashboard.php');
            ?>
        </nav>

        <!-- Main Content -->
        <div class="main-content">
            <!-- Header -->
            <header class="header">
                <button class="btn-toggle" id="sidebarToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="header-right">
                    <div class="dropdown">
                        <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string) ($_SESSION['full_name'] ?? '')); ?>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
                        </ul>
                    </div>
                </div>
            </header>

            <!-- Page Content -->
            <main class="content">
                <div class="content-header">
                    <h2><i class="fas fa-tachometer-alt me-2"></i>Dashboard</h2>
                    <p>Welcome back, <?php echo htmlspecialchars((string) ($_SESSION['full_name'] ?? '')); ?>!</p>
                </div>

                <!-- Period filter -->
                <style>
                .dash-filter{display:flex;flex-wrap:wrap;gap:.4rem;align-items:center;margin-bottom:1rem;}
                .dash-filter .btn{border-radius:9px;font-size:.82rem;font-weight:600;}
                .dash-custom{display:none;gap:.4rem;align-items:center;}
                .dash-custom.show{display:flex;}
                .kpi-card{background:#fff;border:1px solid #eceef2;border-radius:14px;padding:1rem 1.1rem;height:100%;position:relative;overflow:hidden;transition:box-shadow .15s;}
                .kpi-card:hover{box-shadow:0 6px 18px rgba(16,24,40,.08);}
                .kpi-card .kpi-icon{width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center;color:#fff;font-size:1rem;margin-bottom:.6rem;}
                .kpi-card .kpi-label{font-size:.72rem;text-transform:uppercase;letter-spacing:.04em;color:#98a2b3;}
                .kpi-card .kpi-value{font-size:1.5rem;font-weight:700;color:#101828;line-height:1.15;font-variant-numeric:tabular-nums;}
                .kpi-card .kpi-delta{font-size:.74rem;font-weight:600;margin-top:.2rem;}
                .kpi-delta.up{color:#12b76a;} .kpi-delta.down{color:#f04438;} .kpi-delta.flat{color:#98a2b3;}
                .kpi-card .kpi-snap{font-size:.72rem;color:#98a2b3;margin-top:.2rem;}
                .kpi-skel{background:linear-gradient(90deg,#f2f4f7 25%,#eaecf0 37%,#f2f4f7 63%);background-size:400% 100%;animation:kpish 1.2s ease infinite;border-radius:14px;height:118px;}
                @keyframes kpish{0%{background-position:100% 50%}100%{background-position:0 50%}}
                .bg-success{background:#12b76a!important;}.bg-danger{background:#f04438!important;}.bg-primary{background:#2e90fa!important;}
                .bg-warning{background:#f79009!important;}.bg-info{background:#0ba5ec!important;}.bg-secondary{background:#667085!important;}
                </style>
                <div class="dash-filter" id="dashFilter">
                    <span class="text-muted small me-1"><i class="fas fa-filter me-1"></i>Period:</span>
                    <?php
                    $ranges = ['today'=>'Today','yesterday'=>'Yesterday','this_week'=>'This Week','this_month'=>'This Month','this_term'=>'This Term','this_year'=>'This Year'];
                    foreach ($ranges as $rk => $rl):
                    ?>
                        <button class="btn btn-sm <?= $rk==='this_month'?'btn-primary':'btn-outline-secondary' ?>" data-range="<?= $rk ?>"><?= $rl ?></button>
                    <?php endforeach; ?>
                    <button class="btn btn-sm btn-outline-secondary" data-range="custom"><i class="fas fa-calendar-day me-1"></i>Custom</button>
                    <span class="dash-custom" id="dashCustom">
                        <input type="date" id="dashFrom" class="form-control form-control-sm" style="width:150px">
                        <span class="text-muted small">to</span>
                        <input type="date" id="dashTo" class="form-control form-control-sm" style="width:150px">
                        <button class="btn btn-sm btn-primary" id="dashApplyCustom">Apply</button>
                    </span>
                    <span class="ms-auto small text-muted" id="dashRangeLabel"></span>
                </div>

                <!-- KPI grid (AJAX-filled, role-aware) -->
                <div class="row g-3 mb-4" id="kpiGrid">
                    <?php for ($i=0;$i<6;$i++): ?>
                        <div class="col-6 col-md-4 col-xl-2"><div class="kpi-skel"></div></div>
                    <?php endfor; ?>
                </div>

                <!-- Your Plan Widget -->
                <?php
                $_lic      = checkLicense();
                $_plan     = $_lic['plan'] ?? 'premium';
                $_limit    = (int) ($_lic['student_limit'] ?? 0);
                $_mods     = $_lic['modules'] ?? [];
                $_total_m  = defined('EDUTRACK_MODULES') ? count(EDUTRACK_MODULES) : 17;
                $_plan_labels = ['starter'=>'Starter','growth'=>'Growth','premium'=>'Premium'];
                $_plan_icons  = ['starter'=>'fa-seedling','growth'=>'fa-chart-line','premium'=>'fa-star'];
                ?>
                <div class="row mb-4">
                    <div class="col-12">
                        <div class="card plan-widget shadow-sm">
                            <div class="card-body py-3">
                                <div class="d-flex align-items-center flex-wrap gap-3">
                                    <div>
                                        <span class="text-muted small">Your Plan</span>
                                        <div class="fw-bold fs-5">
                                            <i class="fas <?= $_plan_icons[$_plan] ?? 'fa-star' ?> me-2 text-purple" style="color:#6f42c1"></i>
                                            <?= htmlspecialchars($_plan_labels[$_plan] ?? ucfirst($_plan)) ?>
                                        </div>
                                    </div>
                                    <div class="vr d-none d-md-block"></div>
                                    <div>
                                        <span class="text-muted small">Modules Active</span>
                                        <div>
                                            <div class="progress mt-1" style="width:140px;height:8px">
                                                <div class="progress-bar bg-primary"
                                                     style="width:<?= round(count($_mods)/$_total_m*100) ?>%"></div>
                                            </div>
                                            <small><?= count($_mods) ?> / <?= $_total_m ?> modules</small>
                                        </div>
                                    </div>
                                    <div class="vr d-none d-md-block"></div>
                                    <div>
                                        <span class="text-muted small">Student Slots</span>
                                        <?php if ($_limit > 0): ?>
                                        <div>
                                            <div class="progress mt-1" style="width:140px;height:8px">
                                                <div class="progress-bar bg-<?= ($totalStudents >= $_limit * .9) ? 'danger' : 'success' ?>"
                                                     style="width:<?= min(round($totalStudents/$_limit*100), 100) ?>%"></div>
                                            </div>
                                            <small><?= $totalStudents ?> / <?= $_limit ?> used</small>
                                        </div>
                                        <?php else: ?>
                                        <div class="fw-semibold text-success"><i class="fas fa-infinity me-1"></i>Unlimited</div>
                                        <?php endif; ?>
                                    </div>
                                    <?php if ($_plan !== 'premium'): ?>
                                    <div class="ms-auto">
                                        <a href="upgrade.php" class="btn btn-sm btn-outline-primary">
                                            <i class="fas fa-arrow-up me-1"></i>Upgrade Plan
                                        </a>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Charts and Tables -->
                <div class="row">
                    <div class="col-lg-8">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="mb-0"><i class="fas fa-chart-column me-2"></i>Collections vs Expenses</h5>
                                <span class="small text-muted" id="chartRangeLabel"></span>
                            </div>
                            <div class="card-body">
                                <canvas id="collectionChart" height="110"></canvas>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-4">
                        <div class="card h-100">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="mb-0"><i class="fas fa-chart-pie me-2"></i><span id="chart2Title">Breakdown</span></h5>
                            </div>
                            <div class="card-body d-flex align-items-center justify-content-center">
                                <canvas id="dashChart2" height="200"></canvas>
                                <div id="chart2Empty" class="text-muted small text-center" style="display:none">No data for this period.</div>
                            </div>
                        </div>
                    </div>
                    
<?php if (function_exists('hasModule') && hasModule('ai_agent') && in_array($_SESSION['role'] ?? '', ['admin','headteacher','director','supervisor'], true)): ?>
  <!-- AI Assistant Widget -->
<div class="col-md-6 mb-4">
    <div class="card">
        <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-robot me-2"></i>AI Assistant</h5>
            <span class="badge bg-light text-primary">v2.0</span>
        </div>
        <div class="card-body">
            <?php
            // Safely initialize AI features
            require_once 'ai_helpers.php';
            $aiEnabled = initAIFeatures();
            
            if (!$aiEnabled): 
            ?>
            <div class="alert alert-info">
                <i class="fas fa-info-circle me-2"></i>
                AI features are being initialized. Check back soon!
            </div>
            <?php else: 
                $predictor = getAIPredictor();
                $atRisk = $predictor ? $predictor->identifyAtRiskStudents() : [];
                $critical = count(array_filter($atRisk, fn($s) => $s['risk_level'] == 'Critical'));
                $forecast = getRevenueForecastSafe(1);
            ?>
            <div class="row">
                <div class="col-6 mb-3">
                    <div class="d-flex align-items-center p-3 border rounded" onclick="triggerFeature('reminders')" style="cursor: pointer;">
                        <i class="fas fa-bell fa-2x text-warning me-3"></i>
                        <div>
                            <h6 class="mb-0">Fee Reminders</h6>
                            <small class="text-muted">Automated SMS</small>
                        </div>
                    </div>
                </div>
                <div class="col-6 mb-3">
                    <div class="d-flex align-items-center p-3 border rounded" onclick="triggerFeature('analysis')" style="cursor: pointer;">
                        <i class="fas fa-chart-pie fa-2x text-info me-3"></i>
                        <div>
                            <h6 class="mb-0">Smart Analysis</h6>
                            <small class="text-muted">Report insights</small>
                        </div>
                    </div>
                </div>
                <div class="col-6 mb-3">
                    <div class="d-flex align-items-center p-3 border rounded" onclick="triggerFeature('predict')" style="cursor: pointer;">
                        <i class="fas fa-chart-line fa-2x text-success me-3"></i>
                        <div>
                            <h6 class="mb-0">Predictions</h6>
                            <small class="text-muted">AI forecasts</small>
                        </div>
                    </div>
                </div>
                <div class="col-6 mb-3">
                    <div class="d-flex align-items-center p-3 border rounded" onclick="triggerFeature('parents')" style="cursor: pointer;">
                        <i class="fas fa-users fa-2x text-primary me-3"></i>
                        <div>
                            <h6 class="mb-0">Parent Queries</h6>
                            <small class="text-muted">FAQ templates</small>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Quick Stats -->
            <div class="mt-3 p-3 bg-light rounded">
                <div class="d-flex justify-content-between mb-2">
                    <span><i class="fas fa-exclamation-triangle text-danger me-2"></i>Critical Risk:</span>
                    <span class="fw-bold"><?php echo $critical; ?></span>
                </div>
                <div class="d-flex justify-content-between mb-2">
                    <span><i class="fas fa-chart-line text-success me-2"></i>Next Month:</span>
                    <span class="fw-bold"><?php echo $forecast ? formatCurrency($forecast['forecast'][0] ?? 0) : '₵0.00'; ?></span>
                </div>
                <div class="d-flex justify-content-between">
                    <span><i class="fas fa-clock text-info me-2"></i>Reminders Today:</span>
                    <span class="fw-bold"><?php echo getTodayRemindersCount(); ?></span>
                </div>
            </div>
            <?php endif; ?>
            
            <button class="btn btn-primary w-100 mt-3" onclick="toggleChatbot()">
                <i class="fas fa-comment-dots me-2"></i>Chat with AI Assistant
            </button>
        </div>
    </div>
</div>       

<!-- AI Insights Widget -->
<div class="col-md-6 mb-4">
    <div class="card">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0"><i class="fas fa-robot me-2"></i>AI Insights</h5>
        </div>
        <div class="card-body">
            <?php
            require_once 'ai_config.php';
            $recommendations = new AIRecommendations();
            $insights = $recommendations->getDashboardRecommendations();
            $top3 = array_slice($insights, 0, 3);
            ?>
            <?php foreach ($top3 as $insight): ?>
            <div class="alert alert-<?php echo $insight['type']; ?> mb-2">
                <i class="fas fa-<?php echo $insight['icon']; ?> me-2"></i>
                <strong><?php echo $insight['title']; ?></strong>
                <p class="mb-0 small"><?php echo $insight['message']; ?></p>
            </div>
            <?php endforeach; ?>
            <a href="ai_dashboard.php" class="btn btn-sm btn-outline-primary mt-2">
                View All AI Insights <i class="fas fa-arrow-right ms-2"></i>
            </a>
        </div>
    </div>
</div>
<?php endif; ?>

                </div>
                
                

                <!-- Role-aware attention widgets (AJAX-filled) -->
                <div class="row g-3 mt-1" id="dashWidgets">
                    <div class="col-12 text-center text-muted py-3"><i class="fas fa-spinner fa-spin me-1"></i>Loading…</div>
                </div>
            </main>
<?php include 'chatbot.php'; ?>
            <!-- Footer -->
            <footer class="footer">
                <p>&copy; 2024 EduTrack PRO. All rights reserved.</p>
            </footer>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="js/main.js"></script>
<script>
(function () {
    // ── Dashboard: period filter → AJAX KPIs + chart ────────────────────────
    let currentRange = 'this_month';
    let dashChart = null;
    let dashChart2 = null;

    function esc(s){const d=document.createElement('div');d.textContent=s==null?'':s;return d.innerHTML;}
    function fmtCurrency(n){return 'GHS ' + Number(n||0).toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2});}
    function fmtVal(v,f){ if(f==='currency')return fmtCurrency(v); if(f==='percent')return Number(v).toFixed(1)+'%'; return Number(v||0).toLocaleString(); }

    function renderKpis(kpis){
        const grid = document.getElementById('kpiGrid');
        if(!kpis || !kpis.length){ grid.innerHTML='<div class="col-12 text-center text-muted py-4">No metrics for this view.</div>'; return; }
        grid.innerHTML = kpis.map(function(k){
            let trend = '';
            if (k.type === 'period') {
                if (k.delta === null || k.delta === undefined) {
                    trend = '<div class="kpi-snap">no prior data</div>';
                } else {
                    const up = k.delta >= 0;
                    const good = k.good_when_up ? up : !up;
                    const arrow = up ? '&#9650;' : '&#9660;';
                    trend = '<div class="kpi-delta '+(k.delta===0?'flat':(good?'up':'down'))+'">'+arrow+' '+Math.abs(k.delta)+'% <span class="text-muted fw-normal">vs prev</span></div>';
                }
            } else {
                trend = '<div class="kpi-snap">current</div>';
            }
            return '<div class="col-6 col-md-4 col-xl-2"><div class="kpi-card">'
                 + '<div class="kpi-icon bg-'+esc(k.color)+'"><i class="fas '+esc(k.icon)+'"></i></div>'
                 + '<div class="kpi-label">'+esc(k.label)+'</div>'
                 + '<div class="kpi-value">'+fmtVal(k.value,k.format)+'</div>'
                 + trend + '</div></div>';
        }).join('');
    }

    function renderChart(chart){
        const ctx = document.getElementById('collectionChart').getContext('2d');
        const data = {
            labels: chart.labels,
            datasets: [
                { label:'Collections', data:chart.collections, backgroundColor:'rgba(18,183,106,.85)', borderRadius:5, maxBarThickness:34 },
                { label:'Expenses',    data:chart.expenses,    backgroundColor:'rgba(240,68,56,.80)',  borderRadius:5, maxBarThickness:34 }
            ]
        };
        const opts = { responsive:true, plugins:{legend:{position:'top',labels:{boxWidth:12,usePointStyle:true}},
            tooltip:{callbacks:{label:c=>c.dataset.label+': GHS '+Number(c.parsed.y).toLocaleString()}}},
            scales:{ x:{grid:{display:false}}, y:{beginAtZero:true,ticks:{callback:v=>'GHS '+Number(v).toLocaleString()}} } };
        if (dashChart){ dashChart.data=data; dashChart.update(); }
        else dashChart = new Chart(ctx, { type:'bar', data:data, options:opts });
    }

    function renderSecondary(sec){
        const title = document.getElementById('chart2Title');
        const empty = document.getElementById('chart2Empty');
        const cv = document.getElementById('dashChart2');
        if (title) title.textContent = sec.title || 'Breakdown';
        const total = (sec.data||[]).reduce((a,b)=>a+Number(b||0),0);
        if (!sec.data || !sec.data.length || total<=0){
            cv.style.display='none'; if(empty)empty.style.display='block';
            if(dashChart2){dashChart2.destroy();dashChart2=null;} return;
        }
        cv.style.display='block'; if(empty)empty.style.display='none';
        const cfg = { type:sec.type||'doughnut', data:{ labels:sec.labels,
            datasets:[{ data:sec.data, backgroundColor:sec.colors, borderWidth:1, borderColor:'#fff' }] },
            options:{ responsive:true, plugins:{ legend:{position:'bottom',labels:{boxWidth:11,font:{size:11}}},
                tooltip:{callbacks:{label:function(c){ const v=c.parsed; return c.label+': '+(sec.currency?('GHS '+Number(v).toLocaleString()):v); }}} } } };
        if (dashChart2){ dashChart2.destroy(); }
        dashChart2 = new Chart(cv.getContext('2d'), cfg);
    }

    function renderLists(lists){
        const wrap = document.getElementById('dashWidgets');
        if (!lists || !lists.length){ wrap.innerHTML=''; return; }
        wrap.innerHTML = lists.map(function(w){
            const head = '<div class="card-header d-flex justify-content-between align-items-center py-2">'
                + '<h6 class="mb-0"><i class="fas '+esc(w.icon)+' me-2 text-primary"></i>'+esc(w.title)+'</h6>'
                + (w.link?'<a href="'+esc(w.link)+'" class="small">View all</a>':'') + '</div>';
            let body;
            if (!w.rows || !w.rows.length){
                body = '<div class="card-body text-muted small text-center py-3">'+esc(w.empty||'Nothing to show.')+'</div>';
            } else {
                const th = '<tr>'+w.cols.map(c=>'<th class="small text-muted">'+esc(c)+'</th>').join('')+'</tr>';
                const tr = w.rows.map(function(row){ return '<tr>'+row.map(function(cell,i){
                    const last = i===row.length-1;
                    return '<td class="small'+(last?' fw-semibold text-end':'')+'">'+esc(cell)+'</td>'; }).join('')+'</tr>'; }).join('');
                body = '<div class="card-body p-0"><div class="table-responsive"><table class="table table-sm table-hover mb-0"><thead>'+th+'</thead><tbody>'+tr+'</tbody></table></div></div>';
            }
            return '<div class="col-12 col-lg-6"><div class="card h-100">'+head+body+'</div></div>';
        }).join('');
    }

    function load(range, from, to){
        const grid = document.getElementById('kpiGrid');
        grid.querySelectorAll('.kpi-card').forEach(c=>c.style.opacity='.5');
        let url = 'ajax/dashboard_stats.php?range='+encodeURIComponent(range);
        if (range==='custom'){ url += '&from='+encodeURIComponent(from)+'&to='+encodeURIComponent(to); }
        fetch(url).then(r=>r.json()).then(d=>{
            if(!d.success)return;
            renderKpis(d.kpis);
            renderChart(d.chart);
            renderSecondary(d.secondary||{});
            renderLists(d.lists||[]);
            const lbl = d.range.label + ' · ' + d.range.from + ' → ' + d.range.to;
            document.getElementById('dashRangeLabel').textContent = lbl;
            document.getElementById('chartRangeLabel').textContent = d.range.label;
        }).catch(()=>{ grid.innerHTML='<div class="col-12 text-danger text-center py-3">Could not load metrics.</div>'; });
    }

    document.querySelectorAll('#dashFilter [data-range]').forEach(function(btn){
        btn.addEventListener('click', function(){
            const r = this.getAttribute('data-range');
            document.querySelectorAll('#dashFilter [data-range]').forEach(b=>{b.classList.remove('btn-primary');b.classList.add('btn-outline-secondary');});
            this.classList.remove('btn-outline-secondary'); this.classList.add('btn-primary');
            document.getElementById('dashCustom').classList.toggle('show', r==='custom');
            currentRange = r;
            if (r!=='custom') load(r);
        });
    });
    document.getElementById('dashApplyCustom').addEventListener('click', function(){
        const f=document.getElementById('dashFrom').value, t=document.getElementById('dashTo').value;
        if(!f||!t){alert('Pick both dates.');return;}
        load('custom', f, t);
    });

    load('this_month');
})();
</script>
</body>
</html>
