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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'save') {
        $id = $_POST['id'] ?? '';
        $nama = trim($_POST['nama']);
        $semester = $_POST['semester'];
        $aktif = isset($_POST['status_aktif']) ? 1 : 0;

        if ($aktif) {
            $pdo->exec("UPDATE tahun_ajaran SET status_aktif = 0");
        }
        if ($id) {
            $pdo->prepare("UPDATE tahun_ajaran SET nama=:nama, semester=:semester, status_aktif=:aktif WHERE id=:id")
                ->execute(['nama'=>$nama,'semester'=>$semester,'aktif'=>$aktif,'id'=>$id]);
            flash('success', 'Tahun ajaran berhasil diperbarui.');
        } else {
            $pdo->prepare("INSERT INTO tahun_ajaran (nama, semester, status_aktif) VALUES (:nama,:semester,:aktif)")
                ->execute(['nama'=>$nama,'semester'=>$semester,'aktif'=>$aktif]);
            flash('success', 'Tahun ajaran berhasil ditambahkan.');
        }
    } elseif ($action === 'delete') {
        $id = $_POST['id'];
        $cek = $pdo->prepare("SELECT COUNT(*) FROM tagihan_spp WHERE tahun_ajaran_id=:id");
        $cek->execute(['id'=>$id]);
        if ($cek->fetchColumn() > 0) {
            flash('error', 'Tahun ajaran tidak dapat dihapus karena sudah memiliki data tagihan SPP.');
        } else {
            $pdo->prepare("DELETE FROM tahun_ajaran WHERE id=:id")->execute(['id'=>$id]);
            flash('success', 'Tahun ajaran berhasil dihapus.');
        }
    }
    header('Location: tahun_ajaran.php');
    exit;
}

$data = $pdo->query("SELECT * FROM tahun_ajaran ORDER BY nama DESC, semester")->fetchAll();
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="mb-0">Master Tahun Ajaran</h5>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalTA" onclick="resetForm()">
        <i class="bi bi-plus-lg"></i> Tambah Tahun Ajaran
    </button>
</div>

<div class="card">
    <div class="card-body">
        <table class="table table-hover datatable w-100">
            <thead><tr><th>Tahun Ajaran</th><th>Semester</th><th>Status</th><th>Aksi</th></tr></thead>
            <tbody>
            <?php foreach ($data as $row): ?>
                <tr>
                    <td><?= htmlspecialchars($row['nama']) ?></td>
                    <td><?= htmlspecialchars($row['semester']) ?></td>
                    <td><?= $row['status_aktif'] ? '<span class="badge text-bg-success">Aktif</span>' : '<span class="badge text-bg-secondary">Nonaktif</span>' ?></td>
                    <td>
                        <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>

<div class="modal fade" id="modalTA" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">Tambah Tahun Ajaran</h5>
                <button type="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="mb-3">
                    <label class="form-label">Nama Tahun Ajaran</label>
                    <input type="text" name="nama" id="f_nama" class="form-control" placeholder="2025/2026" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Semester</label>
                    <select name="semester" id="f_semester" class="form-select">
                        <option value="Ganjil">Ganjil</option>
                        <option value="Genap">Genap</option>
                    </select>
                </div>
                <div class="form-check">
                    <input type="checkbox" name="status_aktif" id="f_status_aktif" class="form-check-input">
                    <label class="form-check-label" for="f_status_aktif">Jadikan Tahun Ajaran Aktif</label>
                </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">Simpan</button>
            </div>
        </form>
    </div>
</div>

<script>
function resetForm() {
    document.getElementById('modalTitle').innerText = 'Tambah Tahun Ajaran';
    document.getElementById('f_id').value = '';
    document.getElementById('f_nama').value = '';
    document.getElementById('f_semester').value = 'Ganjil';
    document.getElementById('f_status_aktif').checked = false;
}
function editRow(row) {
    document.getElementById('modalTitle').innerText = 'Edit Tahun Ajaran';
    document.getElementById('f_id').value = row.id;
    document.getElementById('f_nama').value = row.nama;
    document.getElementById('f_semester').value = row.semester;
    document.getElementById('f_status_aktif').checked = row.status_aktif == 1;
    new bootstrap.Modal(document.getElementById('modalTA')).show();
}
</script>

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