<?php
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();

// Validasi session - COMMENTED OUT FOR TESTING
/*
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
    ],
];

// 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],
];

// 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],
];

// Data tunggakan
$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],
];

// Calculate totals
$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;

$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);

$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));

$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 - DEBUG MODE</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;
            --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;
        }

        /* DEBUG BANNER */
        .debug-banner {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: white;
            padding: 12px 24px;
            text-align: center;
            font-weight: 700;
            z-index: 10000;
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
        }

        .debug-console {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: #1e293b;
            color: #10b981;
            padding: 12px 24px;
            max-height: 200px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            z-index: 9999;
            border-top: 3px solid #10b981;
        }

        .debug-console-item {
            padding: 4px 0;
            border-bottom: 1px solid #334155;
        }

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

        .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-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);
            display: none;
        }

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

        .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);
        }

        .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);
        }

        .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;
        }

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

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

        .tab-content {
            display: none;
        }

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

        .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);
        }

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

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

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

        .badge-excellent { background: #d1fae5; color: #065f46; }
        .badge-good { background: #dbeafe; color: #1e40af; }
        .badge-average { background: #fef3c7; color: #92400e; }
        .badge-poor { background: #fee2e2; color: #991b1b; }
    </style>
</head>
<body>
    <!-- DEBUG BANNER -->
    <div class="debug-banner">
        <i class="fas fa-bug"></i> DEBUG MODE ACTIVE - Click events will be logged to console below
    </div>

    <!-- DEBUG CONSOLE -->
    <div class="debug-console" id="debugConsole">
        <div class="debug-console-item">[INIT] Dashboard loaded - Waiting for interactions...</div>
    </div>

    <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 (DEBUG)
                    </h1>
                    <p style="color: #64748b; font-size: 14px;">
                        Test mode untuk debugging click events
                    </p>
                </div>

                <div class="header-filters">
                    <!-- Filter Tahun Ajaran -->
                    <div class="dropdown-container" id="taDropdown">
                        <button class="dropdown-toggle" onclick="debugLog('TA Dropdown clicked'); toggleDropdown('taDropdown')">
                            <i class="fas fa-graduation-cap"></i>
                            <span id="selectedTA">TA: <?= $tahunAjaran ?></span>
                            <i class="fas fa-chevron-down"></i>
                        </button>
                        <div class="dropdown-menu">
                            <a href="#" class="dropdown-item" onclick="debugLog('TA 2024-2025 selected'); selectTA('2024-2025'); return false;">
                                <span>TA 2024-2025</span>
                            </a>
                            <a href="#" class="dropdown-item" onclick="debugLog('TA 2023-2024 selected'); selectTA('2023-2024'); return false;">
                                <span>TA 2023-2024</span>
                            </a>
                        </div>
                    </div>

                    <!-- Refresh Button -->
                    <button class="btn btn-primary" onclick="debugLog('Refresh clicked'); location.reload()">
                        <i class="fas fa-sync-alt"></i>
                        Refresh
                    </button>
                </div>
            </div>

            <!-- Tabs -->
            <div class="tabs">
                <button class="tab-btn active" onclick="debugLog('Overview tab clicked'); switchTab('overview', event)">
                    <i class="fas fa-chart-pie"></i>
                    <span>Overview</span>
                </button>
                <button class="tab-btn" onclick="debugLog('SPP tab clicked'); switchTab('spp', event)">
                    <i class="fas fa-money-bill-wave"></i>
                    <span>SPP</span>
                </button>
            </div>
        </div>

        <!-- TAB: OVERVIEW -->
        <div id="overview" class="tab-content active">
            <div class="stats-grid">
                <div class="stat-card">
                    <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">
                    <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>
        </div>

        <!-- TAB: SPP -->
        <div id="spp" class="tab-content">
            <h2 style="padding: 24px; background: white; border-radius: 16px;">
                Data SPP per Sekolah
            </h2>
        </div>
    </div>

    <script>
        // Debug logging function
        function debugLog(message) {
            const console = document.getElementById('debugConsole');
            const timestamp = new Date().toLocaleTimeString();
            const item = document.createElement('div');
            item.className = 'debug-console-item';
            item.innerHTML = `[${timestamp}] ${message}`;
            console.appendChild(item);
            console.scrollTop = console.scrollHeight;
            
            // Also log to browser console
            console.log(`[DEBUG] ${message}`);
        }

        // Log all clicks on document
        document.addEventListener('click', function(e) {
            debugLog(`Click detected on: ${e.target.tagName} - ${e.target.className}`);
        });

        // Toggle dropdown function with extensive logging
        function toggleDropdown(id) {
            debugLog(`toggleDropdown called with id: ${id}`);
            
            const dropdown = document.getElementById(id);
            if (!dropdown) {
                debugLog(`ERROR: Dropdown ${id} not found!`);
                return;
            }
            
            debugLog(`Dropdown found: ${id}`);
            
            const allDropdowns = document.querySelectorAll('.dropdown-container');
            debugLog(`Total dropdowns found: ${allDropdowns.length}`);
            
            allDropdowns.forEach(d => {
                if (d.id !== id) {
                    d.classList.remove('active');
                    debugLog(`Removed active from: ${d.id}`);
                }
            });
            
            const wasActive = dropdown.classList.contains('active');
            dropdown.classList.toggle('active');
            debugLog(`Dropdown ${id} toggled - Now ${wasActive ? 'inactive' : 'ACTIVE'}`);
            
            // Stop event propagation
            if (window.event) {
                window.event.stopPropagation();
                debugLog('Event propagation stopped');
            }
        }

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

        // Select TA function
        function selectTA(ta) {
            debugLog(`selectTA called with: ${ta}`);
            
            const selectedElement = document.getElementById('selectedTA');
            if (selectedElement) {
                selectedElement.textContent = 'TA: ' + ta;
                debugLog(`Updated selectedTA text to: TA: ${ta}`);
            } else {
                debugLog('ERROR: selectedTA element not found!');
            }
            
            const dropdown = document.getElementById('taDropdown');
            if (dropdown) {
                dropdown.classList.remove('active');
                debugLog('Closed taDropdown');
            }
        }

        // Switch tab function with proper event handling
        function switchTab(tabName, event) {
            debugLog(`switchTab called with: ${tabName}`);
            
            // Hide all tabs
            const allTabs = document.querySelectorAll('.tab-content');
            debugLog(`Found ${allTabs.length} tab contents`);
            
            allTabs.forEach(tab => {
                tab.classList.remove('active');
            });
            
            // Remove active from all buttons
            const allButtons = document.querySelectorAll('.tab-btn');
            debugLog(`Found ${allButtons.length} tab buttons`);
            
            allButtons.forEach(btn => {
                btn.classList.remove('active');
            });

            // Show selected tab
            const selectedTab = document.getElementById(tabName);
            if (selectedTab) {
                selectedTab.classList.add('active');
                debugLog(`Activated tab: ${tabName}`);
            } else {
                debugLog(`ERROR: Tab ${tabName} not found!`);
            }
            
            // Add active to clicked button
            if (event && event.currentTarget) {
                event.currentTarget.classList.add('active');
                debugLog('Added active class to clicked button');
            }
        }

        // Log when DOM is ready
        document.addEventListener('DOMContentLoaded', function() {
            debugLog('DOM fully loaded and parsed');
            debugLog('Checking for jQuery: ' + (typeof jQuery !== 'undefined' ? 'YES' : 'NO'));
            debugLog('Checking for Chart.js: ' + (typeof Chart !== 'undefined' ? 'YES' : 'NO'));
            debugLog('Checking for Font Awesome: ' + (document.querySelector('.fa-chart-line') ? 'YES' : 'NO'));
        });

        // Log any JavaScript errors
        window.addEventListener('error', function(e) {
            debugLog(`JavaScript ERROR: ${e.message} at ${e.filename}:${e.lineno}`);
        });

        debugLog('All JavaScript loaded successfully');
    </script>
</body>
</html>