<?php
session_start();

// Validasi session
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    header("Location: ../../index.html?error=session");
    exit;
}

$userRole = strtoupper(trim($_SESSION['role'] ?? ''));
if ($userRole !== 'M' && $userRole !== 'A') {
    header("Location: ../../index.html?error=forbidden");
    exit;
}

// Configuration
$currentMonth = 'JANUARI';
$tahunAjaran = '2024-2025';
$kategoriSiswa = 'SEMUA';

// Data list sekolah
$sekolahList = [
    'SDJ BATAM', 'SDJ CILEGON', 'SDJ JAKBAR', 'SDJ JAKSEL', 
    'SDJ JAKTIM', 'SDJ JAKUT', 'SDJ JAYAPURA', 'SDJ MEDAN',
    'SDJ SEMARANG', 'SDJ SURABAYA', 'SDJ TANGERANG', 'SDJ YOGYAKARTA', 'TKIT TANGERANG'
];

// Data SPP per sekolah untuk 3 TA
$dataSPP = [
    [
        'sekolah' => 'SDJ BATAM',
        'ta_2019' => 885404167,
        'capaian_2019' => 868578000,
        'ta_2021' => 9750000,
        'capaian_2021' => 9750000,
        'ta_2024' => 180000000,
        'capaian_2024' => 176400000
    ],
    [
        'sekolah' => 'SDJ CILEGON',
        'ta_2019' => 1074937500,
        'capaian_2019' => 1074551000,
        'ta_2021' => 16650000,
        'capaian_2021' => 16649000,
        'ta_2024' => 220000000,
        'capaian_2024' => 220000000
    ],
    [
        'sekolah' => 'SDJ JAKBAR',
        'ta_2019' => 1170005000,
        'capaian_2019' => 1034265000,
        'ta_2021' => 20200000,
        'capaian_2021' => 20200000,
        'ta_2024' => 240000000,
        'capaian_2024' => 211200000
    ],
    [
        'sekolah' => 'SDJ JAKSEL',
        'ta_2019' => 940940000,
        'capaian_2019' => 859316000,
        'ta_2021' => 14884000,
        'capaian_2021' => 14890000,
        'ta_2024' => 190000000,
        'capaian_2024' => 172900000
    ],
    [
        'sekolah' => 'SDJ JAKTIM',
        'ta_2019' => 1052442750,
        'capaian_2019' => 1054475329,
        'ta_2021' => 10686000,
        'capaian_2021' => 10907004,
        'ta_2024' => 210000000,
        'capaian_2024' => 210000000
    ],
    [
        'sekolah' => 'SDJ JAKUT',
        'ta_2019' => 799533333,
        'capaian_2019' => 755955001,
        'ta_2021' => 3800000,
        'capaian_2021' => 3800000,
        'ta_2024' => 160000000,
        'capaian_2024' => 152000000
    ],
    [
        'sekolah' => 'SDJ JAYAPURA',
        'ta_2019' => 543552083,
        'capaian_2019' => 516650000,
        'ta_2021' => 13500000,
        'capaian_2021' => 10500000,
        'ta_2024' => 110000000,
        'capaian_2024' => 104500000
    ],
    [
        'sekolah' => 'SDJ MEDAN',
        'ta_2019' => 1475259500,
        'capaian_2019' => 1446951000,
        'ta_2021' => 18183000,
        'capaian_2021' => 18563000,
        'ta_2024' => 295000000,
        'capaian_2024' => 289100000
    ],
    [
        'sekolah' => 'SDJ SEMARANG',
        'ta_2019' => 415250000,
        'capaian_2019' => 416892000,
        'ta_2021' => 9700000,
        'capaian_2021' => 9700000,
        'ta_2024' => 83000000,
        'capaian_2024' => 83000000
    ],
    [
        'sekolah' => 'SDJ SURABAYA',
        'ta_2019' => 1061167583,
        'capaian_2019' => 1008501000,
        'ta_2021' => 12098000,
        'capaian_2021' => 11540500,
        'ta_2024' => 212000000,
        'capaian_2024' => 201400000
    ],
    [
        'sekolah' => 'SDJ TANGERANG',
        'ta_2019' => 1023725000,
        'capaian_2019' => 1020059000,
        'ta_2021' => 2100000,
        'capaian_2021' => 2100000,
        'ta_2024' => 205000000,
        'capaian_2024' => 205000000
    ],
    [
        'sekolah' => 'SDJ YOGYAKARTA',
        'ta_2019' => 0,
        'capaian_2019' => 0,
        'ta_2021' => 0,
        'capaian_2021' => 0,
        'ta_2024' => 0,
        'capaian_2024' => 0
    ],
    [
        'sekolah' => 'TKIT TANGERANG',
        'ta_2019' => 0,
        'capaian_2019' => 0,
        'ta_2021' => 0,
        'capaian_2021' => 0,
        'ta_2024' => 0,
        'capaian_2024' => 0
    ],
];

// Data DKT per sekolah
$dataDKT = [
    ['sekolah' => 'SDJ BATAM', 'target' => 80000000, 'capaian' => 76000000],
    ['sekolah' => 'SDJ CILEGON', 'target' => 100000000, 'capaian' => 100000000],
    ['sekolah' => 'SDJ JAKBAR', 'target' => 120000000, 'capaian' => 105600000],
    ['sekolah' => 'SDJ JAKSEL', 'target' => 95000000, 'capaian' => 86450000],
    ['sekolah' => 'SDJ JAKTIM', 'target' => 105000000, 'capaian' => 105000000],
    ['sekolah' => 'SDJ JAKUT', 'target' => 80000000, 'capaian' => 76000000],
    ['sekolah' => 'SDJ JAYAPURA', 'target' => 55000000, 'capaian' => 52250000],
    ['sekolah' => 'SDJ MEDAN', 'target' => 147000000, 'capaian' => 144060000],
    ['sekolah' => 'SDJ SEMARANG', 'target' => 42000000, 'capaian' => 42000000],
    ['sekolah' => 'SDJ SURABAYA', 'target' => 106000000, 'capaian' => 100700000],
    ['sekolah' => 'SDJ TANGERANG', 'target' => 102000000, 'capaian' => 102000000],
    ['sekolah' => 'SDJ YOGYAKARTA', 'target' => 0, 'capaian' => 0],
    ['sekolah' => 'TKIT TANGERANG', 'target' => 0, 'capaian' => 0],
];

// Data pembayaran bulanan
$dataBulanan = [
    ['bulan' => 'Juli', 'target' => 5000000, 'capaian' => 4750000, 'persentase' => 95],
    ['bulan' => 'Agustus', 'target' => 5000000, 'capaian' => 4600000, 'persentase' => 92],
    ['bulan' => 'September', 'target' => 5000000, 'capaian' => 4400000, 'persentase' => 88],
    ['bulan' => 'Oktober', 'target' => 5000000, 'capaian' => 4500000, 'persentase' => 90],
    ['bulan' => 'November', 'target' => 5000000, 'capaian' => 4750000, 'persentase' => 95],
    ['bulan' => 'Desember', 'target' => 5000000, 'capaian' => 4850000, 'persentase' => 97],
    ['bulan' => 'Januari', 'target' => 5000000, 'capaian' => 4550000, 'persentase' => 91],
    ['bulan' => 'Februari', 'target' => 5000000, 'capaian' => 4650000, 'persentase' => 93],
    ['bulan' => 'Maret', 'target' => 5000000, 'capaian' => 4700000, 'persentase' => 94],
    ['bulan' => 'April', 'target' => 5000000, 'capaian' => 4600000, 'persentase' => 92],
    ['bulan' => 'Mei', 'target' => 5000000, 'capaian' => 4750000, 'persentase' => 95],
    ['bulan' => 'Juni', 'target' => 5000000, 'capaian' => 4800000, 'persentase' => 96],
];

// Data analisa tunggakan per kelas
$dataTunggakan = [
    ['kelas' => 'KELAS 1', '1_bulan' => 5, '2_bulan' => 3, '3_bulan' => 2, '4_bulan' => 1, '5_bulan' => 0, '6_bulan' => 1],
    ['kelas' => 'KELAS 2', '1_bulan' => 4, '2_bulan' => 2, '3_bulan' => 1, '4_bulan' => 0, '5_bulan' => 1, '6_bulan' => 0],
    ['kelas' => 'KELAS 3', '1_bulan' => 6, '2_bulan' => 4, '3_bulan' => 2, '4_bulan' => 1, '5_bulan' => 0, '6_bulan' => 1],
    ['kelas' => 'KELAS 4', '1_bulan' => 3, '2_bulan' => 2, '3_bulan' => 1, '4_bulan' => 1, '5_bulan' => 0, '6_bulan' => 0],
    ['kelas' => 'KELAS 5', '1_bulan' => 5, '2_bulan' => 3, '3_bulan' => 2, '4_bulan' => 0, '5_bulan' => 1, '6_bulan' => 1],
    ['kelas' => 'KELAS 6', '1_bulan' => 4, '2_bulan' => 2, '3_bulan' => 1, '4_bulan' => 1, '5_bulan' => 0, '6_bulan' => 0],
];

// Calculate totals for TA 2024-2025
$totalTarget_2024 = array_sum(array_column($dataSPP, 'ta_2024'));
$totalCapaian_2024 = array_sum(array_column($dataSPP, 'capaian_2024'));
$totalPiutang_2024 = $totalTarget_2024 - $totalCapaian_2024;
$persentase_2024 = $totalTarget_2024 > 0 ? round(($totalCapaian_2024 / $totalTarget_2024) * 100, 1) : 0;

// Calculate DKT totals
$totalTargetDKT = array_sum(array_column($dataDKT, 'target'));
$totalCapaianDKT = array_sum(array_column($dataDKT, 'capaian'));
$totalPiutangDKT = $totalTargetDKT - $totalCapaianDKT;
$persentaseDKT = $totalTargetDKT > 0 ? round(($totalCapaianDKT / $totalTargetDKT) * 100, 1) : 0;

// Helper Functions
function getCategory($persentase) {
    if ($persentase >= 95) return 'EXCELLENT';
    if ($persentase >= 80) return 'GOOD';
    if ($persentase >= 65) return 'AVERAGE';
    return 'POOR';
}

function getCategoryClass($persentase) {
    if ($persentase >= 95) return 'excellent';
    if ($persentase >= 80) return 'good';
    if ($persentase >= 65) return 'average';
    return 'poor';
}

$kategori_2024 = getCategory($persentase_2024);
$kategoriDKT = getCategory($persentaseDKT);

// Count categories
$excellent = count(array_filter($dataSPP, fn($d) => $d['ta_2024'] > 0 && round(($d['capaian_2024'] / $d['ta_2024']) * 100) >= 95));
$good = count(array_filter($dataSPP, fn($d) => $d['ta_2024'] > 0 && round(($d['capaian_2024'] / $d['ta_2024']) * 100) >= 80 && round(($d['capaian_2024'] / $d['ta_2024']) * 100) < 95));
$average = count(array_filter($dataSPP, fn($d) => $d['ta_2024'] > 0 && round(($d['capaian_2024'] / $d['ta_2024']) * 100) >= 65 && round(($d['capaian_2024'] / $d['ta_2024']) * 100) < 80));
$poor = count(array_filter($dataSPP, fn($d) => $d['ta_2024'] > 0 && round(($d['capaian_2024'] / $d['ta_2024']) * 100) < 65));

// Total tunggakan
$totalTunggakan = array_sum(array_map(function($row) {
    return $row['1_bulan'] + $row['2_bulan'] + $row['3_bulan'] + $row['4_bulan'] + $row['5_bulan'] + $row['6_bulan'];
}, $dataTunggakan));
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Kepatuhan Bayar - ACF EDU HUB</title>
    
    <!-- External CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <style>
        :root {
            --primary: #6366f1;
            --secondary: #8b5cf6;
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
            --info: #3b82f6;
            --excellent: #10b981;
            --good: #3b82f6;
            --average: #f59e0b;
            --poor: #ef4444;
            --light: #f8fafc;
            --dark: #1e293b;
            --border: #e2e8f0;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: var(--light);
            color: var(--dark);
            padding: 24px;
            line-height: 1.6;
        }

        .container {
            max-width: 1800px;
            margin: 0 auto;
        }

        .dashboard-header {
            background: white;
            padding: 24px;
            border-radius: 16px;
            margin-bottom: 24px;
            border: 1px solid var(--border);
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
        }

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

        .dashboard-header h1 {
            font-size: 28px;
            font-weight: 800;
            color: var(--dark);
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .header-filters {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            align-items: center;
        }

        .dropdown-container {
            position: relative;
            display: inline-block;
        }

        .dropdown-toggle {
            background: white;
            border: 2px solid var(--border);
            padding: 10px 16px;
            border-radius: 10px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            font-family: 'Inter', sans-serif;
            font-size: 14px;
            font-weight: 600;
            color: var(--dark);
            transition: all 0.3s ease;
            white-space: nowrap;
            min-width: 180px;
        }

        .dropdown-toggle:hover {
            border-color: var(--primary);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(99, 102, 241, 0.2);
        }

        .dropdown-container.active .dropdown-toggle {
            border-color: var(--primary);
            background: rgba(99, 102, 241, 0.05);
        }

        .dropdown-menu {
            position: absolute;
            top: calc(100% + 8px);
            right: 0;
            background: white;
            border-radius: 16px;
            padding: 12px;
            min-width: 280px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.25);
            opacity: 0;
            visibility: hidden;
            transform: translateY(-10px);
            transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
            z-index: 1000;
            border: 1px solid var(--border);
        }

        .dropdown-container.active .dropdown-menu {
            opacity: 1;
            visibility: visible;
            transform: translateY(0);
        }

        .dropdown-header {
            padding: 12px;
            border-bottom: 1px solid var(--border);
            margin-bottom: 8px;
        }

        .dropdown-header h4 {
            font-size: 13px;
            font-weight: 700;
            color: var(--dark);
            margin-bottom: 4px;
        }

        .dropdown-section {
            padding: 4px 0;
        }

        .dropdown-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px 12px;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
            text-decoration: none;
            color: var(--dark);
        }

        .dropdown-item:hover {
            background: linear-gradient(135deg, rgba(99, 102, 241, 0.08) 0%, rgba(139, 92, 246, 0.08) 100%);
            transform: translateX(4px);
        }

        .dropdown-item-left {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .dropdown-text {
            font-size: 13px;
            font-weight: 600;
        }

        .tabs {
            display: flex;
            gap: 8px;
            border-bottom: 2px solid var(--border);
        }

        .tab-btn {
            padding: 12px 24px;
            border: none;
            background: transparent;
            font-size: 14px;
            font-weight: 700;
            color: #64748b;
            cursor: pointer;
            border-bottom: 3px solid transparent;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .tab-btn:hover {
            color: var(--primary);
            background: var(--light);
        }

        .tab-btn.active {
            color: var(--primary);
            border-bottom-color: var(--primary);
        }

        .tab-content {
            display: none;
            animation: fadeIn 0.3s ease;
        }

        .tab-content.active {
            display: block;
        }

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

        .info-box {
            background: linear-gradient(135deg, rgba(99, 102, 241, 0.1) 0%, rgba(139, 92, 246, 0.1) 100%);
            border-radius: 16px;
            padding: 24px;
            margin-bottom: 24px;
            border: 1px solid rgba(99, 102, 241, 0.2);
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin: 24px 0;
        }

        .stat-card {
            background: white;
            border-radius: 16px;
            padding: 24px;
            border: 1px solid var(--border);
            position: relative;
            overflow: hidden;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
        }

        .stat-card.spp::before { background: var(--primary); }
        .stat-card.dkt::before { background: var(--info); }
        .stat-card.excellent::before { background: var(--excellent); }
        .stat-card.tunggakan::before { background: var(--danger); }

        .stat-label {
            font-size: 12px;
            font-weight: 700;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 12px;
        }

        .stat-value {
            font-size: 32px;
            font-weight: 800;
            color: var(--dark);
            margin-bottom: 8px;
        }

        .badge {
            padding: 4px 12px;
            border-radius: 6px;
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
            display: inline-block;
        }

        .badge-excellent { background: #d1fae5; color: #065f46; }
        .badge-good { background: #dbeafe; color: #1e40af; }
        .badge-average { background: #fef3c7; color: #92400e; }
        .badge-poor { background: #fee2e2; color: #991b1b; }

        .chart-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
            margin-bottom: 24px;
        }

        .chart-card {
            background: white;
            border-radius: 16px;
            padding: 24px;
            border: 1px solid var(--border);
        }

        .chart-card.full {
            grid-column: 1 / -1;
        }

        .chart-title {
            font-size: 14px;
            font-weight: 700;
            color: #64748b;
            margin-bottom: 16px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .chart-container {
            position: relative;
            height: 300px;
        }

        .table-card {
            background: white;
            border-radius: 16px;
            border: 1px solid var(--border);
            overflow: hidden;
            margin-bottom: 24px;
        }

        .table-wrapper {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 800px;
        }

        thead th {
            background: var(--light);
            padding: 14px 16px;
            text-align: left;
            font-size: 11px;
            font-weight: 700;
            color: #64748b;
            text-transform: uppercase;
            border-bottom: 2px solid var(--border);
        }

        tbody td {
            padding: 16px;
            border-bottom: 1px solid var(--border);
            font-size: 14px;
        }

        tbody tr:hover {
            background: var(--light);
        }

        .progress-bar {
            width: 100%;
            height: 8px;
            background: var(--border);
            border-radius: 4px;
            overflow: hidden;
            margin-top: 4px;
        }

        .progress-fill {
            height: 100%;
            border-radius: 4px;
            transition: width 0.3s ease;
        }

        .progress-fill.excellent { background: var(--excellent); }
        .progress-fill.good { background: var(--good); }
        .progress-fill.average { background: var(--average); }
        .progress-fill.poor { background: var(--poor); }

        .btn {
            padding: 10px 20px;
            border-radius: 10px;
            font-weight: 700;
            font-size: 14px;
            border: none;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            text-decoration: none;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: var(--primary);
            color: white;
        }

        .btn-primary:hover {
            background: #4f46e5;
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(99, 102, 241, 0.4);
        }

        .btn-success {
            background: var(--success);
            color: white;
        }

        .btn-sm {
            padding: 8px 16px;
            font-size: 13px;
        }

        @media (max-width: 768px) {
            body { padding: 12px; }
            .dashboard-header { padding: 16px; }
            .chart-grid { grid-template-columns: 1fr; }
            .stats-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="dashboard-header">
            <div class="header-top">
                <div>
                    <h1>
                        <i class="fas fa-chart-line" style="color: var(--primary);"></i>
                        Dashboard Kepatuhan Bayar
                    </h1>
                    <p style="color: #64748b; font-size: 14px;">
                        Monitoring komprehensif pembayaran SPP, DKT, DSP & Biaya Lainnya
                    </p>
                </div>

                <div class="header-filters">
                    <div class="dropdown-container" id="taDropdown">
                        <button class="dropdown-toggle" onclick="toggleDropdown('taDropdown')">
                            <i class="fas fa-graduation-cap"></i>
                            <span id="selectedTA">TA: <?= $tahunAjaran ?></span>
                            <i class="fas fa-chevron-down" style="font-size: 10px;"></i>
                        </button>
                        <div class="dropdown-menu">
                            <div class="dropdown-header">
                                <h4>Pilih Tahun Ajaran</h4>
                            </div>
                            <div class="dropdown-section">
                                <a href="#" class="dropdown-item" onclick="selectTA('2024-2025'); return false;">
                                    <div class="dropdown-item-left">
                                        <span class="dropdown-text">TA 2024-2025</span>
                                    </div>
                                </a>
                                <a href="#" class="dropdown-item" onclick="selectTA('2023-2024'); return false;">
                                    <div class="dropdown-item-left">
                                        <span class="dropdown-text">TA 2023-2024</span>
                                    </div>
                                </a>
                            </div>
                        </div>
                    </div>

                    <button class="btn btn-primary" onclick="location.reload()">
                        <i class="fas fa-sync-alt"></i>
                        Refresh
                    </button>
                </div>
            </div>

            <div class="tabs">
                <button class="tab-btn active" onclick="switchTab('overview', event)">
                    <i class="fas fa-chart-pie"></i>
                    <span>Overview</span>
                </button>
                <button class="tab-btn" onclick="switchTab('spp', event)">
                    <i class="fas fa-money-bill-wave"></i>
                    <span>SPP</span>
                </button>
                <button class="tab-btn" onclick="switchTab('dkt', event)">
                    <i class="fas fa-clipboard-list"></i>
                    <span>DKT & Lainnya</span>
                </button>
            </div>
        </div>

        <!-- TAB: OVERVIEW -->
        <div id="overview" class="tab-content active">
            <div class="info-box">
                <h3 style="font-size: 18px; font-weight: 800; margin-bottom: 12px;">Tentang Dashboard</h3>
                <p style="font-size: 14px; line-height: 1.7; color: #475569;">
                    Dashboard ini menyediakan monitoring komprehensif terhadap pembayaran SPP, DKT, dan biaya lainnya.
                </p>
            </div>

            <div class="stats-grid">
                <div class="stat-card spp">
                    <div class="stat-label">Total Target SPP</div>
                    <div class="stat-value">Rp <?= number_format($totalTarget_2024, 0, ',', '.') ?></div>
                    <span class="badge badge-<?= strtolower($kategori_2024) ?>"><?= $kategori_2024 ?></span>
                </div>

                <div class="stat-card dkt">
                    <div class="stat-label">Total Target DKT</div>
                    <div class="stat-value">Rp <?= number_format($totalTargetDKT, 0, ',', '.') ?></div>
                    <span class="badge badge-<?= strtolower($kategoriDKT) ?>"><?= $kategoriDKT ?></span>
                </div>

                <div class="stat-card excellent">
                    <div class="stat-label">Total Capaian</div>
                    <div class="stat-value" style="color: var(--success);">Rp <?= number_format($totalCapaian_2024 + $totalCapaianDKT, 0, ',', '.') ?></div>
                </div>

                <div class="stat-card tunggakan">
                    <div class="stat-label">Siswa Menunggak</div>
                    <div class="stat-value" style="color: var(--danger);"><?= $totalTunggakan ?></div>
                </div>
            </div>

            <div class="chart-grid">
                <div class="chart-card">
                    <div class="chart-title">Trend Pembayaran</div>
                    <div class="chart-container">
                        <canvas id="trendChart"></canvas>
                    </div>
                </div>

                <div class="chart-card">
                    <div class="chart-title">SPP vs DKT</div>
                    <div class="chart-container">
                        <canvas id="comparisonChart"></canvas>
                    </div>
                </div>

                <div class="chart-card full">
                    <div class="chart-title">Kepatuhan per Sekolah</div>
                    <div class="chart-container">
                        <canvas id="schoolChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- TAB: SPP -->
        <div id="spp" class="tab-content">
            <div class="table-card">
                <div class="table-wrapper">
                    <table>
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Sekolah</th>
                                <th>Target</th>
                                <th>Capaian</th>
                                <th>%</th>
                                <th>Kategori</th>
                                <th style="min-width: 150px;">Progress</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $no = 1;
                            foreach($dataSPP as $row): 
                                if ($row['ta_2024'] == 0) continue;
                                $persen = round(($row['capaian_2024'] / $row['ta_2024']) * 100, 1);
                                $kategori = getCategory($persen);
                                $progressClass = getCategoryClass($persen);
                            ?>
                            <tr>
                                <td><?= $no++ ?></td>
                                <td><strong><?= htmlspecialchars($row['sekolah']) ?></strong></td>
                                <td>Rp <?= number_format($row['ta_2024'], 0, ',', '.') ?></td>
                                <td style="color: var(--success);">Rp <?= number_format($row['capaian_2024'], 0, ',', '.') ?></td>
                                <td><strong><?= $persen ?>%</strong></td>
                                <td>
                                    <span class="badge badge-<?= strtolower($kategori) ?>"><?= $kategori ?></span>
                                </td>
                                <td>
                                    <div class="progress-bar">
                                        <div class="progress-fill <?= $progressClass ?>" style="width: <?= $persen ?>%"></div>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- TAB: DKT -->
        <div id="dkt" class="tab-content">
            <div class="table-card">
                <div class="table-wrapper">
                    <table>
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Sekolah</th>
                                <th>Target DKT</th>
                                <th>Capaian DKT</th>
                                <th>%</th>
                                <th>Kategori</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $no = 1;
                            foreach($dataDKT as $row): 
                                if ($row['target'] == 0) continue;
                                $persen = round(($row['capaian'] / $row['target']) * 100, 1);
                                $kategori = getCategory($persen);
                            ?>
                            <tr>
                                <td><?= $no++ ?></td>
                                <td><strong><?= htmlspecialchars($row['sekolah']) ?></strong></td>
                                <td>Rp <?= number_format($row['target'], 0, ',', '.') ?></td>
                                <td style="color: var(--success);">Rp <?= number_format($row['capaian'], 0, ',', '.') ?></td>
                                <td><strong><?= $persen ?>%</strong></td>
                                <td>
                                    <span class="badge badge-<?= strtolower($kategori) ?>"><?= $kategori ?></span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        // ========================================
        // CHART.JS CONFIGURATION
        // ========================================
        Chart.defaults.font.family = 'Inter';
        Chart.defaults.font.size = 12;
        Chart.defaults.color = '#64748b';

        // ========================================
        // DROPDOWN FUNCTIONALITY - FIXED
        // ========================================
        function toggleDropdown(id) {
            console.log('toggleDropdown called:', id);
            
            const dropdown = document.getElementById(id);
            if (!dropdown) {
                console.error('Dropdown not found:', id);
                return;
            }
            
            const allDropdowns = document.querySelectorAll('.dropdown-container');
            
            allDropdowns.forEach(d => {
                if (d.id !== id) {
                    d.classList.remove('active');
                }
            });
            
            dropdown.classList.toggle('active');
            
            // FIXED: Proper event handling
            if (window.event) {
                window.event.stopPropagation();
            }
        }

        // Close dropdowns when clicking outside
        document.addEventListener('click', function(event) {
            if (!event.target.closest('.dropdown-container')) {
                document.querySelectorAll('.dropdown-container').forEach(d => {
                    d.classList.remove('active');
                });
            }
        });

        // ========================================
        // FILTER FUNCTIONS - FIXED
        // ========================================
        function selectTA(ta) {
            console.log('selectTA called:', ta);
            const selectedElement = document.getElementById('selectedTA');
            if (selectedElement) {
                selectedElement.textContent = 'TA: ' + ta;
            }
            
            const dropdown = document.getElementById('taDropdown');
            if (dropdown) {
                dropdown.classList.remove('active');
            }
            
            alert('Filter TA ' + ta + ' diterapkan');
        }

        // ========================================
        // TAB SWITCHING - FIXED
        // ========================================
        function switchTab(tabName, evt) {
            console.log('switchTab called:', tabName);
            
            // Hide all tabs
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // Remove active class from all buttons
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.classList.remove('active');
            });

            // Show selected tab
            const selectedTab = document.getElementById(tabName);
            if (selectedTab) {
                selectedTab.classList.add('active');
            }
            
            // Add active class to clicked button
            if (evt && evt.currentTarget) {
                evt.currentTarget.classList.add('active');
            }
        }

        // ========================================
        // CHARTS INITIALIZATION
        // ========================================
        
        // Trend Chart
        const trendCtx = document.getElementById('trendChart');
        new Chart(trendCtx, {
            type: 'line',
            data: {
                labels: [<?php echo "'" . implode("','", array_column($dataBulanan, 'bulan')) . "'"; ?>],
                datasets: [{
                    label: 'Persentase Kepatuhan',
                    data: [<?php echo implode(',', array_column($dataBulanan, 'persentase')); ?>],
                    borderColor: '#8b5cf6',
                    backgroundColor: 'rgba(139, 92, 246, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } }
            }
        });

        // Comparison Chart
        const comparisonCtx = document.getElementById('comparisonChart');
        new Chart(comparisonCtx, {
            type: 'doughnut',
            data: {
                labels: ['SPP', 'DKT', 'Piutang'],
                datasets: [{
                    data: [<?= $totalCapaian_2024 ?>, <?= $totalCapaianDKT ?>, <?= $totalPiutang_2024 + $totalPiutangDKT ?>],
                    backgroundColor: ['#8b5cf6', '#3b82f6', '#ef4444']
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false
            }
        });

        // School Chart
        const schoolCtx = document.getElementById('schoolChart');
        new Chart(schoolCtx, {
            type: 'bar',
            data: {
                labels: [<?php echo "'" . implode("','", array_column($dataSPP, 'sekolah')) . "'"; ?>],
                datasets: [
                    {
                        label: 'Target',
                        data: [<?php echo implode(',', array_column($dataSPP, 'ta_2024')); ?>],
                        backgroundColor: '#cbd5e1'
                    },
                    {
                        label: 'Capaian',
                        data: [<?php echo implode(',', array_column($dataSPP, 'capaian_2024')); ?>],
                        backgroundColor: '#8b5cf6'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false
            }
        });

        console.log('Dashboard loaded successfully!');
    </script>
</body>
</html>