<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<?php if (!$activePeriod): ?>
<div class="alert alert-warning border-0 shadow-sm" style="border-radius: 12px;">
    <i class="bi bi-exclamation-triangle-fill me-2"></i>Belum ada periode akademik aktif. Harap hubungi administrator untuk mengaktifkan periode akademik berjalan.
</div>
<?php return; endif; ?>

<!-- Executive Header -->
<div class="row align-items-center mb-4">
    <div class="col-md-8">
        <h4 class="mb-1 fw-bold text-dark"><i class="bi bi-shield-check text-primary me-2"></i>Executive Quality Control</h4>
        <p class="text-muted mb-md-0 small">
            Memantau mutu kegiatan belajar mengajar, kehadiran, kedisiplinan, tahfidz, dan pengaduan siswa secara real-time.
        </p>
    </div>
    <div class="col-md-4 text-md-end">
        <span class="badge bg-white shadow-sm text-dark border p-2 px-3 fw-semibold" style="border-radius: 8px;">
            <i class="bi bi-calendar3 text-primary me-1"></i>
            <?= esc($activePeriod['year_name'] ?? '') ?> &mdash; Semester <?= esc($activePeriod['semester'] ?? '') ?>
        </span>
    </div>
</div>

<!-- Summary Cards Grid -->
<div class="row g-3 mb-4">
    <!-- Active Students Card -->
    <div class="col-6 col-md-3">
        <div class="card border-0 shadow-sm bg-white" style="border-radius: 14px;">
            <div class="card-body p-3.5 d-flex align-items-center gap-3">
                <div class="bg-primary bg-opacity-10 text-primary p-2.5 rounded-circle d-flex align-items-center justify-content-center" style="width: 44px; height: 44px;">
                    <i class="bi bi-people-fill fs-5"></i>
                </div>
                <div>
                    <small class="text-muted d-block small" style="font-size: 0.72rem; font-weight: 500;">Siswa Aktif</small>
                    <h5 class="fw-bold text-dark mb-0"><?= $totalActiveStudents ?></h5>
                </div>
            </div>
        </div>
    </div>
    <!-- KBM Rate Card -->
    <div class="col-6 col-md-3">
        <div class="card border-0 shadow-sm bg-white" style="border-radius: 14px;">
            <div class="card-body p-3.5 d-flex align-items-center gap-3">
                <div class="bg-success bg-opacity-10 text-success p-2.5 rounded-circle d-flex align-items-center justify-content-center" style="width: 44px; height: 44px;">
                    <i class="bi bi-book-half fs-5"></i>
                </div>
                <div class="w-100">
                    <small class="text-muted d-block small" style="font-size: 0.72rem; font-weight: 500;">Isian Jurnal Guru</small>
                    <h5 class="fw-bold text-dark mb-0"><?= $filledClassrooms ?> <span class="text-muted fs-6 font-normal">/ <?= $totalClassrooms ?> Kelas</span></h5>
                </div>
            </div>
        </div>
    </div>
    <!-- Total Violations Card -->
    <div class="col-6 col-md-3">
        <div class="card border-0 shadow-sm bg-white" style="border-radius: 14px;">
            <div class="card-body p-3.5 d-flex align-items-center gap-3">
                <div class="bg-danger bg-opacity-10 text-danger p-2.5 rounded-circle d-flex align-items-center justify-content-center" style="width: 44px; height: 44px;">
                    <i class="bi bi-exclamation-octagon-fill fs-5"></i>
                </div>
                <div>
                    <small class="text-muted d-block small" style="font-size: 0.72rem; font-weight: 500;">Kasus Pelanggaran</small>
                    <h5 class="fw-bold text-dark mb-0"><?= $totalViolations ?></h5>
                </div>
            </div>
        </div>
    </div>
    <!-- Active Counseling Card -->
    <div class="col-6 col-md-3">
        <div class="card border-0 shadow-sm bg-white" style="border-radius: 14px;">
            <div class="card-body p-3.5 d-flex align-items-center gap-3">
                <div class="bg-warning bg-opacity-10 text-warning p-2.5 rounded-circle d-flex align-items-center justify-content-center" style="width: 44px; height: 44px;">
                    <i class="bi bi-chat-left-text-fill fs-5"></i>
                </div>
                <div>
                    <small class="text-muted d-block small" style="font-size: 0.72rem; font-weight: 500;">Konseling Aktif</small>
                    <h5 class="fw-bold text-dark mb-0"><?= $activeTicketsCount ?></h5>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Main Graphic Panels -->
<div class="row g-4 mb-4">
    <!-- Today's Attendance Chart -->
    <div class="col-md-4">
        <div class="card border-0 shadow-sm h-100 bg-white" style="border-radius: 14px;">
            <div class="card-header bg-white border-0 pt-4 px-4 pb-0 d-flex justify-content-between align-items-center">
                <h6 class="mb-0 fw-bold text-dark"><i class="bi bi-person-check-fill text-success me-2"></i>Kehadiran Siswa Hari Ini</h6>
                <small class="text-muted small"><?= date('d F Y') ?></small>
            </div>
            <div class="card-body px-4 pb-4 pt-3 d-flex flex-column align-items-center justify-content-center">
                <div style="width: 100%; max-width: 200px; height: 200px; position: relative;">
                    <canvas id="attendanceChart"></canvas>
                </div>
                <div class="row w-100 g-2 text-center mt-3 small">
                    <div class="col-3">
                        <span class="d-block text-success fw-bold"><?= $attendance['hadir'] ?></span>
                        <span class="text-muted small">Hadir</span>
                    </div>
                    <div class="col-3">
                        <span class="d-block text-info fw-bold"><?= $attendance['sakit'] ?></span>
                        <span class="text-muted small">Sakit</span>
                    </div>
                    <div class="col-3">
                        <span class="d-block text-warning fw-bold"><?= $attendance['izin'] ?></span>
                        <span class="text-muted small">Izin</span>
                    </div>
                    <div class="col-3">
                        <span class="d-block text-danger fw-bold"><?= $attendance['alpha'] ?></span>
                        <span class="text-muted small">Alpha</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Weekly Violations Trend -->
    <div class="col-md-8">
        <div class="card border-0 shadow-sm h-100 bg-white" style="border-radius: 14px;">
            <div class="card-header bg-white border-0 pt-4 px-4 pb-0">
                <h6 class="mb-0 fw-bold text-dark"><i class="bi bi-graph-up-arrow text-danger me-2"></i>Tren Kasus Pelanggaran Mingguan</h6>
            </div>
            <div class="card-body px-4 pb-4 pt-3">
                <div style="height: 220px; width: 100%;">
                    <canvas id="violationsChart"></canvas>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-4 mb-4">
    <!-- Academic Average Score per Class -->
    <div class="col-md-6">
        <div class="card border-0 shadow-sm h-100 bg-white" style="border-radius: 14px;">
            <div class="card-header bg-white border-0 pt-4 px-4 pb-0">
                <h6 class="mb-0 fw-bold text-dark"><i class="bi bi-award-fill text-primary me-2"></i>Rata-rata Nilai Akademik per Kelas</h6>
            </div>
            <div class="card-body px-4 pb-4 pt-3">
                <?php if (empty($academicStats)): ?>
                    <div class="text-center py-5 text-muted small">
                        <i class="bi bi-journal-x fs-2 opacity-50 d-block mb-1"></i>Belum ada data nilai akademik diinput untuk periode ini.
                    </div>
                <?php else: ?>
                    <div style="height: 240px; width: 100%;">
                        <canvas id="academicChart"></canvas>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Tahfidz Average Score per Class -->
    <div class="col-md-6">
        <div class="card border-0 shadow-sm h-100 bg-white" style="border-radius: 14px;">
            <div class="card-header bg-white border-0 pt-4 px-4 pb-0">
                <h6 class="mb-0 fw-bold text-dark"><i class="bi bi-book-half text-teal me-2" style="color: #00b894;"></i>Rata-rata Nilai Tahfidz per Kelas</h6>
            </div>
            <div class="card-body px-4 pb-4 pt-3">
                <?php if (empty($tahfidzStats)): ?>
                    <div class="text-center py-5 text-muted small">
                        <i class="bi bi-journal-x fs-2 opacity-50 d-block mb-1"></i>Belum ada setoran nilai tahfidz masuk untuk periode ini.
                    </div>
                <?php else: ?>
                    <div style="height: 240px; width: 100%;">
                        <canvas id="tahfidzChart"></canvas>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div class="row g-4 mb-4">
    <!-- Complaints distribution -->
    <div class="col-md-5">
        <div class="card border-0 shadow-sm h-100 bg-white" style="border-radius: 14px;">
            <div class="card-header bg-white border-0 pt-4 px-4 pb-0">
                <h6 class="mb-0 fw-bold text-dark"><i class="bi bi-chat-right-dots-fill text-warning me-2"></i>Kategori Pengaduan Siswa</h6>
            </div>
            <div class="card-body px-4 pb-4 pt-3 d-flex align-items-center justify-content-center">
                <div style="height: 220px; width: 100%;">
                    <canvas id="complaintsChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Log 5 Letters / SPPD -->
    <div class="col-md-7">
        <div class="card border-0 shadow-sm h-100 bg-white" style="border-radius: 14px;">
            <div class="card-header bg-white border-0 pt-4 px-4 pb-0 d-flex justify-content-between align-items-center">
                <h6 class="mb-0 fw-bold text-dark"><i class="bi bi-envelope-open-fill text-secondary me-2"></i>Penerbitan Surat & SPPD Terbaru</h6>
                <span class="badge bg-secondary bg-opacity-10 text-secondary px-2.5 py-1 text-uppercase small">Administrasi TU</span>
            </div>
            <div class="card-body p-0 pt-3">
                <?php if (empty($latestLetters)): ?>
                    <div class="text-center py-5 text-muted small">
                        <i class="bi bi-envelope-x fs-2 opacity-50 d-block mb-1"></i>Belum ada riwayat penerbitan surat resmi oleh TU.
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0 text-dark" style="font-size: 0.85rem;">
                            <thead class="table-light">
                                <tr>
                                    <th class="ps-4">No. Surat</th>
                                    <th>Penerima / Staf</th>
                                    <th>Tipe Surat</th>
                                    <th class="pe-4">Tanggal</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($latestLetters as $letter): ?>
                                    <tr>
                                        <td class="ps-4 font-monospace text-muted" style="font-size: 0.8rem;"><?= esc($letter['letter_number']) ?></td>
                                        <td>
                                            <strong class="text-dark"><?= esc($letter['officer_name'] ?: ($letter['student_name'] ?: 'Umum/Lainnya')) ?></strong>
                                        </td>
                                        <td>
                                            <?php 
                                            $badgeClass = 'bg-secondary bg-opacity-10 text-secondary';
                                            $labelText = 'Surat';
                                            switch($letter['letter_type']) {
                                                case 'surat_tugas':
                                                    $badgeClass = 'bg-primary bg-opacity-10 text-primary';
                                                    $labelText = 'Surat Tugas';
                                                    break;
                                                case 'sppd':
                                                    $badgeClass = 'bg-warning bg-opacity-10 text-warning';
                                                    $labelText = 'SPPD Dinas';
                                                    break;
                                                case 'keterangan_aktif':
                                                    $badgeClass = 'bg-success bg-opacity-10 text-success';
                                                    $labelText = 'Ket. Aktif';
                                                    break;
                                                case 'mutasi_keluar':
                                                    $badgeClass = 'bg-danger bg-opacity-10 text-danger';
                                                    $labelText = 'Mutasi Siswa';
                                                    break;
                                            }
                                            ?>
                                            <span class="badge rounded-pill px-2.5 py-1 <?= $badgeClass ?>"><?= $labelText ?></span>
                                        </td>
                                        <td class="pe-4 text-muted" style="font-size: 0.8rem;"><?= date('d-m-Y', strtotime($letter['letter_date'])) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Include Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        
        // 1. ATTENDANCE CHART (DOUGHNUT)
        var attendanceCtx = document.getElementById('attendanceChart').getContext('2d');
        new Chart(attendanceCtx, {
            type: 'doughnut',
            data: {
                labels: ['Hadir', 'Sakit', 'Izin', 'Alpha'],
                datasets: [{
                    data: [
                        <?= $attendance['hadir'] ?>,
                        <?= $attendance['sakit'] ?>,
                        <?= $attendance['izin'] ?>,
                        <?= $attendance['alpha'] ?>
                    ],
                    backgroundColor: ['#2ec4b6', '#3a86c8', '#ffb703', '#e63946'],
                    borderWidth: 2,
                    borderColor: '#ffffff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false }
                },
                cutout: '70%'
            }
        });

        // 2. VIOLATIONS TREND CHART (LINE)
        var violationsCtx = document.getElementById('violationsChart').getContext('2d');
        var vDates = <?= json_encode(array_map(function($d) { return date('d M', strtotime($d)); }, array_keys($trendViolations))) ?>;
        var vCounts = <?= json_encode(array_values($trendViolations)) ?>;
        new Chart(violationsCtx, {
            type: 'line',
            data: {
                labels: vDates,
                datasets: [{
                    label: 'Kasus Pelanggaran',
                    data: vCounts,
                    borderColor: '#e63946',
                    backgroundColor: 'rgba(230, 57, 70, 0.08)',
                    fill: true,
                    tension: 0.35,
                    borderWidth: 3,
                    pointRadius: 4,
                    pointBackgroundColor: '#e63946'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: { stepSize: 1, color: '#888' },
                        grid: { color: '#f1f1f1' }
                    },
                    x: { ticks: { color: '#888' }, grid: { display: false } }
                }
            }
        });

        // 3. ACADEMIC GRADES CHART (BAR)
        <?php if (!empty($academicStats)): ?>
        var academicCtx = document.getElementById('academicChart').getContext('2d');
        var acadClasses = <?= json_encode(array_column($academicStats, 'class_name')) ?>;
        var acadScores = <?= json_encode(array_map(function($s) { return round($s, 1); }, array_column($academicStats, 'avg_score'))) ?>;
        new Chart(academicCtx, {
            type: 'bar',
            data: {
                labels: acadClasses,
                datasets: [{
                    data: acadScores,
                    backgroundColor: 'rgba(108, 92, 231, 0.75)',
                    hoverBackgroundColor: '#6c5ce7',
                    borderRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    y: {
                        min: 0,
                        max: 100,
                        ticks: { color: '#888' },
                        grid: { color: '#f1f1f1' }
                    },
                    x: { ticks: { color: '#888' }, grid: { display: false } }
                }
            }
        });
        <?php endif; ?>

        // 4. TAHFIDZ GRADES CHART (BAR)
        <?php if (!empty($tahfidzStats)): ?>
        var tahfidzCtx = document.getElementById('tahfidzChart').getContext('2d');
        var tahfClasses = <?= json_encode(array_column($tahfidzStats, 'class_name')) ?>;
        var tahfScores = <?= json_encode(array_map(function($s) { return round($s, 1); }, array_column($tahfidzStats, 'avg_score'))) ?>;
        new Chart(tahfidzCtx, {
            type: 'bar',
            data: {
                labels: tahfClasses,
                datasets: [{
                    data: tahfScores,
                    backgroundColor: 'rgba(0, 184, 148, 0.75)',
                    hoverBackgroundColor: '#00b894',
                    borderRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    y: {
                        min: 0,
                        max: 100,
                        ticks: { color: '#888' },
                        grid: { color: '#f1f1f1' }
                    },
                    x: { ticks: { color: '#888' }, grid: { display: false } }
                }
            }
        });
        <?php endif; ?>

        // 5. COMPLAINTS DISTRIBUTION CHART (HORIZONTAL BAR)
        var complaintsCtx = document.getElementById('complaintsChart').getContext('2d');
        new Chart(complaintsCtx, {
            type: 'bar',
            data: {
                labels: ['Pribadi', 'Akademik', 'Sarpras', 'Keamanan', 'Pendidikan Lanjut', 'Lainnya'],
                datasets: [{
                    data: [
                        <?= $complaintCats['pribadi'] ?>,
                        <?= $complaintCats['akademik'] ?>,
                        <?= $complaintCats['sarpras'] ?>,
                        <?= $complaintCats['bullying'] ?>,
                        <?= $complaintCats['karir'] ?>,
                        <?= $complaintCats['lainnya'] ?>
                    ],
                    backgroundColor: [
                        '#6c5ce7',
                        '#0984e3',
                        '#00b894',
                        '#d63031',
                        '#e84393',
                        '#ffeaa7'
                    ],
                    borderRadius: 6
                }]
            },
            options: {
                indexAxis: 'y',
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    x: { beginAtZero: true, ticks: { stepSize: 1, color: '#888' }, grid: { color: '#f1f1f1' } },
                    y: { ticks: { color: '#888' }, grid: { display: false } }
                }
            }
        });
    });
</script>

<?= $this->endSection() ?>
