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

<div class="row g-3">

    <!-- Kelas Asal -->
    <div class="col-md-6">
        <div class="card">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-box-arrow-right text-danger"></i>
                <span class="fw-semibold">Kelas Asal</span>
                <?php if ($activePeriod): ?>
                <span class="badge bg-success ms-auto">
                    <?= esc($activePeriod['year_name']) ?> — <?= esc($activePeriod['semester']) ?>
                </span>
                <?php endif; ?>
            </div>
            <div class="card-body">
                <div class="row g-2 mb-3">
                    <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 selected -->
                <div id="selectedInfo" class="mb-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>

                <!-- List siswa scrollable -->
                <div style="max-height:380px; overflow-y:auto; border:1px solid #dee2e6; border-radius:6px" id="asalBody">
                    <div class="text-center text-muted py-4 small">
                        <i class="bi bi-arrow-up-circle fs-3 d-block mb-2 opacity-25"></i>
                        Pilih tingkat dan kelas asal
                    </div>
                </div>

                <!-- Footer actions -->
                <div class="d-flex gap-2 mt-2">
                    <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>
    </div>

    <!-- Kelas Tujuan -->
    <div class="col-md-6">
        <div class="card mb-3">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-box-arrow-in-right text-success"></i>
                <span class="fw-semibold">Kelas Tujuan</span>
            </div>
            <div class="card-body">
                <div class="row g-2 mb-3">
                    <div class="col-6">
                        <label class="form-label small text-muted mb-1">Tingkat</label>
                        <select id="gradeTujuan" 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="kelasTujuan" class="form-select form-select-sm" disabled>
                            <option value="">-- Pilih Kelas --</option>
                        </select>
                    </div>
                </div>

                <!-- List siswa tujuan scrollable -->
                <div style="max-height:380px; overflow-y:auto; border:1px solid #dee2e6; border-radius:6px" id="tujuanBody">
                    <div class="text-center text-muted py-4 small">
                        <i class="bi bi-arrow-up-circle fs-3 d-block mb-2 opacity-25"></i>
                        Pilih tingkat dan kelas tujuan
                    </div>
                </div>
            </div>
        </div>

        <!-- Tombol Pindah -->
        <div class="card">
            <div class="card-body py-2">
                <button class="btn btn-primary w-100" id="btnPindah" disabled>
                    <i class="bi bi-arrow-left-right me-2"></i>
                    Pindahkan <span id="btnPindahCount">0</span> Siswa yang Dipilih
                </button>
            </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>
.student-row {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 8px 12px;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    transition: background .15s;
    user-select: none;
}
.student-row:hover { background: #f8f9fa; }
.student-row.selected {
    background: #d1f5e0 !important;
    border-left: 3px solid #198754;
}
[data-bs-theme="dark"] .student-row:hover { background: #2a3447; }
[data-bs-theme="dark"] .student-row.selected {
    background: #1a3a2a !important;
    border-left: 3px solid #198754;
}
.student-row .select-dot {
    width: 16px; height: 16px;
    border-radius: 50%;
    border: 2px solid #adb5bd;
    flex-shrink: 0;
    transition: all .15s;
}
.student-row.selected .select-dot {
    background: #198754;
    border-color: #198754;
}
</style>

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

<?= $this->section('scripts') ?>
<script>
const allClassrooms = [
    <?php foreach ($classrooms as $c): ?>
    { id: '<?= $c['id'] ?>', gradeId: '<?= $c['grade_id'] ?>', name: '<?= esc($c['name']) ?>' },
    <?php endforeach; ?>
];
const periodId = '<?= $activePeriod['id'] ?>';
let selectedIds = new Set(); // history_id yang dipilih

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

// ── LOAD SISWA KELAS ASAL ────────────────────────────────────
function loadAsalSiswa(classroomId) {
    selectedIds.clear();
    updateUI();

    const body = document.getElementById('asalBody');
    body.innerHTML = '<div class="text-center text-muted py-4 small"><span class="spinner-border spinner-border-sm me-2"></span>Memuat...</div>';

    $.get('/move-class/students', { classroom_id: classroomId, period_id: periodId }, function(res) {
        if (!res.success || res.students.length === 0) {
            body.innerHTML = '<div class="text-center text-muted py-4 small"><i class="bi bi-inbox d-block fs-3 mb-2 opacity-25"></i>Tidak ada siswa di kelas ini</div>';
            return;
        }

        body.innerHTML = res.students.map(s => `
            <div class="student-row" data-history="${s.history_id}" onclick="toggleSelect(this)">
                <div class="select-dot"></div>
                <div class="flex-grow-1">
                    <div class="fw-semibold small">${escHtml(s.full_name)}</div>
                    <div class="text-muted" style="font-size:.75rem">${escHtml(s.nis)}</div>
                </div>
                <span class="badge" style="font-size:.7rem;background:${s.gender=='L'?'#0d6efd':'#e91e8c'}">
                    ${s.gender}
                </span>
            </div>
        `).join('');
    });
}

// ── LOAD SISWA KELAS TUJUAN ──────────────────────────────────
function loadTujuanSiswa(classroomId) {
    const body = document.getElementById('tujuanBody');
    body.innerHTML = '<div class="text-center text-muted py-4 small"><span class="spinner-border spinner-border-sm me-2"></span>Memuat...</div>';

    $.get('/move-class/students', { classroom_id: classroomId, period_id: periodId }, function(res) {
        if (!res.success || res.students.length === 0) {
            body.innerHTML = '<div class="text-center text-muted py-4 small"><i class="bi bi-inbox d-block fs-3 mb-2 opacity-25"></i>Belum ada siswa di kelas ini</div>';
            return;
        }

        body.innerHTML = res.students.map(s => `
            <div class="d-flex align-items-center gap-2 px-3 py-2 border-bottom" style="font-size:.82rem">
                <span class="text-muted">${s.gender == 'L' ? '♂' : '♀'}</span>
                <div class="flex-grow-1">
                    <span class="fw-semibold">${escHtml(s.full_name)}</span>
                    <span class="text-muted ms-1" style="font-size:.75rem">${escHtml(s.nis)}</span>
                </div>
            </div>
        `).join('');
    });
}

// ── 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 hasTujuan = !!$('#kelasTujuan').val();

    // Info selected
    if (count > 0) {
        $('#selectedInfo').show();
        $('#selectedCount').text(count + ' dipilih');
    } else {
        $('#selectedInfo').hide();
    }

    // Tombol pindah
    const canPindah = count > 0 && hasTujuan;
    $('#btnPindah').prop('disabled', !canPindah);
    $('#btnPindahCount').text(count);
}

// ── PROSES PINDAH ────────────────────────────────────────────
$('#btnPindah').on('click', function() {
    if (selectedIds.size === 0 || !$('#kelasTujuan').val()) return;

    const kelasNama  = $('#kelasTujuan option:selected').text();
    const gradeAsal  = $('#gradeAsal').val();
    const gradeTujuan = $('#gradeTujuan').val();
    const isCrossGrade = gradeAsal !== gradeTujuan;

    let confirmHtml = `Pindahkan <strong>${selectedIds.size} siswa</strong> ke kelas <strong>${kelasNama}</strong>?`;
    if (isCrossGrade) {
        confirmHtml += `<br><br><span class="text-warning fw-bold"><i class="bi bi-exclamation-triangle-fill me-1"></i>Perhatian: Anda memindahkan siswa ke tingkat (jenjang) yang berbeda!</span>`;
    }

    Swal.fire({
        title             : 'Konfirmasi Pindah Kelas',
        html              : confirmHtml,
        icon              : isCrossGrade ? 'warning' : 'question',
        showCancelButton  : true,
        confirmButtonText : 'Ya, Pindahkan!',
        cancelButtonText  : 'Batal',
        confirmButtonColor: isCrossGrade ? '#fd7e14' : '#0d6efd',
    }).then(result => {
        if (!result.isConfirmed) return;

        const params = new URLSearchParams({ [csrfName]: csrfHash, classroom_id: $('#kelasTujuan').val() });
        selectedIds.forEach(id => params.append('history_ids[]', id));

        fetch('/move-class/process', {
            method  : 'POST',
            headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
            body    : params,
        })
        .then(r => r.json())
        .then(data => {
            csrfHash = data.csrf_token ?? csrfHash;
            if (data.success) {
                showToast(data.message, 'success');
                clearSelection();
                if ($('#kelasAsal').val())   loadAsalSiswa($('#kelasAsal').val());
                if ($('#kelasTujuan').val())  loadTujuanSiswa($('#kelasTujuan').val());
            } else {
                showToast(data.message, 'danger');
            }
        })
        .catch(() => showToast('Terjadi kesalahan!', 'danger'));
    });
});

// ── EVENT LISTENERS ──────────────────────────────────────────
$('#gradeAsal').on('change', function() {
    const val = this.value;
    buildKelas(val, 'kelasAsal');
    document.getElementById('asalBody').innerHTML =
        '<div class="text-center text-muted py-4 small"><i class="bi bi-arrow-up-circle fs-3 d-block mb-2 opacity-25"></i>Pilih kelas asal</div>';
    selectedIds.clear();
    
    // Clear target classroom and student list
    document.getElementById('kelasTujuan').value = '';
    document.getElementById('tujuanBody').innerHTML =
        '<div class="text-center text-muted py-4 small"><i class="bi bi-arrow-up-circle fs-3 d-block mb-2 opacity-25"></i>Pilih kelas tujuan</div>';
        
    updateUI();
});

$('#kelasAsal').on('change', function() {
    if (this.value) loadAsalSiswa(this.value);
});

$('#gradeTujuan').on('change', function() {
    buildKelas(this.value, 'kelasTujuan');
    document.getElementById('tujuanBody').innerHTML =
        '<div class="text-center text-muted py-4 small"><i class="bi bi-arrow-up-circle fs-3 d-block mb-2 opacity-25"></i>Pilih kelas tujuan</div>';
    updateUI();
});

$('#kelasTujuan').on('change', function() {
    if (this.value) loadTujuanSiswa(this.value);
    updateUI();
});

// ── HELPERS ──────────────────────────────────────────────────
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: 3000 }).show();
}

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

let csrfName = '<?= csrf_token() ?>';
let csrfHash = '<?= csrf_hash() ?>';
</script>
<?= $this->endSection() ?>