<?php
require_once __DIR__ . '/includes/functions.php';
requireLogin();
$pageTitle = 'Tingkat & Kelas';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'save_tingkat') {
        $id = $_POST['id'] ?? '';
        $nama = trim($_POST['nama']);
        if ($id) {
            $pdo->prepare("UPDATE tingkat SET nama=:nama WHERE id=:id")->execute(['nama'=>$nama,'id'=>$id]);
        } else {
            $pdo->prepare("INSERT INTO tingkat (nama) VALUES (:nama)")->execute(['nama'=>$nama]);
        }
        flash('success', 'Tingkat berhasil disimpan.');
    } elseif ($action === 'delete_tingkat') {
        $id = $_POST['id'];
        $cek = $pdo->prepare("SELECT COUNT(*) FROM kelas WHERE tingkat_id=:id"); $cek->execute(['id'=>$id]);
        if ($cek->fetchColumn() > 0) {
            flash('error', 'Tingkat memiliki kelas, hapus kelas terlebih dahulu.');
        } else {
            $pdo->prepare("DELETE FROM tingkat WHERE id=:id")->execute(['id'=>$id]);
            flash('success', 'Tingkat berhasil dihapus.');
        }
    } elseif ($action === 'save_kelas') {
        $id = $_POST['id'] ?? '';
        $params = ['tingkat_id'=>$_POST['tingkat_id'], 'nama'=>trim($_POST['nama_kelas'])];
        if ($id) {
            $params['id'] = $id;
            $pdo->prepare("UPDATE kelas SET tingkat_id=:tingkat_id, nama=:nama WHERE id=:id")->execute($params);
        } else {
            $pdo->prepare("INSERT INTO kelas (tingkat_id, nama) VALUES (:tingkat_id,:nama)")->execute($params);
        }
        flash('success', 'Kelas berhasil disimpan.');
    } elseif ($action === 'delete_kelas') {
        $id = $_POST['id'];
        $cek = $pdo->prepare("SELECT COUNT(*) FROM siswa WHERE kelas_id=:id"); $cek->execute(['id'=>$id]);
        if ($cek->fetchColumn() > 0) {
            flash('error', 'Kelas masih memiliki siswa, pindahkan siswa terlebih dahulu.');
        } else {
            $pdo->prepare("DELETE FROM kelas WHERE id=:id")->execute(['id'=>$id]);
            flash('success', 'Kelas berhasil dihapus.');
        }
    }
    header('Location: tingkat_kelas.php');
    exit;
}

$tingkatList = $pdo->query("SELECT * FROM tingkat ORDER BY nama")->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();

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

<h5 class="mb-3">Master Tingkat &amp; Kelas</h5>

<div class="row g-3">
    <div class="col-md-4">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                Tingkat
                <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#modalTingkat" onclick="resetTingkat()"><i class="bi bi-plus-lg"></i></button>
            </div>
            <div class="card-body p-0">
                <table class="table mb-0">
                    <tbody>
                    <?php foreach ($tingkatList as $row): ?>
                        <tr>
                            <td><?= htmlspecialchars($row['nama']) ?></td>
                            <td class="text-end" style="width:90px">
                                <button class="btn btn-sm btn-outline-primary" onclick='editTingkat(<?= 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_tingkat">
                                    <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>
    </div>

    <div class="col-md-8">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                Kelas
                <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#modalKelas" onclick="resetKelas()"><i class="bi bi-plus-lg"></i></button>
            </div>
            <div class="card-body p-0">
                <table class="table table-hover datatable w-100">
                    <thead><tr><th>Tingkat</th><th>Nama Kelas</th><th>Aksi</th></tr></thead>
                    <tbody>
                    <?php foreach ($kelasList as $row): ?>
                        <tr>
                            <td><?= htmlspecialchars($row['tingkat_nama']) ?></td>
                            <td><?= htmlspecialchars($row['nama']) ?></td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary" onclick='editKelas(<?= 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_kelas">
                                    <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>
    </div>
</div>

<!-- MODAL TINGKAT -->
<div class="modal fade" id="modalTingkat" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <div class="modal-header"><h5 class="modal-title" id="titleTingkat">Tambah Tingkat</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <input type="hidden" name="action" value="save_tingkat">
                <input type="hidden" name="id" id="t_id">
                <label class="form-label">Nama Tingkat</label>
                <input type="text" name="nama" id="t_nama" class="form-control" placeholder="X, XI, XII" required>
            </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>

<!-- MODAL KELAS -->
<div class="modal fade" id="modalKelas" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <div class="modal-header"><h5 class="modal-title" id="titleKelas">Tambah Kelas</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <input type="hidden" name="action" value="save_kelas">
                <input type="hidden" name="id" id="k_id">
                <div class="mb-3">
                    <label class="form-label">Tingkat</label>
                    <select name="tingkat_id" id="k_tingkat_id" class="form-select" required>
                        <?php foreach ($tingkatList as $t): ?>
                            <option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['nama']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Nama Kelas</label>
                    <input type="text" name="nama_kelas" id="k_nama" class="form-control" placeholder="IPA 1" required>
                </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 resetTingkat(){ document.getElementById('titleTingkat').innerText='Tambah Tingkat'; document.getElementById('t_id').value=''; document.getElementById('t_nama').value=''; }
function editTingkat(row){ document.getElementById('titleTingkat').innerText='Edit Tingkat'; document.getElementById('t_id').value=row.id; document.getElementById('t_nama').value=row.nama; new bootstrap.Modal(document.getElementById('modalTingkat')).show(); }
function resetKelas(){ document.getElementById('titleKelas').innerText='Tambah Kelas'; document.getElementById('k_id').value=''; document.getElementById('k_nama').value=''; }
function editKelas(row){ document.getElementById('titleKelas').innerText='Edit Kelas'; document.getElementById('k_id').value=row.id; document.getElementById('k_tingkat_id').value=row.tingkat_id; document.getElementById('k_nama').value=row.nama; new bootstrap.Modal(document.getElementById('modalKelas')).show(); }
</script>

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