<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/functions.php';
checkAdmin();

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        $nis = $_POST['nis'];
        $nama = $_POST['nama'];
        $alamat = $_POST['alamat'];
        $kelamin = $_POST['kelamin'];
        $id_kelas = $_POST['id_kelas'];

        if ($_POST['action'] === 'add') {
            // Default password is NIS same as username for students
            $password = password_hash($nis, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO siswa (nis, nama, alamat, kelamin, id_kelas, password) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute(array($nis, $nama, $alamat, $kelamin, $id_kelas, $password));
            setFlash('success', 'Siswa berhasil ditambahkan.');
        } elseif ($_POST['action'] === 'edit') {
            $old_nis = $_POST['old_nis'];
            $stmt = $pdo->prepare("UPDATE siswa SET nis = ?, nama = ?, alamat = ?, kelamin = ?, id_kelas = ? WHERE nis = ?");
            $stmt->execute(array($nis, $nama, $alamat, $kelamin, $id_kelas, $old_nis));
            setFlash('success', 'Siswa berhasil diupdate.');
        } elseif ($_POST['action'] === 'delete') {
            $stmt = $pdo->prepare("DELETE FROM siswa WHERE nis = ?");
            $stmt->execute(array($nis));
            setFlash('success', 'Siswa berhasil dihapus.');
        }
        redirect('data-siswa.php');
    }
}

$title = "Data Siswa";
require_once 'includes/header.php';

// Pagination Settings
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

// Filter
$filter_kelas = isset($_GET['kelas_id']) ? $_GET['kelas_id'] : '';

// Count Total with Filter
$count_sql = "SELECT COUNT(*) FROM siswa";
if ($filter_kelas) {
    $count_sql .= " WHERE id_kelas = " . (int)$filter_kelas;
}
$totalRows = $pdo->query($count_sql)->fetchColumn();
$totalPages = ceil($totalRows / $limit);

$sql = "SELECT s.*, k.nama as kelas_nama 
        FROM siswa s 
        LEFT JOIN kelas k ON s.id_kelas = k.id";

if ($filter_kelas) {
    $sql .= " WHERE s.id_kelas = :id_kelas";
}

$sql .= " ORDER BY s.nama ASC LIMIT :limit OFFSET :offset";

$siswa_query = $pdo->prepare($sql);
if ($filter_kelas) {
    $siswa_query->bindValue(':id_kelas', $filter_kelas, PDO::PARAM_INT);
}
$siswa_query->bindValue(':limit', $limit, PDO::PARAM_INT);
$siswa_query->bindValue(':offset', $offset, PDO::PARAM_INT);
$siswa_query->execute();
$siswa = $siswa_query->fetchAll();

$kelas = $pdo->query("SELECT * FROM kelas ORDER BY nama ASC")->fetchAll();
?>

<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-6 mb-8">
    <div>
        <h3 class="text-xl font-bold text-slate-800">Manajemen Siswa</h3>
        <p class="text-slate-500 text-sm">Kelola data siswa kelas XII SMA Negeri 1 Barumun.</p>
    </div>
    <div class="flex flex-wrap items-center gap-4 w-full md:w-auto">
        <form action="" method="GET" class="flex items-center gap-3">
            <select name="kelas_id" onchange="this.form.submit()" class="px-4 py-2.5 rounded-xl border border-slate-200 text-sm font-bold text-slate-700 bg-white focus:border-primary outline-none transition-all">
                <option value="">Semua Kelas</option>
                <?php foreach ($kelas as $k): ?>
                    <option value="<?= $k['id'] ?>" <?= $filter_kelas == $k['id'] ? 'selected' : '' ?>><?= $k['nama'] ?></option>
                <?php endforeach; ?>
            </select>
        </form>
        <button onclick="addSiswa()" class="btn-primary flex items-center gap-2 whitespace-nowrap">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path></svg>
            Tambah Siswa
        </button>
    </div>
</div>

<div class="card">
    <div class="overflow-x-auto">
        <table class="w-full text-left">
            <thead class="bg-slate-50 border-b border-slate-200">
                <tr>
                    <th class="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">NIS</th>
                    <th class="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Nama Lengkap</th>
                    <th class="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Kelas</th>
                    <th class="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Gender</th>
                    <th class="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest text-right">Aksi</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
                <?php if (empty($siswa)): ?>
                    <tr>
                        <td colspan="5" class="px-8 py-10 text-center text-slate-400 italic">Belum ada data siswa.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($siswa as $s): ?>
                        <tr class="hover:bg-slate-50 transition-colors text-sm">
                            <td class="px-8 py-4 font-mono text-slate-500"><?= $s['nis'] ?></td>
                            <td class="px-8 py-4 font-bold text-slate-800"><?= $s['nama'] ?></td>
                            <td class="px-8 py-4 text-slate-600"><?= isset($s['kelas_nama']) ? $s['kelas_nama'] : '-' ?></td>
                            <td class="px-8 py-4 text-slate-600"><?= $s['kelamin'] === 'L' ? 'Laki-laki' : 'Perempuan' ?></td>
                            <td class="px-8 py-4 text-right space-x-2">
                                <button onclick="editSiswa(<?= htmlspecialchars(json_encode($s)) ?>)" class="font-bold text-primary hover:text-primary-dark">Edit</button>
                                <form action="" method="POST" class="inline" onsubmit="return confirm('Hapus siswa ini?')">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="nis" value="<?= $s['nis'] ?>">
                                    <button type="submit" class="font-bold text-red-500 hover:text-red-600">Hapus</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?= renderPagination($page, $totalPages, 'data-siswa.php?kelas_id=' . $filter_kelas . '&') ?>

<!-- Modal Template -->
<div id="studentModal" class="fixed inset-0 bg-slate-900/50 hidden items-center justify-center z-50 p-6">
    <div class="bg-white rounded-3xl w-full max-w-2xl p-8 shadow-2xl relative">
        <button onclick="closeModal('studentModal')" class="absolute top-6 right-6 text-slate-400 hover:text-slate-600">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
        </button>
        
        <h3 id="modalTitle" class="text-xl font-bold text-slate-800 mb-6 font-primary">Tambah Siswa</h3>
        
        <form action="" method="POST" class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <input type="hidden" name="action" id="formAction" value="add">
            <input type="hidden" name="old_nis" id="oldNis">
            
            <div class="md:col-span-1">
                <label class="block text-sm font-bold text-slate-700 mb-2">NIS</label>
                <input type="text" name="nis" id="formNis" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all" placeholder="Nomor Induk Siswa">
            </div>
            
            <div class="md:col-span-1">
                <label class="block text-sm font-bold text-slate-700 mb-2">Nama Lengkap</label>
                <input type="text" name="nama" id="formNama" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all" placeholder="Nama Lengkap Siswa">
            </div>

            <div class="md:col-span-1">
                <label class="block text-sm font-bold text-slate-700 mb-2">Jenis Kelamin</label>
                <select name="kelamin" id="formKelamin" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all appearance-none bg-white">
                    <option value="L">Laki-laki</option>
                    <option value="P">Perempuan</option>
                </select>
            </div>

            <div class="md:col-span-1">
                <label class="block text-sm font-bold text-slate-700 mb-2">Kelas</label>
                <select name="id_kelas" id="formKelas" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all appearance-none bg-white">
                    <option value="">Pilih Kelas</option>
                    <?php foreach ($kelas as $k): ?>
                        <option value="<?= $k['id'] ?>"><?= $k['nama'] ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="md:col-span-2">
                <label class="block text-sm font-bold text-slate-700 mb-2">Alamat</label>
                <textarea name="alamat" id="formAlamat" rows="3" class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all" placeholder="Alamat lengkap siswa..."></textarea>
            </div>

            <div class="md:col-span-2 flex gap-4 pt-4">
                <button type="button" onclick="closeModal('studentModal')" class="flex-1 py-3 text-sm font-bold text-slate-500 hover:bg-slate-50 rounded-xl transition-colors">Batal</button>
                <button type="submit" class="flex-1 btn-primary py-3 text-sm">Simpan Data</button>
            </div>
        </form>
    </div>
</div>

<script>
function addSiswa() {
    const el = document.getElementById('studentModal');
    el.classList.remove('hidden');
    el.classList.add('flex');
    document.getElementById('modalTitle').innerText = 'Tambah Siswa';
    document.getElementById('formAction').value = 'add';
    document.querySelector('#studentModal form').reset();
}

function closeModal(id) {
    const el = document.getElementById('studentModal');
    el.classList.add('hidden');
    el.classList.remove('flex');
}

function editSiswa(data) {
    const el = document.getElementById('studentModal');
    el.classList.remove('hidden');
    el.classList.add('flex');
    document.getElementById('modalTitle').innerText = 'Edit Siswa';
    document.getElementById('formAction').value = 'edit';
    
    document.getElementById('oldNis').value = data.nis;
    document.getElementById('formNis').value = data.nis;
    document.getElementById('formNama').value = data.nama;
    document.getElementById('formKelamin').value = data.kelamin;
    document.getElementById('formKelas').value = data.id_kelas;
    document.getElementById('formAlamat').value = data.alamat;
}
</script>

<?php require_once 'includes/footer.php'; ?>
