<?php
// public/dashboard.php
declare(strict_types=1);

require_once __DIR__ . "/../config/db.php";
require_once __DIR__ . "/../config/auth.php";

require_login();

$u    = current_user();
$uid  = (int)($u['id'] ?? 0);
$role = (string)($u['role'] ?? 'REP');
$name = (string)($u['name'] ?? '');

$today = (new DateTime('today'))->format('Y-m-d');
$startOfMonth = (new DateTime('first day of this month'))->format('Y-m-d');
$startOfWeek = (new DateTime('monday this week'))->format('Y-m-d');

// ---------- Helpers ----------
function fetchValue(PDO $pdo, string $sql, array $params = []): int {
    $st = $pdo->prepare($sql);
    $st->execute($params);
    return (int)($st->fetchColumn() ?? 0);
}
function fetchAll(PDO $pdo, string $sql, array $params = []): array {
    $st = $pdo->prepare($sql);
    $st->execute($params);
    return $st->fetchAll(PDO::FETCH_ASSOC);
}

// ---------- REP-specific KPIs ----------
if ($role === 'ADMIN') {
    header('Location: /school-crm/public/admin/dashboard.php');
    exit;
} else {
    // REP Dashboard - Enhanced KPIs
    $kpi = [
        // Visit counts
        'today_visits' => fetchValue($pdo, 
            "SELECT COUNT(*) FROM visits WHERE visited_by = ? AND visit_date = ?", 
            [$uid, $today]),
        'week_visits' => fetchValue($pdo, 
            "SELECT COUNT(*) FROM visits WHERE visited_by = ? AND visit_date >= ?", 
            [$uid, $startOfWeek]),
        'month_visits' => fetchValue($pdo, 
            "SELECT COUNT(*) FROM visits WHERE visited_by = ? AND visit_date >= ?", 
            [$uid, $startOfMonth]),
        'total_visits' => fetchValue($pdo, 
            "SELECT COUNT(*) FROM visits WHERE visited_by = ?", 
            [$uid]),
        
        // School coverage
        'assigned_schools' => fetchValue($pdo, "
            SELECT COUNT(DISTINCT s.id)
            FROM schools s
            WHERE s.gp_id IN (
                SELECT gp_id FROM gp_assignments 
                WHERE user_id = ? AND status = 'ACTIVE'
            )
        ", [$uid]),
        
        'visited_schools' => fetchValue($pdo, "
            SELECT COUNT(DISTINCT school_id) 
            FROM visits 
            WHERE visited_by = ?
        ", [$uid]),
        
        'completed_schools' => fetchValue($pdo, "
            SELECT COUNT(DISTINCT s.id)
            FROM schools s
            WHERE s.id IN (
                SELECT v.school_id
                FROM visits v
                JOIN visit_student_interactions vsi ON vsi.visit_id = v.id
                WHERE v.visited_by = ?
                GROUP BY v.school_id
                HAVING COUNT(DISTINCT vsi.class) >= 12
            )
        ", [$uid]),
        
        // NEW: Schools added by this rep
        'schools_added' => fetchValue($pdo, "
            SELECT COUNT(*) 
            FROM schools 
            WHERE created_by = ?
        ", [$uid]),
        
        'schools_added_this_month' => fetchValue($pdo, "
            SELECT COUNT(*) 
            FROM schools 
            WHERE created_by = ? 
                AND created_at >= ?
        ", [$uid, $startOfMonth]),
        
        // Follow-ups
        'followups_today' => fetchValue($pdo, "
            SELECT COUNT(*) FROM visits 
            WHERE visited_by = ? 
                AND followup_required = 1 
                AND followup_date = ?
        ", [$uid, $today]),
        
        'followups_overdue' => fetchValue($pdo, "
            SELECT COUNT(*) FROM visits 
            WHERE visited_by = ? 
                AND followup_required = 1 
                AND followup_date < ?
                AND followup_date IS NOT NULL
        ", [$uid, $today]),
        
        'followups_week' => fetchValue($pdo, "
            SELECT COUNT(*) FROM visits 
            WHERE visited_by = ? 
                AND followup_required = 1 
                AND followup_date BETWEEN ? AND ?
        ", [$uid, $today, (new DateTime($today))->modify('+7 days')->format('Y-m-d')]),
        
        // Pending verifications
        'pending_verifications' => fetchValue($pdo, "
            SELECT COUNT(*) FROM school_verification 
            WHERE representative_id = ? AND status = 'PENDING'
        ", [$uid]),
        
        'rejected_verifications' => fetchValue($pdo, "
            SELECT COUNT(*) FROM school_verification 
            WHERE representative_id = ? AND status = 'REJECTED'
        ", [$uid]),
        
        // Permission stats
        'permission_granted' => fetchValue($pdo, "
            SELECT COUNT(*) FROM visits 
            WHERE visited_by = ? AND permission_status = 'GRANTED'
        ", [$uid]),
        
        'permission_pending' => fetchValue($pdo, "
            SELECT COUNT(*) FROM visits 
            WHERE visited_by = ? AND permission_status = 'PENDING'
        ", [$uid]),
        
        'permission_denied' => fetchValue($pdo, "
            SELECT COUNT(*) FROM visits 
            WHERE visited_by = ? AND permission_status = 'NOT_ALLOWED'
        ", [$uid]),
    ];
    
    // Calculate percentages
    $kpi['coverage_pct'] = $kpi['assigned_schools'] > 0 
        ? round(($kpi['visited_schools'] / $kpi['assigned_schools']) * 100, 1) 
        : 0;
    
    $kpi['completion_pct'] = $kpi['assigned_schools'] > 0 
        ? round(($kpi['completed_schools'] / $kpi['assigned_schools']) * 100, 1) 
        : 0;

    // Daily visits for chart (last 14 days)
    $daily = fetchAll($pdo, "
        SELECT visit_date AS d, COUNT(*) AS c
        FROM visits
        WHERE visited_by = ? 
            AND visit_date >= DATE_SUB(?, INTERVAL 13 DAY)
        GROUP BY visit_date
        ORDER BY visit_date ASC
    ", [$uid, $today]);

    // Schools added by rep (recent)
    $recently_added_schools = fetchAll($pdo, "
        SELECT 
            s.id,
            s.name AS school_name,
            s.category,
            s.created_at,
            g.name AS gp_name,
            b.name AS block_name,
            d.name AS district_name,
            (
                SELECT COUNT(*) FROM visits v 
                WHERE v.school_id = s.id
            ) AS visit_count
        FROM schools s
        JOIN gps g ON g.id = s.gp_id
        JOIN blocks b ON b.id = g.block_id
        JOIN districts d ON d.id = b.district_id
        WHERE s.created_by = ?
        ORDER BY s.created_at DESC
        LIMIT 10
    ", [$uid]);

    // Schools with most visits
    $topSchools = fetchAll($pdo, "
        SELECT 
            s.name AS school_name,
            g.name AS gp_name,
            COUNT(*) AS visit_count,
            MAX(v.visit_date) AS last_visit,
            COUNT(DISTINCT vsi.class) AS classes_covered
        FROM visits v
        JOIN schools s ON s.id = v.school_id
        JOIN gps g ON g.id = v.gp_id
        LEFT JOIN visit_student_interactions vsi ON vsi.visit_id = v.id
        WHERE v.visited_by = ?
        GROUP BY v.school_id
        ORDER BY visit_count DESC
        LIMIT 10
    ", [$uid]);

    // Recent visits
    $recentVisits = fetchAll($pdo, "
        SELECT 
            v.visit_date,
            v.permission_status,
            s.name AS school_name,
            g.name AS gp_name,
            b.name AS block_name,
            (
                SELECT COUNT(*) 
                FROM visit_student_interactions vsi 
                WHERE vsi.visit_id = v.id
            ) AS students_met
        FROM visits v
        JOIN schools s ON s.id = v.school_id
        JOIN gps g ON g.id = v.gp_id
        JOIN blocks b ON b.id = v.block_id
        WHERE v.visited_by = ?
        ORDER BY v.visit_date DESC, v.id DESC
        LIMIT 15
    ", [$uid]);

    // Upcoming follow-ups
    $followups = fetchAll($pdo, "
        SELECT 
            v.followup_date,
            s.name AS school_name,
            g.name AS gp_name,
            b.name AS block_name,
            DATEDIFF(v.followup_date, ?) AS days_due
        FROM visits v
        JOIN schools s ON s.id = v.school_id
        JOIN gps g ON g.id = v.gp_id
        JOIN blocks b ON b.id = v.block_id
        WHERE v.visited_by = ? 
            AND v.followup_required = 1 
            AND v.followup_date IS NOT NULL
            AND v.followup_date >= ?
        ORDER BY v.followup_date ASC
        LIMIT 10
    ", [$today, $uid, $today]);

    // Pending verifications list
    $pendingVerifications = fetchAll($pdo, "
        SELECT 
            sv.requested_at,
            s.name AS school_name,
            g.name AS gp_name,
            b.name AS block_name,
            sv.status
        FROM school_verification sv
        JOIN schools s ON s.id = sv.school_id
        JOIN gps g ON g.id = s.gp_id
        JOIN blocks b ON b.id = g.block_id
        WHERE sv.representative_id = ? AND sv.status = 'PENDING'
        ORDER BY sv.requested_at DESC
        LIMIT 10
    ", [$uid]);
}

// ---------- Normalize chart arrays (fill missing days) ----------
$labels = [];
$counts = [];
for ($i = 13; $i >= 0; $i--) {
    $d = (new DateTime($today))->modify("-{$i} day")->format('Y-m-d');
    $labels[] = date('d M', strtotime($d));
    $counts[$d] = 0;
}
foreach ($daily as $row) {
    $d = (string)$row['d'];
    if (isset($counts[$d])) $counts[$d] = (int)$row['c'];
}
$dailyCounts = array_values($counts);

// Permission pie data
$permLabels = ['Granted', 'Pending', 'Not Allowed'];
$permCounts = [
    $kpi['permission_granted'],
    $kpi['permission_pending'],
    $kpi['permission_denied']
];

$page_title = "Dashboard - " . htmlspecialchars($name);
require_once __DIR__ . "/partials/header.php";
?>

<!-- Bootstrap Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

<style>
:root {
    --primary: #4361ee;
    --success: #06d6a0;
    --warning: #ffb703;
    --danger: #ef476f;
    --dark: #073b4c;
    --info: #17a2b8;
    --purple: #6f42c1;
    --orange: #fd7e14;
    --light: #f8f9fa;
    --gray: #6c757d;
}

body {
    background: #f5f7fa;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
}

.dashboard-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 16px;
}

/* Welcome Section */
.welcome-section {
    background: linear-gradient(135deg, var(--primary), #3a0ca3);
    color: white;
    border-radius: 24px;
    padding: 24px;
    margin-bottom: 24px;
    box-shadow: 0 10px 30px rgba(67, 97, 238, 0.2);
}

.welcome-title {
    font-size: 1.8rem;
    font-weight: 700;
    margin-bottom: 8px;
}

.welcome-date {
    display: flex;
    align-items: center;
    gap: 20px;
    flex-wrap: wrap;
    opacity: 0.9;
    font-size: 0.95rem;
}

.welcome-date i {
    margin-right: 6px;
}

/* KPI Grid */
.kpi-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 16px;
    margin-bottom: 24px;
}

.kpi-card {
    background: white;
    border-radius: 20px;
    padding: 20px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.03);
    border: 1px solid #e9ecef;
    transition: all 0.2s;
    position: relative;
    overflow: hidden;
}

.kpi-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 24px rgba(0,0,0,0.06);
}

.kpi-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, var(--primary), var(--success));
}

.kpi-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.kpi-icon {
    width: 48px;
    height: 48px;
    background: rgba(67, 97, 238, 0.1);
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--primary);
    font-size: 1.5rem;
}

.kpi-badge {
    padding: 4px 8px;
    background: var(--light);
    border-radius: 20px;
    font-size: 0.7rem;
    font-weight: 600;
    color: var(--gray);
}

.kpi-value {
    font-size: 2rem;
    font-weight: 700;
    color: var(--dark);
    margin-bottom: 4px;
}

.kpi-label {
    color: var(--gray);
    font-size: 0.85rem;
    display: flex;
    align-items: center;
    gap: 6px;
}

.kpi-progress {
    margin-top: 12px;
    height: 6px;
    background: var(--light);
    border-radius: 3px;
    overflow: hidden;
}

.kpi-progress-bar {
    height: 100%;
    background: linear-gradient(90deg, var(--primary), var(--success));
    border-radius: 3px;
    transition: width 0.3s;
}

/* Chart Cards */
.chart-card {
    background: white;
    border-radius: 24px;
    padding: 20px;
    border: 1px solid #e9ecef;
    margin-bottom: 24px;
}

.chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 12px;
}

.chart-title {
    display: flex;
    align-items: center;
    gap: 8px;
}

.chart-title i {
    color: var(--primary);
    font-size: 1.4rem;
}

.chart-title h5 {
    margin: 0;
    font-weight: 600;
    color: var(--dark);
}

.chart-actions {
    display: flex;
    gap: 8px;
}

.chart-container {
    position: relative;
    width: 100%;
    min-height: 300px;
}

/* Table Cards */
.table-card {
    background: white;
    border-radius: 24px;
    padding: 20px;
    border: 1px solid #e9ecef;
    margin-bottom: 24px;
}

.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 12px;
}

.table-title {
    display: flex;
    align-items: center;
    gap: 8px;
}

.table-title i {
    color: var(--primary);
    font-size: 1.4rem;
}

.table-title h5 {
    margin: 0;
    font-weight: 600;
    color: var(--dark);
}

.table-responsive {
    margin: 0;
}

.table {
    margin: 0;
}

.table th {
    border-top: none;
    color: var(--gray);
    font-weight: 500;
    font-size: 0.8rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    padding: 12px 8px;
}

.table td {
    padding: 12px 8px;
    vertical-align: middle;
    color: var(--dark);
}

.status-badge {
    padding: 4px 8px;
    border-radius: 20px;
    font-size: 0.7rem;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}

.badge-success {
    background: rgba(6, 214, 160, 0.1);
    color: var(--success);
}

.badge-warning {
    background: rgba(255, 183, 3, 0.1);
    color: var(--warning);
}

.badge-danger {
    background: rgba(239, 71, 111, 0.1);
    color: var(--danger);
}

.badge-info {
    background: rgba(23, 162, 184, 0.1);
    color: var(--info);
}

.badge-purple {
    background: rgba(111, 66, 193, 0.1);
    color: var(--purple);
}

.badge-primary {
    background: rgba(67, 97, 238, 0.1);
    color: var(--primary);
}

/* Quick Actions */
.quick-actions {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 12px;
    margin-bottom: 24px;
}

.action-btn {
    background: white;
    border: 1px solid #e9ecef;
    border-radius: 16px;
    padding: 16px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    text-decoration: none;
    color: var(--dark);
    transition: all 0.2s;
}

.action-btn:hover {
    background: var(--primary);
    color: white;
    transform: translateY(-2px);
    box-shadow: 0 8px 24px rgba(67, 97, 238, 0.2);
}

.action-btn i {
    font-size: 1.8rem;
}

.action-btn span {
    font-size: 0.9rem;
    font-weight: 500;
}

/* Mobile Responsive */
@media (max-width: 768px) {
    .dashboard-container {
        padding: 12px;
    }
    
    .welcome-section {
        padding: 20px;
    }
    
    .welcome-title {
        font-size: 1.4rem;
    }
    
    .kpi-grid {
        grid-template-columns: 1fr;
    }
    
    .kpi-card {
        padding: 16px;
    }
    
    .kpi-value {
        font-size: 1.8rem;
    }
    
    .chart-container {
        min-height: 250px;
    }
    
    .chart-card, .table-card {
        padding: 16px;
    }
    
    .quick-actions {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .action-btn {
        padding: 12px;
    }
    
    .action-btn i {
        font-size: 1.5rem;
    }
    
    .table td, .table th {
        font-size: 0.85rem;
        padding: 8px 4px;
    }
}

@media (min-width: 769px) and (max-width: 1024px) {
    .kpi-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}
</style>

<div class="dashboard-container">
    <!-- Welcome Section -->
    <div class="welcome-section">
        <div class="welcome-title">
            👋 Welcome back, <?= htmlspecialchars(explode(' ', $name)[0]) ?>!
        </div>
        <div class="welcome-date">
            <span><i class="bi bi-calendar"></i> <?= date('l, d F Y', strtotime($today)) ?></span>
            <span><i class="bi bi-building"></i> <?= $kpi['assigned_schools'] ?> Schools Assigned</span>
            <span><i class="bi bi-check-circle"></i> <?= $kpi['coverage_pct'] ?>% Coverage</span>
            <span><i class="bi bi-plus-circle"></i> <?= $kpi['schools_added'] ?> Schools Added</span>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="quick-actions">
        <a href="/school-crm/public/visit_add.php" class="action-btn">
            <i class="bi bi-plus-circle"></i>
            <span>Add Visit</span>
        </a>
        <a href="/school-crm/public/rep/my_schools.php" class="action-btn">
            <i class="bi bi-building"></i>
            <span>My Schools</span>
        </a>
        <a href="/school-crm/public/rep/school_add.php" class="action-btn">
            <i class="bi bi-building-add"></i>
            <span>Add School</span>
        </a>
        <a href="/school-crm/public/visits.php" class="action-btn">
            <i class="bi bi-clock-history"></i>
            <span>History</span>
        </a>
    </div>

    <!-- KPI Grid -->
    <div class="kpi-grid">
        <!-- Visits Card -->
        <div class="kpi-card">
            <div class="kpi-header">
                <div class="kpi-icon">
                    <i class="bi bi-calendar-check"></i>
                </div>
                <span class="kpi-badge">This Month</span>
            </div>
            <div class="kpi-value"><?= $kpi['month_visits'] ?></div>
            <div class="kpi-label">
                <i class="bi bi-graph-up"></i>
                Visits this month
            </div>
            <div class="kpi-progress">
                <div class="kpi-progress-bar" style="width: <?= min(100, ($kpi['month_visits'] / 20) * 100) ?>%"></div>
            </div>
            <div style="display: flex; justify-content: space-between; margin-top: 8px; font-size: 0.75rem; color: var(--gray);">
                <span>Today: <?= $kpi['today_visits'] ?></span>
                <span>Week: <?= $kpi['week_visits'] ?></span>
                <span>Total: <?= $kpi['total_visits'] ?></span>
            </div>
        </div>

        <!-- Coverage Card -->
        <div class="kpi-card">
            <div class="kpi-header">
                <div class="kpi-icon" style="background: rgba(6, 214, 160, 0.1); color: var(--success);">
                    <i class="bi bi-map"></i>
                </div>
                <span class="kpi-badge">Coverage</span>
            </div>
            <div class="kpi-value"><?= $kpi['coverage_pct'] ?>%</div>
            <div class="kpi-label">
                <i class="bi bi-building"></i>
                <?= $kpi['visited_schools'] ?> of <?= $kpi['assigned_schools'] ?> schools
            </div>
            <div class="kpi-progress">
                <div class="kpi-progress-bar" style="width: <?= $kpi['coverage_pct'] ?>%"></div>
            </div>
        </div>

        <!-- Completion Card -->
        <div class="kpi-card">
            <div class="kpi-header">
                <div class="kpi-icon" style="background: rgba(111, 66, 193, 0.1); color: var(--purple);">
                    <i class="bi bi-check2-all"></i>
                </div>
                <span class="kpi-badge">Completed</span>
            </div>
            <div class="kpi-value"><?= $kpi['completed_schools'] ?></div>
            <div class="kpi-label">
                <i class="bi bi-star"></i>
                Schools with 12+ classes
            </div>
            <div class="kpi-progress">
                <div class="kpi-progress-bar" style="width: <?= $kpi['completion_pct'] ?>%"></div>
            </div>
        </div>

        <!-- Schools Added Card -->
        <div class="kpi-card">
            <div class="kpi-header">
                <div class="kpi-icon" style="background: rgba(23, 162, 184, 0.1); color: var(--info);">
                    <i class="bi bi-building-add"></i>
                </div>
                <span class="kpi-badge">Added</span>
            </div>
            <div class="kpi-value"><?= $kpi['schools_added'] ?></div>
            <div class="kpi-label">
                <i class="bi bi-plus-circle"></i>
                Schools you've added
            </div>
            <div style="display: flex; justify-content: space-between; margin-top: 8px; font-size: 0.75rem; color: var(--gray);">
                <span>This Month: <?= $kpi['schools_added_this_month'] ?></span>
                <span><i class="bi bi-calendar"></i> Total</span>
            </div>
        </div>

        <!-- Follow-ups Card -->
        <div class="kpi-card">
            <div class="kpi-header">
                <div class="kpi-icon" style="background: rgba(255, 183, 3, 0.1); color: var(--warning);">
                    <i class="bi bi-bell"></i>
                </div>
                <span class="kpi-badge">Follow-ups</span>
            </div>
            <div class="kpi-value"><?= $kpi['followups_today'] + $kpi['followups_overdue'] ?></div>
            <div class="kpi-label">
                <i class="bi bi-exclamation-triangle"></i>
                Due / Overdue
            </div>
            <div style="display: flex; justify-content: space-between; margin-top: 12px; font-size: 0.8rem;">
                <span class="text-warning">Today: <?= $kpi['followups_today'] ?></span>
                <span class="text-danger">Overdue: <?= $kpi['followups_overdue'] ?></span>
                <span class="text-info">Week: <?= $kpi['followups_week'] ?></span>
            </div>
        </div>

        <!-- Verifications Card -->
        <?php if ($kpi['pending_verifications'] > 0 || $kpi['rejected_verifications'] > 0): ?>
        <div class="kpi-card">
            <div class="kpi-header">
                <div class="kpi-icon" style="background: rgba(23, 162, 184, 0.1); color: var(--info);">
                    <i class="bi bi-hourglass-split"></i>
                </div>
                <span class="kpi-badge">Verifications</span>
            </div>
            <div class="kpi-value"><?= $kpi['pending_verifications'] ?></div>
            <div class="kpi-label">
                <i class="bi bi-clock"></i>
                Pending verification
            </div>
            <div style="margin-top: 8px; font-size: 0.8rem;">
                <?php if ($kpi['rejected_verifications'] > 0): ?>
                    <span class="text-danger">⚠️ <?= $kpi['rejected_verifications'] ?> rejected</span>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Charts Row -->
    <div class="row g-3 mb-3">
        <div class="col-12 col-lg-8">
            <div class="chart-card">
                <div class="chart-header">
                    <div class="chart-title">
                        <i class="bi bi-bar-chart"></i>
                        <h5>Daily Visits (Last 14 Days)</h5>
                    </div>
                    <div class="chart-actions">
                        <span class="badge bg-light text-dark">vs previous period</span>
                    </div>
                </div>
                <div class="chart-container">
                    <canvas id="dailyChart"></canvas>
                </div>
            </div>
        </div>

        <div class="col-12 col-lg-4">
            <div class="chart-card">
                <div class="chart-header">
                    <div class="chart-title">
                        <i class="bi bi-pie-chart"></i>
                        <h5>Permission Status</h5>
                    </div>
                </div>
                <div class="chart-container" style="min-height: 250px;">
                    <canvas id="permChart"></canvas>
                </div>
                <div class="mt-3 small text-muted">
                    <div class="d-flex justify-content-between">
                        <span>✅ Granted: <?= $kpi['permission_granted'] ?></span>
                        <span>⏳ Pending: <?= $kpi['permission_pending'] ?></span>
                        <span>❌ Denied: <?= $kpi['permission_denied'] ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Tables Row -->
    <div class="row g-3">
        <!-- Recent Visits -->
        <div class="col-12 col-lg-6">
            <div class="table-card">
                <div class="table-header">
                    <div class="table-title">
                        <i class="bi bi-clock-history"></i>
                        <h5>Recent Visits</h5>
                    </div>
                    <a href="/school-crm/public/visits.php" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>School</th>
                                <th>GP/Block</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($recentVisits)): ?>
                                <tr>
                                    <td colspan="4" class="text-center text-muted py-4">
                                        <i class="bi bi-inbox"></i> No visits yet
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($recentVisits as $v): ?>
                                <tr>
                                    <td class="text-nowrap"><?= date('d M', strtotime($v['visit_date'])) ?></td>
                                    <td>
                                        <strong><?= htmlspecialchars($v['school_name']) ?></strong>
                                        <small class="d-block text-muted">👥 <?= $v['students_met'] ?> students</small>
                                    </td>
                                    <td>
                                        <span class="d-block"><?= htmlspecialchars($v['gp_name']) ?></span>
                                        <small class="text-muted"><?= htmlspecialchars($v['block_name']) ?></small>
                                    </td>
                                    <td>
                                        <?php
                                        $statusClass = '';
                                        $statusIcon = '';
                                        if ($v['permission_status'] === 'GRANTED') {
                                            $statusClass = 'badge-success';
                                            $statusIcon = '✅';
                                        } elseif ($v['permission_status'] === 'PENDING') {
                                            $statusClass = 'badge-warning';
                                            $statusIcon = '⏳';
                                        } else {
                                            $statusClass = 'badge-danger';
                                            $statusIcon = '❌';
                                        }
                                        ?>
                                        <span class="status-badge <?= $statusClass ?>">
                                            <?= $statusIcon ?> <?= $v['permission_status'] ?>
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Recently Added Schools -->
        <div class="col-12 col-lg-6">
            <div class="table-card">
                <div class="table-header">
                    <div class="table-title">
                        <i class="bi bi-building-add" style="color: var(--info);"></i>
                        <h5>Recently Added Schools</h5>
                    </div>
                    <a href="/school-crm/public/rep/my_schools.php?filter=added" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Added On</th>
                                <th>School</th>
                                <th>Location</th>
                                <th>Visits</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($recently_added_schools)): ?>
                                <tr>
                                    <td colspan="4" class="text-center text-muted py-4">
                                        <i class="bi bi-building"></i> You haven't added any schools yet
                                        <div class="mt-2">
                                            <a href="/school-crm/public/rep/school_add.php" class="btn btn-sm btn-primary">
                                                <i class="bi bi-plus-circle"></i> Add Your First School
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($recently_added_schools as $s): ?>
                                <tr>
                                    <td class="text-nowrap">
                                        <?= date('d M', strtotime($s['created_at'])) ?>
                                        <small class="d-block text-muted"><?= date('h:i A', strtotime($s['created_at'])) ?></small>
                                    </td>
                                    <td>
                                        <strong><?= htmlspecialchars($s['school_name']) ?></strong>
                                        <small class="d-block text-muted"><?= htmlspecialchars($s['category'] ?? 'N/A') ?></small>
                                    </td>
                                    <td>
                                        <span class="d-block"><?= htmlspecialchars($s['gp_name']) ?></span>
                                        <small class="text-muted"><?= htmlspecialchars($s['block_name']) ?>, <?= htmlspecialchars($s['district_name']) ?></small>
                                    </td>
                                    <td>
                                        <span class="badge-custom badge-info">
                                            <i class="bi bi-eye"></i> <?= $s['visit_count'] ?> visits
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Upcoming Follow-ups -->
        <div class="col-12 col-lg-6">
            <div class="table-card">
                <div class="table-header">
                    <div class="table-title">
                        <i class="bi bi-bell"></i>
                        <h5>Upcoming Follow-ups</h5>
                    </div>
                    <a href="/school-crm/public/followups.php" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Due Date</th>
                                <th>School</th>
                                <th>Location</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($followups)): ?>
                                <tr>
                                    <td colspan="4" class="text-center text-muted py-4">
                                        <i class="bi bi-calendar-check"></i> No upcoming follow-ups
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($followups as $f): ?>
                                <tr>
                                    <td class="text-nowrap">
                                        <?= date('d M', strtotime($f['followup_date'])) ?>
                                        <?php if ($f['days_due'] <= 2): ?>
                                            <span class="badge bg-warning ms-1">Soon</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= htmlspecialchars($f['school_name']) ?></td>
                                    <td>
                                        <span class="d-block"><?= htmlspecialchars($f['gp_name']) ?></span>
                                        <small class="text-muted"><?= htmlspecialchars($f['block_name']) ?></small>
                                    </td>
                                    <td>
                                        <?php if ($f['days_due'] < 0): ?>
                                            <span class="status-badge badge-danger">Overdue</span>
                                        <?php elseif ($f['days_due'] == 0): ?>
                                            <span class="status-badge badge-warning">Today</span>
                                        <?php else: ?>
                                            <span class="status-badge badge-info"><?= $f['days_due'] ?> days</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Top Schools -->
        <div class="col-12 col-lg-6">
            <div class="table-card">
                <div class="table-header">
                    <div class="table-title">
                        <i class="bi bi-trophy"></i>
                        <h5>Most Visited Schools</h5>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>School</th>
                                <th>Visits</th>
                                <th>Classes</th>
                                <th>Last Visit</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($topSchools)): ?>
                                <tr>
                                    <td colspan="4" class="text-center text-muted py-4">
                                        <i class="bi bi-building"></i> No data yet
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($topSchools as $s): ?>
                                <tr>
                                    <td>
                                        <strong><?= htmlspecialchars($s['school_name']) ?></strong>
                                        <small class="d-block text-muted"><?= htmlspecialchars($s['gp_name']) ?></small>
                                    </td>
                                    <td class="fw-bold"><?= $s['visit_count'] ?></td>
                                    <td><?= $s['classes_covered'] ?? 0 ?>/12</td>
                                    <td class="text-nowrap"><?= date('d M', strtotime($s['last_visit'])) ?></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Pending Verifications -->
        <?php if (!empty($pendingVerifications)): ?>
        <div class="col-12 col-lg-6">
            <div class="table-card">
                <div class="table-header">
                    <div class="table-title">
                        <i class="bi bi-hourglass-split"></i>
                        <h5>Pending Verifications</h5>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Requested</th>
                                <th>School</th>
                                <th>Location</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($pendingVerifications as $pv): ?>
                            <tr>
                                <td class="text-nowrap"><?= date('d M', strtotime($pv['requested_at'])) ?></td>
                                <td><?= htmlspecialchars($pv['school_name']) ?></td>
                                <td>
                                    <span class="d-block"><?= htmlspecialchars($pv['gp_name']) ?></span>
                                    <small class="text-muted"><?= htmlspecialchars($pv['block_name']) ?></small>
                                </td>
                                <td>
                                    <span class="status-badge badge-info">
                                        <i class="bi bi-hourglass-split"></i> Pending
                                    </span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<script>
// Daily visits chart
const dailyCtx = document.getElementById('dailyChart').getContext('2d');
new Chart(dailyCtx, {
    type: 'line',
    data: {
        labels: <?= json_encode($labels, JSON_UNESCAPED_SLASHES) ?>,
        datasets: [{
            label: 'Visits',
            data: <?= json_encode($dailyCounts, JSON_UNESCAPED_SLASHES) ?>,
            borderColor: '#4361ee',
            backgroundColor: 'rgba(67, 97, 238, 0.1)',
            tension: 0.4,
            fill: true,
            pointBackgroundColor: '#4361ee',
            pointBorderColor: '#fff',
            pointBorderWidth: 2,
            pointRadius: 4
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: false
            },
            tooltip: {
                backgroundColor: '#1e293b',
                titleColor: '#fff',
                bodyColor: '#fff'
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                grid: {
                    display: true,
                    color: 'rgba(0,0,0,0.05)'
                },
                ticks: {
                    stepSize: 1
                }
            },
            x: {
                grid: {
                    display: false
                },
                ticks: {
                    maxRotation: 45,
                    minRotation: 45
                }
            }
        }
    }
});

// Permission chart
const permCtx = document.getElementById('permChart').getContext('2d');
new Chart(permCtx, {
    type: 'doughnut',
    data: {
        labels: <?= json_encode($permLabels, JSON_UNESCAPED_SLASHES) ?>,
        datasets: [{
            data: <?= json_encode($permCounts, JSON_UNESCAPED_SLASHES) ?>,
            backgroundColor: ['#06d6a0', '#ffb703', '#ef476f'],
            borderWidth: 0
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'bottom',
                labels: {
                    padding: 20,
                    font: {
                        size: 12
                    }
                }
            }
        },
        cutout: '70%'
    }
});
</script>

<?php require_once __DIR__ . "/partials/footer.php"; ?>