<?= $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 flex-grow-1">
            <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>

        <!-- Progress Counter -->
        <div class="ms-auto d-flex align-items-center gap-2">
            <span id="progressText" class="fw-bold text-success fs-6"><?= $totalHafal ?></span>
            <span class="text-muted small">/ 114 Surah Hafal</span>
            <div class="progress ms-2" style="width:120px; height:10px;">
                <div class="progress-bar bg-success" id="progressBar"
                     style="width:<?= round(($totalHafal / 114) * 100) ?>%"></div>
            </div>
        </div>
    </div>
</div>

<!-- Tombol Aksi -->
<div class="d-flex align-items-center gap-2 mb-3 flex-wrap">
    <button class="btn btn-success" id="btnSimpan" onclick="saveHafalan()">
        <i class="bi bi-save me-1"></i> Simpan Hafalan
    </button>
    <button class="btn btn-outline-secondary btn-sm" onclick="toggleAll(true)">
        <i class="bi bi-check-all me-1"></i> Pilih Semua
    </button>
    <button class="btn btn-outline-secondary btn-sm" onclick="toggleAll(false)">
        <i class="bi bi-x-square me-1"></i> Batal Semua
    </button>
    <span class="ms-auto text-muted small">
        🟢 Hafal &nbsp; ⬜ Belum Hafal &nbsp; — klik kartu untuk toggle
    </span>
</div>

<form id="formHafalan">
    <input type="hidden" name="program_id" value="<?= $selectedProgram['id'] ?>">
    <input type="hidden" name="student_id" value="<?= $selectedStudentId ?>">

    <?php foreach ($surahsByJuz as $juz => $surahsInJuz): ?>
    <div class="mb-4">
        <div class="d-flex align-items-center mb-2 gap-2">
            <span class="badge bg-dark px-3 py-2" style="font-size:0.85rem;">Juz <?= $juz ?></span>
            <span class="text-muted small"><?= count($surahsInJuz) ?> surah</span>
            <hr class="flex-grow-1 my-0">
        </div>
        <div class="row g-2">
            <?php foreach ($surahsInJuz as $s): ?>
            <?php
                $isHafal = isset($hafalanMap[$s['id']]) && $hafalanMap[$s['id']]['is_hafal'];
            ?>
            <div class="col-6 col-sm-4 col-md-3 col-xl-2">
                <div class="surah-card card border-0 shadow-sm h-100 user-select-none <?= $isHafal ? 'hafal' : '' ?>"
                     data-id="<?= $s['id'] ?>"
                     onclick="toggleSurah(this)"
                     style="cursor:pointer; transition: all 0.18s; <?= $isHafal ? 'background:#d8f3dc; border-left: 4px solid #2d6a4f !important;' : 'background:#fff;' ?>">
                    <div class="card-body p-2 d-flex flex-column align-items-center text-center">
                        <div class="fw-bold mb-1" style="font-size:1.1rem; color: <?= $isHafal ? '#1b4332' : '#6c757d' ?>">
                            <?= $s['number'] ?>
                        </div>
                        <div class="fw-semibold small lh-sm mb-1" style="color: <?= $isHafal ? '#2d6a4f' : '#333' ?>">
                            <?= esc($s['name_latin']) ?>
                        </div>
                        <div class="text-muted" style="font-size:0.8rem; font-family: 'Traditional Arabic', serif; direction:rtl;">
                            <?= esc($s['name_arabic']) ?>
                        </div>
                        <div class="mt-1" style="font-size:0.68rem; color:#aaa;">
                            <?= $s['total_ayat'] ?> ayat
                        </div>
                        <?php if ($isHafal): ?>
                        <div class="mt-1">
                            <span class="badge bg-success" style="font-size:0.6rem;">✓ Hafal</span>
                        </div>
                        <?php endif; ?>
                    </div>
                    <input type="checkbox" name="hafal_surah_ids[]" value="<?= $s['id'] ?>"
                           <?= $isHafal ? 'checked' : '' ?> class="d-none surah-check">
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endforeach; ?>
</form>

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

<?= $this->section('scripts') ?>
<script>
const CSRF_TOKEN = '<?= csrf_hash() ?>';
const CSRF_NAME  = '<?= csrf_token() ?>';

// 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/hafalan/${programId}?student_id=${studentSelect.value}`;
    }
});

// Set active classroom in filter on page load based on currently selected student
const activeStudentOpt = studentSelect.options[studentSelect.selectedIndex];
if (activeStudentOpt && activeStudentOpt.dataset.classroomId) {
    classroomSelect.value = activeStudentOpt.dataset.classroomId;
    
    // Saring dropdown siswa di client side agar hanya memuat siswa dari kelas ini saja saat page load
    const selectedClassId = activeStudentOpt.dataset.classroomId;
    studentSelect.innerHTML = '';
    originalOptions.forEach(opt => {
        if (opt.value === '' || opt.dataset.classroomId === selectedClassId) {
            studentSelect.appendChild(opt);
        }
    });
    // Set ulang value yang terpilih
    studentSelect.value = activeStudentOpt.value;
}

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

function toggleSurah(card) {
    const check = card.querySelector('.surah-check');
    const isNowHafal = !card.classList.contains('hafal');

    card.classList.toggle('hafal', isNowHafal);
    check.checked = isNowHafal;

    if (isNowHafal) {
        card.style.background    = '#d8f3dc';
        card.style.borderLeft    = '4px solid #2d6a4f';
        card.querySelector('.fw-bold').style.color    = '#1b4332';
        card.querySelector('.fw-semibold').style.color = '#2d6a4f';
    } else {
        card.style.background    = '#fff';
        card.style.borderLeft    = '';
        card.querySelector('.fw-bold').style.color    = '#6c757d';
        card.querySelector('.fw-semibold').style.color = '#333';
    }

    updateCounter();
}

function toggleAll(checked) {
    document.querySelectorAll('.surah-card').forEach(card => {
        const isHafal = card.classList.contains('hafal');
        if (checked !== isHafal) toggleSurah(card);
    });
}

function updateCounter() {
    const total = document.querySelectorAll('.surah-check:checked').length;
    document.getElementById('progressText').textContent = total;
    document.getElementById('progressBar').style.width  = Math.round((total / 114) * 100) + '%';
}

async function saveHafalan() {
    const btn = document.getElementById('btnSimpan');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Menyimpan...';

    const form = document.getElementById('formHafalan');
    const fd   = new FormData(form);
    fd.append(CSRF_NAME, CSRF_TOKEN);

    try {
        const res  = await fetch('/guru/tahfidz/hafalan/save', { method: 'POST', body: fd });
        const data = await res.json();

        if (data.success) {
            showToast('success', `Hafalan berhasil disimpan. Total: <strong>${data.total_hafal}</strong> surah.`);
        } else {
            showToast('danger', data.message || 'Gagal menyimpan.');
        }
    } catch (err) {
        showToast('danger', 'Terjadi kesalahan koneksi.');
    } finally {
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-save me-1"></i> Simpan Hafalan';
    }
}

function showToast(type, msg) {
    const el = document.createElement('div');
    el.className = `alert alert-${type} alert-dismissible fade show position-fixed top-0 end-0 m-3 shadow`;
    el.style.zIndex = 9999;
    el.innerHTML = msg + '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
    document.body.appendChild(el);
    setTimeout(() => el.remove(), 5000);
}
</script>
<?= $this->endSection() ?>
