<?php
// Start output buffering at the very beginning
ob_start();
require_once '../includes/header.php';
require_once '../includes/navbar.php';

$page_title = "Data Semester";
$role = $_SESSION['role'] ?? '';

if ($role !== 'admin') {
    header("Location: " . BASE_URL . "login.php");
    exit;
}

// Generate CSRF token jika belum ada
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Ambil tahun ajaran aktif
$tahun_aktif = [];
$query_tahun = "SELECT * FROM bind_tahunajaran WHERE aktif = TRUE LIMIT 1";
$result_tahun = $conn->query($query_tahun);
if ($result_tahun->num_rows > 0) {
    $tahun_aktif = $result_tahun->fetch_assoc();
}

// Handle CRUD Operations
// CREATE - Tambah Semester
if (isset($_POST['tambah_semester'])) {
    // Validasi CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $_SESSION['error'] = "Token keamanan tidak valid!";
        header('Location: semester.php');
        exit;
    }
    
    $semester = $conn->real_escape_string($_POST['semester']);
    $aktif = isset($_POST['aktif']) ? 1 : 0;
    
    // Validasi tahun ajaran aktif
    if (empty($tahun_aktif)) {
        $_SESSION['error'] = "Tidak ada tahun ajaran yang aktif!";
        header('Location: semester.php');
        exit;
    }
    
    $id_tahunajaran = $tahun_aktif['id_tahunajaran'];
    
    if (!empty($semester)) {
        // Cek apakah semester sudah ada untuk tahun ajaran ini
        $check_query = "SELECT COUNT(*) as total FROM bind_semester 
                       WHERE semester = '$semester' 
                       AND id_tahunajaran = $id_tahunajaran";
        $check_result = $conn->query($check_query);
        $exists = $check_result->fetch_assoc()['total'];
        
        if ($exists > 0) {
            $_SESSION['error'] = "Semester <strong>$semester</strong> sudah ada untuk tahun ajaran ini!";
        } else {
            // Jika mengaktifkan semester ini, nonaktifkan semester lain
            if ($aktif) {
                $conn->query("UPDATE bind_semester SET aktif = FALSE WHERE id_tahunajaran = $id_tahunajaran");
            }
            
            $query = "INSERT INTO bind_semester (id_tahunajaran, semester, aktif) 
                     VALUES ($id_tahunajaran, '$semester', $aktif)";
            if ($conn->query($query)) {
                $_SESSION['success'] = "Semester <strong>$semester</strong> berhasil ditambahkan!";
            } else {
                $_SESSION['error'] = "Gagal menambahkan semester: " . $conn->error;
            }
        }
    } else {
        $_SESSION['error'] = "Semester tidak boleh kosong!";
    }
    
    header('Location: semester.php');
    exit;
}

// UPDATE - Edit Semester
if (isset($_POST['edit_semester'])) {
    // Validasi CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $_SESSION['error'] = "Token keamanan tidak valid!";
        header('Location: semester.php');
        exit;
    }
    
    $id_semester = (int)$_POST['id_semester'];
    $semester = $conn->real_escape_string($_POST['semester']);
    $aktif = isset($_POST['aktif']) ? 1 : 0;
    
    if (!empty($semester)) {
        // Cek apakah semester sudah ada (kecuali untuk dirinya sendiri)
        $check_query = "SELECT COUNT(*) as total FROM bind_semester 
                       WHERE semester = '$semester' 
                       AND id_semester != $id_semester 
                       AND id_tahunajaran = {$tahun_aktif['id_tahunajaran']}";
        $check_result = $conn->query($check_query);
        $exists = $check_result->fetch_assoc()['total'];
        
        if ($exists > 0) {
            $_SESSION['error'] = "Semester <strong>$semester</strong> sudah ada untuk tahun ajaran ini!";
        } else {
            // Jika mengaktifkan semester ini, nonaktifkan semester lain
            if ($aktif) {
                $conn->query("UPDATE bind_semester SET aktif = FALSE WHERE id_tahunajaran = {$tahun_aktif['id_tahunajaran']}");
            }
            
            $query = "UPDATE bind_semester 
                     SET semester = '$semester', 
                         aktif = $aktif 
                     WHERE id_semester = $id_semester";
            if ($conn->query($query)) {
                $_SESSION['success'] = "Semester berhasil diperbarui!";
            } else {
                $_SESSION['error'] = "Gagal memperbarui semester: " . $conn->error;
            }
        }
    } else {
        $_SESSION['error'] = "Semester tidak boleh kosong!";
    }
    
    header('Location: semester.php');
    exit;
}

// DELETE - Hapus Semester
if (isset($_POST['hapus_semester'])) {
    // Validasi CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $_SESSION['error'] = "Token keamanan tidak valid!";
        header('Location: semester.php');
        exit;
    }
    
    $id_semester = (int)$_POST['id_semester'];
    $semester = $conn->real_escape_string($_POST['semester']);
    
    // Cek apakah semester aktif
    $check_aktif_query = "SELECT aktif FROM bind_semester WHERE id_semester = $id_semester";
    $check_aktif_result = $conn->query($check_aktif_query);
    $is_aktif = $check_aktif_result->fetch_assoc()['aktif'];
    
    if ($is_aktif) {
        $_SESSION['error'] = "Semester <strong>$semester</strong> tidak dapat dihapus karena sedang aktif!";
        header('Location: semester.php');
        exit;
    }
    
    // Cek apakah semester digunakan di tabel lain
    $check_query = "SELECT COUNT(*) as total_usage FROM bind_nilai WHERE id_semester = $id_semester";
    $check_result = $conn->query($check_query);
    $total_usage = $check_result->fetch_assoc()['total_usage'];
    
    if ($total_usage > 0) {
        $_SESSION['error'] = "Semester <strong>$semester</strong> tidak dapat dihapus karena masih digunakan di data nilai!";
    } else {
        $query = "DELETE FROM bind_semester WHERE id_semester = $id_semester";
        if ($conn->query($query)) {
            $_SESSION['success'] = "Semester <strong>$semester</strong> berhasil dihapus!";
        } else {
            $_SESSION['error'] = "Gagal menghapus semester: " . $conn->error;
        }
    }
    
    header('Location: semester.php');
    exit;
}

// Konfigurasi pagination
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;
$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';

// Query data semester - hanya tampilkan untuk tahun ajaran aktif
$where = " WHERE s.id_tahunajaran = {$tahun_aktif['id_tahunajaran']}";
if (!empty($search)) {
    $where .= " AND (s.semester LIKE '%$search%' OR t.tahun_ajaran LIKE '%$search%')";
}

$query_count = "SELECT COUNT(*) as total FROM bind_semester s $where";
$result_count = $conn->query($query_count);
$total_data = $result_count->fetch_assoc()['total'];
$total_pages = ceil($total_data / $limit);

$query = "SELECT s.*, t.tahun_ajaran 
          FROM bind_semester s 
          LEFT JOIN bind_tahunajaran t ON s.id_tahunajaran = t.id_tahunajaran 
          $where 
          ORDER BY s.semester ASC 
          LIMIT $limit OFFSET $offset";
$result = $conn->query($query);

// Hitung data yang ditampilkan
$start_data = $offset + 1;
$end_data = min($offset + $limit, $total_data);

// End output buffering and clean any output before this point
ob_end_clean();
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data Semester</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    <style>
        .btn-disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .tooltip-inner {
            max-width: 300px;
        }
    </style>
</head>
<body>
    <?php include '../includes/navbar.php'; ?>

<div class="container mt-4">
    <div class="row mb-4">
        <div class="col-md-6">
            <h2><i class="bi bi-calendar-range me-2"></i> Data Semester</h2>
            <?php if (!empty($tahun_aktif)): ?>
                <p class="text-muted">Tahun Ajaran Aktif: <strong><?= $tahun_aktif['tahun_ajaran'] ?></strong></p>
            <?php else: ?>
                <p class="text-danger">Tidak ada tahun ajaran yang aktif</p>
            <?php endif; ?>
        </div>
        <div class="col-md-6 text-end">
            <?php if (!empty($tahun_aktif)): ?>
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#tambahSemesterModal">
                    <i class="bi bi-plus-circle me-1"></i> Tambah Semester
                </button>
            <?php else: ?>
                <button type="button" class="btn btn-primary" disabled title="Tidak ada tahun ajaran aktif">
                    <i class="bi bi-plus-circle me-1"></i> Tambah Semester
                </button>
            <?php endif; ?>
            <a href="#" class="btn btn-outline-secondary" onclick="window.print()">
                <i class="bi bi-printer me-1"></i> Cetak
            </a>
        </div>
    </div>

    <?php if (empty($tahun_aktif)): ?>
        <div class="alert alert-warning" role="alert">
            <i class="bi bi-exclamation-triangle me-2"></i>
            <strong>Peringatan!</strong> Tidak ada tahun ajaran yang aktif. Silakan hubungi administrator untuk mengaktifkan tahun ajaran.
        </div>
    <?php endif; ?>

    <div class="card shadow-sm">
        <div class="card-body">
            <div class="row mb-3">
                <div class="col-md-6">
                    <form method="GET" class="d-flex">
                        <input type="text" name="search" class="form-control me-2" placeholder="Cari semester atau tahun ajaran..." value="<?= htmlspecialchars($search) ?>">
                        
                        <button type="submit" class="btn btn-primary me-2">
                            <i class="bi bi-search"></i>
                        </button>
                        
                        <a href="<?= basename($_SERVER['PHP_SELF']); ?>" class="btn btn-secondary">
                            <i class="bi bi-x-circle"></i>
                        </a>
                    </form>
                </div>
                <div class="col-md-6 text-end">
                    <div class="d-flex align-items-center justify-content-end">
                        <!-- Informasi Menampilkan Data -->
                        <p class="text-muted mb-0 me-3">
                            Menampilkan <?= $start_data ?>-<?= $end_data ?> dari <?= $total_data ?> data
                        </p>
                        
                        <!-- Dropdown Limit -->
                        <form method="GET" class="d-inline">
                            <?php if (!empty($search)): ?>
                                <input type="hidden" name="search" value="<?= htmlspecialchars($search) ?>">
                            <?php endif; ?>
                            <select name="limit" class="form-select d-inline-block w-auto" onchange="this.form.submit()">
                                <option value="10" <?= $limit == 10 ? 'selected' : '' ?>>10</option>
                                <option value="20" <?= $limit == 20 ? 'selected' : '' ?>>20</option>
                                <option value="30" <?= $limit == 30 ? 'selected' : '' ?>>30</option>
                                <option value="50" <?= $limit == 50 ? 'selected' : '' ?>>50</option>
                                <option value="100" <?= $limit == 100 ? 'selected' : '' ?>>100</option>
                                <option value="<?= $total_data ?>" <?= $limit == $total_data ? 'selected' : '' ?>>All</option>
                            </select>
                        </form>
                    </div>
                </div>
            </div>

            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead class="table-dark">
                        <tr>
                            <th width="50">No</th>
                            <th>Semester</th>
                            <th>Tahun Ajaran</th>
                            <th>Status</th>
                            <th width="150">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($result->num_rows > 0): ?>
                            <?php $no = $offset + 1; ?>
                            <?php while ($row = $result->fetch_assoc()): ?>
                                <tr>
                                    <td><?= $no++; ?></td>
                                    <td>
                                        <span class="badge bg-primary fs-6"><?= htmlspecialchars($row['semester']); ?></span>
                                    </td>
                                    <td><?= htmlspecialchars($row['tahun_ajaran']); ?></td>
                                    <td>
                                        <?php if ($row['aktif']): ?>
                                            <span class="badge bg-success"><i class="bi bi-check-circle me-1"></i> Aktif</span>
                                        <?php else: ?>
                                            <span class="badge bg-secondary"><i class="bi bi-x-circle me-1"></i> Nonaktif</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#editSemesterModal<?= $row['id_semester'] ?>">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <?php if ($row['aktif']): ?>
                                            <button type="button" class="btn btn-sm btn-danger btn-disabled" 
                                                    data-bs-toggle="tooltip" 
                                                    data-bs-placement="top" 
                                                    title="Semester aktif tidak dapat dihapus">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        <?php else: ?>
                                            <button type="button" class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#hapusSemesterModal<?= $row['id_semester'] ?>">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>

                                <!-- Modal Edit Semester -->
                                <div class="modal fade" id="editSemesterModal<?= $row['id_semester'] ?>" tabindex="-1" aria-labelledby="editSemesterModalLabel<?= $row['id_semester'] ?>" aria-hidden="true">
                                    <div class="modal-dialog">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="editSemesterModalLabel<?= $row['id_semester'] ?>">Edit Semester</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                            </div>
                                            <form method="POST">
                                                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                                                <div class="modal-body">
                                                    <input type="hidden" name="id_semester" value="<?= $row['id_semester'] ?>">
                                                    <div class="mb-3">
                                                        <label for="semester_edit<?= $row['id_semester'] ?>" class="form-label">Semester</label>
                                                        <select class="form-select" id="semester_edit<?= $row['id_semester'] ?>" name="semester" required>
                                                            <option value="Ganjil" <?= $row['semester'] == 'Ganjil' ? 'selected' : '' ?>>Ganjil</option>
                                                            <option value="Genap" <?= $row['semester'] == 'Genap' ? 'selected' : '' ?>>Genap</option>
                                                        </select>
                                                    </div>
                                                    <div class="mb-3">
                                                        <div class="form-check form-switch">
                                                            <input class="form-check-input" type="checkbox" id="aktif_edit<?= $row['id_semester'] ?>" name="aktif" <?= $row['aktif'] ? 'checked' : '' ?>>
                                                            <label class="form-check-label" for="aktif_edit<?= $row['id_semester'] ?>">
                                                                Aktifkan Semester
                                                            </label>
                                                        </div>
                                                        <div class="form-text">Jika diaktifkan, semester lain akan otomatis dinonaktifkan</div>
                                                    </div>
                                                    <div class="mb-3">
                                                        <label class="form-label">Tahun Ajaran</label>
                                                        <input type="text" class="form-control" value="<?= htmlspecialchars($row['tahun_ajaran']) ?>" readonly disabled>
                                                        <div class="form-text">Tahun ajaran tidak dapat diubah</div>
                                                    </div>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                                                    <button type="submit" name="edit_semester" class="btn btn-primary">Simpan Perubahan</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>

                                <!-- Modal Hapus Semester -->
                                <?php if (!$row['aktif']): ?>
                                <div class="modal fade" id="hapusSemesterModal<?= $row['id_semester'] ?>" tabindex="-1" aria-labelledby="hapusSemesterModalLabel<?= $row['id_semester'] ?>" aria-hidden="true">
                                    <div class="modal-dialog">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="hapusSemesterModalLabel<?= $row['id_semester'] ?>">Konfirmasi Hapus</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                            </div>
                                            <form method="POST">
                                                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                                                <div class="modal-body">
                                                    <input type="hidden" name="id_semester" value="<?= $row['id_semester'] ?>">
                                                    <input type="hidden" name="semester" value="<?= htmlspecialchars($row['semester']) ?>">
                                                    <div class="alert alert-warning">
                                                        <i class="bi bi-exclamation-triangle me-2"></i>
                                                        <strong>Perhatian!</strong> Pastikan semester ini tidak digunakan dalam sistem sebelum menghapus.
                                                    </div>
                                                    <p>Apakah Anda yakin ingin menghapus semester <strong><?= htmlspecialchars($row['semester']) ?></strong>?</p>
                                                    <p class="text-muted">Tahun Ajaran: <?= htmlspecialchars($row['tahun_ajaran']) ?></p>
                                                    <p class="text-danger"><small>Tindakan ini tidak dapat dibatalkan!</small></p>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                                                    <button type="submit" name="hapus_semester" class="btn btn-danger">Hapus</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                                <?php endif; ?>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="5" class="text-center text-muted">
                                    <div class="py-4">
                                        <i class="bi bi-calendar-x display-4 text-muted"></i>
                                        <p class="mt-3">Tidak ada data semester</p>
                                        <?php if (!empty($search)): ?>
                                            <p class="text-muted">Coba gunakan kata kunci lain atau <a href="<?= basename($_SERVER['PHP_SELF']); ?>" class="text-primary">reset pencarian</a></p>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination - Hanya tampil jika total data lebih dari 10 -->
            <?php if ($total_data > 10): ?>
                <nav aria-label="Page navigation">
                    <ul class="pagination justify-content-center">
                        <?php if ($page > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?= $page - 1 ?>&limit=<?= $limit ?><?= !empty($search) ? '&search=' . urlencode($search) : '' ?>">
                                    <i class="bi bi-chevron-left"></i> Previous
                                </a>
                            </li>
                        <?php endif; ?>

                        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                            <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                                <a class="page-link" href="?page=<?= $i ?>&limit=<?= $limit ?><?= !empty($search) ? '&search=' . urlencode($search) : '' ?>"><?= $i ?></a>
                            </li>
                        <?php endfor; ?>

                        <?php if ($page < $total_pages): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?= $page + 1 ?>&limit=<?= $limit ?><?= !empty($search) ? '&search=' . urlencode($search) : '' ?>">
                                    Next <i class="bi bi-chevron-right"></i>
                                </a>
                            </li>
                        <?php endif; ?>
                    </ul>
                </nav>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Modal Tambah Semester -->
<?php if (!empty($tahun_aktif)): ?>
<div class="modal fade" id="tambahSemesterModal" tabindex="-1" aria-labelledby="tambahSemesterModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="tambahSemesterModalLabel">Tambah Semester Baru</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="semester" class="form-label">Semester</label>
                        <select class="form-select" id="semester" name="semester" required>
                            <option value="">Pilih Semester</option>
                            <option value="Ganjil">Ganjil</option>
                            <option value="Genap">Genap</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="aktif" name="aktif">
                            <label class="form-check-label" for="aktif">
                                Aktifkan Semester
                            </label>
                        </div>
                        <div class="form-text">Jika diaktifkan, semester lain akan otomatis dinonaktifkan</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Tahun Ajaran</label>
                        <input type="text" class="form-control" value="<?= htmlspecialchars($tahun_aktif['tahun_ajaran']) ?>" readonly disabled>
                        <div class="form-text">Semester akan ditambahkan untuk tahun ajaran aktif ini</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" name="tambah_semester" class="btn btn-primary">Simpan</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Inisialisasi tooltip
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl)
    });

    // Tampilkan modal success/error jika ada pesan
    <?php if (isset($_SESSION['success'])): ?>
        const successMessage = "<?= addslashes($_SESSION['success']) ?>";
        if (successMessage) {
            // Buat modal success secara dinamis
            const successModalHTML = `
                <div class="modal fade" id="successModal" tabindex="-1" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                            <div class="modal-header border-0">
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body text-center">
                                <i class="bi bi-check-circle text-success" style="font-size: 4rem;"></i>
                                <h4 class="mt-3 text-success">Berhasil!</h4>
                                <p>${successMessage}</p>
                            </div>
                            <div class="modal-footer border-0 justify-content-center">
                                <button type="button" class="btn btn-success" data-bs-dismiss="modal">
                                    OK
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // Tambahkan modal ke body
            document.body.insertAdjacentHTML('beforeend', successModalHTML);
            
            // Tampilkan modal
            const modal = new bootstrap.Modal(document.getElementById('successModal'));
            modal.show();
            
            // Hapus modal setelah ditutup
            document.getElementById('successModal').addEventListener('hidden.bs.modal', function () {
                this.remove();
            });
        }
    <?php unset($_SESSION['success']); ?>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['error'])): ?>
        const errorMessage = "<?= addslashes($_SESSION['error']) ?>";
        if (errorMessage) {
            // Buat modal error secara dinamis
            const errorModalHTML = `
                <div class="modal fade" id="errorModal" tabindex="-1" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                            <div class="modal-header border-0">
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body text-center">
                                <i class="bi bi-x-circle text-danger" style="font-size: 4rem;"></i>
                                <h4 class="mt-3 text-danger">Error!</h4>
                                <p>${errorMessage}</p>
                            </div>
                            <div class="modal-footer border-0 justify-content-center">
                                <button type="button" class="btn btn-danger" data-bs-dismiss="modal">
                                    OK
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // Tambahkan modal ke body
            document.body.insertAdjacentHTML('beforeend', errorModalHTML);
            
            // Tampilkan modal
            const modal = new bootstrap.Modal(document.getElementById('errorModal'));
            modal.show();
            
            // Hapus modal setelah ditutup
            document.getElementById('errorModal').addEventListener('hidden.bs.modal', function () {
                this.remove();
            });
        }
    <?php unset($_SESSION['error']); ?>
    <?php endif; ?>
});
</script>

</body>
</html>

<?php
// Pastikan tidak ada output setelah ini
?>