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

$page_title = "Data Mata Pelajaran";
$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 Mata Pelajaran
if (isset($_POST['tambah_mapel'])) {
    // Validasi CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $_SESSION['error'] = "Token keamanan tidak valid!";
        header('Location: index.php');
        exit;
    }
    
    $kode_mapel = $conn->real_escape_string(trim($_POST['kode_mapel']));
    $nama_mapel = $conn->real_escape_string(trim($_POST['nama_mapel']));
    $kelompok = $conn->real_escape_string($_POST['kelompok']);
    $kkm = (int)$_POST['kkm'];
    
    // Validasi tahun ajaran aktif
    if (empty($tahun_aktif)) {
        $_SESSION['error'] = "Tidak ada tahun ajaran yang aktif!";
        header('Location: index.php');
        exit;
    }
    
    $id_tahunajaran = $tahun_aktif['id_tahunajaran'];
    
    if (!empty($kode_mapel) && !empty($nama_mapel)) {
        // Cek apakah kode mapel sudah ada
        $check_query = "SELECT COUNT(*) as total FROM bind_mapel WHERE kode_mapel = '$kode_mapel' AND id_tahunajaran = $id_tahunajaran";
        $check_result = $conn->query($check_query);
        $exists = $check_result->fetch_assoc()['total'];
        
        if ($exists > 0) {
            $_SESSION['error'] = "Kode mata pelajaran '$kode_mapel' sudah ada untuk tahun ajaran ini!";
        } else {
            $query = "INSERT INTO bind_mapel (kode_mapel, nama_mapel, kelompok, kkm, id_tahunajaran) 
                     VALUES ('$kode_mapel', '$nama_mapel', '$kelompok', $kkm, $id_tahunajaran)";
            if ($conn->query($query)) {
                $_SESSION['success'] = "Mata pelajaran <strong>$nama_mapel</strong> berhasil ditambahkan!";
            } else {
                $_SESSION['error'] = "Gagal menambahkan mata pelajaran: " . $conn->error;
            }
        }
    } else {
        $_SESSION['error'] = "Kode dan nama mata pelajaran tidak boleh kosong!";
    }
    
    header('Location: index.php');
    exit;
}

// UPDATE - Edit Mata Pelajaran
if (isset($_POST['edit_mapel'])) {
    // Validasi CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $_SESSION['error'] = "Token keamanan tidak valid!";
        header('Location: index.php');
        exit;
    }
    
    $id_mapel = (int)$_POST['id_mapel'];
    $kode_mapel = $conn->real_escape_string(trim($_POST['kode_mapel']));
    $nama_mapel = $conn->real_escape_string(trim($_POST['nama_mapel']));
    $kelompok = $conn->real_escape_string($_POST['kelompok']);
    $kkm = (int)$_POST['kkm'];
    
    if (!empty($kode_mapel) && !empty($nama_mapel)) {
        // Cek apakah kode mapel sudah ada (kecuali untuk dirinya sendiri)
        $check_query = "SELECT COUNT(*) as total FROM bind_mapel 
                       WHERE kode_mapel = '$kode_mapel' 
                       AND id_mapel != $id_mapel 
                       AND id_tahunajaran = {$tahun_aktif['id_tahunajaran']}";
        $check_result = $conn->query($check_query);
        $exists = $check_result->fetch_assoc()['total'];
        
        if ($exists > 0) {
            $_SESSION['error'] = "Kode mata pelajaran '$kode_mapel' sudah ada untuk tahun ajaran ini!";
        } else {
            $query = "UPDATE bind_mapel 
                     SET kode_mapel = '$kode_mapel', 
                         nama_mapel = '$nama_mapel', 
                         kelompok = '$kelompok', 
                         kkm = $kkm 
                     WHERE id_mapel = $id_mapel";
            if ($conn->query($query)) {
                $_SESSION['success'] = "Mata pelajaran berhasil diperbarui!";
            } else {
                $_SESSION['error'] = "Gagal memperbarui mata pelajaran: " . $conn->error;
            }
        }
    } else {
        $_SESSION['error'] = "Kode dan nama mata pelajaran tidak boleh kosong!";
    }
    
    header('Location: index.php');
    exit;
}

// DELETE - Hapus Mata Pelajaran
if (isset($_POST['hapus_mapel'])) {
    // Validasi CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $_SESSION['error'] = "Token keamanan tidak valid!";
        header('Location: index.php');
        exit;
    }
    
    $id_mapel = (int)$_POST['id_mapel'];
    $nama_mapel = $conn->real_escape_string($_POST['nama_mapel']);
    
    // Cek apakah mata pelajaran digunakan di tabel lain
    $check_query = "SELECT COUNT(*) as total_usage FROM bind_nilai WHERE id_mapel = $id_mapel";
    $check_result = $conn->query($check_query);
    $total_usage = $check_result->fetch_assoc()['total_usage'];
    
    if ($total_usage > 0) {
        $_SESSION['error'] = "Mata pelajaran <strong>$nama_mapel</strong> tidak dapat dihapus karena masih digunakan di data nilai!";
    } else {
        $query = "DELETE FROM bind_mapel WHERE id_mapel = $id_mapel";
        if ($conn->query($query)) {
            $_SESSION['success'] = "Mata pelajaran <strong>$nama_mapel</strong> berhasil dihapus!";
        } else {
            $_SESSION['error'] = "Gagal menghapus mata pelajaran: " . $conn->error;
        }
    }
    
    header('Location: index.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 mata pelajaran - hanya tampilkan untuk tahun ajaran aktif
$where = " WHERE m.id_tahunajaran = {$tahun_aktif['id_tahunajaran']}";
if (!empty($search)) {
    $where .= " AND (m.kode_mapel LIKE '%$search%' OR m.nama_mapel LIKE '%$search%')";
}

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

$query = "SELECT m.*, t.tahun_ajaran 
          FROM bind_mapel m 
          LEFT JOIN bind_tahunajaran t ON m.id_tahunajaran = t.id_tahunajaran 
          $where 
          ORDER BY m.kelompok, m.nama_mapel 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 Mata Pelajaran</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">
</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-journal-bookmark me-2"></i> Data Mata Pelajaran</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="#tambahMapelModal">
                    <i class="bi bi-plus-circle me-1"></i> Tambah Mata Pelajaran
                </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 Mata Pelajaran
                </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 kode atau nama mata pelajaran..." 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>Kode</th>
                            <th>Nama Mata Pelajaran</th>
                            <th>Kelompok</th>
                            <th>KKM</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"><?= htmlspecialchars($row['kode_mapel']); ?></span></td>
                                    <td><?= htmlspecialchars($row['nama_mapel']); ?></td>
                                    <td>
                                        <?php 
                                        $kelompok_badge = '';
                                        switch($row['kelompok']) {
                                            case 'A': $kelompok_badge = 'badge bg-success'; break;
                                            case 'B': $kelompok_badge = 'badge bg-info'; break;
                                            case 'C': $kelompok_badge = 'badge bg-warning'; break;
                                            default: $kelompok_badge = 'badge bg-secondary';
                                        }
                                        ?>
                                        <span class="<?= $kelompok_badge ?>">Kelompok <?= $row['kelompok'] ?></span>
                                    </td>
                                    <td>
                                        <span class="badge bg-secondary"><?= $row['kkm'] ?></span>
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#editMapelModal<?= $row['id_mapel'] ?>">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <button type="button" class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#hapusMapelModal<?= $row['id_mapel'] ?>">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </td>
                                </tr>

                                <!-- Modal Edit Mata Pelajaran -->
                                <div class="modal fade" id="editMapelModal<?= $row['id_mapel'] ?>" tabindex="-1" aria-labelledby="editMapelModalLabel<?= $row['id_mapel'] ?>" aria-hidden="true">
                                    <div class="modal-dialog">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="editMapelModalLabel<?= $row['id_mapel'] ?>">Edit Mata Pelajaran</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_mapel" value="<?= $row['id_mapel'] ?>">
                                                    <div class="mb-3">
                                                        <label for="kode_mapel_edit<?= $row['id_mapel'] ?>" class="form-label">Kode Mata Pelajaran</label>
                                                        <input type="text" class="form-control" id="kode_mapel_edit<?= $row['id_mapel'] ?>" name="kode_mapel" value="<?= htmlspecialchars($row['kode_mapel']) ?>" required>
                                                    </div>
                                                    <div class="mb-3">
                                                        <label for="nama_mapel_edit<?= $row['id_mapel'] ?>" class="form-label">Nama Mata Pelajaran</label>
                                                        <input type="text" class="form-control" id="nama_mapel_edit<?= $row['id_mapel'] ?>" name="nama_mapel" value="<?= htmlspecialchars($row['nama_mapel']) ?>" required>
                                                    </div>
                                                    <div class="mb-3">
                                                        <label for="kelompok_edit<?= $row['id_mapel'] ?>" class="form-label">Kelompok</label>
                                                        <select class="form-select" id="kelompok_edit<?= $row['id_mapel'] ?>" name="kelompok" required>
                                                            <option value="A" <?= $row['kelompok'] == 'A' ? 'selected' : '' ?>>A (Wajib)</option>
                                                            <option value="B" <?= $row['kelompok'] == 'B' ? 'selected' : '' ?>>B (Wajib)</option>
                                                            <option value="C" <?= $row['kelompok'] == 'C' ? 'selected' : '' ?>>C (Peminatan)</option>
                                                        </select>
                                                    </div>
                                                    <div class="mb-3">
                                                        <label for="kkm_edit<?= $row['id_mapel'] ?>" class="form-label">KKM (Kriteria Ketuntasan Minimal)</label>
                                                        <input type="number" class="form-control" id="kkm_edit<?= $row['id_mapel'] ?>" name="kkm" value="<?= $row['kkm'] ?>" min="0" max="100" required>
                                                    </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_mapel" class="btn btn-primary">Simpan Perubahan</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>

                                <!-- Modal Hapus Mata Pelajaran -->
                                <div class="modal fade" id="hapusMapelModal<?= $row['id_mapel'] ?>" tabindex="-1" aria-labelledby="hapusMapelModalLabel<?= $row['id_mapel'] ?>" aria-hidden="true">
                                    <div class="modal-dialog">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="hapusMapelModalLabel<?= $row['id_mapel'] ?>">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_mapel" value="<?= $row['id_mapel'] ?>">
                                                    <input type="hidden" name="nama_mapel" value="<?= htmlspecialchars($row['nama_mapel']) ?>">
                                                    <p>Apakah Anda yakin ingin menghapus mata pelajaran <strong><?= htmlspecialchars($row['nama_mapel']) ?></strong>?</p>
                                                    <p class="text-muted">Kode: <?= htmlspecialchars($row['kode_mapel']) ?> | 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_mapel" class="btn btn-danger">Hapus</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="7" class="text-center text-muted">
                                    <div class="py-4">
                                        <i class="bi bi-journal-x display-4 text-muted"></i>
                                        <p class="mt-3">Tidak ada data mata pelajaran</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 Mata Pelajaran -->
<?php if (!empty($tahun_aktif)): ?>
<div class="modal fade" id="tambahMapelModal" tabindex="-1" aria-labelledby="tambahMapelModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="tambahMapelModalLabel">Tambah Mata Pelajaran 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="kode_mapel" class="form-label">Kode Mata Pelajaran</label>
                        <input type="text" class="form-control" id="kode_mapel" name="kode_mapel" placeholder="Contoh: MAT, BIN, ING" required>
                        <div class="form-text">Masukkan kode unik untuk mata pelajaran</div>
                    </div>
                    <div class="mb-3">
                        <label for="nama_mapel" class="form-label">Nama Mata Pelajaran</label>
                        <input type="text" class="form-control" id="nama_mapel" name="nama_mapel" placeholder="Contoh: Matematika, Bahasa Indonesia" required>
                    </div>
                    <div class="mb-3">
                        <label for="kelompok" class="form-label">Kelompok</label>
                        <select class="form-select" id="kelompok" name="kelompok" required>
                            <option value="">Pilih Kelompok</option>
                            <option value="A">A (Wajib)</option>
                            <option value="B">B (Wajib)</option>
                            <option value="C">C (Peminatan)</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="kkm" class="form-label">KKM (Kriteria Ketuntasan Minimal)</label>
                        <input type="number" class="form-control" id="kkm" name="kkm" value="75" min="0" max="100" required>
                        <div class="form-text">Nilai KKM antara 0-100</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">Mata pelajaran 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_mapel" 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() {
    // 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
?>