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

<div class="row g-3">
    <!-- Panel Kiri: Filter & Daftar Siswa -->
    <div class="col-md-5">
        <div class="card">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-piggy-bank text-primary"></i>
                <span class="fw-semibold">Daftar Siswa</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 p-2">
                <div class="row g-2 mb-2 px-2">
                    <div class="col-6">
                        <label class="form-label small text-muted mb-1">Tingkat</label>
                        <select id="filterGrade" class="form-select form-select-sm" onchange="onGradeChange()">
                            <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="filterClassroom" class="form-select form-select-sm" disabled onchange="onClassroomChange()">
                            <option value="">-- Pilih Kelas --</option>
                        </select>
                    </div>
                </div>

                <div style="max-height:420px; overflow-y:auto; border:1px solid #dee2e6; border-radius:6px" id="studentBody">
                    <div class="text-center text-muted py-5 small">
                        <i class="bi bi-funnel fs-2 d-block mb-2 opacity-25"></i>
                        Pilih tingkat dan kelas
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Panel Kanan: Detail & Transaksi -->
    <div class="col-md-7">
        <div class="card" id="detailCard" style="display:none">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-person text-info"></i>
                <span class="fw-semibold" id="detailName">-</span>
                <span class="badge bg-light text-dark ms-2" id="detailNis">-</span>
                <span class="ms-auto fw-bold text-success" id="detailBalance" style="font-size:1.1rem">Rp 0</span>
            </div>
            <div class="card-body p-3">
                <!-- Form Transaksi -->
                <form id="transactionForm" class="row g-2 mb-3 pb-3 border-bottom">
                    <div class="col-12">
                        <div class="btn-group w-100" role="group">
                            <input type="radio" class="btn-check" name="transaction_type" value="setoran" id="typeSetoran" checked>
                            <label class="btn btn-sm btn-outline-success" for="typeSetoran">
                                <i class="bi bi-plus-circle me-1"></i>Setoran
                            </label>
                            <input type="radio" class="btn-check" name="transaction_type" value="penarikan" id="typePenarikan">
                            <label class="btn btn-sm btn-outline-danger" for="typePenarikan">
                                <i class="bi bi-dash-circle me-1"></i>Penarikan
                            </label>
                        </div>
                    </div>
                    <div class="col-6">
                        <label class="form-label small text-muted mb-1">Nominal (Rp)</label>
                        <input type="number" id="inputAmount" class="form-control form-control-sm" placeholder="0" min="1" required>
                    </div>
                    <div class="col-6">
                        <label class="form-label small text-muted mb-1">Tanggal</label>
                        <input type="date" id="inputDate" class="form-control form-control-sm" value="<?= date('Y-m-d') ?>" required>
                    </div>
                    <div class="col-8">
                        <label class="form-label small text-muted mb-1">Catatan</label>
                        <input type="text" id="inputNotes" class="form-control form-control-sm" placeholder="Catatan transaksi...">
                    </div>
                    <div class="col-4 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary btn-sm w-100">
                            <i class="bi bi-save me-1"></i>Simpan
                        </button>
                    </div>
                </form>

                <!-- Riwayat Transaksi -->
                <div class="d-flex align-items-center justify-content-between mb-2">
                    <span class="fw-semibold small"><i class="bi bi-clock-history me-1"></i>Riwayat Transaksi</span>
                    <span class="text-muted small" id="historyCount"></span>
                </div>
                <div style="max-height:300px; overflow-y:auto" id="historyBody">
                    <div class="text-center text-muted py-3 small">Belum ada transaksi</div>
                </div>
            </div>
        </div>

        <!-- Placeholder -->
        <div class="text-center text-muted py-5" id="emptyDetail">
            <i class="bi bi-arrow-left-circle fs-1 d-block mb-2 opacity-25"></i>
            <small>Pilih siswa dari daftar di sebelah kiri</small>
        </div>
    </div>
</div>

<style>
.student-row-tab {
    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-tab:hover { background: #f8f9fa; }
.student-row-tab.active { background: #e8f0fe; border-left: 3px solid #0d6efd; }
[data-bs-theme="dark"] .student-row-tab:hover { background: #2a3447; }
[data-bs-theme="dark"] .student-row-tab.active { background: #172a4a; }
.txn-row { display: flex; align-items: center; justify-content: space-between;
    padding: 6px 10px; border-bottom: 1px solid #f0f0f0; font-size: .82rem; }
.txn-row:last-child { border-bottom: none; }
.txn-setoran { color: #198754; }
.txn-penarikan { color: #dc3545; }
</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 PERIOD_ID = <?= $activePeriod['id'] ?? 0 ?>;
let currentStudentId = null;

function onGradeChange() {
    const gradeId = document.getElementById('filterGrade').value;
    const selClass = document.getElementById('filterClassroom');
    selClass.innerHTML = '<option value="">-- Pilih Kelas --</option>';
    allClassrooms
        .filter(c => !gradeId || c.gradeId === gradeId)
        .forEach(c => selClass.appendChild(new Option(c.name, c.id)));
    selClass.disabled = !gradeId;
    document.getElementById('studentBody').innerHTML =
        '<div class="text-center text-muted py-5 small"><i class="bi bi-funnel fs-2 d-block mb-2 opacity-25"></i>Pilih kelas</div>';
    resetDetail();
}

function onClassroomChange() {
    const classroomId = document.getElementById('filterClassroom').value;
    if (!classroomId) return;
    resetDetail();
    loadStudents(classroomId);
}

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

    fetch(`/student/by-class?classroom_id=${classroomId}&period_id=${PERIOD_ID}`)
        .then(r => r.json())
        .then(data => {
            const students = data.students ?? [];
            if (students.length === 0) {
                body.innerHTML = '<div class="text-center text-muted py-5 small"><i class="bi bi-inbox fs-2 d-block mb-2 opacity-25"></i>Tidak ada siswa</div>';
                return;
            }
            body.innerHTML = students.map(s => `
                <div class="student-row-tab" data-id="${s.id}" onclick="selectStudent(${s.id})">
                    <div class="flex-grow-1">
                        <div class="fw-semibold small">${escHtml(s.full_name)}</div>
                        <div class="text-muted" style="font-size:.72rem">${escHtml(s.nis)}</div>
                    </div>
                    <span class="badge" style="font-size:.7rem;background:${s.gender=='L'?'#0d6efd':'#e91e8c'}">${s.gender}</span>
                </div>
            `).join('');
        });
}

function selectStudent(studentId) {
    currentStudentId = studentId;
    document.querySelectorAll('.student-row-tab').forEach(el => el.classList.remove('active'));
    document.querySelector(`.student-row-tab[data-id="${studentId}"]`)?.classList.add('active');
    loadHistory();
}

function loadHistory() {
    if (!currentStudentId) return;
    document.getElementById('emptyDetail').style.display = 'none';
    document.getElementById('detailCard').style.display = '';

    fetch(`/tabungan/history/${currentStudentId}`)
        .then(r => r.json())
        .then(data => {
            if (!data.success) return;
            document.getElementById('detailName').textContent = data.student.full_name;
            document.getElementById('detailNis').textContent = 'NIS: ' + data.student.nis;
            document.getElementById('detailBalance').textContent = 'Rp ' + formatNumber(data.balance);
            document.getElementById('historyCount').textContent = data.history.length + ' transaksi';

            const body = document.getElementById('historyBody');
            if (data.history.length === 0) {
                body.innerHTML = '<div class="text-center text-muted py-3 small">Belum ada transaksi</div>';
                return;
            }
            body.innerHTML = data.history.map(t => `
                <div class="txn-row">
                    <div>
                        <span class="fw-semibold ${t.transaction_type === 'setoran' ? 'txn-setoran' : 'txn-penarikan'}">
                            ${t.transaction_type === 'setoran' ? '+' : '-'} Rp ${formatNumber(t.amount)}
                        </span>
                        ${t.notes ? `<span class="text-muted ms-2" style="font-size:.72rem">${escHtml(t.notes)}</span>` : ''}
                    </div>
                    <div class="text-end">
                        <div class="small text-muted">${t.transaction_date}</div>
                        <div style="font-size:.7rem;color:#888">
                            <span class="me-2">Saldo: Rp ${formatNumber(t.balance_after)}</span>
                            <a href="/tabungan/print-slip/${t.id}" target="_blank" class="text-muted" title="Cetak Slip">
                                <i class="bi bi-printer"></i>
                            </a>
                            <button class="btn btn-link btn-sm text-danger p-0 ms-1" title="Hapus" onclick="deleteTransaction(${t.id})">
                                <i class="bi bi-trash" style="font-size:.7rem"></i>
                            </button>
                        </div>
                    </div>
                </div>
            `).join('');
        });
}

function resetDetail() {
    currentStudentId = null;
    document.getElementById('emptyDetail').style.display = '';
    document.getElementById('detailCard').style.display = 'none';
}

document.getElementById('transactionForm').addEventListener('submit', function(e) {
    e.preventDefault();
    if (!currentStudentId) {
        alert('Pilih siswa terlebih dahulu!');
        return;
    }

    const amount = parseFloat(document.getElementById('inputAmount').value);
    if (!amount || amount <= 0) {
        alert('Nominal harus lebih dari 0!');
        return;
    }

    const params = new URLSearchParams();
    params.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');
    params.append('student_id', currentStudentId);
    params.append('transaction_type', document.querySelector('input[name="transaction_type"]:checked').value);
    params.append('amount', amount);
    params.append('transaction_date', document.getElementById('inputDate').value);
    params.append('notes', document.getElementById('inputNotes').value);

    fetch('/tabungan/store', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' },
        body: params,
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            document.getElementById('inputAmount').value = '';
            document.getElementById('inputNotes').value = '';
            loadHistory();
            showToast(data.message, 'success');
        } else {
            showToast(data.message, 'danger');
        }
    });
});

function deleteTransaction(id) {
    if (!confirm('Hapus transaksi ini?')) return;

    const params = new URLSearchParams();
    params.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');

    fetch(`/tabungan/delete/${id}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' },
        body: params,
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            loadHistory();
            showToast(data.message, 'success');
        } else {
            showToast(data.message, 'danger');
        }
    });
}

function showToast(msg, type) {
    const wrapper = document.createElement('div');
    wrapper.className = 'position-fixed bottom-0 end-0 p-3';
    wrapper.style.zIndex = '9999';
    wrapper.innerHTML = `<div class="toast align-items-center text-white bg-${type} border-0 show">
        <div class="d-flex"><div class="toast-body fw-semibold small">${escHtml(msg)}</div>
        <button class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button></div></div>`;
    document.body.appendChild(wrapper);
    setTimeout(() => wrapper.remove(), 3000);
}

function formatNumber(n) {
    return parseFloat(n).toLocaleString('id-ID');
}

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