<?php
$activeYearName = $activeYear['name'] ?? 'Tidak ada TA aktif';
$nextYearId     = $nextYear['id'] ?? null;
$nextYearName   = $nextYear['name'] ?? null;
?>

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

<div class="row g-3">

    <!-- KIRI: Siswa Kelas Asal -->
    <div class="col-md-6 d-flex flex-column" style="min-height:0">
        <div class="card flex-grow-1 d-flex flex-column" style="max-height:calc(100vh - 160px)">
            <div class="card-header d-flex align-items-center gap-2 flex-shrink-0">
                <i class="bi bi-box-arrow-right text-danger"></i>
                <span class="fw-semibold">Kelas Asal</span>
                <span class="badge bg-success ms-auto">
                    <?= esc($activePeriod['year_name']) ?> — <?= esc($activePeriod['semester']) ?>
                </span>
            </div>

            <!-- Filter -->
            <div class="p-3 pb-2 border-bottom flex-shrink-0">
                <div class="row g-2">
                    <div class="col-6">
                        <label class="form-label small text-muted mb-1">Tingkat</label>
                        <select id="gradeAsal" class="form-select form-select-sm">
                            <option value="">-- Pilih Tingkat --</option>
                            <?php foreach ($grades as $grade): ?>
                            <option value="<?= $grade['id'] ?>"><?= esc($grade['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-6">
                        <label class="form-label small text-muted mb-1">Kelas</label>
                        <select id="kelasAsal" class="form-select form-select-sm" disabled>
                            <option value="">-- Pilih Kelas --</option>
                        </select>
                    </div>
                </div>
                <!-- Info dipilih -->
                <div id="selectedInfo" class="mt-2" style="display:none">
                    <div class="d-flex align-items-center justify-content-between">
                        <span class="badge bg-success px-2" id="selectedCount">0 dipilih</span>
                        <button class="btn btn-link btn-sm text-danger p-0 text-decoration-none" onclick="clearSelection()">
                            <i class="bi bi-x me-1"></i>Batal pilih
                        </button>
                    </div>
                </div>
            </div>

            <!-- Tabel siswa asal (scrollable) -->
            <div class="flex-grow-1 overflow-auto" style="min-height:0">
                <table class="table table-hover table-sm mb-0" id="tableAsal">
                    <thead class="table-light sticky-top">
                        <tr>
                            <th style="width:36%">Nama</th>
                            <th style="width:28%">NIS</th>
                            <th style="width:18%">NISN</th>
                            <th style="width:18%">L/P</th>
                        </tr>
                    </thead>
                    <tbody id="asalBody">
                        <tr>
                            <td colspan="4" class="text-center text-muted py-4">
                                <i class="bi bi-arrow-up-circle fs-3 d-block mb-2 opacity-25"></i>
                                <small>Pilih tingkat dan kelas asal</small>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- Footer aksi -->
            <div class="card-footer d-flex gap-2 flex-shrink-0">
                <button class="btn btn-sm btn-outline-secondary" onclick="selectAll()">
                    <i class="bi bi-check-all me-1"></i>Pilih Semua
                </button>
                <button class="btn btn-sm btn-outline-danger" onclick="clearSelection()">
                    <i class="bi bi-x me-1"></i>Batal
                </button>
            </div>
        </div>
    </div>

    <!-- KANAN: Kelas Tujuan + Aksi -->
    <div class="col-md-6 d-flex flex-column gap-3" style="min-height:0">

        <!-- Jika TA berikutnya belum dibuat, tampilkan alert -->
        <?php if (!$nextYear): ?>
        <div class="alert alert-warning d-flex align-items-start gap-3 mb-0">
            <i class="bi bi-exclamation-triangle-fill fs-4 mt-1 flex-shrink-0"></i>
            <div>
                <strong>Tahun Ajaran Berikutnya Belum Dibuat</strong><br>
                <span class="small">
                    Untuk menaikkan kelas, buat tahun ajaran
                    <strong><?= esc($nextYearExpected ?? '...') ?></strong> terlebih dahulu.
                </span>
                <div class="mt-2">
                    <a href="/academic-year" class="btn btn-sm btn-warning">
                        <i class="bi bi-plus-circle me-1"></i>Buat Tahun Ajaran
                    </a>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Card Kelas Tujuan -->
        <div class="card d-flex flex-column <?= !$nextYear ? 'opacity-50 pe-none' : '' ?>" style="max-height:calc(100vh - 280px)">
            <div class="card-header d-flex align-items-center gap-2 flex-shrink-0">
                <i class="bi bi-box-arrow-in-right text-success"></i>
                <span class="fw-semibold">Kelas Tujuan</span>
            </div>

            <!-- Info tahun ajaran tujuan (auto-detect, tidak ada dropdown) -->
            <div class="p-3 pb-2 border-bottom flex-shrink-0">
                <div class="row g-2">
                    <div class="col-12">
                        <label class="form-label small text-muted mb-1">Tahun Ajaran Tujuan</label>
                        <?php if ($nextYear): ?>
                        <div class="d-flex align-items-center gap-2 p-2 rounded" style="background:#f0fdf4;border:1px solid #86efac">
                            <i class="bi bi-calendar-check text-success"></i>
                            <span class="fw-semibold"><?= esc($nextYearName) ?></span>
                            <span class="badge bg-success ms-auto">Auto-detect</span>
                        </div>
                        <?php else: ?>
                        <div class="d-flex align-items-center gap-2 p-2 rounded" style="background:#fef9c3;border:1px solid #fcd34d">
                            <i class="bi bi-exclamation-circle text-warning"></i>
                            <span class="text-muted small">Belum ada — buat TA <?= esc($nextYearExpected ?? '') ?> dulu</span>
                        </div>
                        <?php endif; ?>
                    </div>
                    <div class="col-6">
                        <label class="form-label small text-muted mb-1">Tingkat</label>
                        <select id="gradeTujuan" class="form-select form-select-sm" disabled onchange="onGradeTujuanChange()">
                            <option value="">-- Pilih Tingkat --</option>
                            <?php foreach ($grades as $grade): ?>
                            <option value="<?= $grade['id'] ?>"><?= esc($grade['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-6">
                        <label class="form-label small text-muted mb-1">Kelas</label>
                        <select id="kelasTujuan" class="form-select form-select-sm" disabled onchange="onKelasTujuanChange()">
                            <option value="">-- Pilih Kelas --</option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- Tabel siswa tujuan (scrollable) -->
            <div class="flex-grow-1 overflow-auto" style="min-height:0">
                <table class="table table-hover table-sm mb-0">
                    <thead class="table-light sticky-top">
                        <tr>
                            <th style="width:40%">Nama</th>
                            <th style="width:30%">NIS</th>
                            <th style="width:30%">L/P</th>
                        </tr>
                    </thead>
                    <tbody id="tujuanBody">
                        <tr>
                            <td colspan="3" class="text-center text-muted py-4">
                                <i class="bi bi-arrow-up-circle fs-3 d-block mb-2 opacity-25"></i>
                                <small>Pilih tahun ajaran dan kelas tujuan</small>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Card Aksi -->
        <div class="card flex-shrink-0">
            <div class="card-body py-3">
                <div class="row g-2">
                    <div class="col-12">
                        <button class="btn btn-primary w-100" id="btnPromote" disabled onclick="doPromote()">
                            <span id="btnPromoteLabel">
                                <i class="bi bi-arrow-up-circle me-1"></i>
                                Naikkan <span id="btnPromoteCount">0</span> Siswa ke Kelas Ini
                            </span>
                            <span id="btnPromoteLoading" style="display:none">
                                <span class="spinner-border spinner-border-sm me-1"></span>Memproses...
                            </span>
                        </button>
                    </div>
                </div>
                <div class="mt-2">
                    <small class="text-muted">
                        <i class="bi bi-info-circle me-1"></i>
                        <strong>Naikkan</strong>: assign siswa ke kelas tujuan di Semester 1 tahun ajaran baru.
                    </small>
                </div>
            </div>
        </div>

    </div>
</div>

<!-- Toast -->
<div class="position-fixed bottom-0 end-0 p-3" style="z-index:9999">
    <div id="toastMsg" class="toast align-items-center text-white border-0" role="alert">
        <div class="d-flex">
            <div class="toast-body fw-semibold" id="toastText"></div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    </div>
</div>

<style>
/* Row selectable */
#asalBody tr.student-row {
    cursor: pointer;
    transition: background .12s;
    user-select: none;
}
#asalBody tr.student-row:hover td {
    background-color: #f0fdf4 !important;
    box-shadow: inset 0 0 0 9999px #f0fdf4 !important;
}
[data-bs-theme="dark"] #asalBody tr.student-row:hover td {
    background-color: #1a3a2a !important;
    box-shadow: inset 0 0 0 9999px #1a3a2a !important;
}
#asalBody tr.student-row.selected td {
    background-color: #d1fae5 !important;
    box-shadow: inset 0 0 0 9999px #d1fae5 !important;
}
[data-bs-theme="dark"] #asalBody tr.student-row.selected td {
    background-color: #1a3a2a !important;
    box-shadow: inset 0 0 0 9999px #1a3a2a !important;
}
#asalBody tr.student-row.selected td:first-child {
    border-left: 3px solid #198754;
}
/* Sticky thead dalam overflow */
.overflow-auto thead.sticky-top th {
    top: 0;
    z-index: 1;
    background: #f8f9fa;
}
[data-bs-theme="dark"] .overflow-auto thead.sticky-top th {
    background: #2a3447;
}
</style>

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

<?= $this->section('scripts') ?>
<script>
const PERIOD_ASAL_ID = <?= $activePeriod['id'] ?>;
 const CSRF_NAME      = '<?= csrf_token() ?>';
let   csrfToken      = '<?= csrf_hash() ?>';
const NEXT_YEAR_ID   = <?= $nextYearId ? $nextYearId : 'null' ?>;
const NEXT_YEAR_NAME = '<?= esc($nextYearName ?? '') ?>';

// Kelas asal dari TA aktif (di-embed dari PHP)
const allClassroomsAsal = [
    <?php foreach ($classrooms as $c): ?>
    {
        id      : '<?= $c['id'] ?>',
        gradeId : '<?= $c['grade_id'] ?>',
        name    : '<?= esc($c['name']) ?>',
    },
    <?php endforeach; ?>
];


let selectedIds = new Set(); // history_id yang dipilih


// ── BUILD DROPDOWN KELAS ─────────────────────────────────────
function buildKelas(gradeId, targetSelectId, source) {
    const sel = document.getElementById(targetSelectId);
    sel.innerHTML = '<option value="">-- Pilih Kelas --</option>';
    source
        .filter(c => !gradeId || c.gradeId === String(gradeId))
        .forEach(c => sel.appendChild(new Option(c.name, c.id)));
    sel.disabled = !gradeId || source.length === 0;
}

// ── EVENT: Tingkat Asal ──────────────────────────────────────
document.getElementById('gradeAsal').addEventListener('change', function() {
    buildKelas(this.value, 'kelasAsal', allClassroomsAsal);
    resetAsalBody();
    clearSelection();
});

// ── EVENT: Kelas Asal ────────────────────────────────────────
document.getElementById('kelasAsal').addEventListener('change', function() {
    clearSelection();
    if (this.value) {
        loadAsalSiswa(this.value);
    } else {
        resetAsalBody();
    }
});

// ── AUTO-INIT: load kelas tujuan dari TA berikutnya ─────────
// Tidak ada dropdown — NEXT_YEAR_ID sudah diketahui dari server
let allClassroomsTujuan = [];

if (NEXT_YEAR_ID) {
    fetch(`/promote-class/classrooms-by-year?year_id=${NEXT_YEAR_ID}`)
        .then(r => r.json())
        .then(data => {
            if (data.has_classrooms) {
                allClassroomsTujuan = data.classrooms.map(c => ({
                    id      : String(c.id),
                    gradeId : String(c.grade_id),
                    name    : c.name,
                }));
                document.getElementById('gradeTujuan').disabled = false;
            } else {
                // Belum ada kelas di TA berikutnya
                document.getElementById('tujuanBody').innerHTML = emptyRow(3,
                    'Belum ada kelas di TA ' + NEXT_YEAR_NAME + '. <a href="/classroom">Buat kelas dulu</a>'
                );
            }
        });
}

// ── EVENT: Tingkat Tujuan ────────────────────────────────────
function onGradeTujuanChange() {
    buildKelas(document.getElementById('gradeTujuan').value, 'kelasTujuan', allClassroomsTujuan);
    resetTujuanBody();
    updateActionButtons();
}

// ── EVENT: Kelas Tujuan ──────────────────────────────────────
function onKelasTujuanChange() {
    const classroomId = document.getElementById('kelasTujuan').value;
    if (classroomId && NEXT_YEAR_ID) {
        loadTujuanSiswa(classroomId, NEXT_YEAR_ID);
    } else {
        resetTujuanBody();
    }
    updateActionButtons();
}

// ── LOAD SISWA ASAL ──────────────────────────────────────────
function loadAsalSiswa(classroomId) {
    setAsalLoading();

    fetch(`/promote-class/students?classroom_id=${classroomId}&period_id=${PERIOD_ASAL_ID}&target_year_id=${NEXT_YEAR_ID || ''}`)
        .then(r => r.json())
        .then(data => {
            if (!data.success || data.students.length === 0) {
                document.getElementById('asalBody').innerHTML = emptyRow(4, 'Tidak ada siswa di kelas ini');
                return;
            }
            renderAsalSiswa(data.students);
        })
        .catch(() => {
            document.getElementById('asalBody').innerHTML = emptyRow(4, 'Gagal memuat data');
        });
}

function renderAsalSiswa(students) {
    const html = students.map(s => `
        <tr class="student-row" data-history="${s.history_id}" onclick="toggleSelect(this)">
            <td class="fw-semibold small">${escHtml(s.full_name)}</td>
            <td class="small">${escHtml(s.nis)}</td>
            <td class="small text-muted">${escHtml(s.nisn ?? '-')}</td>
            <td>
                <span class="badge" style="font-size:.7rem;background:${s.gender=='L'?'#0d6efd':'#e91e8c'}">
                    ${s.gender}
                </span>
            </td>
        </tr>
    `).join('');
    document.getElementById('asalBody').innerHTML = html;
}

// ── LOAD SISWA TUJUAN ────────────────────────────────────────
function loadTujuanSiswa(classroomId, yearId) {
    document.getElementById('tujuanBody').innerHTML =
        `<tr><td colspan="3" class="text-center py-3 text-muted small">
            <span class="spinner-border spinner-border-sm me-1"></span>Memuat...
        </td></tr>`;

    fetch(`/promote-class/target-students?classroom_id=${classroomId}&year_id=${yearId}`)
        .then(r => r.json())
        .then(data => {
            if (!data.success || data.students.length === 0) {
                document.getElementById('tujuanBody').innerHTML = emptyRow(3, 'Belum ada siswa di kelas ini');
                return;
            }
            const html = data.students.map(s => `
                <tr>
                    <td class="fw-semibold small">${escHtml(s.full_name)}</td>
                    <td class="small">${escHtml(s.nis)}</td>
                    <td>
                        <span class="badge" style="font-size:.7rem;background:${s.gender=='L'?'#0d6efd':'#e91e8c'}">
                            ${s.gender}
                        </span>
                    </td>
                </tr>
            `).join('');
            document.getElementById('tujuanBody').innerHTML = html;
        })
        .catch(() => {
            document.getElementById('tujuanBody').innerHTML = emptyRow(3, 'Gagal memuat data');
        });
}

// ── SELECT / DESELECT ROW ────────────────────────────────────
function toggleSelect(el) {
    const hid = el.dataset.history;
    if (selectedIds.has(hid)) {
        selectedIds.delete(hid);
        el.classList.remove('selected');
    } else {
        selectedIds.add(hid);
        el.classList.add('selected');
    }
    updateUI();
}

function selectAll() {
    document.querySelectorAll('#asalBody .student-row').forEach(el => {
        selectedIds.add(el.dataset.history);
        el.classList.add('selected');
    });
    updateUI();
}

function clearSelection() {
    selectedIds.clear();
    document.querySelectorAll('#asalBody .student-row').forEach(el => {
        el.classList.remove('selected');
    });
    updateUI();
}

// ── UPDATE UI ────────────────────────────────────────────────
function updateUI() {
    const count = selectedIds.size;
    const info  = document.getElementById('selectedInfo');
    info.style.display = count > 0 ? '' : 'none';
    document.getElementById('selectedCount').textContent = count + ' dipilih';
    updateActionButtons();
}

function updateActionButtons() {
    const count     = selectedIds.size;
    const hasTujuan = !!document.getElementById('kelasTujuan').value;

    // Tombol Naikkan: perlu siswa dipilih + TA berikutnya ada + kelas tujuan dipilih
    const btnPromote = document.getElementById('btnPromote');
    btnPromote.disabled = !(count > 0 && NEXT_YEAR_ID && hasTujuan);
    document.getElementById('btnPromoteCount').textContent = count;
}

// ── PROSES NAIKKAN ───────────────────────────────────────────
function doPromote() {
    const targetClassroomId = document.getElementById('kelasTujuan').value;
    const kelasNama         = document.getElementById('kelasTujuan').options[
                                document.getElementById('kelasTujuan').selectedIndex].text;

    if (selectedIds.size === 0 || !targetClassroomId || !NEXT_YEAR_ID) return;

    Swal.fire({
        title            : 'Konfirmasi Kenaikan Kelas',
        html             : `Naikkan <strong>${selectedIds.size} siswa</strong> ke<br>
                            <strong>${kelasNama}</strong> pada TA <strong>${NEXT_YEAR_NAME}</strong>?<br>
                            <small class="text-muted">Siswa akan ditempatkan di Semester 1 tahun ajaran ini.</small>`,
        icon             : 'question',
        showCancelButton : true,
        confirmButtonText: 'Ya, Naikkan!',
        cancelButtonText : 'Batal',
        confirmButtonColor: '#0d6efd',
    }).then(result => {
        if (!result.isConfirmed) return;

        setPromoteLoading(true);

        const params = new URLSearchParams({
            [CSRF_NAME]      : csrfToken,
            classroom_id     : targetClassroomId,
            target_year_id   : NEXT_YEAR_ID,
        });
        selectedIds.forEach(id => params.append('history_ids[]', id));

        fetch('/promote-class/promote', {
            method  : 'POST',
            headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
            body    : params,
        })
        .then(r => r.json())
        .then(data => {
            csrfToken = data.csrf_token ?? csrfToken;
            if (data.success) {
                showToast(data.message, 'success');
                const kelasAsalId = document.getElementById('kelasAsal').value;
                if (kelasAsalId) loadAsalSiswa(kelasAsalId);
                loadTujuanSiswa(targetClassroomId, NEXT_YEAR_ID);
                clearSelection();
            } else {
                showToast(data.message, 'danger');
            }
            setPromoteLoading(false);
        })
        .catch(() => {
            showToast('Terjadi kesalahan!', 'danger');
            setPromoteLoading(false);
        });
    });
}

// ── LOADING HELPERS ───────────────────────────────────────────
function setPromoteLoading(on) {
    const btn = document.getElementById('btnPromote');
    btn.disabled = on;
    document.getElementById('btnPromoteLabel').style.display  = on ? 'none' : '';
    document.getElementById('btnPromoteLoading').style.display = on ? '' : 'none';
    if (!on) updateActionButtons();
}

// ── HELPERS ──────────────────────────────────────────────────
function resetAsalBody() {
    document.getElementById('asalBody').innerHTML = emptyRow(4, 'Pilih tingkat dan kelas asal');
}

function resetTujuanBody() {
    document.getElementById('tujuanBody').innerHTML = emptyRow(3, 'Pilih tahun ajaran dan kelas tujuan');
}

function setAsalLoading() {
    document.getElementById('asalBody').innerHTML =
        `<tr><td colspan="4" class="text-center py-3 text-muted small">
            <span class="spinner-border spinner-border-sm me-1"></span>Memuat...
        </td></tr>`;
}

function emptyRow(colspan, msg) {
    return `<tr><td colspan="${colspan}" class="text-center text-muted py-4">
        <i class="bi bi-inbox fs-3 d-block mb-2 opacity-25"></i>
        <small>${msg}</small>
    </td></tr>`;
}

function showToast(msg, type = 'success') {
    const el = document.getElementById('toastMsg');
    el.className = `toast align-items-center text-white border-0 bg-${type}`;
    document.getElementById('toastText').textContent = msg;
    new bootstrap.Toast(el, { delay: 3500 }).show();
}

function escHtml(str) {
    return String(str ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;')
        .replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
}
</script>
<?= $this->endSection() ?>
