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

<div class="container-fluid px-4 py-3">

    <div class="d-flex align-items-center justify-content-between mb-4">
        <div>
            <h5 class="fw-bold mb-0">Data Leger Nilai</h5>
            <small class="text-muted">Pilih Tahun Ajaran → Semester → Kelas</small>
        </div>
        <div class="d-flex gap-2">
            <a href="/leger-import" class="btn btn-outline-secondary btn-sm">
                <i class="bi bi-upload me-1"></i>Import Leger
            </a>
            <?php if ($legerData && !empty($legerData['students'])): ?>
                <a href="/leger-import/print?classroom_id=<?= $selectedClassroomId ?>&period_id=<?= $selectedPeriodId ?>"
                   class="btn btn-outline-success btn-sm" target="_blank">
                    <i class="bi bi-printer me-1"></i>Cetak
                </a>
                <a href="/leger-import/export-excel?classroom_id=<?= $selectedClassroomId ?>&period_id=<?= $selectedPeriodId ?>"
                   class="btn btn-outline-primary btn-sm">
                    <i class="bi bi-file-earmark-excel me-1"></i>Export Excel
                </a>
            <?php endif; ?>
        </div>
    </div>

    <!-- Filter: Tahun Ajaran → Semester → Kelas -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body py-3">
            <div class="row g-3 align-items-end">
                <div class="col-md-3">
                    <label class="form-label fw-semibold mb-1">Tahun Ajaran</label>
                    <select id="selYear" class="form-select form-select-sm">
                        <option value="">-- Pilih Tahun Ajaran --</option>
                        <?php foreach ($allYears as $y): ?>
                            <option value="<?= $y['id'] ?>" <?= ($selectedYearId == $y['id']) ? 'selected' : '' ?>>
                                <?= esc($y['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label fw-semibold mb-1">Semester</label>
                    <select id="selPeriod" class="form-select form-select-sm">
                        <option value="">-- Pilih Semester --</option>
                        <?php foreach ($allPeriods as $p): ?>
                            <option value="<?= $p['id'] ?>" <?= ($selectedPeriodId == $p['id']) ? 'selected' : '' ?>>
                                <?= esc($p['semester']) ?><?= $p['is_active'] ? ' (Aktif)' : '' ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label fw-semibold mb-1">Kelas</label>
                    <select id="selClassroom" class="form-select form-select-sm">
                        <option value="">-- Pilih Kelas --</option>
                        <?php foreach ($allClassrooms as $c): ?>
                            <option value="<?= $c['id'] ?>" <?= ($selectedClassroomId == $c['id']) ? 'selected' : '' ?>>
                                <?= esc($c['grade_name'] . ' — ' . $c['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <button id="btnTampilkan" class="btn btn-primary btn-sm w-100">
                        <i class="bi bi-search me-1"></i>Tampilkan
                    </button>
                </div>
            </div>
        </div>
    </div>

    <?php if ($selectedClassroomId && $selectedPeriodId): ?>

        <?php if (!$legerData || empty($legerData['students'])): ?>
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center py-5 text-muted">
                    <i class="bi bi-inbox fs-1 d-block mb-2"></i>
                    <p class="mb-1">Belum ada data leger untuk kelas dan periode ini</p>
                    <a href="/leger-import" class="btn btn-primary btn-sm mt-2">
                        <i class="bi bi-upload me-1"></i>Import Leger
                    </a>
                </div>
            </div>

        <?php else: ?>
            <?php
            $students     = $legerData['students'];
            $subjectCodes = $legerData['subject_codes']; // [{id,code,name}, ...]
            $totalSiswa   = count($students);
            $totals       = array_column($students, 'total');
            $maxTotal     = max($totals);
            $minTotal     = min($totals);
            $avgTotal     = array_sum($totals) / $totalSiswa;

            // Rata-rata per mapel
            $avgBySubject = [];
            foreach ($subjectCodes as $s) {
                $vals = array_filter(array_map(fn($row) => $row['grades'][$s['id']] ?? null, $students));
                $avgBySubject[$s['id']] = count($vals) > 0 ? array_sum($vals) / count($vals) : 0;
            }

            // Ranking
            $totalsForRank = array_column($students, 'total');
            arsort($totalsForRank);
            $ranks = [];
            $rank = 1;
            foreach ($totalsForRank as $idx => $val) { $ranks[$idx] = $rank++; }

            // Group mapel untuk header
            $paiCodes   = array_values(array_filter($subjectCodes, fn($s) => in_array($s['code'], ['QH','AA','FIK','SKI'])));
            $mulokCodes = array_values(array_filter($subjectCodes, fn($s) => in_array($s['code'], ['BAJ','TAQ'])));
            $singleCodes= array_values(array_filter($subjectCodes, fn($s) => !in_array($s['code'], ['QH','AA','FIK','SKI','BAJ','TAQ'])));
            ?>

            <!-- Summary -->
            <div class="row g-3 mb-4">
                <div class="col-6 col-md-3">
                    <div class="card border-0 bg-primary text-white shadow-sm">
                        <div class="card-body py-3 d-flex align-items-center gap-3">
                            <i class="bi bi-people-fill fs-3 opacity-75"></i>
                            <div><div class="fs-4 fw-bold"><?= $totalSiswa ?></div><small>Total Siswa</small></div>
                        </div>
                    </div>
                </div>
                <div class="col-6 col-md-3">
                    <div class="card border-0 bg-success text-white shadow-sm">
                        <div class="card-body py-3 d-flex align-items-center gap-3">
                            <i class="bi bi-journal-check fs-3 opacity-75"></i>
                            <div><div class="fs-4 fw-bold"><?= count($subjectCodes) ?></div><small>Mapel</small></div>
                        </div>
                    </div>
                </div>
                <div class="col-6 col-md-3">
                    <div class="card border-0 bg-info text-white shadow-sm">
                        <div class="card-body py-3 d-flex align-items-center gap-3">
                            <i class="bi bi-graph-up fs-3 opacity-75"></i>
                            <div><div class="fs-4 fw-bold"><?= number_format($avgTotal, 1) ?></div><small>Rata-rata Total</small></div>
                        </div>
                    </div>
                </div>
                <div class="col-6 col-md-3">
                    <div class="card border-0 bg-warning text-dark shadow-sm">
                        <div class="card-body py-3 d-flex align-items-center gap-3">
                            <i class="bi bi-trophy-fill fs-3 opacity-75"></i>
                            <div><div class="fs-4 fw-bold"><?= number_format($maxTotal, 0) ?></div><small>Total Tertinggi</small></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Tabel Leger -->
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 fw-semibold">
                        <i class="bi bi-table me-2 text-primary"></i>
                        Leger — <?= esc($classroom['name'] ?? '') ?> |
                        <?= esc($period['semester'] ?? '') ?> <?= esc($period['year_name'] ?? '') ?>
                    </h6>
                    <small class="text-muted">Scroll kanan →</small>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered table-hover align-middle mb-0" style="font-size:.8rem;">
                            <thead>
                                <tr class="table-dark">
                                    <th rowspan="2" class="align-middle text-center" style="width:30px;">#</th>
                                    <th rowspan="2" class="align-middle" style="width:75px;">NIS</th>
                                    <th rowspan="2" class="align-middle" style="min-width:180px;">Nama Siswa</th>
                                    <th rowspan="2" class="align-middle text-center" style="width:35px;">JK</th>
                                    <?php if (!empty($paiCodes)): ?>
                                        <th colspan="<?= count($paiCodes) ?>" class="text-center" style="background:#1a3a5c;">PAI</th>
                                    <?php endif; ?>
                                    <?php foreach ($singleCodes as $s): ?>
                                        <th rowspan="2" class="text-center align-middle" style="min-width:50px;" title="<?= esc($s['name']) ?>">
                                            <?= esc($s['code']) ?>
                                        </th>
                                    <?php endforeach; ?>
                                    <?php if (!empty($mulokCodes)): ?>
                                        <th colspan="<?= count($mulokCodes) ?>" class="text-center" style="background:#1a3a5c;">MULOK</th>
                                    <?php endif; ?>
                                    <th rowspan="2" class="text-center align-middle" style="width:60px;">Total</th>
                                    <th rowspan="2" class="text-center align-middle" style="width:50px;">Rank</th>
                                </tr>
                                <tr class="table-secondary">
                                    <?php foreach ($paiCodes as $s): ?>
                                        <th class="text-center" style="min-width:48px;"><?= esc($s['code']) ?></th>
                                    <?php endforeach; ?>
                                    <?php foreach ($mulokCodes as $s): ?>
                                        <th class="text-center" style="min-width:48px;"><?= esc($s['code']) ?></th>
                                    <?php endforeach; ?>
                                </tr>
                                <!-- Baris rata-rata -->
                                <tr class="table-info" style="font-size:.75rem; font-weight:600;">
                                    <td colspan="4" class="text-center text-muted">Rata-rata</td>
                                    <?php foreach ($subjectCodes as $s): ?>
                                        <td class="text-center"><?= number_format($avgBySubject[$s['id']] ?? 0, 1) ?></td>
                                    <?php endforeach; ?>
                                    <td class="text-center"><?= number_format($avgTotal, 1) ?></td>
                                    <td></td>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($students as $idx => $row): ?>
                                <tr>
                                    <td class="text-center"><?= $idx + 1 ?></td>
                                    <td><?= esc($row['student']['nis']) ?></td>
                                    <td><?= esc($row['student']['full_name']) ?></td>
                                    <td class="text-center">
                                        <span class="badge" style="background:<?= $row['student']['gender']=='L' ? '#0d6efd' : '#e91e8c' ?>">
                                            <?= $row['student']['gender'] ?>
                                        </span>
                                    </td>
                                    <?php foreach ($subjectCodes as $s): ?>
                                        <?php $score = $row['grades'][$s['id']] ?? null; ?>
                                        <td class="text-center <?= ($score !== null && $score < 70) ? 'table-danger' : '' ?>">
                                            <?= $score !== null ? number_format($score, 0) : '<span class="text-muted">-</span>' ?>
                                        </td>
                                    <?php endforeach; ?>
                                    <td class="text-center fw-bold <?= ($row['total'] >= $maxTotal) ? 'text-success' : (($row['total'] <= $minTotal) ? 'text-danger' : '') ?>">
                                        <?= number_format($row['total'], 0) ?>
                                    </td>
                                    <td class="text-center">
                                        <?php $r = $ranks[$idx]; ?>
                                        <?php if ($r == 1): ?>
                                            <span class="badge" style="background:#ffd700;color:#333;">1</span>
                                        <?php elseif ($r == 2): ?>
                                            <span class="badge bg-secondary">2</span>
                                        <?php elseif ($r == 3): ?>
                                            <span class="badge" style="background:#cd7f32;">3</span>
                                        <?php else: ?>
                                            <span class="text-muted"><?= $r ?></span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        <?php endif; ?>

    <?php else: ?>
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center py-5 text-muted">
                <i class="bi bi-arrow-up-circle fs-1 d-block mb-2"></i>
                Pilih Tahun Ajaran, Semester, dan Kelas di atas untuk menampilkan leger
            </div>
        </div>
    <?php endif; ?>

</div>

<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
const selYear     = document.getElementById('selYear');
const selPeriod   = document.getElementById('selPeriod');
const selClassroom= document.getElementById('selClassroom');
const btnTampilkan= document.getElementById('btnTampilkan');

// Load semester saat tahun ajaran berubah
selYear.addEventListener('change', function() {
    const yearId = this.value;
    selPeriod.innerHTML = '<option value="">Memuat...</option>';
    selClassroom.innerHTML = '<option value="">-- Pilih Kelas --</option>';

    if (!yearId) { selPeriod.innerHTML = '<option value="">-- Pilih Semester --</option>'; return; }

    fetch('/leger-import/get-periods?year_id=' + yearId)
        .then(r => r.json())
        .then(data => {
            selPeriod.innerHTML = '<option value="">-- Pilih Semester --</option>';
            data.forEach(p => {
                selPeriod.innerHTML += `<option value="${p.id}">${p.semester}${p.is_active==1?' (Aktif)':''}</option>`;
            });
        });
});

// Load kelas yang punya leger saat semester berubah
selPeriod.addEventListener('change', function() {
    const periodId = this.value;
    selClassroom.innerHTML = '<option value="">Memuat...</option>';

    if (!periodId) { selClassroom.innerHTML = '<option value="">-- Pilih Kelas --</option>'; return; }

    fetch('/leger-import/get-classrooms?period_id=' + periodId)
        .then(r => r.json())
        .then(data => {
            selClassroom.innerHTML = '<option value="">-- Pilih Kelas --</option>';
            if (data.length === 0) {
                selClassroom.innerHTML = '<option value="">Belum ada leger di periode ini</option>';
                return;
            }
            data.forEach(c => {
                selClassroom.innerHTML += `<option value="${c.id}">${c.grade_name} — ${c.name}</option>`;
            });
        });
});

// Tombol tampilkan
btnTampilkan.addEventListener('click', function() {
    const yearId     = selYear.value;
    const periodId   = selPeriod.value;
    const classroomId= selClassroom.value;
    if (!periodId || !classroomId) { alert('Pilih semester dan kelas terlebih dahulu!'); return; }
    window.location.href = `/leger-import/view?year_id=${yearId}&period_id=${periodId}&classroom_id=${classroomId}`;
});
</script>
<?= $this->endSection() ?>