<?= $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-pencil-square text-success me-2"></i>Edit Program Tahfidz</h5>
        <small class="text-muted">Perbarui nama, guru pengampu, atau status program</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/<?= $program['id'] ?>/update">
                    <?= 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"
                               value="<?= esc(old('name', $program['name'])) ?>" required>
                    </div>

                    <!-- Tipe tidak bisa diubah (karena mempengaruhi siswa yang sudah terdaftar) -->
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Tipe Program</label>
                        <div class="form-control bg-light text-muted">
                            <?php
                            $icon      = match($program['type']) { 'pk' => '🏫', 'boarding' => '🌙', default => '☀️' };
                            $typeLabel = match($program['type']) { 'pk' => 'Program Khusus', 'boarding' => 'Boarding', default => 'KBM Pagi' };
                            ?>
                            <?= $icon ?> <?= $typeLabel ?>
                            <small class="text-muted ms-2">(tidak bisa diubah)</small>
                        </div>
                        <input type="hidden" name="type" value="<?= esc($program['type']) ?>">
                    </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"><?= esc(old('description', $program['description'])) ?></textarea>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-semibold">Status</label>
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="is_active" id="isActive"
                                   value="1" <?= $program['is_active'] ? 'checked' : '' ?>>
                            <label class="form-check-label" for="isActive">Program Aktif</label>
                        </div>
                    </div>

                    <?php
                    $db = \Config\Database::connect();
                    $waGroupVal = $db->table('settings')->where('setting_key', 'wa_group_id_' . $program['id'])->get()->getRowArray()['setting_value'] ?? '';
                    ?>
                    <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="<?= esc(old('wa_group_id', $waGroupVal)) ?>">
                            <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">Ubah guru pengampu jika diperlukan.</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'] ?>"
                                           <?= in_array($t['id'], $assignedIds) ? 'checked' : '' ?>>
                                    <label class="form-check-label small" for="teacher_<?= $t['id'] ?>">
                                        <span class="fw-semibold"><?= esc($t['name']) ?></span>
                                        <?php $tId = teacher_id_number($t); if ($tId): ?>
                                        <span class="text-muted"> — <?= 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 Perubahan
                        </button>
                        <a href="/admin/tahfidz/programs/<?= $program['id'] ?>/students"
                           class="btn btn-outline-primary">
                            <i class="bi bi-people me-1"></i>Kelola Siswa
                        </a>
                        <a href="/admin/tahfidz" class="btn btn-outline-secondary ms-auto">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() ?>
