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

<style>
.stat-card {
    border-radius: 14px;
    padding: 18px 20px;
    position: relative;
    overflow: hidden;
    transition: transform .2s, box-shadow .2s;
    height: 100%;
    color: #fff;
}
.stat-card:hover { transform: translateY(-3px); box-shadow: 0 8px 25px rgba(0,0,0,.15); }
.bg-stat-1 { background: linear-gradient(135deg,#0d6efd,#3d8bfd); }
.bg-stat-2 { background: linear-gradient(135deg,#6f42c1,#a06ee1); }
.bg-stat-3 { background: linear-gradient(135deg,#20c997,#48dba4); }
.bg-stat-4 { background: linear-gradient(135deg,#fd7e14,#ffa04d); }
.bg-stat-5 { background: linear-gradient(135deg,#dc3545,#f06574); }

.stat-value { font-size: 2rem; font-weight: 700; line-height: 1; }
.stat-label { font-size: .78rem; opacity: .88; margin-top: 4px; }
.stat-icon { position:absolute; right:14px; top:50%; transform:translateY(-50%); font-size:2.6rem; opacity:.18; }

/* Quick action buttons */
.quick-btn {
    border-radius: 12px;
    padding: 16px 10px;
    font-size: .8rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 6px;
    transition: all .2s;
    background: var(--bs-body-bg);
    border: 1px solid var(--bs-border-color);
}
.quick-btn:hover {
    transform: translateY(-3px);
    background: var(--primary);
    color: #fff !important;
    border-color: var(--primary);
    box-shadow: 0 5px 15px rgba(13, 110, 253, 0.15);
}
.quick-btn i { font-size: 1.5rem; }

/* Table styles */
.table-responsive {
    border-radius: 10px;
    overflow: hidden;
}
</style>

<!-- ── STAT CARDS ─────────────────────────────────────────── -->
<div class="row g-3 mb-4">
    <div class="col-6 col-md-4 col-lg-2.4 style-col-5">
        <div class="stat-card bg-stat-1">
            <div class="stat-value"><?= number_format($total_active_students) ?></div>
            <div class="stat-label">Siswa Aktif</div>
            <i class="bi bi-people stat-icon"></i>
        </div>
    </div>
    <div class="col-6 col-md-4 col-lg-2.4 style-col-5">
        <div class="stat-card bg-stat-2">
            <div class="stat-value"><?= number_format($total_teachers) ?></div>
            <div class="stat-label">Total Guru</div>
            <i class="bi bi-person-badge stat-icon"></i>
        </div>
    </div>
    <div class="col-6 col-md-4 col-lg-2.4 style-col-5">
        <div class="stat-card bg-stat-3">
            <div class="stat-value"><?= number_format($total_classrooms) ?></div>
            <div class="stat-label">Total Kelas</div>
            <i class="bi bi-door-open stat-icon"></i>
        </div>
    </div>
    <div class="col-6 col-md-6 col-lg-2.4 style-col-5">
        <div class="stat-card bg-stat-4">
            <div class="stat-value"><?= number_format($total_active_letters) ?></div>
            <div class="stat-label">Surat Aktif Terbit</div>
            <i class="bi bi-file-earmark-text stat-icon"></i>
        </div>
    </div>
    <div class="col-6 col-md-6 col-lg-2.4 style-col-5">
        <div class="stat-card bg-stat-5">
            <div class="stat-value"><?= number_format($total_mutasi_letters) ?></div>
            <div class="stat-label">Surat Mutasi Terbit</div>
            <i class="bi bi-envelope-open stat-icon"></i>
        </div>
    </div>
</div>

<style>
@media (min-width: 992px) {
    .style-col-5 {
        flex: 0 0 20%;
        max-width: 20%;
    }
}
</style>

<!-- ── ROW TENGAH: Periode & Gender | Akses Cepat ── -->
<div class="row g-3 mb-4">

    <!-- Periode Aktif & Gender -->
    <div class="col-md-6">
        <div class="card h-100 border-0 shadow-sm">
            <div class="card-header bg-transparent py-3 d-flex align-items-center gap-2 border-0">
                <i class="bi bi-calendar3 text-primary fs-5"></i>
                <span class="fw-bold">Periode Aktif</span>
            </div>
            <div class="card-body pt-0">
                <?php if ($active_period): ?>
                <div class="text-center mb-3">
                    <span class="badge bg-primary fs-6 px-3 py-2">
                        <?= esc($active_period['year_name']) ?> &mdash; <?= esc($active_period['semester']) ?>
                    </span>
                </div>
                <hr class="my-2 opacity-50">
                <div class="d-flex justify-content-around text-center">
                    <div>
                        <i class="bi bi-gender-male fs-4 text-primary"></i>
                        <div class="fw-bold fs-5"><?= $gender_stats['L'] ?></div>
                        <div class="small text-muted">Laki-laki</div>
                    </div>
                    <div class="border-start border-end px-3">
                        <i class="bi bi-gender-female fs-4 text-danger"></i>
                        <div class="fw-bold fs-5"><?= $gender_stats['P'] ?></div>
                        <div class="small text-muted">Perempuan</div>
                    </div>
                    <div>
                        <i class="bi bi-people-fill fs-4 text-success"></i>
                        <div class="fw-bold fs-5"><?= $gender_stats['L'] + $gender_stats['P'] ?></div>
                        <div class="small text-muted">Total</div>
                    </div>
                </div>
                <?php if (($gender_stats['L'] + $gender_stats['P']) > 0): ?>
                <div class="mt-3">
                    <?php
                    $total = $gender_stats['L'] + $gender_stats['P'];
                    $pctL  = round($gender_stats['L'] / $total * 100);
                    $pctP  = 100 - $pctL;
                    ?>
                    <div class="d-flex rounded overflow-hidden" style="height:8px">
                        <div class="bg-primary" style="width:<?= $pctL ?>%"></div>
                        <div class="bg-danger" style="width:<?= $pctP ?>%"></div>
                    </div>
                    <div class="d-flex justify-content-between small text-muted mt-1">
                        <span>L <?= $pctL ?>%</span>
                        <span>P <?= $pctP ?>%</span>
                    </div>
                </div>
                <?php endif; ?>
                <?php else: ?>
                <div class="text-center py-4">
                    <i class="bi bi-calendar-x text-warning fs-2"></i>
                    <p class="text-muted small mt-2">Belum ada periode aktif</p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Akses Cepat Administratif -->
    <div class="col-md-6">
        <div class="card h-100 border-0 shadow-sm">
            <div class="card-header bg-transparent py-3 d-flex align-items-center gap-2 border-0">
                <i class="bi bi-grid text-primary fs-5"></i>
                <span class="fw-bold">Pintasan Layanan</span>
            </div>
            <div class="card-body pt-0">
                <div class="row g-2 mb-3">
                    <div class="col-6">
                        <a href="/attendance-sheet" class="quick-btn text-decoration-none text-dark-emphasis">
                            <i class="bi bi-journal-check text-primary"></i>
                            <span class="fw-medium">Cetak Presensi</span>
                        </a>
                    </div>
                    <div class="col-6">
                        <a href="/letter/keterangan-aktif" class="quick-btn text-decoration-none text-dark-emphasis">
                            <i class="bi bi-file-earmark-text text-success"></i>
                            <span class="fw-medium">Surat Aktif</span>
                        </a>
                    </div>
                    <div class="col-6">
                        <a href="/letter/mutasi" class="quick-btn text-decoration-none text-dark-emphasis">
                            <i class="bi bi-envelope-open text-danger"></i>
                            <span class="fw-medium">Surat Mutasi</span>
                        </a>
                    </div>
                    <div class="col-6">
                        <a href="/letter" class="quick-btn text-decoration-none text-dark-emphasis">
                            <i class="bi bi-clock-history text-secondary"></i>
                            <span class="fw-medium">Riwayat Surat</span>
                        </a>
                    </div>
                </div>
                <hr class="my-2 opacity-50">
                <table class="table table-sm table-borderless mb-0 small">
                    <tr>
                        <td class="text-muted py-1 ps-0"><i class="bi bi-person-circle me-1"></i>Nama Petugas</td>
                        <td class="fw-semibold py-1 text-end"><?= esc(session('user_name')) ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted py-1 ps-0"><i class="bi bi-shield-check me-1"></i>Hak Akses</td>
                        <td class="py-1 text-end"><span class="badge bg-info text-dark">Tata Usaha</span></td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- ── REKAP PER TINGKAT & KELAS (Dinamis dengan L/P) ── -->
<?php
// Kelompokkan class_summary per grade
$gradeGroups = [];
foreach ($class_summary as $row) {
    $gName = $row['grade_name'];
    if (!isset($gradeGroups[$gName])) {
        $gradeGroups[$gName] = ['classes' => [], 'total' => 0, 'male' => 0, 'female' => 0];
    }
    $gradeGroups[$gName]['classes'][] = $row;
    $gradeGroups[$gName]['total']  += $row['total'];
    $gradeGroups[$gName]['male']   += $row['male_count'];
    $gradeGroups[$gName]['female'] += $row['female_count'];
}

$gradeColors = ['#1e3a5f','#4a2c6e','#0f4c5c','#8b4513','#1a4a1a','#4a1a3a'];
$colorIdx = 0;
?>

<div class="card border-0 shadow-sm mb-4">
    <div class="card-header bg-transparent py-3 d-flex align-items-center gap-2 border-0">
        <i class="bi bi-bar-chart-fill text-primary fs-5"></i>
        <span class="fw-bold">Rekapitulasi Siswa per Tingkat & Kelas</span>
    </div>
    <div class="card-body pt-0">
        <?php if (!empty($gradeGroups)): ?>
        <div class="row g-3">
            <?php foreach ($gradeGroups as $gradeName => $gradeData): 
                $color = $gradeColors[$colorIdx % count($gradeColors)];
                $colorIdx++;
            ?>
            <div class="col-md-6 col-lg-4">
                <div class="card border-0 h-100 shadow-sm" style="border-top: 4px solid <?= $color ?> !important;">
                    <div class="card-body p-3">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <h6 class="fw-bold text-dark mb-0">Tingkat <?= esc($gradeName) ?></h6>
                            <span class="badge bg-secondary rounded-pill"><?= number_format($gradeData['total']) ?> Siswa</span>
                        </div>
                        <div class="text-muted small mb-3">
                            <i class="bi bi-gender-male text-primary me-1"></i>L: <?= $gradeData['male'] ?> 
                            &nbsp;&middot;&nbsp; 
                            <i class="bi bi-gender-female text-danger me-1"></i>P: <?= $gradeData['female'] ?>
                        </div>
                        <div class="list-group list-group-flush" style="max-height: 200px; overflow-y: auto;">
                            <?php foreach ($gradeData['classes'] as $cls): ?>
                            <div class="list-group-item d-flex justify-content-between align-items-center px-0 py-2 bg-transparent">
                                <span class="fw-semibold text-dark-emphasis small"><?= esc($cls['class_name']) ?></span>
                                <span class="text-muted small">
                                    <strong><?= $cls['total'] ?></strong> 
                                    <span class="text-muted" style="font-size: 0.72rem;">(L:<?= $cls['male_count'] ?> P:<?= $cls['female_count'] ?>)</span>
                                </span>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php else: ?>
        <div class="text-center py-4 text-muted">
            <i class="bi bi-info-circle fs-3 d-block mb-2 text-warning"></i>
            Belum ada data tingkat atau kelas yang tersedia.
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- ── RIWAYAT SURAT TERBARU ─────────────────────────────── -->
<div class="row g-3">
    <div class="col-12">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-transparent py-3 d-flex align-items-center justify-content-between border-0">
                <div class="d-flex align-items-center gap-2">
                    <i class="bi bi-envelope-check text-primary fs-5"></i>
                    <span class="fw-bold">Surat Resmi Terbaru Diterbitkan</span>
                </div>
                <a href="/letter" class="btn btn-sm btn-link text-decoration-none">Lihat Semua Riwayat →</a>
            </div>
            <div class="card-body pt-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>No. Surat</th>
                                <th>Nama Siswa</th>
                                <th>Jenis Surat</th>
                                <th>Tanggal Cetak</th>
                                <th>Tujuan / Alasan</th>
                                <th class="text-center">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($recent_letters)): ?>
                            <tr>
                                <td colspan="6" class="text-center py-4 text-muted">Belum ada surat yang diterbitkan.</td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($recent_letters as $log): ?>
                            <tr>
                                <td><code><?= esc($log['letter_number']) ?></code></td>
                                <td class="fw-semibold"><?= esc($log['student_name']) ?></td>
                                <td>
                                    <?php if ($log['letter_type'] === 'keterangan_aktif'): ?>
                                    <span class="badge bg-success bg-opacity-10 text-success">Keterangan Aktif</span>
                                    <?php else: ?>
                                    <span class="badge bg-danger bg-opacity-10 text-danger">Mutasi Keluar</span>
                                    <?php endif; ?>
                                </td>
                                <td><?= date('d-m-Y', strtotime($log['letter_date'])) ?></td>
                                <td>
                                    <span class="small text-muted">
                                        <?= esc($log['purpose'] ?: ($log['destination'] . ' - ' . $log['reason'])) ?>
                                    </span>
                                </td>
                                <td class="text-center">
                                    <?php if ($log['letter_type'] === 'keterangan_aktif'): ?>
                                    <a href="/letter/keterangan-aktif/print/<?= $log['id'] ?>" target="_blank" class="btn btn-sm btn-outline-primary py-0 px-2">
                                        <i class="bi bi-printer me-1"></i> Cetak Ulang
                                    </a>
                                    <?php else: ?>
                                    <a href="/letter/mutasi/print/<?= $log['id'] ?>" target="_blank" class="btn btn-sm btn-outline-danger py-0 px-2">
                                        <i class="bi bi-printer me-1"></i> Cetak Ulang
                                    </a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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