<?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'])) {
        if ($_POST['action'] === 'add') {
            $nama = $_POST['nama'];
            $stmt = $pdo->prepare("INSERT INTO kelas (nama) VALUES (?)");
            $stmt->execute(array($nama));
            setFlash('success', 'Kelas berhasil ditambahkan.');
        } elseif ($_POST['action'] === 'edit') {
            $id = $_POST['id'];
            $nama = $_POST['nama'];
            $stmt = $pdo->prepare("UPDATE kelas SET nama = ? WHERE id = ?");
            $stmt->execute(array($nama, $id));
            setFlash('success', 'Kelas berhasil diupdate.');
        } elseif ($_POST['action'] === 'delete') {
            $id = $_POST['id'];
            $stmt = $pdo->prepare("DELETE FROM kelas WHERE id = ?");
            $stmt->execute(array($id));
            setFlash('success', 'Kelas berhasil dihapus.');
        }
        redirect('data-kelas.php');
    }
}

$title = "Data Kelas";
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;

// Count Total
$totalRows = $pdo->query("SELECT COUNT(*) FROM kelas")->fetchColumn();
$totalPages = ceil($totalRows / $limit);

$kelas_result = $pdo->prepare("SELECT * FROM kelas ORDER BY nama ASC LIMIT :limit OFFSET :offset");
$kelas_result->bindValue(':limit', $limit, PDO::PARAM_INT);
$kelas_result->bindValue(':offset', $offset, PDO::PARAM_INT);
$kelas_result->execute();
$kelas = $kelas_result->fetchAll();
?>

<div class="flex justify-between items-center mb-8">
    <div>
        <h3 class="text-xl font-bold text-slate-800">Manajemen Kelas</h3>
        <p class="text-slate-500 text-sm">Kelola data kelas siswa SMA Negeri 1 Barumun.</p>
    </div>
    <button onclick="openModal('addModal')" class="btn-primary flex items-center gap-2">
        <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 Kelas
    </button>
</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">ID</th>
                    <th class="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Nama Kelas</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($kelas)): ?>
                    <tr>
                        <td colspan="3" class="px-8 py-10 text-center text-slate-400 italic">Belum ada data kelas.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($kelas as $k): ?>
                        <tr class="hover:bg-slate-50 transition-colors">
                            <td class="px-8 py-4 text-sm text-slate-600">#<?= $k['id'] ?></td>
                            <td class="px-8 py-4 text-sm font-bold text-slate-800"><?= $k['nama'] ?></td>
                            <td class="px-8 py-4 text-right space-x-2">
                                <button onclick="editKelas(<?= $k['id'] ?>, '<?= addslashes($k['nama']) ?>')" class="text-sm font-bold text-primary hover:text-primary-dark">Edit</button>
                                <form action="" method="POST" class="inline" onsubmit="return confirm('Hapus kelas ini?')">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= $k['id'] ?>">
                                    <button type="submit" class="text-sm 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-kelas.php?') ?>

<!-- Add Modal -->
<div id="addModal" 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-md p-8 shadow-2xl">
        <h3 class="text-xl font-bold text-slate-800 mb-6">Tambah Kelas Baru</h3>
        <form action="" method="POST" class="space-y-6">
            <input type="hidden" name="action" value="add">
            <div>
                <label class="block text-sm font-bold text-slate-700 mb-2">Nama Kelas</label>
                <input type="text" name="nama" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all" placeholder="Misal: XII MIPA 1">
            </div>
            <div class="flex gap-4 pt-4">
                <button type="button" onclick="closeModal('addModal')" 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</button>
            </div>
        </form>
    </div>
</div>

<!-- Edit Modal -->
<div id="editModal" 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-md p-8 shadow-2xl">
        <h3 class="text-xl font-bold text-slate-800 mb-6">Edit Kelas</h3>
        <form action="" method="POST" class="space-y-6">
            <input type="hidden" name="action" value="edit">
            <input type="hidden" name="id" id="edit_id">
            <div>
                <label class="block text-sm font-bold text-slate-700 mb-2">Nama Kelas</label>
                <input type="text" name="nama" id="edit_nama" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all" placeholder="Misal: XII MIPA 1">
            </div>
            <div class="flex gap-4 pt-4">
                <button type="button" onclick="closeModal('editModal')" 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">Update</button>
            </div>
        </form>
    </div>
</div>

<script>
function openModal(id) {
    const el = document.getElementById(id);
    el.classList.remove('hidden');
    el.classList.add('flex');
}
function closeModal(id) {
    const el = document.getElementById(id);
    el.classList.add('hidden');
    el.classList.remove('flex');
}
function editKelas(id, nama) {
    document.getElementById('edit_id').value = id;
    document.getElementById('edit_nama').value = nama;
    openModal('editModal');
}
</script>

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