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

<div class="d-flex align-items-center justify-content-between mb-4">
    <div>
        <h5 class="fw-bold mb-0"><i class="bi bi-plus-circle text-success me-2"></i>Buat Program Tahfidz</h5>
        <small class="text-muted">Program baru akan aktif untuk periode yang dipilih</small>
    </div>
    <a href="/admin/tahfidz" class="btn btn-sm btn-outline-secondary">
        <i class="bi bi-arrow-left me-1"></i> Kembali
    </a>
</div>

<?php if (session()->getFlashdata('errors')): ?>
<div class="alert alert-danger alert-dismissible fade show">
    <ul class="mb-0">
        <?php foreach (session()->getFlashdata('errors') as $err): ?>
        <li><?= esc($err) ?></li>
        <?php endforeach; ?>
    </ul>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="row justify-content-center">
    <div class="col-lg-7">
        <div class="card border-0 shadow-sm">
            <div class="card-body p-4">
                <form method="POST" action="/admin/tahfidz/store">
                    <?= csrf_field() ?>

                    <div class="mb-3">
                        <label class="form-label fw-semibold" for="name">Nama Program <span class="text-danger">*</span></label>
                        <input type="text" name="name" id="name" class="form-control"
                               placeholder="cth: Tahfidz KBM Pagi, Program Khusus 2025, Boarding Pondok..."
                               value="<?= old('name') ?>" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-semibold">Tipe Program <span class="text-danger">*</span></label>
                        <div class="row g-2">
                            <?php foreach (['kbm' => ['☀️', 'KBM Pagi', 'Semua siswa di jam pelajaran pagi'], 'pk' => ['🏫', 'Program Khusus', 'Siswa kelas PK, jam tambahan di luar KBM'], 'boarding' => ['🌙', 'Boarding', 'Siswa boarding, lintas kelas']] as $type => [$icon, $label, $desc]): ?>
                            <div class="col-md-4">
                                <input type="radio" name="type" id="type_<?= $type ?>" value="<?= $type ?>"
                                       class="btn-check" <?= (old('type') ?: 'kbm') === $type ? 'checked' : '' ?> required>
                                <label class="btn btn-outline-secondary w-100 h-100 text-start p-3" for="type_<?= $type ?>">
                                    <div class="fs-4 mb-1"><?= $icon ?></div>
                                    <div class="fw-semibold"><?= $label ?></div>
                                    <div class="text-muted" style="font-size:0.75rem;"><?= $desc ?></div>
                                </label>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-semibold" for="academic_period_id">Periode Akademik <span class="text-danger">*</span></label>
                        <select name="academic_period_id" id="academic_period_id" class="form-select" required>
                            <option value="">-- Pilih Periode --</option>
                            <?php foreach ($periods as $period): ?>
                            <option value="<?= $period['id'] ?>"
                                    <?= (old('academic_period_id') ?: ($activePeriod['id'] ?? '')) == $period['id'] ? 'selected' : '' ?>>
                                <?= esc($period['year_name']) ?> — Semester <?= $period['semester'] ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-semibold" for="description">Deskripsi</label>
                        <textarea name="description" id="description" class="form-control" rows="2"
                                  placeholder="Keterangan tambahan (opsional)"><?= old('description') ?></textarea>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-semibold d-flex justify-content-between align-items-center mb-1" for="wa_group_id">
                            <span>WhatsApp Group ID</span>
                            <button type="button" id="btnLoadWaGroups" class="btn btn-xs btn-outline-success py-0 px-2 fw-semibold" style="font-size: 0.72rem; border-radius: 4px;">
                                <i class="bi bi-arrow-clockwise"></i> Muat Grup dari WA
                            </button>
                        </label>
                        <div class="input-group">
                            <input type="text" name="wa_group_id" id="wa_group_id" class="form-control"
                                   placeholder="cth: 120363024843928192@g.us (opsional)"
                                   value="<?= old('wa_group_id') ?>">
                            <select id="selectWaGroup" class="form-select d-none">
                                <option value="">-- Pilih Grup --</option>
                            </select>
                            <button type="button" id="btnToggleWaInput" class="btn btn-outline-secondary d-none" title="Ubah input manual">
                                <i class="bi bi-keyboard"></i>
                            </button>
                        </div>
                        <div class="form-text text-muted" style="font-size:0.75rem;">
                            ID Grup WA untuk pengiriman notifikasi/rekap setoran. Gunakan tombol untuk memuat grup dari akun Sidobe Anda.
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-semibold">Guru Pengampu</label>
                        <div class="text-muted small mb-2">Pilih satu atau lebih guru yang akan mengampu program ini.</div>
                        <div class="row g-2" style="max-height:250px; overflow-y:auto;">
                            <?php foreach ($teachers as $t): ?>
                            <div class="col-md-6">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox"
                                           name="teacher_ids[]" value="<?= $t['id'] ?>"
                                           id="teacher_<?= $t['id'] ?>">
                                    <label class="form-check-label" for="teacher_<?= $t['id'] ?>">
                                        <span class="fw-semibold small"><?= esc($t['name']) ?></span>
                                        <?php $tId = teacher_id_number($t); if ($tId): ?>
                                        <span class="text-muted" style="font-size:0.72rem;"> — <?= esc($tId) ?></span>
                                        <?php endif; ?>
                                    </label>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-success px-4">
                            <i class="bi bi-save me-2"></i>Simpan & Lanjut ke Siswa
                        </button>
                        <a href="/admin/tahfidz" class="btn btn-outline-secondary">Batal</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const btnLoad = document.getElementById('btnLoadWaGroups');
    const inputGroup = document.getElementById('wa_group_id');
    const selectGroup = document.getElementById('selectWaGroup');
    const btnToggle = document.getElementById('btnToggleWaInput');

    if (btnLoad) {
        btnLoad.addEventListener('click', async function() {
            btnLoad.disabled = true;
            btnLoad.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Loading...';

            try {
                const res = await fetch('/admin/tahfidz/get-wa-groups');
                const result = await res.json();

                if (result.success && result.data.length > 0) {
                    selectGroup.innerHTML = '<option value="">-- Pilih Grup --</option>';
                    result.data.forEach(g => {
                        const opt = document.createElement('option');
                        opt.value = g.id;
                        opt.textContent = `${g.name} (${g.id})`;
                        if (g.id === inputGroup.value) {
                            opt.selected = true;
                        }
                        selectGroup.appendChild(opt);
                    });

                    // Tampilkan dropdown select, sembunyikan input text
                    inputGroup.classList.add('d-none');
                    selectGroup.classList.remove('d-none');
                    btnToggle.classList.remove('d-none');
                } else {
                    alert(result.message || 'Grup tidak ditemukan. Pastikan nomor pengirim di dashboard Sidobe sudah terhubung.');
                }
            } catch (err) {
                alert('Gagal memuat daftar grup WhatsApp.');
            } finally {
                btnLoad.disabled = false;
                btnLoad.innerHTML = '<i class="bi bi-arrow-clockwise"></i> Muat Grup dari WA';
            }
        });
    }

    if (selectGroup) {
        selectGroup.addEventListener('change', function() {
            inputGroup.value = this.value;
        });
    }

    if (btnToggle) {
        btnToggle.addEventListener('click', function() {
            if (inputGroup.classList.contains('d-none')) {
                inputGroup.classList.remove('d-none');
                selectGroup.classList.add('d-none');
                this.innerHTML = '<i class="bi bi-list-ul"></i>';
            } else {
                inputGroup.classList.add('d-none');
                selectGroup.classList.remove('d-none');
                this.innerHTML = '<i class="bi bi-keyboard"></i>';
            }
        });
    }
});
</script>

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