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

/* Grade cards */
.grade-card { border-radius: 12px; overflow: hidden; height: 100%; transition: transform .2s, box-shadow .2s; }
.grade-card:hover { transform: translateY(-2px); box-shadow: 0 6px 18px rgba(0,0,0,.1); }
.grade-header { padding: 12px 16px; font-weight: 700; font-size: 1rem; color: #fff; }
.grade-body { padding: 14px; background: var(--bs-body-bg); border: 1px solid var(--bs-border-color); border-top:none; border-radius: 0 0 12px 12px; }
.grade-total { font-size: 2rem; font-weight: 700; text-align: center; }
.class-list { max-height: 220px; overflow-y: auto; margin-top: 10px; }
.class-item { display:flex; justify-content:space-between; align-items:center; padding: 6px 8px; border-bottom: 1px solid var(--bs-border-color); font-size: .83rem; }
.class-item:last-child { border-bottom: none; }

/* Quick action buttons */
.quick-btn { border-radius: 10px; padding: 12px 8px; font-size:.78rem; display:flex; flex-direction:column; align-items:center; gap:4px; transition: transform .15s; }
.quick-btn:hover { transform: translateY(-2px); }
.quick-btn i { font-size: 1.3rem; }
</style>

<!-- ── STAT CARDS ─────────────────────────────────────────── -->
<div class="row g-3 mb-4">
    <div class="col-6 col-md-3">
        <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-3">
        <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-3">
        <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-3">
        <div class="stat-card bg-stat-4">
            <div class="stat-value"><?= number_format($total_subjects) ?></div>
            <div class="stat-label">Mata Pelajaran</div>
            <i class="bi bi-book stat-icon"></i>
        </div>
    </div>
</div>

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

    <!-- Identitas Lembaga -->
    <div class="col-md-6 col-lg-4">
        <div class="card h-100">
            <div class="card-header py-2 d-flex align-items-center gap-2">
                <i class="bi bi-building text-primary"></i>
                <span class="fw-semibold">Identitas Lembaga</span>
            </div>
            <div class="card-body">
                <?php if ($setting && ($setting['school_name'] ?? null)): ?>
                <div class="d-flex align-items-start gap-3">
                    <?php if (!empty($setting['logo'])): ?>
                    <img src="<?= base_url('uploads/settings/' . $setting['logo']) ?>"
                         alt="Logo" style="width:56px;height:56px;object-fit:contain">
                    <?php else: ?>
                    <div class="bg-primary bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center"
                         style="width:56px;height:56px;flex-shrink:0">
                        <i class="bi bi-building fs-3 text-primary"></i>
                    </div>
                    <?php endif; ?>
                    <div>
                        <h6 class="mb-1 fw-bold"><?= esc($setting['school_name']) ?></h6>
                        <div class="small text-muted">NPSN: <?= esc($setting['npsn'] ?? '-') ?></div>
                        <div class="small text-muted">
                            Akreditasi:
                            <span class="badge bg-success"><?= esc($setting['accreditation'] ?? '-') ?></span>
                        </div>
                        <div class="small text-muted mt-1">
                            <i class="bi bi-person-circle me-1"></i><?= esc($setting['principal_name'] ?? '-') ?>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                <div class="text-center py-4">
                    <i class="bi bi-exclamation-circle text-warning fs-2"></i>
                    <p class="text-muted small mt-2">Data lembaga belum diisi</p>
                    <a href="/settings" class="btn btn-sm btn-primary">Lengkapi</a>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Periode Aktif & Gender -->
    <div class="col-md-6 col-lg-4">
        <div class="card h-100">
            <div class="card-header py-2 d-flex align-items-center gap-2">
                <i class="bi bi-calendar3 text-primary"></i>
                <span class="fw-semibold">Periode Aktif</span>
            </div>
            <div class="card-body">
                <?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">
                <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>
                    <a href="/academic-period" class="btn btn-sm btn-primary">Atur Periode</a>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Akses Cepat + Info -->
    <div class="col-md-12 col-lg-4">
        <div class="card h-100">
            <div class="card-header py-2 d-flex align-items-center gap-2">
                <i class="bi bi-grid text-primary"></i>
                <span class="fw-semibold">Akses Cepat</span>
            </div>
            <div class="card-body">
                <div class="row g-2 mb-3">
                    <div class="col-4"><a href="/student" class="btn btn-outline-primary quick-btn w-100"><i class="bi bi-people"></i><span>Siswa</span></a></div>
                    <div class="col-4"><a href="/teacher" class="btn btn-outline-success quick-btn w-100"><i class="bi bi-person-badge"></i><span>Guru</span></a></div>
                    <div class="col-4"><a href="/attendance" class="btn btn-outline-info quick-btn w-100"><i class="bi bi-calendar-check"></i><span>Absensi</span></a></div>
                    <div class="col-4"><a href="/attendance/qr-scan" class="btn btn-outline-warning quick-btn w-100"><i class="bi bi-qr-code-scan"></i><span>Scan QR</span></a></div>
                    <div class="col-4"><a href="/asc-schedule" class="btn btn-outline-secondary quick-btn w-100"><i class="bi bi-calendar3-week"></i><span>Jadwal</span></a></div>
                    <div class="col-4"><a href="/settings" class="btn btn-outline-danger quick-btn w-100"><i class="bi bi-gear"></i><span>Setting</span></a></div>
                </div>
                <hr class="my-2">
                <table class="table table-sm table-borderless mb-0 small">
                    <tr>
                        <td class="text-muted py-1"><i class="bi bi-person-circle me-1"></i>Login sebagai</td>
                        <td class="fw-semibold py-1"><?= esc(session('user_name')) ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted py-1"><i class="bi bi-shield-check me-1"></i>Role</td>
                        <td class="py-1"><span class="badge bg-primary"><?= ucfirst(session('user_role')) ?></span></td>
                    </tr>
                    <tr>
                        <td class="text-muted py-1"><i class="bi bi-clock me-1"></i>Tanggal</td>
                        <td class="py-1"><?= date('d M Y, H:i') ?></td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- ── REKAP PER GRADE (Dinamis dari DB) ──────────────────── -->
<?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'];
}

// Warna header per grade (cycling)
$gradeColors = ['#1e3a5f','#4a2c6e','#0f4c5c','#8b4513','#1a4a1a','#4a1a3a'];
$colorIdx = 0;
?>

<?php if (!empty($gradeGroups)): ?>
<div class="row g-3 mb-3">
    <div class="col-12">
        <h6 class="text-muted fw-semibold mb-0 small text-uppercase" style="letter-spacing:.06em">
            <i class="bi bi-bar-chart me-1"></i>Rekap Siswa per Tingkat
        </h6>
    </div>
</div>
<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="grade-card">
            <div class="grade-header" style="background:<?= $color ?>">
                <i class="bi bi-mortarboard-fill me-2"></i>KELAS <?= esc($gradeName) ?>
            </div>
            <div class="grade-body">
                <div class="grade-total text-body"><?= number_format($gradeData['total']) ?><small class="fs-6 fw-normal text-muted ms-1">siswa</small></div>
                <div class="text-center small text-muted mb-2">
                    <i class="bi bi-gender-male text-primary"></i> <?= $gradeData['male'] ?>
                    &nbsp;|&nbsp;
                    <i class="bi bi-gender-female text-danger"></i> <?= $gradeData['female'] ?>
                </div>
                <div class="class-list">
                    <?php if (empty($gradeData['classes'])): ?>
                    <div class="text-center text-muted py-2 small">Belum ada kelas</div>
                    <?php else: ?>
                    <?php foreach ($gradeData['classes'] as $cls): ?>
                    <div class="class-item">
                        <span class="fw-medium"><?= esc($cls['class_name']) ?></span>
                        <span class="text-muted">
                            <?= $cls['total'] ?>
                            <small>(L:<?= $cls['male_count'] ?> P:<?= $cls['female_count'] ?>)</small>
                        </span>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php else: ?>
<div class="alert alert-info">
    <i class="bi bi-info-circle me-2"></i>
    Belum ada data kelas pada periode aktif.
    <a href="/class-assignment" class="alert-link">Assign siswa ke kelas</a>.
</div>
<?php endif; ?>

<!-- ── SISWA TERBARU ──────────────────────────────────────── -->
<div class="row g-3 mt-1">
    <div class="col-12">
        <div class="card">
            <div class="card-header py-2 d-flex align-items-center justify-content-between">
                <div class="d-flex align-items-center gap-2">
                    <i class="bi bi-person-plus text-primary"></i>
                    <span class="fw-semibold">Siswa Terbaru Ditambahkan</span>
                </div>
                <a href="/student" class="btn btn-sm btn-link text-decoration-none">Lihat semua →</a>
            </div>
            <div class="card-body p-0">
                <?php if (!empty($recent_students)): ?>
                <div class="list-group list-group-flush">
                    <?php foreach ($recent_students as $s): ?>
                    <div class="list-group-item py-2 d-flex align-items-center gap-3">
                        <div class="bg-primary bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center flex-shrink-0"
                             style="width:36px;height:36px">
                            <i class="bi bi-person text-primary"></i>
                        </div>
                        <div class="flex-grow-1 min-w-0">
                            <div class="fw-semibold small text-truncate"><?= esc($s['full_name']) ?></div>
                            <div class="text-muted small">NIS: <?= esc($s['nis']) ?> &middot; <?= esc($s['entry_year']) ?></div>
                        </div>
                        <a href="/student/show/<?= $s['id'] ?>" class="btn btn-sm btn-outline-primary flex-shrink-0">
                            <i class="bi bi-eye"></i>
                        </a>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php else: ?>
                <div class="text-center text-muted py-5">
                    <i class="bi bi-inbox fs-3 d-block mb-2 opacity-25"></i>
                    <small>Belum ada data siswa</small>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

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