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

<?php
    $icon       = match($program['type']) { 'pk' => '🏫', 'boarding' => '🌙', default => '☀️' };
    $badge      = match($program['type']) { 'pk' => 'warning', 'boarding' => 'primary', default => 'success' };
    $typeLabel  = match($program['type']) { 'pk' => 'Program Khusus', 'boarding' => 'Boarding', default => 'KBM Pagi' };
?>

<!-- Header -->
<div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
    <div>
        <h5 class="fw-bold mb-0">
            <i class="bi bi-people-fill text-<?= $badge ?> me-2"></i>Kelola Siswa
        </h5>
        <small class="text-muted">
            <?= $icon ?> <strong><?= esc($program['name']) ?></strong>
            &bull; <span class="badge bg-<?= $badge ?> bg-opacity-15 text-<?= $badge ?>"><?= $typeLabel ?></span>
        </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('success')): ?>
<div class="alert alert-success alert-dismissible fade show shadow-sm">
    <?= session()->getFlashdata('success') ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="row g-3">
    <!-- Panel Kiri: Metode Pemilihan Siswa -->
    <div class="col-lg-6">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-light border-0 p-0">
                <!-- Nav Tabs Pemilihan -->
                <ul class="nav nav-tabs nav-fill" id="methodTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active py-3 fw-bold" id="kelas-tab" data-bs-toggle="tab" data-bs-target="#kelas-pane" type="button" role="tab">
                            <i class="bi bi-building me-2"></i>Pilih per Kelas
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link py-3 fw-bold" id="individu-tab" data-bs-toggle="tab" data-bs-target="#individu-pane" type="button" role="tab">
                            <i class="bi bi-person-check me-2"></i>Pilih per Siswa
                        </button>
                    </li>
                </ul>
            </div>
            <div class="card-body tab-content">
                <!-- TAB 1: PILIH KELAS (MASSAL) -->
                <div class="tab-pane fade show active" id="kelas-pane" role="tabpanel">
                    <p class="text-muted small">Ceklis kelas untuk meng-import semua siswa aktif di kelas tersebut secara massal.</p>
                    
                    <!-- Search filter kelas -->
                    <input type="text" id="searchKelas" class="form-control form-control-sm mb-3" placeholder="🔍 Filter nama kelas...">

                    <!-- Select All / None -->
                    <div class="d-flex align-items-center justify-content-between mb-2">
                        <div class="d-flex gap-2">
                            <button class="btn btn-outline-secondary btn-xs py-0 px-2" onclick="selectAllKelas(true)">
                                <i class="bi bi-check-all me-1"></i>Semua
                            </button>
                            <button class="btn btn-outline-secondary btn-xs py-0 px-2" onclick="selectAllKelas(false)">
                                <i class="bi bi-x-square me-1"></i>Kosongkan
                            </button>
                        </div>
                        <span class="text-muted small" id="selectedCount">0 kelas dipilih</span>
                    </div>

                    <!-- Grid Kelas (Cards) dengan Scroll -->
                    <div style="max-height: 420px; overflow-y: auto; overflow-x: hidden; padding-right: 5px;">
                        <div class="row g-2" id="kelasGrid">
                            <?php
                            $grouped = [];
                            foreach ($classrooms as $cls) {
                                $grouped[$cls['grade_name']][] = $cls;
                            }
                            ?>
                            <?php foreach ($grouped as $grade => $kelasList): ?>
                            <div class="col-12">
                                <div class="text-muted small fw-semibold mb-1 mt-1 text-uppercase" style="font-size:0.7rem; letter-spacing:0.05em;">
                                    <?= esc($grade) ?>
                                </div>
                            </div>
                            <?php foreach ($kelasList as $cls): ?>
                            <?php
                                $jumlahSiswa  = $studentCountMap[$cls['id']] ?? 0;
                                $sudahEnroll  = in_array($cls['id'], $enrolledClassroomIds);
                            ?>
                            <div class="col-6 kelas-card-wrap" data-name="<?= strtolower(esc($cls['name'])) ?> <?= strtolower(esc($grade)) ?>">
                                <label class="kelas-card card border shadow-sm h-100 w-100 m-0 user-select-none"
                                       for="kelas_<?= $cls['id'] ?>"
                                       style="cursor:pointer; transition: all 0.15s; border: 1px solid #dee2e6;">
                                    <div class="card-body p-2 d-flex align-items-center gap-2">
                                        <input type="checkbox" class="form-check-input kelas-check flex-shrink-0 mt-0"
                                               id="kelas_<?= $cls['id'] ?>" value="<?= $cls['id'] ?>"
                                               <?= $sudahEnroll ? 'checked' : '' ?>
                                               style="width:1.1em; height:1.1em;">
                                        <div class="flex-grow-1 min-width-0">
                                            <div class="fw-semibold small text-truncate"><?= esc($cls['name']) ?></div>
                                            <div class="d-flex align-items-center gap-1 flex-wrap">
                                                <span class="text-muted" style="font-size:0.7rem;">
                                                    <i class="bi bi-people me-1"></i><?= $jumlahSiswa ?> siswa
                                                </span>
                                                <?php if ($sudahEnroll): ?>
                                                <span class="badge bg-success bg-opacity-15 text-success" style="font-size:0.62rem;">
                                                    ✓ Ter-import
                                                </span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </label>
                            </div>
                            <?php endforeach; ?>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Tombol Import -->
                    <div class="mt-3 pt-2 border-top">
                        <button class="btn btn-<?= $badge ?> w-100" id="btnImport" onclick="importSiswa()">
                            <i class="bi bi-person-plus me-2"></i>
                            Import Siswa dari Kelas Terpilih
                        </button>
                        <div id="importResult" class="mt-2"></div>
                    </div>
                </div>

                <!-- TAB 2: PILIH SISWA (INDIVIDU LINTAS KELAS) -->
                <div class="tab-pane fade" id="individu-pane" role="tabpanel">
                    <p class="text-muted small">Cari dan tambahkan siswa ke dalam program satu per satu secara personal.</p>
                    
                    <div class="row g-2 mb-3">
                        <div class="col-6">
                            <select id="filterKelasSiswa" class="form-select form-select-sm">
                                <option value="">-- Semua Kelas --</option>
                                <?php
                                $classNames = array_unique(array_column($allStudents, 'classroom_name'));
                                sort($classNames);
                                foreach ($classNames as $name):
                                ?>
                                <option value="<?= esc($name) ?>"><?= esc($name) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-6">
                            <input type="text" id="searchSiswa" class="form-control form-control-sm" placeholder="🔍 Cari nama atau NIS...">
                        </div>
                    </div>

                    <!-- Select All / None Siswa -->
                    <div class="d-flex align-items-center justify-content-between mb-2">
                        <div class="d-flex gap-2">
                            <button class="btn btn-outline-secondary btn-xs py-0 px-2" onclick="selectAllSiswa(true)">
                                <i class="bi bi-check-all me-1"></i>Semua
                            </button>
                            <button class="btn btn-outline-secondary btn-xs py-0 px-2" onclick="selectAllSiswa(false)">
                                <i class="bi bi-x-square me-1"></i>Kosongkan
                            </button>
                        </div>
                        <span class="text-muted small" id="selectedSiswaCount">0 siswa dipilih</span>
                    </div>

                    <div id="siswaListWrap" style="max-height: 400px; overflow-y: auto; border: 1px solid #dee2e6; border-radius: 6px;">
                        <?php
                        $siswaGrouped = [];
                        foreach ($allStudents as $st) {
                            $siswaGrouped[$st['classroom_name']][] = $st;
                        }
                        ?>
                        <?php foreach ($siswaGrouped as $className => $siswas): ?>
                        <div class="kelas-siswa-group" data-kelas="<?= esc($className) ?>">
                            <div class="px-3 py-1 bg-light border-bottom border-top sticky-top"
                                 style="font-size:0.72rem; font-weight:600; color:#6c757d; letter-spacing:0.04em; text-transform:uppercase; z-index: 10;">
                                <?= esc($className) ?>
                                <span class="text-muted fw-normal">(<?= count($siswas) ?>)</span>
                            </div>
                            <?php foreach ($siswas as $st): ?>
                            <?php $enrolled = in_array($st['id'], $enrolledIds); ?>
                            <?php if ($enrolled): ?>
                            <!-- Jika sudah terdaftar, tampilkan tanpa checkbox untuk efisiensi visual -->
                            <div class="d-flex align-items-center justify-content-between px-3 py-2 border-bottom siswa-item bg-light bg-opacity-50 text-muted"
                                 data-search="<?= strtolower(esc($st['full_name'])) ?> <?= esc($st['nis']) ?>">
                                <div>
                                    <div class="d-flex align-items-center gap-2">
                                        <span class="fw-semibold small text-decoration-line-through"><?= esc($st['full_name']) ?></span>
                                        <span class="badge bg-secondary bg-opacity-10 text-secondary fw-semibold" style="font-size: 0.65rem; padding: 2px 6px;">Sudah Masuk</span>
                                    </div>
                                    <div class="text-muted animate-pulse" style="font-size:0.72rem;"><?= esc($st['nis']) ?></div>
                                </div>
                                <span class="text-success small fw-semibold"><i class="bi bi-check-circle-fill me-1"></i>Terdaftar</span>
                            </div>
                            <?php else: ?>
                            <label class="d-flex align-items-center justify-content-between px-3 py-2 border-bottom siswa-item user-select-none m-0"
                                   for="chk_siswa_<?= $st['id'] ?>"
                                   style="cursor: pointer; transition: background 0.15s;"
                                   data-search="<?= strtolower(esc($st['full_name'])) ?> <?= esc($st['nis']) ?>">
                                <div class="d-flex align-items-center gap-2">
                                    <input type="checkbox" class="form-check-input siswa-check flex-shrink-0 mt-0"
                                           id="chk_siswa_<?= $st['id'] ?>" value="<?= $st['id'] ?>"
                                           style="width:1.1em; height:1.1em;">
                                    <div>
                                        <div class="d-flex align-items-center gap-2">
                                            <span class="fw-semibold small"><?= esc($st['full_name']) ?></span>
                                            <?php if ($st['gender'] === 'L'): ?>
                                            <span class="badge bg-primary bg-opacity-10 text-primary fw-semibold" style="font-size: 0.65rem; padding: 2px 6px;">Putra</span>
                                            <?php else: ?>
                                            <span class="badge bg-danger bg-opacity-10 text-danger fw-semibold" style="font-size: 0.65rem; padding: 2px 6px;">Putri</span>
                                            <?php endif; ?>
                                        </div>
                                        <div class="text-muted" style="font-size:0.72rem;"><?= esc($st['nis']) ?></div>
                                    </div>
                                </div>
                            </label>
                            <?php endif; ?>
                            <?php endforeach; ?>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Tombol Import Siswa Terpilih -->
                    <div class="mt-3 pt-2 border-top">
                        <button class="btn btn-<?= $badge ?> w-100" id="btnImportBulk" onclick="importSiswaBulk()">
                            <i class="bi bi-person-plus-fill me-2"></i>
                            Import Siswa Terpilih
                        </button>
                        <div id="importBulkResult" class="mt-2"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Danger zone: Reset -->
        <div class="card border-0 shadow-sm mt-3 border-danger border-opacity-25">
            <div class="card-body py-2">
                <form method="POST" action="/admin/tahfidz/programs/<?= $program['id'] ?>/clear-students"
                      onsubmit="return confirm('Yakin ingin menghapus SEMUA siswa dari program ini?')">
                    <?= csrf_field() ?>
                    <button class="btn btn-sm btn-outline-danger w-100">
                        <i class="bi bi-trash3 me-1"></i>Hapus Semua Siswa dari Program
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- Panel Kanan: Daftar Siswa Terdaftar -->
    <div class="col-lg-6">
        <?= view('admin/tahfidz/_enrolled_table', [
            'enrolledStudents' => $enrolledStudents,
            'program'          => $program,
            'isBoarding'       => true,
        ]) ?>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
const CSRF_TOKEN = '<?= csrf_hash() ?>';
const CSRF_NAME  = '<?= csrf_token() ?>';
const PROGRAM_ID = <?= $program['id'] ?>;
const PERIOD_ID  = <?= $activePeriod['id'] ?? 'null' ?>;

// ── TAB 1: PILIH KELAS ──
document.getElementById('searchKelas')?.addEventListener('input', function () {
    const q = this.value.toLowerCase();
    document.querySelectorAll('.kelas-card-wrap').forEach(el => {
        el.style.display = el.dataset.name.includes(q) ? '' : 'none';
    });
});

function updateSelectedCount() {
    const n = document.querySelectorAll('.kelas-check:checked').length;
    document.getElementById('selectedCount').textContent = n + ' kelas dipilih';
}

document.querySelectorAll('.kelas-check').forEach(chk => {
    applyCardStyle(chk);
    chk.addEventListener('change', function() {
        applyCardStyle(this);
        updateSelectedCount();
    });
});

function applyCardStyle(chk) {
    const card = chk.closest('.kelas-card');
    if (!card) return;
    if (chk.checked) {
        card.style.background   = '#d8f3dc';
        card.style.borderColor  = '#2d6a4f';
        card.style.borderWidth  = '2px';
        card.style.borderStyle  = 'solid';
    } else {
        card.style.background   = '';
        card.style.borderColor  = '';
        card.style.borderWidth  = '';
        card.style.borderStyle  = '';
    }
}

function selectAllKelas(val) {
    document.querySelectorAll('.kelas-check').forEach(chk => {
        if (chk.closest('.kelas-card-wrap').style.display !== 'none') {
            chk.checked = val;
            applyCardStyle(chk);
        }
    });
    updateSelectedCount();
}

updateSelectedCount();

async function importSiswa() {
    const checked = Array.from(document.querySelectorAll('.kelas-check:checked')).map(c => c.value);
    if (checked.length === 0) {
        showResult('warning', 'Pilih minimal 1 kelas terlebih dahulu.');
        return;
    }

    const btn = document.getElementById('btnImport');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Memproses...';

    const fd = new FormData();
    fd.append(CSRF_NAME, CSRF_TOKEN);
    fd.append('period_id', PERIOD_ID);
    checked.forEach(id => fd.append('classroom_ids[]', id));

    try {
        const res  = await fetch(`/admin/tahfidz/programs/${PROGRAM_ID}/add-from-classrooms`, { method: 'POST', body: fd });
        const data = await res.json();

        if (data.success) {
            showResult('success', `✅ ${data.message} &mdash; Memuat ulang halaman...`);
            setTimeout(() => location.reload(), 1500);
        } else {
            showResult('danger', data.message || 'Terjadi kesalahan.');
        }
    } catch(e) {
        showResult('danger', 'Koneksi gagal.');
    } finally {
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-person-plus me-2"></i>Import Siswa dari Kelas Terpilih';
    }
}

function showResult(type, msg) {
    const el = document.getElementById('importResult');
    el.innerHTML = `<div class="alert alert-${type} py-2 small mb-0">${msg}</div>`;
}

// ── TAB 2: PILIH SISWA INDIVIDU ──
function filterTabIndividu() {
    const filterSelect = document.getElementById('filterKelasSiswa');
    const searchInput = document.getElementById('searchSiswa');
    if (!filterSelect || !searchInput) return;

    const classVal = filterSelect.value.trim().toLowerCase();
    const qVal = searchInput.value.trim().toLowerCase();

    document.querySelectorAll('.kelas-siswa-group').forEach(g => {
        const groupKelas = g.dataset.kelas ? g.dataset.kelas.trim().toLowerCase() : '';
        const classMatch = !classVal || groupKelas === classVal;

        if (classMatch) {
            let visibleInGroup = 0;
            const items = g.querySelectorAll('.siswa-item');
            items.forEach(el => {
                const searchMatch = el.dataset.search.includes(qVal);
                if (searchMatch) {
                    el.style.display = 'flex';
                    visibleInGroup++;
                } else {
                    el.style.display = 'none';
                }
            });

            // Tampilkan grup kelas jika ada siswa yang cocok
            g.style.display = visibleInGroup > 0 ? '' : 'none';

            // Tampilkan header nama kelas
            const header = g.firstElementChild;
            if (header) {
                header.style.display = visibleInGroup > 0 ? '' : 'none';
            }
        } else {
            // Jika kelas tidak cocok, sembunyikan seluruh grup
            g.style.display = 'none';
        }
    });
}

document.getElementById('filterKelasSiswa')?.addEventListener('change', function() {
    localStorage.setItem('tahfidz_filter_kelas', this.value);
    filterTabIndividu();
});
document.getElementById('searchSiswa')?.addEventListener('input', function() {
    localStorage.setItem('tahfidz_search_siswa', this.value);
    filterTabIndividu();
});

// Pemicu filter saat tab 'Pilih per Siswa' dibuka
document.getElementById('individu-tab')?.addEventListener('shown.bs.tab', function () {
    localStorage.setItem('tahfidz_active_tab', 'individu');
    filterTabIndividu();
});
document.getElementById('kelas-tab')?.addEventListener('shown.bs.tab', function () {
    localStorage.setItem('tahfidz_active_tab', 'kelas');
});

// Jalankan filter saat pertama kali halaman dimuat
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initTabState);
} else {
    initTabState();
}

function initTabState() {
    // 1. Kembalikan filter dropdown dan search input
    const savedKelas = localStorage.getItem('tahfidz_filter_kelas');
    const savedSearch = localStorage.getItem('tahfidz_search_siswa');
    
    if (savedKelas && document.getElementById('filterKelasSiswa')) {
        document.getElementById('filterKelasSiswa').value = savedKelas;
    }
    if (savedSearch && document.getElementById('searchSiswa')) {
        document.getElementById('searchSiswa').value = savedSearch;
    }
    
    // Jalankan filter individu agar sinkron
    filterTabIndividu();

    // 2. Kembalikan state tab aktif
    const activeTab = localStorage.getItem('tahfidz_active_tab');
    if (activeTab === 'individu') {
        const triggerEl = document.querySelector('#individu-tab');
        if (triggerEl) {
            bootstrap.Tab.getInstance(triggerEl)?.show() || new bootstrap.Tab(triggerEl).show();
        }
    }
}

// Update label "X siswa dipilih" di Tab 2
function updateSelectedSiswaCount() {
    const n = document.querySelectorAll('.siswa-check:checked').length;
    document.getElementById('selectedSiswaCount').textContent = n + ' siswa dipilih';
}

// Style checkbox change
document.addEventListener('change', function(e) {
    if (e.target.classList.contains('siswa-check')) {
        updateSelectedSiswaCount();
    }
});

function selectAllSiswa(val) {
    document.querySelectorAll('.siswa-check').forEach(chk => {
        // Hanya tandai checkbox siswa yang saat ini terlihat (memenuhi filter kelas & search)
        const item = chk.closest('.siswa-item');
        if (item && item.style.display !== 'none') {
            chk.checked = val;
        }
    });
    updateSelectedSiswaCount();
}

async function importSiswaBulk() {
    const checked = Array.from(document.querySelectorAll('.siswa-check:checked')).map(c => c.value);
    if (checked.length === 0) {
        showBulkResult('warning', 'Pilih minimal 1 siswa terlebih dahulu.');
        return;
    }

    const btn = document.getElementById('btnImportBulk');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Memproses...';

    const fd = new FormData();
    fd.append(CSRF_NAME, CSRF_TOKEN);
    checked.forEach(id => fd.append('student_ids[]', id));

    try {
        const res  = await fetch(`/admin/tahfidz/programs/${PROGRAM_ID}/add-students-bulk`, { method: 'POST', body: fd });
        const data = await res.json();

        if (data.success) {
            showBulkResult('success', `✅ ${data.message} &mdash; Memuat ulang halaman...`);
            setTimeout(() => location.reload(), 1500);
        } else {
            showBulkResult('danger', data.message || 'Terjadi kesalahan.');
        }
    } catch(e) {
        showBulkResult('danger', 'Koneksi gagal.');
    } finally {
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-person-plus-fill me-2"></i>Import Siswa Terpilih';
    }
}

function showBulkResult(type, msg) {
    const el = document.getElementById('importBulkResult');
    el.innerHTML = `<div class="alert alert-${type} py-2 small mb-0">${msg}</div>`;
}

// Tombol hapus di panel kanan (tabel terdaftar)
document.addEventListener('click', async function (e) {
    const btn = e.target.closest('.btn-toggle-siswa');
    if (!btn) return;

    if (!confirm('Yakin ingin mengeluarkan siswa ini dari program?')) return;

    const studentId = btn.dataset.id;
    btn.disabled = true;

    const fd = new FormData();
    fd.append(CSRF_NAME, CSRF_TOKEN);
    fd.append('student_id', studentId);

    try {
        const res  = await fetch(`/admin/tahfidz/programs/${PROGRAM_ID}/toggle-student`, { method: 'POST', body: fd });
        const data = await res.json();

        if (data.success) {
            location.reload();
        } else {
            btn.disabled = false;
            alert('Gagal memproses.');
        }
    } catch(e) {
        btn.disabled = false;
        alert('Koneksi gagal.');
    }
});
</script>
<?= $this->endSection() ?>
