<?php
require_once __DIR__ . '/includes/functions.php';
requireLogin();
$pageTitle = 'Data Siswa';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'save') {
        $id = $_POST['id'] ?? '';
        $params = [
            'nis' => trim($_POST['nis']),
            'nisn' => trim($_POST['nisn']),
            'nama' => trim($_POST['nama']),
            'kelas_id' => $_POST['kelas_id'] ?: null,
            'jenis_kelamin' => $_POST['jenis_kelamin'],
            'nama_ortu' => trim($_POST['nama_ortu']),
            'no_hp_ortu' => trim($_POST['no_hp_ortu']),
            'nominal_spp' => (float)str_replace('.', '', $_POST['nominal_spp']),
            'status' => $_POST['status'],
        ];
        if ($id) {
            $params['id'] = $id;
            $pdo->prepare("UPDATE siswa SET nis=:nis, nisn=:nisn, nama=:nama, kelas_id=:kelas_id, jenis_kelamin=:jenis_kelamin, nama_ortu=:nama_ortu, no_hp_ortu=:no_hp_ortu, nominal_spp=:nominal_spp, status=:status WHERE id=:id")->execute($params);
            flash('success', 'Data siswa berhasil diperbarui.');
        } else {
            $pdo->prepare("INSERT INTO siswa (nis,nisn,nama,kelas_id,jenis_kelamin,nama_ortu,no_hp_ortu,nominal_spp,status) VALUES (:nis,:nisn,:nama,:kelas_id,:jenis_kelamin,:nama_ortu,:no_hp_ortu,:nominal_spp,:status)")->execute($params);
            flash('success', 'Data siswa berhasil ditambahkan.');
        }
    } elseif ($action === 'delete') {
        $id = $_POST['id'];
        $cek = $pdo->prepare("SELECT COUNT(*) FROM tagihan_spp WHERE siswa_id=:id"); $cek->execute(['id'=>$id]);
        if ($cek->fetchColumn() > 0) {
            flash('error', 'Siswa tidak dapat dihapus karena sudah memiliki riwayat tagihan SPP. Ubah status menjadi nonaktif/lulus.');
        } else {
            $pdo->prepare("DELETE FROM siswa WHERE id=:id")->execute(['id'=>$id]);
            flash('success', 'Data siswa berhasil dihapus.');
        }
    } elseif ($action === 'import') {
        if (empty($_FILES['csv_file']['tmp_name'])) {
            flash('error', 'Silakan pilih file CSV terlebih dahulu.');
            header('Location: siswa.php');
            exit;
        }

        $handle = fopen($_FILES['csv_file']['tmp_name'], 'r');
        $firstLine = fgets($handle);
        $firstLineClean = preg_replace('/^\xEF\xBB\xBF/', '', $firstLine);
        $skippedSepLine = strpos(trim($firstLineClean), 'sep=') === 0;
        $sampleLine = $skippedSepLine ? fgets($handle) : $firstLineClean;
        $delimiter = substr_count($sampleLine, ';') >= substr_count($sampleLine, ',') ? ';' : ',';
        rewind($handle);
        if ($skippedSepLine) fgets($handle);
        $headerRow = fgetcsv($handle, 0, $delimiter);

        $berhasil = 0; $dilewati = 0; $errors = [];
        $baris = 1;

        $stmtCekNis = $pdo->prepare("SELECT id FROM siswa WHERE nis=:nis");
        $stmtInsert = $pdo->prepare("INSERT INTO siswa (nis,nisn,nama,kelas_id,jenis_kelamin,nama_ortu,no_hp_ortu,nominal_spp,status) VALUES (:nis,:nisn,:nama,:kelas_id,:jk,:ortu,:hp,:nominal,:status)");

        function normalisasiTeks($s) { return strtolower(preg_replace('/[^a-z0-9]/i', '', (string)$s)); }
        function intiNamaKelas($kelasNama, $tingkatNama) {
            $kelasNama = trim((string)$kelasNama); $tingkatNama = trim((string)$tingkatNama);
            if ($tingkatNama !== '' && stripos($kelasNama, $tingkatNama) === 0) $kelasNama = substr($kelasNama, strlen($tingkatNama));
            $kelasNama = preg_replace('/^[^a-z0-9]+/i', '', $kelasNama);
            return normalisasiTeks($kelasNama);
        }

        $tingkatListImport = $pdo->query("SELECT * FROM tingkat")->fetchAll();
        $petaTingkat = [];
        foreach ($tingkatListImport as $tg) { $petaTingkat[normalisasiTeks($tg['nama'])] = $tg['id']; }
        $kelasListImport = $pdo->query("SELECT k.id, k.tingkat_id, t.nama as tingkat_nama, k.nama as kelas_nama FROM kelas k JOIN tingkat t ON t.id=k.tingkat_id")->fetchAll();
        $petaKelas = [];
        foreach ($kelasListImport as $kl) { $petaKelas[$kl['tingkat_id'].'|'.intiNamaKelas($kl['kelas_nama'],$kl['tingkat_nama'])] = $kl['id']; }

        while (($cols = fgetcsv($handle, 0, $delimiter)) !== false) {
            $baris++;
            if (count($cols) === 1 && trim($cols[0]) === '') continue;
            if (count($cols) < 9) { $errors[] = "Baris $baris: jumlah kolom tidak sesuai, dilewati."; $dilewati++; continue; }
            [$nis, $nisn, $nama, $jk, $tingkat, $kelas, $nominal, $ortu, $hp, $status] = array_pad($cols, 10, '');
            $nis = trim($nis); $nama = trim($nama);
            if ($nis === '' || $nama === '') { $errors[] = "Baris $baris: NIS/Nama kosong."; $dilewati++; continue; }
            $stmtCekNis->execute(['nis' => $nis]); $nisAdaSudah = $stmtCekNis->fetch(); $stmtCekNis->closeCursor();
            if ($nisAdaSudah) { $errors[] = "Baris $baris: NIS $nis sudah ada."; $dilewati++; continue; }
            $kelasId = null;
            if (trim($tingkat) !== '' && trim($kelas) !== '') {
                $tingkatId = $petaTingkat[normalisasiTeks($tingkat)] ?? null;
                if ($tingkatId === null) { $errors[] = "Baris $baris: Tingkat \"$tingkat\" tidak ditemukan."; }
                else { $kunciCari = $tingkatId.'|'.intiNamaKelas($kelas, $tingkat); if (isset($petaKelas[$kunciCari])) $kelasId = $petaKelas[$kunciCari]; else $errors[] = "Baris $baris: Kelas \"$tingkat $kelas\" tidak ditemukan."; }
            }
            $jkNorm = strtolower(trim($jk));
            $jk = ($jkNorm === 'p' || strpos($jkNorm, 'perempuan') !== false) ? 'P' : 'L';
            $statusValid = ['aktif','lulus','pindah','nonaktif'];
            $status = in_array(strtolower(trim($status)), $statusValid) ? strtolower(trim($status)) : 'aktif';
            $nominalBersih = (float) preg_replace('/[^0-9]/', '', $nominal);
            $stmtInsert->execute(['nis'=>$nis,'nisn'=>trim($nisn),'nama'=>$nama,'kelas_id'=>$kelasId,'jk'=>$jk,'ortu'=>trim($ortu),'hp'=>trim($hp),'nominal'=>$nominalBersih,'status'=>$status]);
            $stmtInsert->closeCursor();
            $berhasil++;
        }
        fclose($handle);
        $pesan = "Import selesai: $berhasil siswa berhasil ditambahkan, $dilewati dilewati.";
        if (!empty($errors)) { $pesan .= ' Catatan: '.implode(' | ', array_slice($errors,0,8)); if (count($errors)>8) $pesan .= ' ...dan '.(count($errors)-8).' catatan lainnya.'; }
        flash($berhasil > 0 ? 'success' : 'error', $pesan);
    }
    header('Location: siswa.php');
    exit;
}

// -------- FILTER --------
$fTingkat  = $_GET['tingkat_id'] ?? '';
$fKelas    = $_GET['kelas_id'] ?? '';
$fStatus   = $_GET['status'] ?? '';

$sql = "SELECT s.*, k.nama as kelas_nama, t.nama as tingkat_nama FROM siswa s
        LEFT JOIN kelas k ON k.id=s.kelas_id LEFT JOIN tingkat t ON t.id=k.tingkat_id WHERE 1=1";
$params = [];
if ($fTingkat) { $sql .= " AND t.id=:tingkat_id"; $params['tingkat_id'] = $fTingkat; }
if ($fKelas)   { $sql .= " AND s.kelas_id=:kelas_id"; $params['kelas_id'] = $fKelas; }
if ($fStatus)  { $sql .= " AND s.status=:status"; $params['status'] = $fStatus; }
$sql .= " ORDER BY t.nama, k.nama, s.nama";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$data = $stmt->fetchAll();

$kelasList  = $pdo->query("SELECT k.*, t.nama as tingkat_nama FROM kelas k JOIN tingkat t ON t.id=k.tingkat_id ORDER BY t.nama, k.nama")->fetchAll();
$tingkatList = $pdo->query("SELECT * FROM tingkat ORDER BY nama")->fetchAll();

// Filter kelas dropdown: tampilkan hanya kelas di tingkat terpilih
$kelasDropdown = $fTingkat ? array_filter($kelasList, fn($kl) => $kl['tingkat_id'] == $fTingkat) : $kelasList;

include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>

<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
    <h5 class="mb-0">Data Siswa</h5>
    <div class="d-flex gap-2">
        <a href="export_siswa.php?action=template" class="btn btn-outline-secondary"><i class="bi bi-download"></i> Download Template</a>
        <a href="export_siswa.php?action=export" class="btn btn-outline-success"><i class="bi bi-file-earmark-spreadsheet"></i> Export CSV</a>
        <button class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#modalImport"><i class="bi bi-upload"></i> Import CSV</button>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalSiswa" onclick="resetForm()"><i class="bi bi-plus-lg"></i> Tambah Siswa</button>
    </div>
</div>

<!-- FILTER BAR -->
<div class="card mb-3">
    <div class="card-body py-2">
        <form method="GET" class="row g-2 align-items-end" id="formFilter">
            <div class="col-md-3">
                <label class="form-label small mb-1">Tingkat</label>
                <select name="tingkat_id" class="form-select form-select-sm" onchange="document.getElementById('formFilter').submit()">
                    <option value="">Semua Tingkat</option>
                    <?php foreach ($tingkatList as $t): ?>
                        <option value="<?= $t['id'] ?>" <?= $fTingkat==$t['id']?'selected':'' ?>>Tingkat <?= htmlspecialchars($t['nama']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label small mb-1">Kelas</label>
                <select name="kelas_id" class="form-select form-select-sm" onchange="document.getElementById('formFilter').submit()">
                    <option value="">Semua Kelas</option>
                    <?php foreach ($kelasDropdown as $kl): ?>
                        <option value="<?= $kl['id'] ?>" <?= $fKelas==$kl['id']?'selected':'' ?>><?= htmlspecialchars(formatKelasLabel($kl['tingkat_nama'], $kl['nama'])) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label small mb-1">Status</label>
                <select name="status" class="form-select form-select-sm" onchange="document.getElementById('formFilter').submit()">
                    <option value="">Semua Status</option>
                    <option value="aktif" <?= $fStatus==='aktif'?'selected':'' ?>>Aktif</option>
                    <option value="lulus" <?= $fStatus==='lulus'?'selected':'' ?>>Lulus</option>
                    <option value="pindah" <?= $fStatus==='pindah'?'selected':'' ?>>Pindah</option>
                    <option value="nonaktif" <?= $fStatus==='nonaktif'?'selected':'' ?>>Nonaktif</option>
                </select>
            </div>
            <div class="col-md-2 d-flex gap-2">
                <a href="siswa.php" class="btn btn-sm btn-outline-secondary w-100"><i class="bi bi-x"></i> Reset</a>
            </div>
            <div class="col-md-2 text-end">
                <span class="badge text-bg-primary fs-6"><?= count($data) ?> siswa</span>
            </div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-body">
        <table class="table table-hover datatable w-100">
            <thead><tr><th>NIS</th><th>Nama</th><th>Kelas</th><th>Ortu / Wali</th><th>SPP / Bulan</th><th>Status</th><th>Aksi</th></tr></thead>
            <tbody>
            <?php foreach ($data as $row): ?>
                <tr>
                    <td><?= htmlspecialchars($row['nis']) ?></td>
                    <td><?= htmlspecialchars($row['nama']) ?></td>
                    <td><?= htmlspecialchars(formatKelasLabel($row['tingkat_nama'] ?? '', $row['kelas_nama'] ?? '')) ?></td>
                    <td><?= htmlspecialchars($row['nama_ortu']) ?><br><small class="text-muted"><?= htmlspecialchars($row['no_hp_ortu']) ?></small></td>
                    <td><?= rupiah($row['nominal_spp']) ?></td>
                    <td><span class="badge text-bg-<?= $row['status']==='aktif'?'success':'secondary' ?>"><?= ucfirst($row['status']) ?></span></td>
                    <td>
                        <a href="laporan_per_siswa.php?siswa_id=<?= $row['id'] ?>" class="btn btn-sm btn-outline-secondary" title="Riwayat Pembayaran"><i class="bi bi-clock-history"></i></a>
                        <button class="btn btn-sm btn-outline-primary" onclick='editRow(<?= htmlspecialchars(json_encode($row), ENT_QUOTES) ?>)'><i class="bi bi-pencil"></i></button>
                        <form method="POST" class="d-inline" onsubmit="return confirmDelete()">
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="id" value="<?= $row['id'] ?>">
                            <button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash"></i></button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- MODAL IMPORT CSV -->
<div class="modal fade" id="modalImport" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" enctype="multipart/form-data" class="modal-content">
            <div class="modal-header"><h5 class="modal-title">Import Data Siswa dari CSV</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <input type="hidden" name="action" value="import">
                <ol class="small text-muted mb-3">
                    <li>Klik <strong>Download Template</strong> dulu kalau belum punya filenya.</li>
                    <li>Isi data sesuai kolom template (jangan ubah urutan/nama kolom).</li>
                    <li>NIS yang sudah terdaftar akan otomatis dilewati (tidak menimpa data lama).</li>
                </ol>
                <div class="mb-3"><label class="form-label">Pilih File CSV</label><input type="file" name="csv_file" class="form-control" accept=".csv" required></div>
            </div>
            <div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Batal</button><button type="submit" class="btn btn-primary"><i class="bi bi-upload"></i> Import Sekarang</button></div>
        </form>
    </div>
</div>

<div class="modal fade" id="modalSiswa" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <form method="POST" class="modal-content">
            <div class="modal-header"><h5 class="modal-title" id="modalTitle">Tambah Siswa</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <input type="hidden" name="action" value="save"><input type="hidden" name="id" id="f_id">
                <div class="row">
                    <div class="col-md-4 mb-3"><label class="form-label">NIS</label><input type="text" name="nis" id="f_nis" class="form-control" required></div>
                    <div class="col-md-4 mb-3"><label class="form-label">NISN</label><input type="text" name="nisn" id="f_nisn" class="form-control"></div>
                    <div class="col-md-4 mb-3"><label class="form-label">Jenis Kelamin</label><select name="jenis_kelamin" id="f_jk" class="form-select"><option value="L">Laki-laki</option><option value="P">Perempuan</option></select></div>
                </div>
                <div class="mb-3"><label class="form-label">Nama Lengkap</label><input type="text" name="nama" id="f_nama" class="form-control" required></div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Kelas</label>
                        <select name="kelas_id" id="f_kelas_id" class="form-select">
                            <option value="">-- Pilih Kelas --</option>
                            <?php foreach ($kelasList as $k): ?><option value="<?= $k['id'] ?>"><?= htmlspecialchars(formatKelasLabel($k['tingkat_nama'], $k['nama'])) ?></option><?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6 mb-3"><label class="form-label">Nominal SPP / Bulan</label><input type="text" name="nominal_spp" id="f_nominal" class="form-control" oninput="formatRupiahInput(this)" required></div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3"><label class="form-label">Nama Orang Tua / Wali</label><input type="text" name="nama_ortu" id="f_ortu" class="form-control"></div>
                    <div class="col-md-6 mb-3"><label class="form-label">No. HP Orang Tua</label><input type="text" name="no_hp_ortu" id="f_hp" class="form-control"></div>
                </div>
                <div class="mb-3"><label class="form-label">Status</label>
                    <select name="status" id="f_status" class="form-select">
                        <option value="aktif">Aktif</option><option value="lulus">Lulus</option><option value="pindah">Pindah</option><option value="nonaktif">Nonaktif</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Batal</button><button class="btn btn-primary">Simpan</button></div>
        </form>
    </div>
</div>

<script>
function resetForm() {
    document.getElementById('modalTitle').innerText = 'Tambah Siswa';
    ['f_id','f_nis','f_nisn','f_nama','f_ortu','f_hp','f_nominal'].forEach(id => document.getElementById(id).value = '');
    document.getElementById('f_jk').value = 'L';
    document.getElementById('f_kelas_id').value = '';
    document.getElementById('f_status').value = 'aktif';
}
function editRow(row) {
    document.getElementById('modalTitle').innerText = 'Edit Siswa';
    document.getElementById('f_id').value = row.id;
    document.getElementById('f_nis').value = row.nis;
    document.getElementById('f_nisn').value = row.nisn;
    document.getElementById('f_nama').value = row.nama;
    document.getElementById('f_jk').value = row.jenis_kelamin;
    document.getElementById('f_kelas_id').value = row.kelas_id || '';
    document.getElementById('f_nominal').value = new Intl.NumberFormat('id-ID').format(row.nominal_spp);
    document.getElementById('f_ortu').value = row.nama_ortu;
    document.getElementById('f_hp').value = row.no_hp_ortu;
    document.getElementById('f_status').value = row.status;
    new bootstrap.Modal(document.getElementById('modalSiswa')).show();
}
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>