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

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

if ($role !== 'admin' && $role !== 'guru') {
    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();
}

// Ambil data semester aktif
$semester_aktif = [];
$query_semester = "SELECT * FROM bind_semester WHERE aktif = TRUE AND id_tahunajaran = {$tahun_aktif['id_tahunajaran']} LIMIT 1";
$result_semester = $conn->query($query_semester);
if ($result_semester->num_rows > 0) {
    $semester_aktif = $result_semester->fetch_assoc();
}

// Ambil data mata pelajaran
$mapel_options = [];
$query_mapel = "SELECT * FROM bind_mapel WHERE id_tahunajaran = {$tahun_aktif['id_tahunajaran']} ORDER BY nama_mapel";
$result_mapel = $conn->query($query_mapel);
while ($row = $result_mapel->fetch_assoc()) {
    $mapel_options[$row['id_mapel']] = $row['nama_mapel'];
}

// Ambil data siswa (menggunakan bind_datasiswa)
$siswa_options = [];
$query_siswa = "SELECT ds.id_datasiswa, s.nis, s.nama_lengkap 
                FROM bind_siswa s 
                JOIN bind_datasiswa ds ON s.id_siswa = ds.id_siswa 
                WHERE ds.id_tahunajaran = {$tahun_aktif['id_tahunajaran']} 
                AND ds.status = 'Aktif'
                ORDER BY s.nama_lengkap";
$result_siswa = $conn->query($query_siswa);
while ($row = $result_siswa->fetch_assoc()) {
    $siswa_options[$row['id_datasiswa']] = $row['nama_lengkap'] . " (NIS: " . $row['nis'] . ")";
}

// Handle CRUD Operations
// CREATE - Tambah Nilai
if (isset($_POST['tambah_nilai'])) {
    // 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_datasiswa = (int)$_POST['id_datasiswa'];
    $id_tahunajaran = $tahun_aktif['id_tahunajaran'];
    $id_mapel = (int)$_POST['id_mapel'];
    $id_semester = (int)$_POST['id_semester'];
    $np_pengetahuan = !empty($_POST['np_pengetahuan']) ? (float)$_POST['np_pengetahuan'] : NULL;
    
    // Validasi dan konversi predikat pengetahuan
    $predikat_pengetahuan = NULL;
    if (!empty($_POST['predikat_pengetahuan']) && in_array($_POST['predikat_pengetahuan'], ['A', 'B', 'C', 'D'])) {
        $predikat_pengetahuan = $_POST['predikat_pengetahuan'];
    }
    
    $np_keterampilan = !empty($_POST['np_keterampilan']) ? (float)$_POST['np_keterampilan'] : NULL;
    
    // Validasi dan konversi predikat keterampilan
    $predikat_keterampilan = NULL;
    if (!empty($_POST['predikat_keterampilan']) && in_array($_POST['predikat_keterampilan'], ['A', 'B', 'C', 'D'])) {
        $predikat_keterampilan = $_POST['predikat_keterampilan'];
    }
    
    // Validasi dan konversi nsss
    $nsss = NULL;
    if (!empty($_POST['nsss']) && in_array($_POST['nsss'], ['SB', 'B', 'C', 'K'])) {
        $nsss = $_POST['nsss'];
    }
    
    // Validasi data
    if (empty($id_datasiswa) || empty($id_mapel) || empty($id_semester)) {
        $_SESSION['error'] = "Siswa, Mata Pelajaran, dan Semester harus diisi!";
        header('Location: index.php');
        exit;
    }
    
    // Cek apakah nilai sudah ada
    $check_query = "SELECT COUNT(*) as total FROM bind_nilai 
                   WHERE id_datasiswa = $id_datasiswa 
                   AND id_tahunajaran = $id_tahunajaran
                   AND id_mapel = $id_mapel
                   AND id_semester = $id_semester";
    $check_result = $conn->query($check_query);
    $exists = $check_result->fetch_assoc()['total'];
    
    if ($exists > 0) {
        $_SESSION['error'] = "Nilai untuk siswa, mata pelajaran, dan semester ini sudah ada!";
    } else {
        // Debug: Tampilkan nilai yang akan disimpan
        error_log("Data yang akan disimpan:");
        error_log("id_datasiswa: " . $id_datasiswa);
        error_log("id_tahunajaran: " . $id_tahunajaran);
        error_log("id_mapel: " . $id_mapel);
        error_log("id_semester: " . $id_semester);
        error_log("np_pengetahuan: " . $np_pengetahuan);
        error_log("predikat_pengetahuan: " . $predikat_pengetahuan);
        error_log("np_keterampilan: " . $np_keterampilan);
        error_log("predikat_keterampilan: " . $predikat_keterampilan);
        error_log("nsss: " . $nsss);
        
        $query = "INSERT INTO bind_nilai 
                 (id_datasiswa, id_tahunajaran, id_mapel, id_semester, np_pengetahuan, predikat_pengetahuan, np_keterampilan, predikat_keterampilan, nsss) 
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $conn->prepare($query);
        
        // Gunakan binding parameter dengan tipe yang tepat
        // i = integer, d = double, s = string
        $stmt->bind_param(
            "iiiiddsss", 
            $id_datasiswa, 
            $id_tahunajaran, 
            $id_mapel, 
            $id_semester, 
            $np_pengetahuan, 
            $predikat_pengetahuan,
            $np_keterampilan,
            $predikat_keterampilan,
            $nsss
        );
        
        if ($stmt->execute()) {
            $_SESSION['success'] = "Nilai berhasil ditambahkan!";
        } else {
            $_SESSION['error'] = "Gagal menambahkan nilai: " . $stmt->error;
        }
        $stmt->close();
    }
    
    header('Location: index.php');
    exit;
}

// UPDATE - Edit Nilai
if (isset($_POST['edit_nilai'])) {
    // 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_nilai = (int)$_POST['id_nilai'];
    $np_pengetahuan = !empty($_POST['np_pengetahuan']) ? (float)$_POST['np_pengetahuan'] : NULL;
    
    // Validasi dan konversi predikat pengetahuan
    $predikat_pengetahuan = NULL;
    if (!empty($_POST['predikat_pengetahuan']) && in_array($_POST['predikat_pengetahuan'], ['A', 'B', 'C', 'D'])) {
        $predikat_pengetahuan = $_POST['predikat_pengetahuan'];
    }
    
    $np_keterampilan = !empty($_POST['np_keterampilan']) ? (float)$_POST['np_keterampilan'] : NULL;
    
    // Validasi dan konversi predikat keterampilan
    $predikat_keterampilan = NULL;
    if (!empty($_POST['predikat_keterampilan']) && in_array($_POST['predikat_keterampilan'], ['A', 'B', 'C', 'D'])) {
        $predikat_keterampilan = $_POST['predikat_keterampilan'];
    }
    
    // Validasi dan konversi nsss
    $nsss = NULL;
    if (!empty($_POST['nsss']) && in_array($_POST['nsss'], ['SB', 'B', 'C', 'K'])) {
        $nsss = $_POST['nsss'];
    }
    
    $query = "UPDATE bind_nilai 
             SET np_pengetahuan = ?, 
                 predikat_pengetahuan = ?,
                 np_keterampilan = ?,
                 predikat_keterampilan = ?,
                 nsss = ?
             WHERE id_nilai = ?";
    
    $stmt = $conn->prepare($query);
    
    // Gunakan binding parameter dengan tipe yang tepat
    $stmt->bind_param(
        "dssssi", 
        $np_pengetahuan, 
        $predikat_pengetahuan,
        $np_keterampilan,
        $predikat_keterampilan,
        $nsss,
        $id_nilai
    );
    
    if ($stmt->execute()) {
        $_SESSION['success'] = "Nilai berhasil diperbarui!";
    } else {
        $_SESSION['error'] = "Gagal memperbarui nilai: " . $stmt->error;
    }
    $stmt->close();
    
    header('Location: index.php');
    exit;
}

// DELETE - Hapus Nilai
if (isset($_POST['hapus_nilai'])) {
    // 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_nilai = (int)$_POST['id_nilai'];
    
    $query = "DELETE FROM bind_nilai WHERE id_nilai = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $id_nilai);
    
    if ($stmt->execute()) {
        $_SESSION['success'] = "Nilai berhasil dihapus!";
    } else {
        $_SESSION['error'] = "Gagal menghapus nilai: " . $stmt->error;
    }
    $stmt->close();
    
    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']) : '';
$filter_semester = isset($_GET['filter_semester']) ? (int)$_GET['filter_semester'] : '';
$filter_mapel = isset($_GET['filter_mapel']) ? (int)$_GET['filter_mapel'] : '';

// Query data nilai - menggunakan join dengan bind_datasiswa
$where = " WHERE n.id_tahunajaran = {$tahun_aktif['id_tahunajaran']}";
if (!empty($search)) {
    $where .= " AND (s.nama_lengkap LIKE '%$search%' OR s.nis LIKE '%$search%')";
}
if (!empty($filter_semester)) {
    $where .= " AND n.id_semester = $filter_semester";
}
if (!empty($filter_mapel)) {
    $where .= " AND n.id_mapel = $filter_mapel";
}

$query_count = "SELECT COUNT(*) as total 
                FROM bind_nilai n
                JOIN bind_datasiswa ds ON n.id_datasiswa = ds.id_datasiswa
                JOIN bind_siswa s ON ds.id_siswa = s.id_siswa
                $where";
$result_count = $conn->query($query_count);
$total_data = $result_count->fetch_assoc()['total'];
$total_pages = ceil($total_data / $limit);

$query = "SELECT n.*, 
                 s.nis, s.nama_lengkap, 
                 m.nama_mapel, 
                 sem.semester,
                 t.tahun_ajaran,
                 ds.id_datasiswa
          FROM bind_nilai n
          JOIN bind_datasiswa ds ON n.id_datasiswa = ds.id_datasiswa
          JOIN bind_siswa s ON ds.id_siswa = s.id_siswa
          JOIN bind_mapel m ON n.id_mapel = m.id_mapel
          JOIN bind_semester sem ON n.id_semester = sem.id_semester
          JOIN bind_tahunajaran t ON n.id_tahunajaran = t.id_tahunajaran
          $where 
          ORDER BY s.nama_lengkap, m.nama_mapel
          LIMIT $limit OFFSET $offset";
$result = $conn->query($query);

// Ambil data semester untuk filter
$semester_options = [];
$query_semesters = "SELECT * FROM bind_semester WHERE id_tahunajaran = {$tahun_aktif['id_tahunajaran']} ORDER BY semester";
$result_semesters = $conn->query($query_semesters);
while ($row = $result_semesters->fetch_assoc()) {
    $semester_options[$row['id_semester']] = $row['semester'];
}

// 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 Nilai Siswa</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">
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />
    <style>
        .btn-disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .tooltip-inner {
            max-width: 300px;
        }
        .table th {
            vertical-align: middle;
        }
        .badge-nilai {
            font-size: 0.8rem;
        }
        .form-control:disabled {
            background-color: #e9ecef;
            opacity: 1;
        }
        /* Select2 Custom Styling */
        .select2-container--bootstrap-5 .select2-selection {
            min-height: 38px;
        }
        .select2-container--bootstrap-5 .select2-selection--single .select2-selection__rendered {
            line-height: 36px;
        }
        .select2-container--bootstrap-5 .select2-selection--multiple .select2-selection__rendered {
            line-height: 24px;
        }
    </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-journal-check me-2"></i> Data Nilai Siswa</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) && !empty($semester_aktif)): ?>
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#tambahNilaiModal">
                    <i class="bi bi-plus-circle me-1"></i> Tambah Nilai
                </button>
            <?php else: ?>
                <button type="button" class="btn btn-primary" disabled title="Tidak ada tahun ajaran atau semester aktif">
                    <i class="bi bi-plus-circle me-1"></i> Tambah Nilai
                </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 flex-wrap gap-2">
                        <input type="text" name="search" class="form-control" placeholder="Cari siswa atau NIS..." value="<?= htmlspecialchars($search) ?>" style="width: 250px;">
                        
                        <select name="filter_semester" class="form-select" style="width: 150px;">
                            <option value="">Semua Semester</option>
                            <?php foreach ($semester_options as $id => $nama): ?>
                                <option value="<?= $id ?>" <?= $filter_semester == $id ? 'selected' : '' ?>><?= htmlspecialchars($nama) ?></option>
                            <?php endforeach; ?>
                        </select>
                        
                        <select name="filter_mapel" class="form-select select2-filter" style="width: 200px;">
                            <option value="">Semua Mapel</option>
                            <?php foreach ($mapel_options as $id => $nama): ?>
                                <option value="<?= $id ?>" <?= $filter_mapel == $id ? 'selected' : '' ?>><?= htmlspecialchars($nama) ?></option>
                            <?php endforeach; ?>
                        </select>
                        
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-search"></i>
                        </button>
                        
                        <a href="index.php" 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; ?>
                            <?php if (!empty($filter_semester)): ?>
                                <input type="hidden" name="filter_semester" value="<?= $filter_semester ?>">
                            <?php endif; ?>
                            <?php if (!empty($filter_mapel)): ?>
                                <input type="hidden" name="filter_mapel" value="<?= $filter_mapel ?>">
                            <?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>Siswa</th>
                            <th>NIS</th>
                            <th>Mata Pelajaran</th>
                            <th>Semester</th>
                            <th>Nilai Pengetahuan</th>
                            <th>Nilai Keterampilan</th>
                            <th>Sikap</th>
                            <th width="120">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><?= htmlspecialchars($row['nama_lengkap']); ?></td>
                                    <td><?= htmlspecialchars($row['nis']); ?></td>
                                    <td><?= htmlspecialchars($row['nama_mapel']); ?></td>
                                    <td>
                                        <span class="badge bg-primary"><?= htmlspecialchars($row['semester']); ?></span>
                                    </td>
                                    <td>
                                        <?php if (!empty($row['np_pengetahuan'])): ?>
                                            <span class="badge bg-info badge-nilai"><?= $row['np_pengetahuan'] ?></span>
                                            <?php if (!empty($row['predikat_pengetahuan'])): ?>
                                                <small class="text-muted">(<?= $row['predikat_pengetahuan'] ?>)</small>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if (!empty($row['np_keterampilan'])): ?>
                                            <span class="badge bg-warning text-dark badge-nilai"><?= $row['np_keterampilan'] ?></span>
                                            <?php if (!empty($row['predikat_keterampilan'])): ?>
                                                <small class="text-muted">(<?= $row['predikat_keterampilan'] ?>)</small>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if (!empty($row['nsss'])): ?>
                                            <?php
                                            $badge_class = 'bg-secondary';
                                            if ($row['nsss'] == 'SB') $badge_class = 'bg-success';
                                            if ($row['nsss'] == 'B') $badge_class = 'bg-info';
                                            if ($row['nsss'] == 'C') $badge_class = 'bg-warning';
                                            if ($row['nsss'] == 'K') $badge_class = 'bg-danger';
                                            ?>
                                            <span class="badge <?= $badge_class ?>"><?= $row['nsss'] ?></span>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#editNilaiModal<?= $row['id_nilai'] ?>">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <button type="button" class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#hapusNilaiModal<?= $row['id_nilai'] ?>">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </td>
                                </tr>

                                <!-- Modal Edit Nilai -->
                                <div class="modal fade" id="editNilaiModal<?= $row['id_nilai'] ?>" tabindex="-1" aria-labelledby="editNilaiModalLabel<?= $row['id_nilai'] ?>" aria-hidden="true">
                                    <div class="modal-dialog modal-lg">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="editNilaiModalLabel<?= $row['id_nilai'] ?>">Edit Nilai</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_nilai" value="<?= $row['id_nilai'] ?>">
                                                    
                                                    <div class="row mb-3">
                                                        <div class="col-md-6">
                                                            <label class="form-label">Siswa</label>
                                                            <input type="text" class="form-control" value="<?= htmlspecialchars($row['nama_lengkap']) ?> (<?= $row['nis'] ?>)" readonly disabled>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <label class="form-label">Mata Pelajaran</label>
                                                            <input type="text" class="form-control" value="<?= htmlspecialchars($row['nama_mapel']) ?>" readonly disabled>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="row mb-3">
                                                        <div class="col-md-6">
                                                            <label class="form-label">Tahun Ajaran</label>
                                                            <input type="text" class="form-control" value="<?= htmlspecialchars($row['tahun_ajaran']) ?>" readonly disabled>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <label class="form-label">Semester</label>
                                                            <input type="text" class="form-control" value="<?= htmlspecialchars($row['semester']) ?>" readonly disabled>
                                                        </div>
                                                    </div>
                                                    
                                                    <hr>
                                                    
                                                    <div class="row mb-3">
                                                        <div class="col-md-6">
                                                            <label for="np_pengetahuan_edit<?= $row['id_nilai'] ?>" class="form-label">Nilai Pengetahuan</label>
                                                            <input type="number" step="0.01" min="0" max="100" class="form-control" id="np_pengetahuan_edit<?= $row['id_nilai'] ?>" name="np_pengetahuan" value="<?= $row['np_pengetahuan'] ?>">
                                                        </div>
                                                        <div class="col-md-6">
                                                            <label for="predikat_pengetahuan_edit<?= $row['id_nilai'] ?>" class="form-label">Predikat Pengetahuan</label>
                                                            <select class="form-select" id="predikat_pengetahuan_edit<?= $row['id_nilai'] ?>" name="predikat_pengetahuan">
                                                                <option value="">Pilih Predikat</option>
                                                                <option value="A" <?= $row['predikat_pengetahuan'] == 'A' ? 'selected' : '' ?>>A</option>
                                                                <option value="B" <?= $row['predikat_pengetahuan'] == 'B' ? 'selected' : '' ?>>B</option>
                                                                <option value="C" <?= $row['predikat_pengetahuan'] == 'C' ? 'selected' : '' ?>>C</option>
                                                                <option value="D" <?= $row['predikat_pengetahuan'] == 'D' ? 'selected' : '' ?>>D</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="row mb-3">
                                                        <div class="col-md-6">
                                                            <label for="np_keterampilan_edit<?= $row['id_nilai'] ?>" class="form-label">Nilai Keterampilan</label>
                                                            <input type="number" step="0.01" min="0" max="100" class="form-control" id="np_keterampilan_edit<?= $row['id_nilai'] ?>" name="np_keterampilan" value="<?= $row['np_keterampilan'] ?>">
                                                        </div>
                                                        <div class="col-md-6">
                                                            <label for="predikat_keterampilan_edit<?= $row['id_nilai'] ?>" class="form-label">Predikat Keterampilan</label>
                                                            <select class="form-select" id="predikat_keterampilan_edit<?= $row['id_nilai'] ?>" name="predikat_keterampilan">
                                                                <option value="">Pilih Predikat</option>
                                                                <option value="A" <?= $row['predikat_keterampilan'] == 'A' ? 'selected' : '' ?>>A</option>
                                                                <option value="B" <?= $row['predikat_keterampilan'] == 'B' ? 'selected' : '' ?>>B</option>
                                                                <option value="C" <?= $row['predikat_keterampilan'] == 'C' ? 'selected' : '' ?>>C</option>
                                                                <option value="D" <?= $row['predikat_keterampilan'] == 'D' ? 'selected' : '' ?>>D</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="mb-3">
                                                        <label for="nsss_edit<?= $row['id_nilai'] ?>" class="form-label">Nilai Sikap Spiritual dan Sosial</label>
                                                        <select class="form-select" id="nsss_edit<?= $row['id_nilai'] ?>" name="nsss">
                                                            <option value="">Pilih Nilai Sikap</option>
                                                            <option value="SB" <?= $row['nsss'] == 'SB' ? 'selected' : '' ?>>Sangat Baik (SB)</option>
                                                            <option value="B" <?= $row['nsss'] == 'B' ? 'selected' : '' ?>>Baik (B)</option>
                                                            <option value="C" <?= $row['nsss'] == 'C' ? 'selected' : '' ?>>Cukup (C)</option>
                                                            <option value="K" <?= $row['nsss'] == 'K' ? 'selected' : '' ?>>Kurang (K)</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                                                    <button type="submit" name="edit_nilai" class="btn btn-primary">Simpan Perubahan</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>

                                <!-- Modal Hapus Nilai -->
                                <div class="modal fade" id="hapusNilaiModal<?= $row['id_nilai'] ?>" tabindex="-1" aria-labelledby="hapusNilaiModalLabel<?= $row['id_nilai'] ?>" aria-hidden="true">
                                    <div class="modal-dialog">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="hapusNilaiModalLabel<?= $row['id_nilai'] ?>">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_nilai" value="<?= $row['id_nilai'] ?>">
                                                    <div class="alert alert-warning">
                                                        <i class="bi bi-exclamation-triangle me-2"></i>
                                                        <strong>Perhatian!</strong> Data nilai yang dihapus tidak dapat dikembalikan.
                                                    </div>
                                                    <p>Apakah Anda yakin ingin menghapus nilai untuk:</p>
                                                    <ul>
                                                        <li><strong>Siswa:</strong> <?= htmlspecialchars($row['nama_lengkap']) ?></li>
                                                        <li><strong>Mata Pelajaran:</strong> <?= htmlspecialchars($row['nama_mapel']) ?></li>
                                                        <li><strong>Semester:</strong> <?= htmlspecialchars($row['semester']) ?></li>
                                                    </ul>
                                                    <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_nilai" class="btn btn-danger">Hapus</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="9" 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 nilai</p>
                                        <?php if (!empty($search) || !empty($filter_semester) || !empty($filter_mapel)): ?>
                                            <p class="text-muted">Coba ubah filter atau <a href="index.php" 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) : '' ?><?= !empty($filter_semester) ? '&filter_semester=' . $filter_semester : '' ?><?= !empty($filter_mapel) ? '&filter_mapel=' . $filter_mapel : '' ?>">
                                    <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) : '' ?><?= !empty($filter_semester) ? '&filter_semester=' . $filter_semester : '' ?><?= !empty($filter_mapel) ? '&filter_mapel=' . $filter_mapel : '' ?>"><?= $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) : '' ?><?= !empty($filter_semester) ? '&filter_semester=' . $filter_semester : '' ?><?= !empty($filter_mapel) ? '&filter_mapel=' . $filter_mapel : '' ?>">
                                    Next <i class="bi bi-chevron-right"></i>
                                </a>
                            </li>
                        <?php endif; ?>
                    </ul>
                </nav>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Modal Tambah Nilai -->
<?php if (!empty($tahun_aktif) && !empty($semester_aktif)): ?>
<div class="modal fade" id="tambahNilaiModal" tabindex="-1" aria-labelledby="tambahNilaiModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="tambahNilaiModalLabel">Tambah Nilai 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="row mb-3">
                        <div class="col-md-6">
                            <label for="id_datasiswa" class="form-label">Siswa <span class="text-danger">*</span></label>
                            <select class="form-select select2-siswa" id="id_datasiswa" name="id_datasiswa" required>
                                <option value="">Pilih Siswa</option>
                                <?php foreach ($siswa_options as $id => $nama): ?>
                                    <option value="<?= $id ?>"><?= htmlspecialchars($nama) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="id_mapel" class="form-label">Mata Pelajaran <span class="text-danger">*</span></label>
                            <select class="form-select select2-mapel" id="id_mapel" name="id_mapel" required>
                                <option value="">Pilih Mata Pelajaran</option>
                                <?php foreach ($mapel_options as $id => $nama): ?>
                                    <option value="<?= $id ?>"><?= htmlspecialchars($nama) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label">Tahun Ajaran</label>
                            <input type="text" class="form-control" value="<?= htmlspecialchars($tahun_aktif['tahun_ajaran']) ?>" readonly disabled>
                            <input type="hidden" name="id_tahunajaran" value="<?= $tahun_aktif['id_tahunajaran'] ?>">
                        </div>
                        <div class="col-md-6">
                            <label for="id_semester" class="form-label">Semester <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" value="<?= htmlspecialchars($semester_aktif['semester']) ?>" readonly disabled>
                            <input type="hidden" name="id_semester" value="<?= $semester_aktif['id_semester'] ?>">
                            <div class="form-text">Semester aktif saat ini</div>
                        </div>
                    </div>
                    
                    <hr>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="np_pengetahuan" class="form-label">Nilai Pengetahuan</label>
                            <input type="number" step="0.01" min="0" max="100" class="form-control" id="np_pengetahuan" name="np_pengetahuan">
                        </div>
                        <div class="col-md-6">
                            <label for="predikat_pengetahuan" class="form-label">Predikat Pengetahuan</label>
                            <select class="form-select" id="predikat_pengetahuan" name="predikat_pengetahuan">
                                <option value="">Pilih Predikat</option>
                                <option value="A">A</option>
                                <option value="B">B</option>
                                <option value="C">C</option>
                                <option value="D">D</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="np_keterampilan" class="form-label">Nilai Keterampilan</label>
                            <input type="number" step="0.01" min="0" max="100" class="form-control" id="np_keterampilan" name="np_keterampilan">
                        </div>
                        <div class="col-md-6">
                            <label for="predikat_keterampilan" class="form-label">Predikat Keterampilan</label>
                            <select class="form-select" id="predikat_keterampilan" name="predikat_keterampilan">
                                <option value="">Pilih Predikat</option>
                                <option value="A">A</option>
                                <option value="B">B</option>
                                <option value="C">C</option>
                                <option value="D">D</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="nsss" class="form-label">Nilai Sikap Spiritual dan Sosial</label>
                        <select class="form-select" id="nsss" name="nsss">
                            <option value="">Pilih Nilai Sikap</option>
                            <option value="SB">Sangat Baik (SB)</option>
                            <option value="B">Baik (B)</option>
                            <option value="C">Cukup (C)</option>
                            <option value="K">Kurang (K)</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" name="tambah_nilai" class="btn btn-primary">Simpan</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- JavaScript Libraries -->
<!-- jQuery harus dipuat sebelum Select2 -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
$(document).ready(function() {
    // Inisialisasi Select2 untuk filter mata pelajaran
    $('.select2-filter').select2({
        theme: 'bootstrap-5',
        width: 'style',
        placeholder: 'Semua Mapel',
        allowClear: true
    });

    // Inisialisasi Select2 untuk modal tambah nilai
    // Pastikan modal sudah ada sebelum menginisialisasi Select2
    if ($('#tambahNilaiModal').length) {
        $('.select2-siswa').select2({
            theme: 'bootstrap-5',
            width: '100%',
            placeholder: 'Pilih Siswa',
            allowClear: true,
            dropdownParent: $('#tambahNilaiModal')
        });

        $('.select2-mapel').select2({
            theme: 'bootstrap-5',
            width: '100%',
            placeholder: 'Pilih Mata Pelajaran',
            allowClear: true,
            dropdownParent: $('#tambahNilaiModal')
        });
    }

    // 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
?>