<?php
/**
 * ============================================================
 * DASHBOARD KEPATUHAN PEMBAYARAN - ADMIN PANEL
 * Modern Design with Tailwind CSS - WITH ACTIVE IMPORT
 * ============================================================
 */

/* ================= ERROR HANDLING ================= */
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('log_errors', '1');

/* ================= BASIC SETUP ================= */
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/* ================= PATH DETECTION ================= */
$possible_paths = [
    __DIR__ . '/../../DataBase/koneksi.php',
    __DIR__ . '/../../database/koneksi.php',
    __DIR__ . '/../../config/koneksi.php',
    __DIR__ . '/../../../DataBase/koneksi.php',

];

$connection_file = null;
foreach ($possible_paths as $path) {
    if (file_exists($path)) {
        $connection_file = $path;
        break;
    }
}

if (!$connection_file) {
    die("
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset='UTF-8'>
        <title>Error - Koneksi Database</title>
        <script src='https://cdn.tailwindcss.com'></script>
    </head>
    <body class='bg-gray-50 p-8'>
        <div class='max-w-2xl mx-auto bg-white rounded-2xl shadow-lg p-8 border-l-4 border-red-500'>
            <h1 class='text-2xl font-bold text-red-600 mb-4'>❌ Error: File Koneksi Database Tidak Ditemukan</h1>
            <p class='mb-4'>File koneksi database tidak ditemukan di lokasi manapun.</p>
            <a href='../../dashboard.php' class='inline-block px-6 py-3 bg-primary text-white rounded-lg hover:bg-primary-dark'>← Kembali ke Dashboard</a>
        </div>
    </body>
    </html>
    ");
}

/* ================= REQUIRE CONNECTION ================= */
require_once $connection_file;

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

if (!function_exists('checkRole')) {
    die("Error: Function checkRole() tidak ditemukan.");
}

checkRole(['A', 'ADMIN']);

$user_name = $_SESSION['full_name'] ?? $_SESSION['username'] ?? 'Admin';
$user_id = $_SESSION['user_id'] ?? 0;

/* ================= DATABASE CONNECTION CHECK ================= */
if (!isset($conn) || $conn->connect_error) {
    if (!defined('DB_HOST')) define('DB_HOST', 'localhost');
    if (!defined('DB_USER')) define('DB_USER', 'root');
    if (!defined('DB_PASS')) define('DB_PASS', '');
    if (!defined('DB_NAME')) define('DB_NAME', 'inventory_acf');
    
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        die("Database Connection Failed: " . $conn->connect_error);
    }
    $conn->set_charset('utf8mb4');
}

/* ================= HELPERS ================= */
function rupiah(float $n): string {
    return 'Rp ' . number_format($n, 0, ',', '.');
}

function persen(float $c, float $t): float {
    return $t > 0 ? round(($c / $t) * 100, 2) : 0;
}

function kategori(float $p): string {
    if ($p >= 95) return 'EXCELLENT';
    if ($p >= 85) return 'GOOD';
    if ($p >= 70) return 'AVERAGE';
    return 'POOR';
}

function getStatusColor(string $status): string {
    return match($status) {
        'EXCELLENT' => 'green',
        'GOOD' => 'blue',
        'AVERAGE' => 'amber',
        'POOR' => 'red',
        default => 'gray'
    };
}

/* ================= GET PERIODS ================= */
$periods = [];
try {
    $res = $conn->query("
        SELECT DISTINCT TRIM(period) period
        FROM kepatuhan_pembayaran
        WHERE UPPER(TRIM(month)) = 'TOTAL'
        ORDER BY period DESC
    ");

    if ($res) {
        while ($r = $res->fetch_assoc()) {
            $periods[] = $r['period'];
        }
    }
} catch (Exception $e) {
    error_log("Error fetching periods: " . $e->getMessage());
}

/* ================= STATE ================= */
$currentPeriod   = $_GET['period']   ?? ($periods[0] ?? '');
$currentCategory = strtoupper($_GET['category'] ?? 'ALL');

/* ================= ADMIN STATISTICS ================= */
$adminStats = [
    'total_sekolah' => 0,
    'total_kategori' => 0,
    'total_records' => 0,
    'last_update' => '-'
];

if (!empty($currentPeriod)) {
    try {
        $stmt = $conn->prepare("SELECT COUNT(DISTINCT ta) as total FROM kepatuhan_pembayaran WHERE TRIM(period) = ?");
        $stmt->bind_param("s", $currentPeriod);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result) {
            $adminStats['total_sekolah'] = $result->fetch_assoc()['total'] ?? 0;
        }
        $stmt->close();

        $stmt = $conn->prepare("SELECT COUNT(DISTINCT category) as total FROM kepatuhan_pembayaran WHERE TRIM(period) = ?");
        $stmt->bind_param("s", $currentPeriod);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result) {
            $adminStats['total_kategori'] = $result->fetch_assoc()['total'] ?? 0;
        }
        $stmt->close();

        $stmt = $conn->prepare("SELECT COUNT(*) as total FROM kepatuhan_pembayaran WHERE TRIM(period) = ?");
        $stmt->bind_param("s", $currentPeriod);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result) {
            $adminStats['total_records'] = $result->fetch_assoc()['total'] ?? 0;
        }
        $stmt->close();
    } catch (Exception $e) {
        error_log("Error fetching admin stats: " . $e->getMessage());
    }
}

/* ================= DATA QUERY ================= */
$rows = [];
$summary = [
    'total_target' => 0,
    'total_capaian' => 0,
    'total_piutang' => 0,
    'persen' => 0
];

if (!empty($currentPeriod)) {
    try {
        if ($currentCategory === 'ALL') {
            $stmt = $conn->prepare("
                SELECT
                    TRIM(ta) ta,
                    SUM(target) target,
                    SUM(capaian) capaian
                FROM kepatuhan_pembayaran
                WHERE TRIM(period) = ?
                  AND UPPER(TRIM(month)) = 'TOTAL'
                  AND UPPER(TRIM(category)) IN ('DSP','DKT','SPP','SERAGAM')
                GROUP BY TRIM(ta)
                ORDER BY ta
            ");
            $stmt->bind_param("s", $currentPeriod);
        } else {
            $stmt = $conn->prepare("
                SELECT
                    TRIM(ta) ta,
                    SUM(target) target,
                    SUM(capaian) capaian
                FROM kepatuhan_pembayaran
                WHERE TRIM(period) = ?
                  AND UPPER(TRIM(month)) = 'TOTAL'
                  AND UPPER(TRIM(category)) = ?
                GROUP BY TRIM(ta)
                ORDER BY ta
            ");
            $stmt->bind_param("ss", $currentPeriod, $currentCategory);
        }

        $stmt->execute();
        $res = $stmt->get_result();

        while ($r = $res->fetch_assoc()) {
            $target  = (float)$r['target'];
            $capaian = (float)$r['capaian'];
            $piutang = $target - $capaian;
            $persenVal = persen($capaian, $target);

            $rows[] = [
                'ta' => $r['ta'],
                'target' => $target,
                'capaian' => $capaian,
                'piutang' => $piutang,
                'persen' => $persenVal,
                'kategori' => kategori($persenVal)
            ];

            $summary['total_target']  += $target;
            $summary['total_capaian'] += $capaian;
            $summary['total_piutang'] += $piutang;
        }

        $summary['persen'] = persen(
            $summary['total_capaian'],
            $summary['total_target']
        );

        $stmt->close();
    } catch (Exception $e) {
        error_log("Error fetching data: " . $e->getMessage());
    }
}

/* ================= CATEGORY BREAKDOWN ================= */
$categoryBreakdown = [];
$categories = ['SPP', 'DKT', 'DSP', 'SERAGAM'];

if (!empty($currentPeriod)) {
    foreach ($categories as $cat) {
        try {
            $stmt = $conn->prepare("
                SELECT
                    SUM(target) as target,
                    SUM(capaian) as capaian
                FROM kepatuhan_pembayaran
                WHERE TRIM(period) = ?
                  AND UPPER(TRIM(month)) = 'TOTAL'
                  AND UPPER(TRIM(category)) = ?
            ");
            $stmt->bind_param("ss", $currentPeriod, $cat);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($row = $result->fetch_assoc()) {
                $target = (float)($row['target'] ?? 0);
                $capaian = (float)($row['capaian'] ?? 0);
                $categoryBreakdown[$cat] = [
                    'target' => $target,
                    'capaian' => $capaian,
                    'persen' => persen($capaian, $target)
                ];
            }
            $stmt->close();
        } catch (Exception $e) {
            error_log("Error fetching category $cat: " . $e->getMessage());
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Kepatuhan Pembayaran - ACF EDU HUB</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <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;900&display=swap" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#7AB2B2',
                        'primary-dark': '#4D869C',
                        'primary-light': '#CDE8E5',
                        accent: '#EEF7FF',
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        .stat-card {
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        .stat-card:hover {
            transform: translateY(-4px);
        }
    </style>
</head>
<body class="bg-gradient-to-br from-slate-50 via-blue-50 to-slate-100 min-h-screen font-sans">
    
    <div class="p-4 lg:p-6 max-w-[1600px] mx-auto">
        
        <!-- BACK BUTTON - FINAL -->
        <div class="mb-4">
            <a href="/inventoryACF/pages/admin/home_admin.php"
            class="inline-flex items-center gap-2 px-5 py-2.5 bg-white text-slate-700 rounded-xl font-semibold text-sm hover:shadow-lg hover:bg-slate-50 transition-all border border-slate-200">
                <i class="fas fa-arrow-left text-primary"></i>
                Kembali ke Dashboard Utama
            </a>
        </div>


        <?php if (empty($periods)): ?>
        <!-- Alert jika tidak ada data -->
        <div class="bg-amber-50 border-l-4 border-amber-500 rounded-xl p-4 mb-4">
            <div class="flex items-start gap-3">
                <div class="w-10 h-10 bg-amber-500 rounded-lg flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-exclamation-triangle text-white"></i>
                </div>
                <div>
                    <h3 class="text-lg font-bold text-amber-900 mb-1">⚠️ Tidak Ada Data</h3>
                    <p class="text-sm text-amber-800">Tabel <strong>kepatuhan_pembayaran</strong> belum memiliki data atau belum dibuat.</p>
                    <a href="import.php" class="inline-block mt-2 px-4 py-2 bg-amber-500 text-white rounded-lg font-semibold text-sm hover:bg-amber-600 transition-all">
                        <i class="fas fa-upload mr-1"></i>Import Data Sekarang
                    </a>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- HEADER SECTION - Compact -->
        <div class="bg-gradient-to-r from-primary via-primary-dark to-primary-dark rounded-2xl shadow-xl shadow-primary/20 p-5 lg:p-6 mb-5 relative overflow-hidden">
            <div class="absolute top-0 right-0 w-40 h-40 bg-white/10 rounded-full -mr-20 -mt-20"></div>
            <div class="absolute bottom-0 left-0 w-32 h-32 bg-white/5 rounded-full -ml-16 -mb-16"></div>
            
            <div class="relative z-10">
                <div class="flex flex-wrap items-center justify-between gap-3 mb-4">
                    <div class="flex items-center gap-3">
                        <div class="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center backdrop-blur-sm">
                            <i class="fas fa-money-check-alt text-white text-lg"></i>
                        </div>
                        <div>
                            <h1 class="text-xl lg:text-2xl font-black text-white tracking-tight">
                                Dashboard Kepatuhan Pembayaran
                            </h1>
                            <p class="text-white/80 text-xs lg:text-sm font-medium">
                                Periode: <?= htmlspecialchars($currentPeriod ?: 'Belum Ada Data') ?>
                            </p>
                        </div>
                    </div>
                    <div class="flex items-center gap-2">
                        <span class="px-3 py-1 bg-red-500 text-white rounded-full text-xs font-bold">
                            <i class="fas fa-shield-alt mr-1"></i>Admin
                        </span>
                        <div class="hidden sm:flex items-center gap-2 bg-white/10 rounded-lg px-3 py-1 backdrop-blur-sm">
                            <i class="fas fa-user text-white text-sm"></i>
                            <span class="text-white text-sm font-semibold"><?= htmlspecialchars($user_name) ?></span>
                        </div>
                    </div>
                </div>
                
                <!-- Admin Stats Bar - Compact -->
                <div class="grid grid-cols-2 lg:grid-cols-4 gap-3 pt-4 border-t border-white/10">
                    <div class="flex items-center gap-2">
                        <div class="w-8 h-8 bg-white/10 rounded-lg flex items-center justify-center backdrop-blur-sm">
                            <i class="fas fa-school text-white text-sm"></i>
                        </div>
                        <div>
                            <p class="text-white/60 text-xs font-semibold">Sekolah</p>
                            <p class="text-white text-base font-black"><?= $adminStats['total_sekolah'] ?></p>
                        </div>
                    </div>
                    <div class="flex items-center gap-2">
                        <div class="w-8 h-8 bg-white/10 rounded-lg flex items-center justify-center backdrop-blur-sm">
                            <i class="fas fa-layer-group text-white text-sm"></i>
                        </div>
                        <div>
                            <p class="text-white/60 text-xs font-semibold">Kategori</p>
                            <p class="text-white text-base font-black"><?= $adminStats['total_kategori'] ?></p>
                        </div>
                    </div>
                    <div class="flex items-center gap-2">
                        <div class="w-8 h-8 bg-white/10 rounded-lg flex items-center justify-center backdrop-blur-sm">
                            <i class="fas fa-database text-white text-sm"></i>
                        </div>
                        <div>
                            <p class="text-white/60 text-xs font-semibold">Records</p>
                            <p class="text-white text-base font-black"><?= number_format($adminStats['total_records']) ?></p>
                        </div>
                    </div>
                    <div class="flex items-center gap-2">
                        <div class="w-8 h-8 bg-white/10 rounded-lg flex items-center justify-center backdrop-blur-sm">
                            <i class="fas fa-check-circle text-green-400 text-sm"></i>
                        </div>
                        <div>
                            <p class="text-white/60 text-xs font-semibold">Status</p>
                            <p class="text-green-400 text-base font-black">Connected</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php if (!empty($periods)): ?>
        <!-- CONTROLS - Compact -->
        <div class="bg-white rounded-xl shadow-md p-4 mb-5">
            <div class="flex flex-wrap items-center justify-between gap-3">
                <div class="flex items-center gap-2">
                    <label class="text-xs font-bold text-slate-700">
                        <i class="fas fa-calendar-alt mr-1 text-primary"></i>Periode:
                    </label>
                    <select id="periodSelect" 
                            onchange="window.location.href='?period='+this.value+'&category=<?= $currentCategory ?>'"
                            class="px-3 py-1.5 border-2 border-slate-200 rounded-lg text-sm font-semibold text-slate-700 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all">
                        <?php foreach ($periods as $p): ?>
                        <option value="<?= htmlspecialchars($p) ?>" <?= $p === $currentPeriod ? 'selected' : '' ?>>
                            <?= htmlspecialchars($p) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="flex gap-2 flex-wrap">
                    <button onclick="window.print()" 
                            class="px-3 py-1.5 bg-gradient-to-r from-green-500 to-green-600 text-white rounded-lg text-xs font-semibold hover:shadow-lg transition-all">
                        <i class="fas fa-file-pdf mr-1"></i>PDF
                    </button>
                    <button onclick="alert('Fitur Excel akan segera tersedia!')" 
                            class="px-3 py-1.5 bg-gradient-to-r from-primary to-primary-dark text-white rounded-lg text-xs font-semibold hover:shadow-lg transition-all">
                        <i class="fas fa-file-excel mr-1"></i>Excel
                    </button>
                    <a href="import.php"
                       class="px-3 py-1.5 bg-gradient-to-r from-red-500 to-red-600 text-white rounded-lg text-xs font-semibold hover:shadow-lg transition-all inline-flex items-center">
                        <i class="fas fa-upload mr-1"></i>Import
                    </a>
                </div>
            </div>
        </div>

        <!-- TABS - Compact -->
        <div class="bg-white rounded-xl shadow-md p-4 mb-5">
            <div class="flex flex-wrap gap-2">
                <?php
                $cats = [
                    'ALL' => ['icon' => 'fa-list', 'label' => 'SEMUA'],
                    'SPP' => ['icon' => 'fa-money-bill-wave', 'label' => 'SPP'],
                    'DKT' => ['icon' => 'fa-book', 'label' => 'DKT'],
                    'DSP' => ['icon' => 'fa-graduation-cap', 'label' => 'DSP'],
                    'SERAGAM' => ['icon' => 'fa-tshirt', 'label' => 'SERAGAM']
                ];
                foreach ($cats as $k => $v):
                    $isActive = $currentCategory === $k;
                ?>
                <a href="?period=<?= urlencode($currentPeriod) ?>&category=<?= $k ?>"
                   class="px-4 py-2 rounded-lg font-bold text-xs transition-all <?= $isActive ? 'bg-gradient-to-r from-primary to-primary-dark text-white shadow-md' : 'bg-slate-100 text-slate-600 hover:bg-slate-200' ?>">
                    <i class="fas <?= $v['icon'] ?> mr-1"></i><?= $v['label'] ?>
                </a>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- SUMMARY STATS - Compact -->
        <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-5">
            <!-- Total Target -->
            <div class="stat-card bg-white rounded-xl shadow-md p-4 border-t-4 border-blue-500">
                <div class="flex items-start justify-between">
                    <div class="flex-1">
                        <p class="text-xs font-semibold text-slate-500 uppercase mb-1">Target</p>
                        <h3 class="text-lg lg:text-xl font-black text-slate-800 break-words"><?= rupiah($summary['total_target']) ?></h3>
                    </div>
                    <div class="w-10 h-10 bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-bullseye text-white"></i>
                    </div>
                </div>
            </div>

            <!-- Total Capaian -->
            <div class="stat-card bg-white rounded-xl shadow-md p-4 border-t-4 border-green-500">
                <div class="flex items-start justify-between">
                    <div class="flex-1">
                        <p class="text-xs font-semibold text-slate-500 uppercase mb-1">Capaian</p>
                        <h3 class="text-lg lg:text-xl font-black text-slate-800 break-words"><?= rupiah($summary['total_capaian']) ?></h3>
                    </div>
                    <div class="w-10 h-10 bg-gradient-to-br from-green-500 to-green-600 rounded-xl flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-check-circle text-white"></i>
                    </div>
                </div>
            </div>

            <!-- Total Piutang -->
            <div class="stat-card bg-white rounded-xl shadow-md p-4 border-t-4 border-red-500">
                <div class="flex items-start justify-between">
                    <div class="flex-1">
                        <p class="text-xs font-semibold text-slate-500 uppercase mb-1">Piutang</p>
                        <h3 class="text-lg lg:text-xl font-black text-slate-800 break-words"><?= rupiah($summary['total_piutang']) ?></h3>
                    </div>
                    <div class="w-10 h-10 bg-gradient-to-br from-red-500 to-red-600 rounded-xl flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-exclamation-triangle text-white"></i>
                    </div>
                </div>
            </div>

            <!-- Tingkat Kepatuhan -->
            <div class="stat-card bg-white rounded-xl shadow-md p-4 border-t-4 border-primary">
                <div class="flex items-start justify-between">
                    <div class="flex-1">
                        <p class="text-xs font-semibold text-slate-500 uppercase mb-1">Kepatuhan</p>
                        <h3 class="text-3xl font-black text-slate-800"><?= $summary['persen'] ?>%</h3>
                    </div>
                    <div class="w-10 h-10 bg-gradient-to-br from-primary to-primary-dark rounded-xl flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-chart-pie text-white"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- CATEGORY BREAKDOWN - Compact -->
        <?php if ($currentCategory === 'ALL' && !empty($categoryBreakdown)): ?>
        <div class="bg-white rounded-xl shadow-md p-5 mb-5">
            <h3 class="text-base font-bold text-slate-800 mb-4 flex items-center gap-2">
                <i class="fas fa-layer-group text-primary"></i>
                Breakdown Per Kategori
            </h3>
            
            <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
                <?php 
                $catColors = [
                    'SPP' => ['from' => 'blue-500', 'to' => 'blue-600'],
                    'DKT' => ['from' => 'green-500', 'to' => 'green-600'],
                    'DSP' => ['from' => 'purple-500', 'to' => 'purple-600'],
                    'SERAGAM' => ['from' => 'orange-500', 'to' => 'orange-600']
                ];
                foreach ($categoryBreakdown as $catName => $catData): 
                    $color = $catColors[$catName] ?? ['from' => 'gray-500', 'to' => 'gray-600'];
                ?>
                <div class="bg-slate-50 p-4 rounded-xl border border-slate-200 hover:border-primary/30 hover:shadow-md transition-all">
                    <div class="flex items-center justify-between mb-2">
                        <h4 class="text-sm font-bold text-slate-800"><?= $catName ?></h4>
                        <span class="text-lg font-black text-primary"><?= $catData['persen'] ?>%</span>
                    </div>
                    <div class="w-full bg-slate-200 rounded-full h-2 mb-3 overflow-hidden">
                        <div class="bg-gradient-to-r from-<?= $color['from'] ?> to-<?= $color['to'] ?> h-2 rounded-full transition-all duration-500" 
                             style="width: <?= $catData['persen'] ?>%"></div>
                    </div>
                    <div class="space-y-1 text-xs">
                        <div class="flex justify-between">
                            <span class="text-slate-600">Target:</span>
                            <span class="font-bold text-slate-800"><?= rupiah($catData['target']) ?></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-slate-600">Capaian:</span>
                            <span class="font-bold text-slate-800"><?= rupiah($catData['capaian']) ?></span>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- CHART - Compact -->
        <?php if (!empty($rows)): ?>
        <div class="bg-white rounded-xl shadow-md p-5 mb-5">
            <h3 class="text-base font-bold text-slate-800 mb-4 flex items-center gap-2">
                <i class="fas fa-chart-line text-primary"></i>
                Grafik Kepatuhan Per Sekolah
            </h3>
            <div class="h-64">
                <canvas id="complianceChart"></canvas>
            </div>
        </div>
        <?php endif; ?>

        <!-- TABLE - Compact -->
        <div class="bg-white rounded-xl shadow-md overflow-hidden">
            <div class="p-5 border-b border-slate-100">
                <h3 class="text-base font-bold text-slate-800 flex items-center gap-2">
                    <i class="fas fa-table text-primary"></i>
                    Detail Per Sekolah
                </h3>
            </div>
            
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead class="bg-slate-50 border-b border-slate-200">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-bold text-slate-600 uppercase">No</th>
                            <th class="px-4 py-3 text-left text-xs font-bold text-slate-600 uppercase">Sekolah</th>
                            <th class="px-4 py-3 text-right text-xs font-bold text-slate-600 uppercase">Target</th>
                            <th class="px-4 py-3 text-right text-xs font-bold text-slate-600 uppercase">Capaian</th>
                            <th class="px-4 py-3 text-right text-xs font-bold text-slate-600 uppercase">Piutang</th>
                            <th class="px-4 py-3 text-center text-xs font-bold text-slate-600 uppercase">%</th>
                            <th class="px-4 py-3 text-center text-xs font-bold text-slate-600 uppercase">Status</th>
                            <th class="px-4 py-3 text-center text-xs font-bold text-slate-600 uppercase">Aksi</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100">
                    <?php if (!$rows): ?>
                        <tr>
                            <td colspan="8" class="px-4 py-8 text-center">
                                <i class="fas fa-inbox text-slate-400 text-3xl mb-2"></i>
                                <p class="text-slate-500 text-sm">Tidak ada data untuk periode dan kategori ini</p>
                            </td>
                        </tr>
                    <?php else: 
                        foreach ($rows as $i => $r):
                        $statusColor = getStatusColor($r['kategori']);
                    ?>
                        <tr class="hover:bg-slate-50 transition-colors">
                            <td class="px-4 py-3 text-xs text-slate-600"><?= $i + 1 ?></td>
                            <td class="px-4 py-3 text-sm font-bold text-slate-800"><?= htmlspecialchars($r['ta']) ?></td>
                            <td class="px-4 py-3 text-right text-xs font-semibold text-slate-700"><?= rupiah($r['target']) ?></td>
                            <td class="px-4 py-3 text-right text-xs font-semibold text-green-600"><?= rupiah($r['capaian']) ?></td>
                            <td class="px-4 py-3 text-right text-xs font-semibold text-red-600"><?= rupiah($r['piutang']) ?></td>
                            <td class="px-4 py-3 text-center text-base font-black text-slate-800"><?= $r['persen'] ?>%</td>
                            <td class="px-4 py-3 text-center">
                                <span class="inline-block px-2 py-1 rounded-full text-xs font-bold bg-<?= $statusColor ?>-100 text-<?= $statusColor ?>-700">
                                    <?= $r['kategori'] ?>
                                </span>
                            </td>
                            <td class="px-4 py-3 text-center">
                                <button onclick="alert('Detail: <?= htmlspecialchars($r['ta']) ?>')" 
                                        class="px-3 py-1 bg-gradient-to-r from-primary to-primary-dark text-white rounded-lg text-xs font-semibold hover:shadow-md transition-all">
                                    <i class="fas fa-eye mr-1"></i>Detail
                                </button>
                            </td>
                        </tr>
                    <?php 
                        endforeach;
                    endif; 
                    ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>

    </div>

    <?php if (!empty($rows)): ?>
    <script>
        const ctx = document.getElementById('complianceChart');
        if (ctx) {
            const chartData = {
                labels: [<?php echo implode(',', array_map(function($r) { return "'" . addslashes($r['ta']) . "'"; }, $rows)); ?>],
                datasets: [{
                    label: 'Tingkat Kepatuhan (%)',
                    data: [<?php echo implode(',', array_map(function($r) { return $r['persen']; }, $rows)); ?>],
                    backgroundColor: 'rgba(122, 178, 178, 0.2)',
                    borderColor: 'rgba(122, 178, 178, 1)',
                    borderWidth: 2,
                    fill: true,
                    tension: 0.4,
                    pointBackgroundColor: 'rgba(122, 178, 178, 1)',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 4,
                    pointHoverRadius: 6
                }]
            };

            new Chart(ctx, {
                type: 'line',
                data: chartData,
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.8)',
                            padding: 10,
                            titleFont: { size: 12, weight: 'bold' },
                            bodyFont: { size: 11 },
                            borderColor: 'rgba(122, 178, 178, 0.5)',
                            borderWidth: 1,
                            cornerRadius: 6,
                            callbacks: {
                                label: function(context) {
                                    return 'Kepatuhan: ' + context.parsed.y + '%';
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)',
                                drawBorder: false
                            },
                            ticks: {
                                font: { size: 10, weight: '600' },
                                color: '#64748b',
                                callback: function(value) {
                                    return value + '%';
                                }
                            }
                        },
                        x: {
                            grid: {
                                display: false,
                                drawBorder: false
                            },
                            ticks: {
                                font: { size: 9, weight: '600' },
                                color: '#64748b',
                                maxRotation: 45,
                                minRotation: 45
                            }
                        }
                    }
                }
            });
        }
    </script>
    <?php endif; ?>

</body>
</html>

<?php 
if (isset($conn)) {
    $conn->close();
}
?>