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

<?= $this->include('guru/tahfidz/_subnav') ?>

<!-- Filter Bar -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-body py-2 d-flex align-items-center flex-wrap gap-3">
        <!-- Pilih Kelas -->
        <div class="d-flex align-items-center gap-2">
            <span class="text-muted small fw-semibold">Kelas:</span>
            <select id="classroomSelect" class="form-select form-select-sm" style="max-width:180px;">
                <option value="">-- Semua Kelas --</option>
                <?php
                $uniqueClassrooms = [];
                foreach ($students as $st) {
                    if ($st['classroom_id'] && !isset($uniqueClassrooms[$st['classroom_id']])) {
                        $uniqueClassrooms[$st['classroom_id']] = $st['classroom_name'];
                    }
                }
                asort($uniqueClassrooms);
                foreach ($uniqueClassrooms as $cid => $cname):
                ?>
                <option value="<?= $cid ?>"><?= esc($cname) ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <!-- Pilih Siswa -->
        <div class="d-flex align-items-center gap-2">
            <span class="text-muted small fw-semibold">Siswa:</span>
            <select id="studentSelect" class="form-select form-select-sm" style="max-width:280px;">
                <?php foreach ($students as $st): ?>
                <option value="<?= $st['id'] ?>" data-classroom-id="<?= esc($st['classroom_id']) ?>" <?= $st['id'] == $selectedStudentId ? 'selected' : '' ?>>
                    <?= esc($st['full_name']) ?> (<?= esc($st['nis']) ?>)
                </option>
                <?php endforeach; ?>
            </select>
        </div>
    </div>
</div>

<!-- Ringkasan Atas -->
<?php if ($selectedStudentId): ?>
<div class="row g-3 mb-3">
    <div class="col-6 col-md-3">
        <div class="card border-0 shadow-sm text-center py-3">
            <div class="fs-2 fw-bold text-success"><?= $totalHafal ?></div>
            <div class="text-muted small">Surah Hafal</div>
            <div class="text-muted" style="font-size:0.72rem;">dari 114 surah</div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="card border-0 shadow-sm text-center py-3">
            <?php $juzSelesai = count(array_filter($progressJuz, fn($j) => $j['persen'] === 100)); ?>
            <div class="fs-2 fw-bold text-primary"><?= $juzSelesai ?></div>
            <div class="text-muted small">Juz Selesai</div>
            <div class="text-muted" style="font-size:0.72rem;">dari 30 juz</div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="card border-0 shadow-sm text-center py-3">
            <div class="fs-2 fw-bold text-warning"><?= $avgNilai !== null ? number_format($avgNilai, 1) : '—' ?></div>
            <div class="text-muted small">Rata-rata Nilai</div>
            <div class="text-muted" style="font-size:0.72rem;">dari semua setoran</div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="card border-0 shadow-sm text-center py-3">
            <div class="fs-2 fw-bold text-info"><?= round(($totalHafal / 114) * 100) ?>%</div>
            <div class="text-muted small">Total Progress</div>
            <div class="progress mt-1 mx-3" style="height:6px;">
                <div class="progress-bar bg-info" style="width:<?= round(($totalHafal / 114) * 100) ?>%"></div>
            </div>
        </div>
    </div>
</div>

<!-- 30 Juz Visualization -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-header bg-light border-0 py-3">
        <div class="fw-bold"><i class="bi bi-grid-3x3-gap me-2 text-success"></i>Progress per Juz</div>
    </div>
    <div class="card-body">
        <div class="row g-2">
            <?php foreach ($progressJuz as $juz => $data): ?>
            <?php
                $pct   = $data['persen'];
                $color = match(true) {
                    $pct === 100 => '#2d6a4f',
                    $pct >= 50   => '#52b788',
                    $pct > 0     => '#b7e4c7',
                    default      => '#e9ecef',
                };
                $textColor = $pct > 50 ? 'white' : '#333';
            ?>
            <div class="col-6 col-sm-4 col-md-2">
                <div class="rounded p-2 text-center position-relative" style="background:<?= $color ?>; min-height:70px;">
                    <div class="fw-bold" style="color:<?= $textColor ?>; font-size:1rem;">Juz <?= $juz ?></div>
                    <div style="color:<?= $textColor ?>; font-size:0.85rem; opacity:0.9;">
                        <?= $data['hafal'] ?>/<?= $data['total_surah'] ?> surah
                    </div>
                    <div style="color:<?= $textColor ?>; font-size:0.75rem;">
                        <?= $pct ?>%
                    </div>
                    <?php if ($pct === 100): ?>
                    <div class="position-absolute top-0 end-0 p-1">✅</div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- Riwayat Setoran Terakhir -->
<?php if (!empty($recentSetoran)): ?>
<div class="card border-0 shadow-sm">
    <div class="card-header bg-light border-0 py-3">
        <div class="fw-bold"><i class="bi bi-clock-history me-2 text-muted"></i>Setoran Terakhir</div>
    </div>
    <div class="table-responsive">
        <table class="table table-sm table-hover align-middle mb-0">
            <thead class="table-light">
                <tr>
                    <th>Tanggal</th>
                    <th>Surah</th>
                    <th>Ayat</th>
                    <th>Jenis</th>
                    <th class="text-center">Nilai</th>
                    <th>Catatan</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($recentSetoran as $s): ?>
                <tr>
                    <td class="text-muted small"><?= date('d/m/Y', strtotime($s['setoran_date'])) ?></td>
                    <td>
                        <?php if ($s['is_iqra']): ?>
                            <div class="fw-semibold small text-success">Iqra <?= $s['iqra_no'] ?></div>
                        <?php else: ?>
                            <div class="fw-semibold small"><?= esc($s['name_latin']) ?></div>
                            <div class="text-muted" style="font-size:0.8rem; font-family: serif;"><?= esc($s['name_arabic']) ?></div>
                        <?php endif; ?>
                    </td>
                    <td class="small">
                        <?php if ($s['is_iqra']): ?>
                            Hal. <?= $s['iqra_page_start'] ?>–<?= $s['iqra_page_end'] ?>
                        <?php else: ?>
                            <?= $s['ayat_start'] ?>–<?= $s['ayat_end'] ?>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span class="badge bg-<?= $s['jenis'] === 'ziyadah' ? 'success' : 'info' ?> bg-opacity-15 text-<?= $s['jenis'] === 'ziyadah' ? 'success' : 'info' ?>" style="font-size:0.7rem;">
                            <?= $s['jenis'] === 'ziyadah' ? 'Ziyadah' : "Mura'jaah" ?>
                        </span>
                    </td>
                    <td class="text-center">
                        <?php
                        $v = $s['nilai'];
                        $cls = match(true) { $v>=95=>'success', $v>=85=>'primary', $v>=75=>'info', $v>=60=>'warning', default=>'danger' };
                        ?>
                        <span class="badge bg-<?= $cls ?>"><?= $v ?></span>
                    </td>
                    <td class="text-muted small fst-italic"><?= esc($s['catatan'] ?: '—') ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<?php endif; ?>

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

<?= $this->section('scripts') ?>
<script>
// Filter Siswa Berdasarkan Kelas Terpilih
const classroomSelect = document.getElementById('classroomSelect');
const studentSelect   = document.getElementById('studentSelect');
const originalOptions = Array.from(studentSelect.options);

classroomSelect.addEventListener('change', function() {
    const selectedClassId = this.value;
    studentSelect.innerHTML = '';
    
    let hasMatch = false;
    originalOptions.forEach(opt => {
        if (opt.value === '') {
            studentSelect.appendChild(opt);
            return;
        }
        if (selectedClassId === '' || opt.dataset.classroomId === selectedClassId) {
            studentSelect.appendChild(opt);
            hasMatch = true;
        }
    });
    
    if (hasMatch) {
        studentSelect.selectedIndex = 0;
        const programId = <?= $selectedProgram['id'] ?>;
        window.location = `/guru/tahfidz/progress/${programId}?student_id=${studentSelect.value}`;
    }
});

const activeStudentOpt = studentSelect.options[studentSelect.selectedIndex];
if (activeStudentOpt && activeStudentOpt.dataset.classroomId) {
    classroomSelect.value = activeStudentOpt.dataset.classroomId;
    
    const selectedClassId = activeStudentOpt.dataset.classroomId;
    studentSelect.innerHTML = '';
    originalOptions.forEach(opt => {
        if (opt.value === '' || opt.dataset.classroomId === selectedClassId) {
            studentSelect.appendChild(opt);
        }
    });
    studentSelect.value = activeStudentOpt.value;
}

studentSelect?.addEventListener('change', function () {
    const programId = <?= $selectedProgram['id'] ?>;
    window.location = `/guru/tahfidz/progress/${programId}?student_id=${this.value}`;
});
</script>
<?= $this->endSection() ?>
