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

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

<div class="row g-3">
    <!-- Form Setoran -->
    <div class="col-lg-5">
        <!-- Form Input -->
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-success bg-opacity-10 border-0 py-3">
                <div class="fw-bold text-success">
                    <i class="bi bi-journal-plus me-2"></i>
                    <?= esc(match($selectedProgram['type']) { 'pk' => 'Tahfidz PK', 'boarding' => 'Tahfidz Boarding', default => 'Tahfidz KBM Pagi' }) ?>
                </div>
            </div>
            <div class="card-body">
                <form id="formSetoran">
                    <input type="hidden" name="program_id" value="<?= $selectedProgram['id'] ?>">

                    <!-- Pilih Kelas (Untuk mempermudah filter KBM Pagi/PK) -->
                    <div class="mb-3">
                        <label class="form-label fw-semibold" for="filter_classroom_id">Kelas</label>
                        <select id="filter_classroom_id" class="form-select">
                            <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>

                    <!-- Siswa -->
                    <div class="mb-3">
                        <label class="form-label fw-semibold" for="student_id">Siswa <span class="text-danger">*</span></label>
                        <select name="student_id" id="student_id" class="form-select" required>
                            <option value="">-- Pilih Siswa --</option>
                            <?php foreach ($students as $st): ?>
                            <option value="<?= $st['id'] ?>" 
                                    data-classroom-id="<?= esc($st['classroom_id']) ?>"
                                    <?= $selectedStudentId == $st['id'] ? 'selected' : '' ?>>
                                <?= esc($st['full_name']) ?> (<?= esc($st['nis']) ?>)
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- Tipe Setoran (Al-Quran / Iqra) -->
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Tipe Setoran <span class="text-danger">*</span></label>
                        <div class="d-flex gap-3">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="is_iqra" id="tipe_quran" value="0" checked>
                                <label class="form-check-label" for="tipe_quran">Al-Qur'an</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="is_iqra" id="tipe_iqra" value="1">
                                <label class="form-check-label" for="tipe_iqra">Iqra</label>
                            </div>
                        </div>
                    </div>

                    <!-- Quran Fields -->
                    <div id="quranFieldsContainer">
                        <!-- Surah -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold" for="surah_id">Surah <span class="text-danger">*</span></label>
                            <select name="surah_id" id="surah_id" class="form-select" required>
                                <option value="">-- Pilih Surah --</option>
                                <?php foreach ($surahs as $s): ?>
                                <option value="<?= $s['id'] ?>" data-total="<?= $s['total_ayat'] ?>">
                                    <?= $s['number'] ?>. <?= esc($s['name_latin']) ?> (<?= $s['name_arabic'] ?>) — <?= $s['total_ayat'] ?> ayat
                                </option>
                                <?php endforeach; ?>
                            </select>
                            <div id="surahInfo" class="form-text text-muted mt-1" style="display:none;"></div>
                        </div>

                        <!-- Ayat -->
                        <div class="row g-2 mb-3">
                            <div class="col-6">
                                <label class="form-label fw-semibold" for="ayat_start">Ayat Dari <span class="text-danger">*</span></label>
                                <input type="number" name="ayat_start" id="ayat_start" class="form-control" min="1" value="1" required>
                            </div>
                            <div class="col-6">
                                <label class="form-label fw-semibold" for="ayat_end">Sampai Ayat <span class="text-danger">*</span></label>
                                <input type="number" name="ayat_end" id="ayat_end" class="form-control" min="1" required>
                            </div>
                        </div>
                    </div>

                    <!-- Iqra Fields -->
                    <div id="iqraFieldsContainer" style="display: none;">
                        <div class="mb-3">
                            <label class="form-label fw-semibold" for="iqra_no">Jilid Iqra <span class="text-danger">*</span></label>
                            <select name="iqra_no" id="iqra_no" class="form-select">
                                <option value="">-- Pilih Jilid --</option>
                                <?php for ($i = 1; $i <= 6; $i++): ?>
                                <option value="<?= $i ?>">Iqra <?= $i ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div class="row g-2 mb-3">
                            <div class="col-6">
                                <label class="form-label fw-semibold" for="iqra_page_start">Halaman Dari <span class="text-danger">*</span></label>
                                <input type="number" name="iqra_page_start" id="iqra_page_start" class="form-control" min="1" value="1">
                            </div>
                            <div class="col-6">
                                <label class="form-label fw-semibold" for="iqra_page_end">Sampai Halaman <span class="text-danger">*</span></label>
                                <input type="number" name="iqra_page_end" id="iqra_page_end" class="form-control" min="1">
                            </div>
                        </div>
                    </div>

                    <!-- Jenis -->
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Jenis Setoran <span class="text-danger">*</span></label>
                        <div class="d-flex gap-3">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="jenis" id="jenis_ziyadah" value="ziyadah" checked>
                                <label class="form-check-label" for="jenis_ziyadah">
                                    <span class="badge bg-success bg-opacity-15 text-success">Ziyadah</span>
                                    <small class="text-muted d-block" style="font-size:0.7rem;">Hafalan baru</small>
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="jenis" id="jenis_murajaah" value="murajaah">
                                <label class="form-check-label" for="jenis_murajaah">
                                    <span class="badge bg-info bg-opacity-15 text-info">Mura'jaah</span>
                                    <small class="text-muted d-block" style="font-size:0.7rem;">Mengulang</small>
                                </label>
                            </div>
                        </div>
                    </div>

                    <!-- Nilai -->
                    <div class="mb-3">
                        <label class="form-label fw-semibold" for="nilai">
                            Nilai (0–100) <span class="text-danger">*</span>
                            <span id="nilaiLabel" class="badge ms-2 bg-primary">85 — Jayyid Jiddan</span>
                        </label>
                        <input type="number" name="nilai" id="nilai" class="form-control" min="0" max="100" value="85" required>
                        <div class="d-flex justify-content-between text-muted mt-1" style="font-size:0.72rem;">
                            <span>60 (Maqbul)</span>
                            <span>75 (Jayyid)</span>
                            <span>85 (Jayyid Jiddan)</span>
                            <span>95+ (Mumtaz)</span>
                        </div>
                    </div>

                    <!-- Tanggal -->
                    <div class="mb-3">
                        <label class="form-label fw-semibold" for="setoran_date">Tanggal</label>
                        <input type="date" name="setoran_date" id="setoran_date" class="form-control"
                               value="<?= date('Y-m-d') ?>" max="<?= date('Y-m-d') ?>">
                    </div>

                    <!-- Catatan -->
                    <div class="mb-3">
                        <label class="form-label fw-semibold" for="catatan">Catatan</label>
                        <textarea name="catatan" id="catatan" class="form-control" rows="2"
                                  placeholder="Tajwid, kelancaran, dll..."></textarea>
                    </div>

                    <button type="submit" id="btnSubmit" class="btn btn-success w-100">
                        <i class="bi bi-save me-2"></i>Simpan Setoran
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- Setoran Hari Ini -->
    <div class="col-lg-7">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-light border-0 py-3 d-flex align-items-center justify-content-between">
                <div class="fw-bold"><i class="bi bi-calendar-check me-2 text-success"></i>Setoran Hari Ini</div>
                <span class="badge bg-success" id="todayCount"><?= count($todaySetorans) ?></span>
            </div>
            <div class="card-body p-0">
                <div id="todayList">
                    <?php if (empty($todaySetorans)): ?>
                    <div class="text-center text-muted py-5" id="emptyMsg">
                        <i class="bi bi-inbox fs-1 d-block mb-2 opacity-25"></i>
                        Belum ada setoran hari ini
                    </div>
                    <?php else: ?>
                    <div class="list-group list-group-flush" id="setoranItems">
                        <?php foreach ($todaySetorans as $s): ?>
                        <div class="list-group-item px-3 py-2" id="setoran-<?= $s['id'] ?>">
                            <div class="d-flex align-items-start justify-content-between gap-2">
                                <div class="flex-grow-1">
                                    <div class="fw-semibold small"><?= esc($s['full_name']) ?> <span class="text-muted fw-normal">(<?= esc($s['nis']) ?>)</span></div>
                                    <div class="text-muted small">
                                        <?php if ($s['is_iqra']): ?>
                                            <span class="fw-bold text-success">Iqra <?= $s['iqra_no'] ?></span>
                                            <span class="text-dark">Halaman <?= $s['iqra_page_start'] ?>–<?= $s['iqra_page_end'] ?></span>
                                        <?php else: ?>
                                            <?= esc($s['name_arabic']) ?> — <?= esc($s['name_latin']) ?>
                                            <span class="text-dark">Ayat <?= $s['ayat_start'] ?>–<?= $s['ayat_end'] ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <div class="d-flex gap-2 mt-1">
                                        <span class="badge bg-<?= $s['jenis'] === 'ziyadah' ? 'success' : 'info' ?> bg-opacity-15 text-<?= $s['jenis'] === 'ziyadah' ? 'success' : 'info' ?>">
                                            <?= $s['jenis'] === 'ziyadah' ? 'Ziyadah' : "Mura'jaah" ?>
                                        </span>
                                        <?= renderNilaiBadge($s['nilai']) ?>
                                    </div>
                                    <?php if ($s['catatan']): ?>
                                    <div class="text-muted small mt-1 fst-italic"><?= esc($s['catatan']) ?></div>
                                    <?php endif; ?>
                                    
                                    <!-- WhatsApp Report Button -->
                                    <div class="mt-2">
                                        <?php 
                                        $phone = $s['father_phone'] ?: ($s['mother_phone'] ?: '');
                                        if ($phone) {
                                            // Clean phone number format (e.g. 08xx -> 628xx)
                                            $cleanPhone = preg_replace('/[^0-9]/', '', $phone);
                                            if (str_starts_with($cleanPhone, '0')) {
                                                $cleanPhone = '62' . substr($cleanPhone, 1);
                                            }
                                            $jenisReport = $s['jenis'] === 'ziyadah' ? 'Ziyadah (hafalan baru)' : "Mura'jaah (mengulang)";
                                            $msg = "Assalamualaikum Wr. Wb. Bapak/Ibu Wali Murid dari Ananda *" . esc($s['full_name']) . "*. Kami melaporkan setoran Tahfidz hari ini:\n\n";
                                            if ($s['is_iqra']) {
                                                $msg .= "• Membaca: *Iqra " . $s['iqra_no'] . "*\n";
                                                $msg .= "• Halaman: *" . $s['iqra_page_start'] . " - " . $s['iqra_page_end'] . "*\n";
                                            } else {
                                                $msg .= "• Surah: *" . esc($s['name_latin']) . " (" . esc($s['name_arabic']) . ")*\n";
                                                $msg .= "• Ayat: *" . $s['ayat_start'] . " - " . $s['ayat_end'] . "*\n";
                                            }
                                            $msg .= "• Jenis Setoran: *" . $jenisReport . "*\n";
                                            $msg .= "• Nilai: *" . $s['nilai'] . "*\n";
                                            if ($s['catatan']) {
                                                $msg .= "• Catatan Guru: _" . esc($s['catatan']) . "_\n";
                                            }
                                            $msg .= "\nSemoga berkah dan selalu istiqomah dalam menjaga kalamullah. Syukran, Wassalamualaikum Wr. Wb.";
                                            $waUrl = "https://wa.me/" . $cleanPhone . "?text=" . urlencode($msg);
                                            ?>
                                            <a href="<?= $waUrl ?>" target="_blank" class="btn btn-xs btn-outline-success py-0 px-2 small" style="font-size: 0.72rem;">
                                                <i class="bi bi-whatsapp"></i> Lapor Orangtua
                                            </a>
                                            <?php
                                        } else {
                                            ?>
                                            <span class="text-muted small fst-italic" style="font-size: 0.72rem;">(No WA Ortu belum diisi)</span>
                                            <?php
                                        }
                                        ?>
                                    </div>
                                </div>
                                <button class="btn btn-sm btn-link text-danger p-0 flex-shrink-0 btn-delete-setoran"
                                        data-id="<?= $s['id'] ?>" title="Hapus">
                                    <i class="bi bi-trash3"></i>
                                </button>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
function renderNilaiBadge($nilai) {
    if ($nilai >= 95) return "<span class='badge bg-success'>{$nilai} — Mumtaz</span>";
    if ($nilai >= 85) return "<span class='badge bg-primary'>{$nilai} — Jayyid Jiddan</span>";
    if ($nilai >= 75) return "<span class='badge bg-info text-dark'>{$nilai} — Jayyid</span>";
    if ($nilai >= 60) return "<span class='badge bg-warning text-dark'>{$nilai} — Maqbul</span>";
    return "<span class='badge bg-danger'>{$nilai} — Dhoif</span>";
}
?>

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

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

// Update nilai label
const nilaiSlider = document.getElementById('nilai');
const nilaiLabel  = document.getElementById('nilaiLabel');

function updateNilaiLabel() {
    const v = parseInt(nilaiSlider.value);
    let label = '', cls = 'bg-secondary';
    if (v >= 95)      { label = v + ' — Mumtaz';         cls = 'bg-success'; }
    else if (v >= 85) { label = v + ' — Jayyid Jiddan';  cls = 'bg-primary'; }
    else if (v >= 75) { label = v + ' — Jayyid';         cls = 'bg-info text-dark'; }
    else if (v >= 60) { label = v + ' — Maqbul';         cls = 'bg-warning text-dark'; }
    else              { label = v + ' — Dhoif';           cls = 'bg-danger'; }
    nilaiLabel.textContent = label;
    nilaiLabel.className   = 'badge ms-2 ' + cls;
}
// Filter Siswa Berdasarkan Kelas Terpilih
const filterClassroom = document.getElementById('filter_classroom_id');
const studentSelect   = document.getElementById('student_id');
const originalOptions = Array.from(studentSelect.options);

filterClassroom.addEventListener('change', function() {
    const selectedClassroomId = this.value;
    
    // Reset dropdown siswa
    studentSelect.innerHTML = '';
    
    originalOptions.forEach(opt => {
        // Tampilkan opsi default/kosong
        if (opt.value === '') {
            studentSelect.appendChild(opt);
            return;
        }
        
        // Saring berdasarkan classroom_id
        if (selectedClassroomId === '' || opt.dataset.classroomId === selectedClassroomId) {
            studentSelect.appendChild(opt);
        }
    });
    
    studentSelect.value = ''; // Reset pilihan siswa
});

nilaiSlider.addEventListener('input', updateNilaiLabel);
nilaiSlider.addEventListener('change', updateNilaiLabel);
updateNilaiLabel();

// Update max ayat saat ganti surah
document.getElementById('surah_id').addEventListener('change', function () {
    const opt  = this.options[this.selectedIndex];
    const total = opt.dataset.total || '';
    const info  = document.getElementById('surahInfo');
    if (total) {
        document.getElementById('ayat_end').max = total;
        document.getElementById('ayat_end').value = total;
        info.textContent = 'Total ayat: ' + total;
        info.style.display = 'block';
    } else {
        info.style.display = 'none';
    }
});

// Toggle Al-Quran / Iqra fields
const tipeQuranRadio = document.getElementById('tipe_quran');
const tipeIqraRadio  = document.getElementById('tipe_iqra');
const quranFields    = document.getElementById('quranFieldsContainer');
const iqraFields     = document.getElementById('iqraFieldsContainer');

const surahSelect      = document.getElementById('surah_id');
const ayatStartInput   = document.getElementById('ayat_start');
const ayatEndInput     = document.getElementById('ayat_end');

const iqraNoSelect       = document.getElementById('iqra_no');
const iqraPageStartInput = document.getElementById('iqra_page_start');
const iqraPageEndInput   = document.getElementById('iqra_page_end');

function toggleTipeSetoran() {
    if (tipeIqraRadio.checked) {
        quranFields.style.display = 'none';
        iqraFields.style.display = 'block';
        
        surahSelect.removeAttribute('required');
        ayatStartInput.removeAttribute('required');
        ayatEndInput.removeAttribute('required');
        
        iqraNoSelect.setAttribute('required', 'required');
        iqraPageStartInput.setAttribute('required', 'required');
        iqraPageEndInput.setAttribute('required', 'required');
    } else {
        quranFields.style.display = 'block';
        iqraFields.style.display = 'none';
        
        surahSelect.setAttribute('required', 'required');
        ayatStartInput.setAttribute('required', 'required');
        ayatEndInput.setAttribute('required', 'required');
        
        iqraNoSelect.removeAttribute('required');
        iqraPageStartInput.removeAttribute('required');
        iqraPageEndInput.removeAttribute('required');
    }
}

tipeQuranRadio.addEventListener('change', toggleTipeSetoran);
tipeIqraRadio.addEventListener('change', toggleTipeSetoran);
toggleTipeSetoran();

// Submit form
document.getElementById('formSetoran').addEventListener('submit', async function (e) {
    e.preventDefault();
    const btn = document.getElementById('btnSubmit');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Menyimpan...';

    const fd = new FormData(this);
    fd.append(CSRF_NAME, CSRF_TOKEN);

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

        if (data.success) {
            showToast('success', data.message);
            this.reset();
            updateNilaiLabel();
            // Reload today list
            location.reload();
        } else {
            showToast('danger', data.message || 'Gagal menyimpan.');
        }
    } catch (err) {
        showToast('danger', 'Terjadi kesalahan.');
    } finally {
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-save me-2"></i>Simpan Setoran';
    }
});

// Delete setoran
document.addEventListener('click', async function (e) {
    const btn = e.target.closest('.btn-delete-setoran');
    if (!btn) return;
    if (!confirm('Hapus setoran ini?')) return;

    const id = btn.dataset.id;
    const fd = new FormData();
    fd.append(CSRF_NAME, CSRF_TOKEN);

    const res  = await fetch('/guru/tahfidz/setoran/delete/' + id, { method: 'POST', body: fd });
    const data = await res.json();

    if (data.success) {
        document.getElementById('setoran-' + id)?.remove();
        const count = document.querySelectorAll('#setoranItems .list-group-item').length;
        document.getElementById('todayCount').textContent = count;
        showToast('success', 'Setoran dihapus.');
    } else {
        showToast('danger', 'Gagal menghapus.');
    }
});

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(), 4000);
}
</script>
<?= $this->endSection() ?>
