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

<div class="row g-3">

    <!-- KIRI: Siswa belum punya kelas -->
    <div class="col-md-6">
        <div class="card" style="height:calc(100vh - 160px); display:flex; flex-direction:column">
            <div class="card-header d-flex align-items-center justify-content-between">
                <div class="d-flex align-items-center gap-2">
                    <i class="bi bi-people text-primary"></i>
                    <span class="fw-semibold">Siswa Belum Ada Kelas</span>
                </div>
                <span class="badge bg-secondary" id="unassignedCount"><?= count($unassigned) ?></span>
            </div>

            <!-- Search -->
            <div class="px-3 pt-3 pb-2" style="flex-shrink:0">
                <input type="text" id="searchUnassigned" class="form-control form-control-sm"
                    placeholder="Cari nama / NIS...">
            </div>

            <!-- Info selected -->
            <div class="px-3 pb-2" id="selectedInfo" style="display:none; flex-shrink:0">
                <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>

            <!-- Daftar siswa -->
            <div style="flex:1; overflow-y:auto; min-height:0">
                <?php if (empty($unassigned)): ?>
                <div class="text-center text-muted py-5">
                    <i class="bi bi-check-circle fs-2 text-success d-block mb-2"></i>
                    Semua siswa sudah memiliki kelas
                </div>
                <?php else: ?>
                <div id="unassignedList">
                    <?php foreach ($unassigned as $student): ?>
                    <div class="student-row d-flex align-items-center gap-2 px-3 py-2 border-bottom"
                        data-id="<?= $student['id'] ?>"
                        data-name="<?= esc(strtolower($student['full_name'])) ?>"
                        data-nis="<?= esc(strtolower($student['nis'])) ?>"
                        onclick="toggleSelect(this)"
                        style="cursor:pointer; transition:background .15s">
                        <div class="select-indicator rounded-circle border border-2 flex-shrink-0"
                            style="width:18px;height:18px;transition:all .15s"></div>
                        <div class="flex-grow-1">
                            <div class="fw-semibold small"><?= esc($student['full_name']) ?></div>
                            <div class="text-muted" style="font-size:.75rem"><?= esc($student['nis']) ?></div>
                        </div>
                        <span class="badge"
                            style="font-size:.7rem;background:<?= $student['gender'] == 'L' ? '#0d6efd' : '#e91e8c' ?>">
                            <?= $student['gender'] ?>
                        </span>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>

            <div class="card-footer d-flex gap-2" style="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: Pilih Kelas + Siswa -->
    <div class="col-md-6">
        <div class="card" style="height:calc(100vh - 160px); display:flex; flex-direction:column">

            <!-- Header -->
            <div class="card-header d-flex align-items-center gap-2" style="flex-shrink:0">
                <i class="bi bi-door-open text-primary"></i>
                <span class="fw-semibold">Pilih Kelas</span>
                <span class="badge bg-primary bg-opacity-10 text-primary small">
                    <?= esc($activePeriod['year_name']) ?> — <?= esc($activePeriod['semester']) ?>
                </span>
            </div>

            <!-- Dropdown -->
            <div class="px-3 pt-3 pb-2" style="flex-shrink:0">
                <select id="classroomSelect" class="form-select form-select-sm" onchange="onClassroomChange()">
                    <option value="">-- Pilih Kelas --</option>
                    <?php foreach ($classrooms as $classroom): ?>
                    <option value="<?= $classroom['id'] ?>"
                        data-capacity="<?= $classroom['capacity'] ?>"
                        data-grade="<?= esc($classroom['grade_name']) ?>"
                        data-name="<?= esc($classroom['name']) ?>"
                        data-major="<?= esc($classroom['major_name'] ?? '') ?>">
                        <?= esc($classroom['grade_name']) ?> — <?= esc($classroom['name']) ?>
                        <?php if ($classroom['major_name']): ?>
                        (<?= esc($classroom['major_name']) ?>)
                        <?php endif; ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Info kapasitas + tombol assign -->
            <div class="px-3 pb-2" id="classroomMeta" style="display:none; flex-shrink:0">
                <div class="d-flex align-items-center justify-content-between">
                    <div>
                        <span class="fw-semibold small" id="panelClassName"></span>
                        <span class="text-muted small ms-1" id="panelCapacity"></span>
                    </div>
                    <button class="btn btn-success btn-sm px-3" id="btnAssign"
                        onclick="doAssign()" style="display:none">
                        <i class="bi bi-plus-lg me-1"></i>
                        Assign <span id="btnAssignCount"></span> Siswa ke Sini
                    </button>
                </div>
            </div>

            <!-- Move panel -->
            <div class="px-3 pb-2" id="movePanel" style="display:none; flex-shrink:0">
                <div class="d-flex align-items-center gap-2 p-2 bg-warning bg-opacity-10 rounded border border-warning">
                    <i class="bi bi-arrow-left-right text-warning flex-shrink-0"></i>
                    <span class="small text-nowrap">Pindahkan <strong id="movePanelName"></strong> ke:</span>
                    <select id="moveTargetSelect" class="form-select form-select-sm">
                        <option value="">-- Pilih --</option>
                        <?php foreach ($classrooms as $classroom): ?>
                        <option value="<?= $classroom['id'] ?>">
                            <?= esc($classroom['grade_name']) ?> — <?= esc($classroom['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <button class="btn btn-sm btn-warning flex-shrink-0" onclick="confirmMove()">Pindah</button>
                    <button class="btn btn-sm btn-link text-muted p-0 flex-shrink-0" onclick="cancelMove()">
                        <i class="bi bi-x"></i>
                    </button>
                </div>
            </div>

            <!-- Placeholder (saat belum pilih kelas) -->
            <div id="classroomPlaceholder" style="flex:1; display:flex; flex-direction:column; align-items:center; justify-content:center" class="text-muted">
                <i class="bi bi-arrow-left-circle fs-2 mb-2 opacity-25"></i>
                <p class="small mb-0">Pilih kelas di atas untuk melihat isinya</p>
            </div>

            <!-- Daftar siswa di kelas (scrollable) -->
            <div id="classroomBody" style="flex:1; overflow-y:auto; min-height:0; display:none">
                <div id="classStudentList"></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>

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

<?= $this->section('scripts') ?>
<script>
const PERIOD_ID  = <?= $activePeriod['id'] ?>;
const CSRF_NAME  = '<?= csrf_token() ?>';
let   csrfToken  = '<?= csrf_hash() ?>';

let selectedIds     = new Set();
let currentClassId  = null;
let moveHistoryId   = null;
let moveStudentName = '';

// ── SEARCH ────────────────────────────────────────────────────
document.getElementById('searchUnassigned').addEventListener('input', function() {
    const q = this.value.toLowerCase();
    document.querySelectorAll('#unassignedList .student-row').forEach(row => {
        row.style.display =
            (row.dataset.name.includes(q) || row.dataset.nis.includes(q)) ? '' : 'none';
    });
});

// ── SELECT SISWA (KIRI) ───────────────────────────────────────
function toggleSelect(el) {
    const id = el.dataset.id;
    if (selectedIds.has(id)) {
        selectedIds.delete(id);
        el.style.background = '';
        styleIndicator(el.querySelector('.select-indicator'), false);
    } else {
        selectedIds.add(id);
        el.style.background = '#d1fae5';
        styleIndicator(el.querySelector('.select-indicator'), true);
    }
    updateUI();
}

function styleIndicator(el, active) {
    el.style.background  = active ? '#22c55e' : '';
    el.style.borderColor = active ? '#22c55e' : '#dee2e6';
}

function selectAll() {
    document.querySelectorAll('#unassignedList .student-row').forEach(row => {
        if (row.style.display === 'none') return;
        selectedIds.add(row.dataset.id);
        row.style.background = '#d1fae5';
        styleIndicator(row.querySelector('.select-indicator'), true);
    });
    updateUI();
}

function clearSelection() {
    selectedIds.clear();
    document.querySelectorAll('#unassignedList .student-row').forEach(row => {
        row.style.background = '';
        styleIndicator(row.querySelector('.select-indicator'), false);
    });
    updateUI();
}

function updateUI() {
    const info = document.getElementById('selectedInfo');
    info.style.display = selectedIds.size > 0 ? '' : 'none';
    document.getElementById('selectedCount').textContent = selectedIds.size + ' dipilih';

    const btn = document.getElementById('btnAssign');
    if (currentClassId && selectedIds.size > 0) {
        btn.style.display = '';
        document.getElementById('btnAssignCount').textContent = selectedIds.size;
    } else {
        btn.style.display = 'none';
    }
}

// ── PILIH KELAS (KANAN) ───────────────────────────────────────
function onClassroomChange() {
    const select = document.getElementById('classroomSelect');
    const id     = select.value;

    if (!id) {
        currentClassId = null;
        document.getElementById('classroomMeta').style.display        = 'none';
        document.getElementById('classroomPlaceholder').style.display = '';
        document.getElementById('classroomBody').style.display        = 'none';
        document.getElementById('classStudentList').innerHTML         = '';
        cancelMove();
        updateUI();
        return;
    }

    currentClassId = id;
    const opt = select.options[select.selectedIndex];

    let label = opt.dataset.grade + ' — ' + opt.dataset.name;
    if (opt.dataset.major) label += ' (' + opt.dataset.major + ')';
    document.getElementById('panelClassName').textContent          = label;
    document.getElementById('classroomMeta').style.display         = '';
    document.getElementById('classroomPlaceholder').style.display  = 'none';
    document.getElementById('classroomBody').style.display         = '';

    loadClassStudents(id, opt.dataset.capacity);
    updateUI();
}

function loadClassStudents(classroomId, capacity) {
    document.getElementById('classStudentList').innerHTML =
        '<div class="text-center text-muted py-4 small"><span class="spinner-border spinner-border-sm me-2"></span>Memuat...</div>';

    fetch('/class-assignment/students?classroom_id=' + classroomId + '&period_id=' + PERIOD_ID)
        .then(r => r.json())
        .then(data => renderClassStudents(data.students, capacity));
}

function renderClassStudents(students, capacity) {
    const list = document.getElementById('classStudentList');
    const cap  = parseInt(capacity);

    document.getElementById('panelCapacity').textContent =
        students.length + '/' + cap + ' siswa' +
        (students.length >= cap ? ' (penuh)' : '');

    if (students.length === 0) {
        list.innerHTML = `
            <div class="text-center text-muted py-5 small">
                <i class="bi bi-inbox d-block fs-3 mb-2 opacity-25"></i>
                Belum ada siswa di kelas ini
            </div>`;
        return;
    }

    list.innerHTML = students.map(s => `
        <div class="d-flex align-items-center gap-2 px-3 py-2 border-bottom"
            id="sitem-${s.history_id}" style="font-size:.82rem">
            <span class="text-muted" style="width:16px">
                ${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>
            <button class="btn btn-sm btn-outline-warning py-0 px-2"
                style="font-size:.7rem"
                onclick="openMove(${s.history_id}, '${escHtml(s.full_name)}')"
                title="Pindah kelas">
                <i class="bi bi-arrow-left-right"></i>
            </button>
        </div>
    `).join('');
}

// ── ASSIGN ────────────────────────────────────────────────────
function doAssign() {
    if (!currentClassId || selectedIds.size === 0) return;

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

    const params = new URLSearchParams({ [CSRF_NAME]: csrfToken, classroom_id: currentClassId, period_id: PERIOD_ID });
    selectedIds.forEach(id => params.append('student_ids[]', id));

    fetch('/class-assignment/assign', {
        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) {
            selectedIds.forEach(id => {
                document.querySelector(`.student-row[data-id="${id}"]`)?.remove();
            });
            document.getElementById('unassignedCount').textContent =
                document.querySelectorAll('#unassignedList .student-row').length;

            const opt = document.getElementById('classroomSelect')
                .options[document.getElementById('classroomSelect').selectedIndex];
            loadClassStudents(currentClassId, opt.dataset.capacity);

            clearSelection();
            showToast(data.message, 'success');
        } else {
            showToast(data.message, 'danger');
        }
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-plus-lg me-1"></i>Assign <span id="btnAssignCount">0</span> Siswa ke Sini';
        updateUI();
    })
    .catch(() => {
        showToast('Terjadi kesalahan!', 'danger');
        btn.disabled = false;
        updateUI();
    });
}

// ── PINDAH KELAS ──────────────────────────────────────────────
function openMove(historyId, studentName) {
    moveHistoryId   = historyId;
    moveStudentName = studentName;

    const select = document.getElementById('moveTargetSelect');
    [...select.options].forEach(opt => {
        opt.disabled = (opt.value == currentClassId);
    });
    select.value = '';

    document.getElementById('movePanelName').textContent = studentName;
    document.getElementById('movePanel').style.display   = '';
}

function cancelMove() {
    moveHistoryId = null;
    document.getElementById('movePanel').style.display = 'none';
}

function confirmMove() {
    const targetId = document.getElementById('moveTargetSelect').value;
    if (!targetId) { showToast('Pilih kelas tujuan!', 'warning'); return; }

    fetch('/class-assignment/move', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({ [CSRF_NAME]: csrfToken, history_id: moveHistoryId, classroom_id: targetId })
    })
    .then(r => r.json())
    .then(data => {
        csrfToken = data.csrf_token ?? csrfToken;
        if (data.success) {
            const opt = document.getElementById('classroomSelect')
                .options[document.getElementById('classroomSelect').selectedIndex];
            loadClassStudents(currentClassId, opt.dataset.capacity);
            cancelMove();
            showToast(data.message, 'success');
        } else {
            showToast(data.message, 'danger');
        }
    })
    .catch(() => showToast('Terjadi kesalahan!', 'danger'));
}

// ── 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;');
}
</script>
<?= $this->endSection() ?>