<?php
session_start();
// Mengaktifkan Tailwind CSS melalui CDN
echo '<script src="https://cdn.tailwindcss.com"></script>';
echo '<style>
    body { font-family: "Inter", sans-serif; background-color: #f4f7f9; }
    .math-display { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; background-color: #f0f9ff; border: 1px solid #bfdbfe; color: #1e40af; padding: 0.75rem; border-radius: 0.5rem; overflow-x: auto; }
    /* CSS untuk Media Cetak */
    @media print {
        body { background-color: #fff; padding: 1rem; }
        .no-print, .no-print * { display: none !important; }
        .table-print { width: 100%; border-collapse: collapse; }
        .table-print th, .table-print td { border: 1px solid #000; padding: 8px; text-align: center; vertical-align: middle; }
        .table-print th { background-color: #f2f2f2; font-weight: bold; }
    }
</style>';

// --- KONFIGURASI DATABASE ---
 $db_host = 'ftp.sdmuhammadiyah03kreatif.sch.id';
 $db_user = 'sdmr6339';
 $db_pass = 'hGC5tMNvnmXE87';
 $db_name = 'sdmr6339_grade_calculator';
 $conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) die("Koneksi database gagal: " . $conn->connect_error);

// --- VARIABEL GLOBAL ---
 $action = $_GET['action'] ?? 'list_schools';
 $message = $_SESSION['message'] ?? '';
 $message_type = $_SESSION['message_type'] ?? 'info';
unset($_SESSION['message'], $_SESSION['message_type']);

// --- FUNGSI-FUNGSI DATABASE ---
function getSchool($conn, $id) {
    $stmt = $conn->prepare("SELECT * FROM schools WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}
function getClass($conn, $id) {
    $stmt = $conn->prepare("SELECT c.*, s.name as school_name FROM classes c JOIN schools s ON c.school_id = s.id WHERE c.id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}
function getStudent($conn, $id) {
    $stmt = $conn->prepare("SELECT st.*, c.name as class_name, c.kktp FROM students st JOIN classes c ON st.class_id = c.id WHERE st.id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}
function getAssessment($conn, $class_id) {
    $stmt = $conn->prepare("SELECT * FROM assessments WHERE class_id = ?");
    $stmt->bind_param("i", $class_id);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}

// --- PROSES POST REQUEST ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_school'])) {
        $stmt = $conn->prepare("INSERT INTO schools (name) VALUES (?)");
        $stmt->bind_param("s", $_POST['school_name']);
        if ($stmt->execute()) {
            $_SESSION['message'] = "Sekolah berhasil ditambahkan!";
            $_SESSION['message_type'] = "success";
        } else {
            $_SESSION['message'] = "Gagal menambahkan sekolah.";
            $_SESSION['message_type'] = "error";
        }
        header("Location: ?");
        exit;
    } elseif (isset($_POST['add_class'])) {
        $stmt = $conn->prepare("INSERT INTO classes (school_id, name, kktp) VALUES (?, ?, ?)");
        $stmt->bind_param("isd", $_POST['school_id'], $_POST['class_name'], $_POST['kktp']);
        if ($stmt->execute()) {
            $_SESSION['message'] = "Kelas berhasil ditambahkan!";
            $_SESSION['message_type'] = "success";
        } else {
            $_SESSION['message'] = "Gagal menambahkan kelas.";
            $_SESSION['message_type'] = "error";
        }
        header("Location: ?action=view_class&school_id=" . $_POST['school_id']);
        exit;
    } elseif (isset($_POST['add_student'])) {
        $stmt = $conn->prepare("INSERT INTO students (class_id, name, student_number) VALUES (?, ?, ?)");
        $stmt->bind_param("iss", $_POST['class_id'], $_POST['student_name'], $_POST['student_number']);
        if ($stmt->execute()) {
            $_SESSION['message'] = "Siswa berhasil ditambahkan!";
            $_SESSION['message_type'] = "success";
        } else {
            $_SESSION['message'] = "Gagal menambahkan siswa. Mungkin NIS sudah ada.";
            $_SESSION['message_type'] = "error";
        }
        header("Location: ?action=view_class_dashboard&class_id=" . $_POST['class_id']);
        exit;
    }
}

// --- ALGORITMA PERHITUNGAN ---
function calculateFinalScores($assessment_config, $student_answers, $slm_scores, &$chapters_with_scores) {
    $kktp = $assessment_config['kktp'];
    $pg_total_soal = $assessment_config['pg_total'];
    $isian_total_soal = $assessment_config['isian_total'];
    $essay_total_soal = $assessment_config['essay_total'];
    $pg_benar = $student_answers['pg_correct'];
    $isian_benar = $student_answers['isian_correct'];
    $essay_benar = $student_answers['essay_correct'];

    $total_tp_count = 0;
    foreach ($assessment_config['chapters'] as $chapter) {
        $total_tp_count += count($chapter['tps']);
    }
    if ($total_tp_count === 0) return 0;

    $pg_ach_rate = ($pg_total_soal > 0) ? $pg_benar / $pg_total_soal : 0;
    $isian_ach_rate = ($isian_total_soal > 0) ? $isian_benar / $isian_total_soal : 0;
    $essay_ach_rate = ($essay_total_soal > 0) ? $essay_benar / $essay_total_soal : 0;

    $pg_max_per_tp = ($total_tp_count > 0) ? floor($pg_total_soal / $total_tp_count) : 0;
    $isian_max_per_tp = ($total_tp_count > 0) ? floor($isian_total_soal / $total_tp_count) : 0;
    $essay_max_per_tp = ($total_tp_count > 0) ? floor($essay_total_soal / $total_tp_count) : 0;

    $pg_remainder = $pg_total_soal - ($pg_max_per_tp * $total_tp_count);
    $isian_remainder = $isian_total_soal - ($isian_max_per_tp * $total_tp_count);
    $essay_remainder = $essay_total_soal - ($essay_max_per_tp * $total_tp_count);

    $tp_counter = 0;
    $total_final_bab_score_sum = 0;

    foreach ($assessment_config['chapters'] as $chapter_index => &$chapter) {
        $chapter_id = $chapter['id'];
        $bab_score_sum_tp_normalized = 0;
        
        foreach ($chapter['tps'] as $tp_index => &$tp) {
            $tp_counter++;
            $tp_pg_max = $pg_max_per_tp + ($tp_counter <= $pg_remainder ? 1 : 0);
            $tp_isian_max = $isian_max_per_tp + ($tp_counter <= $isian_remainder ? 1 : 0);
            $tp_essay_max = $essay_max_per_tp + ($tp_counter <= $essay_remainder ? 1 : 0);

            $tp_pg_achieved = $tp_pg_max * $pg_ach_rate;
            $tp_isian_achieved = $tp_isian_max * $isian_ach_rate;
            $tp_essay_achieved = $tp_essay_max * $essay_ach_rate;

            $total_achieved_raw = $tp_pg_achieved + $tp_isian_achieved + $tp_essay_achieved;
            $total_max_raw = $tp_pg_max + $tp_isian_max + $tp_essay_max;

            $nilai_akhir_tp_100 = ($total_max_raw > 0) ? ($total_achieved_raw / $total_max_raw) * 100 : 0;
            $tp['score_100'] = $nilai_akhir_tp_100;
            $bab_score_sum_tp_normalized += $nilai_akhir_tp_100;
        }
        unset($tp);

        $bab_score_normalized_tp = (count($chapter['tps']) > 0) ? $bab_score_sum_tp_normalized / count($chapter['tps']) : 0;
        $slm_score = $slm_scores[$chapter_id] ?? 0;
        
        $final_bab_score = ($slm_score > 0) ? ($bab_score_normalized_tp + $slm_score) / 2 : $bab_score_normalized_tp;
        $chapter['final_score'] = $final_bab_score;
        $chapter['status'] = ($final_bab_score >= $kktp) ? 'KOMPETEN' : 'BELUM KOMPETEN';
        
        $chapters_with_scores[$chapter_id] = $chapter;
        $total_final_bab_score_sum += $final_bab_score;
    }
    unset($chapter);

    return (count($assessment_config['chapters']) > 0) ? $total_final_bab_score_sum / count($assessment_config['chapters']) : 0;
}

// --- TAMPILAN HTML & ROUTER ---
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sistem Penilaian Berbasis TP</title>
</head>
<body class="p-4 md:p-8">
    <div class="w-full max-w-full mx-auto bg-white p-6 md:p-10 shadow-2xl rounded-xl border border-gray-100">
        <h1 class="text-3xl font-extrabold text-center text-red-700 mb-6">Sistem Penilaian Berbasis TP</h1>

        <?php if ($message): ?>
            <div class="bg-<?php echo ($message_type === 'success') ? 'green' : 'red'; ?>-100 border border-<?php echo ($message_type === 'success') ? 'green' : 'red'; ?>-400 text-<?php echo ($message_type === 'success') ? 'green' : 'red'; ?>-700 px-4 py-3 rounded relative mb-4" role="alert">
                <span class="block sm:inline"><?php echo htmlspecialchars($message); ?></span>
            </div>
        <?php endif; ?>

        <?php
        // --- ROUTER ---
        switch ($action) {
            case 'list_schools':
                // Perbaikan untuk mode viewer
                if (isset($_SESSION['is_viewer']) && $_SESSION['is_viewer']) {
                    $first_class = $conn->query("SELECT id FROM classes ORDER BY id LIMIT 1")->fetch_assoc();
                    if ($first_class) {
                        header("Location: ?action=view_class_scores&class_id=" . $first_class['id']);
                        exit;
                    } else {
                        // Tampilkan pesan tapi jangan exit, biarkan halaman tetap tampil
                        echo "<div class='text-center p-10'><h2 class='text-2xl font-bold text-gray-800'>Mode Viewer</h2><p class='text-gray-600'>Tidak ada kelas yang dapat ditampilkan.</p>";
                        echo "<p class='mt-4'><a href='?action=viewer_logout' class='bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg transition'>Keluar dari Mode Viewer</a></p></div>";
                        // Lanjutkan ke bagian bawah untuk menampilkan footer
                        break;
                    }
                }

                $schools = $conn->query("SELECT * FROM schools ORDER BY name");
                ?>
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold text-gray-800">Daftar Sekolah</h2>
                    <div class="flex gap-4">
                        <a href="?action=viewer_login_form" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded-lg transition">👁️ Masuk ke Mode Viewer</a>
                        <a href="?action=add_school_form" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg transition">+ Tambah Sekolah</a>
                    </div>
                </div>
                <div class="overflow-x-auto shadow rounded-lg">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50"><tr><th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nama Sekolah</th><th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th></tr></thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php while($school = $schools->fetch_assoc()): ?>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?php echo htmlspecialchars($school['name']); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                    <a href="?action=view_class&school_id=<?php echo $school['id']; ?>" class="text-indigo-600 hover:text-indigo-900 mr-3">Kelola Kelas</a>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
                <?php
                break;

            case 'viewer_login_form':
                ?>
                <div class="flex justify-center items-center min-h-screen">
                    <div class="w-full max-w-md p-8 bg-white rounded-xl shadow-2xl">
                        <h2 class="text-2xl font-bold text-center text-gray-800 mb-6">Masuk ke Mode Viewer</h2>
                        <form method="POST" action="?action=viewer_login" class="space-y-4">
                            <div>
                                <label for="viewer_key" class="block text-sm font-medium text-gray-700">Masukkan Kunci Viewer</label>
                                <input type="password" id="viewer_key" name="viewer_key" required class="mt-1 p-2 block w-full border-gray-300 rounded-md">
                            </div>
                            <button type="submit" class="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">Masuk</button>
                        </form>
                        <p class="text-center text-sm text-gray-500 mt-4">
                            <a href="?" class="hover:underline">Kembali ke Halaman Admin</a>
                        </p>
                    </div>
                </div>
                <?php
                break;

            case 'viewer_login':
                $stmt = $conn->prepare("SELECT setting_value FROM settings WHERE setting_name = 'viewer_key'");
                $stmt->execute();
                $result = $stmt->get_result();
                $stored_key = $result->fetch_assoc()['setting_value'] ?? null;

                if ($stored_key && $_POST['viewer_key'] === $stored_key) {
                    $_SESSION['is_viewer'] = true;
                    $_SESSION['message'] = "Anda telah masuk ke Mode Viewer (Read-Only).";
                    $_SESSION['message_type'] = "success";
                    header("Location: ?");
                    exit;
                } else {
                    $_SESSION['message'] = "Kunci Viewer salah. Akses ditolak.";
                    $_SESSION['message_type'] = "error";
                    header("Location: ?action=viewer_login_form");
                    exit;
                }
                break;

            case 'viewer_exit_to_admin':
                // Hanya boleh diakses jika sedang dalam mode viewer
                if (!isset($_SESSION['is_viewer']) || !$_SESSION['is_viewer']) {
                    $_SESSION['message'] = "Akses tidak sah.";
                    $_SESSION['message_type'] = "error";
                    header("Location: ?");
                    exit;
                }
                ?>
                <div class="flex justify-center items-center min-h-screen">
                    <div class="w-full max-w-md p-8 bg-white rounded-xl shadow-2xl">
                        <h2 class="text-2xl font-bold text-center text-gray-800 mb-6">Konfirmasi Keluar dari Mode Viewer</h2>
                        <p class="text-center text-gray-600 mb-6">Masukkan Kunci Admin untuk kembali ke mode pengelolaan.</p>
                        <form method="POST" action="?action=viewer_exit_to_admin_process" class="space-y-4">
                            <div>
                                <label for="admin_key" class="block text-sm font-medium text-gray-700">Masukkan Kunci Admin</label>
                                <input type="password" id="admin_key" name="admin_key" required class="mt-1 p-2 block w-full border-gray-300 rounded-md">
                            </div>
                            <div class="flex gap-4">
                                <button type="submit" class="flex-1 w-full bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded">Masuk ke Mode Admin</button>
                                <a href="?action=viewer_logout" class="flex-1 w-full bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded text-center">Tetap di Mode Viewer</a>
                            </div>
                        </form>
                    </div>
                </div>
                <?php
                break;

            case 'viewer_exit_to_admin_process':
                $stmt = $conn->prepare("SELECT setting_value FROM settings WHERE setting_name = 'admin_key'");
                $stmt->execute();
                $result = $stmt->get_result();
                $stored_admin_key = $result->fetch_assoc()['setting_value'] ?? null;

                if ($stored_admin_key && $_POST['admin_key'] === $stored_admin_key) {
                    unset($_SESSION['is_viewer']);
                    $_SESSION['message'] = "Anda telah keluar dari Mode Viewer dan masuk ke Mode Admin.";
                    $_SESSION['message_type'] = "success";
                    header("Location: ?");
                    exit;
                } else {
                    $_SESSION['message'] = "Kunci Admin salah. Anda tetap di Mode Viewer.";
                    $_SESSION['message_type'] = "error";
                    header("Location: ?action=viewer_exit_to_admin");
                    exit;
                }
                break;

            case 'viewer_logout':
                // Hapus sesi viewer sepenuhnya
                unset($_SESSION['is_viewer']);
                $_SESSION['message'] = "Anda telah keluar dari Mode Viewer.";
                $_SESSION['message_type'] = "info";
                header("Location: ?");
                exit;
                break;

            case 'add_school_form':
                if (isset($_SESSION['is_viewer']) && $_SESSION['is_viewer']) { header("Location: ?"); exit; }
                ?>
                <h2 class="text-2xl font-bold text-gray-800 mb-6">Tambah Sekolah Baru</h2>
                <form method="POST" class="space-y-4">
                    <div>
                        <label for="school_name" class="block text-sm font-medium text-gray-700">Nama Sekolah</label>
                        <input type="text" id="school_name" name="school_name" required class="mt-1 p-2 block w-full border-gray-300 rounded-md">
                    </div>
                    <div class="flex gap-4">
                        <button type="submit" name="add_school" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">Simpan</button>
                        <a href="?" class="bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded text-center">Batal</a>
                    </div>
                </form>
                <?php
                break;

            case 'view_class':
                if (isset($_SESSION['is_viewer']) && $_SESSION['is_viewer']) { /* Allow viewer to see class list to pick one */ }
                $school_id = $_GET['school_id'];
                $school = getSchool($conn, $school_id);
                $classes = $conn->prepare("SELECT * FROM classes WHERE school_id = ? ORDER BY name");
                $classes->bind_param("i", $school_id);
                $classes->execute();
                $result_classes = $classes->get_result();
                ?>
                <div class="mb-6">
                    <a href="?" class="text-blue-600 hover:text-blue-800">&larr; Kembali ke Daftar Sekolah</a>
                    <h2 class="text-2xl font-bold text-gray-800 mt-2">Kelas di <?php echo htmlspecialchars($school['name']); ?></h2>
                </div>
                <div class="flex justify-between items-center mb-6">
                    <h3 class="text-xl font-semibold">Daftar Kelas</h3>
                    <?php if (!isset($_SESSION['is_viewer']) || !$_SESSION['is_viewer']): ?>
                        <a href="?action=add_class_form&school_id=<?php echo $school_id; ?>" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg transition">+ Tambah Kelas</a>
                    <?php endif; ?>
                </div>
                <div class="overflow-x-auto shadow rounded-lg mb-8">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50"><tr><th>Nama Kelas</th><th>KKM</th><th class="text-right">Aksi</th></tr></thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php while($class = $result_classes->fetch_assoc()): ?>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap"><?php echo htmlspecialchars($class['name']); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap"><?php echo $class['kktp']; ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                    <a href="?action=view_class_scores&class_id=<?php echo $class['id']; ?>" class="text-indigo-600 hover:text-indigo-900">Lihat Nilai</a>
                                    <?php if (!isset($_SESSION['is_viewer']) || !$_SESSION['is_viewer']): ?>
                                        <a href="?action=view_class_dashboard&class_id=<?php echo $class['id']; ?>" class="text-indigo-600 hover:text-indigo-900 ml-3">Kelola</a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
                <?php
                break;
            
            case 'add_class_form':
                if (isset($_SESSION['is_viewer']) && $_SESSION['is_viewer']) { header("Location: ?"); exit; }
                $school_id = $_GET['school_id'];
                $school = getSchool($conn, $school_id);
                ?>
                <div class="mb-6"><a href="?action=view_class&school_id=<?php echo $school_id; ?>" class="text-blue-600 hover:text-blue-800">&larr; Kembali</a></div>
                <h2 class="text-2xl font-bold text-gray-800 mb-6">Tambah Kelas Baru di <?php echo htmlspecialchars($school['name']); ?></h2>
                <form method="POST" class="space-y-4">
                    <input type="hidden" name="school_id" value="<?php echo $school_id; ?>">
                    <div>
                        <label for="class_name" class="block text-sm font-medium text-gray-700">Nama Kelas</label>
                        <input type="text" id="class_name" name="class_name" required class="mt-1 p-2 block w-full border-gray-300 rounded-md">
                    </div>
                    <div>
                        <label for="kktp" class="block text-sm font-medium text-gray-700">KKM/KKTP</label>
                        <input type="number" id="kktp" name="kktp" value="75" min="0" max="100" required class="mt-1 p-2 block w-full border-gray-300 rounded-md">
                    </div>
                    <div class="flex gap-4">
                        <button type="submit" name="add_class" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">Simpan</button>
                        <a href="?action=view_class&school_id=<?php echo $school_id; ?>" class="bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded text-center">Batal</a>
                    </div>
                </form>
                <?php
                break;

            case 'view_class_dashboard':
                if (isset($_SESSION['is_viewer']) && $_SESSION['is_viewer']) { header("Location: ?"); exit; }
                $class_id = $_GET['class_id'];
                $class = getClass($conn, $class_id);
                $assessment = getAssessment($conn, $class_id);
                $students = $conn->prepare("SELECT * FROM students WHERE class_id = ? ORDER BY name");
                $students->bind_param("i", $class_id);
                $students->execute();
                $result_students = $students->get_result();
                ?>
                <div class="mb-6">
                    <a href="?action=view_class&school_id=<?php echo $class['school_id']; ?>" class="text-blue-600 hover:text-blue-800">&larr; Kembali ke Daftar Kelas</a>
                    <h2 class="text-2xl font-bold text-gray-800 mt-2">Dashboard Kelas: <?php echo htmlspecialchars($class['name']); ?></h2>
                    <p class="text-gray-600">KKM: <?php echo $class['kktp']; ?></p>
                </div>
                <div class="bg-gray-50 p-6 rounded-xl mb-8">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-xl font-semibold">Daftar Siswa</h3>
                        <a href="?action=add_student_form&class_id=<?php echo $class_id; ?>" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg transition">+ Tambah Siswa</a>
                    </div>
                    <div class="overflow-x-auto shadow rounded-lg">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-100"><tr><th>Nama</th><th>NIS</th><th class="text-right">Aksi</th></tr></thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                <?php while($student = $result_students->fetch_assoc()): ?>
                                <tr>
                                    <td class="px-6 py-4 whitespace-nowrap"><?php echo htmlspecialchars($student['name']); ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap"><?php echo htmlspecialchars($student['student_number']); ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                        <?php if ($assessment): ?>
                                            <a href="?action=grade_student&student_id=<?php echo $student['id']; ?>" class="text-green-600 hover:text-green-900">Input Nilai</a>
                                        <?php else: ?>
                                            <span class="text-gray-400">Konfigurasi Asesmen Dulu</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="bg-yellow-50 p-6 rounded-xl mb-8">
                    <h3 class="text-xl font-semibold mb-4">Konfigurasi Asesmen</h3>
                    <?php if ($assessment): ?>
                        <p class="text-green-700 font-semibold mb-2">Asesmen telah dikonfigurasi: <strong><?php echo htmlspecialchars($assessment['name']); ?></strong></p>
                        <p class="text-sm text-gray-600 mb-4">Total Soal: PG(<?php echo $assessment['pg_total'];?>), Isian(<?php echo $assessment['isian_total'];?>), Essay(<?php echo $assessment['essay_total'];?>)</p>
                        <a href="?action=configure_assessment&class_id=<?php echo $class_id; ?>" class="bg-orange-600 hover:bg-orange-700 text-white font-bold py-2 px-4 rounded">Edit Konfigurasi</a>
                    <?php else: ?>
                        <p class="text-red-700 font-semibold mb-4">Belum ada konfigurasi asesmen untuk kelas ini.</p>
                        <a href="?action=configure_assessment&class_id=<?php echo $class_id; ?>" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">+ Buat Konfigurasi Asesmen</a>
                    <?php endif; ?>
                </div>
                <div class="bg-green-50 p-6 rounded-xl mt-8">
                    <h3 class="text-xl font-semibold mb-4">Rekapitulasi Nilai Siswa</h3>
                    <?php if ($assessment): ?>
                        <p class="text-gray-600 mb-4">Lihat nilai akhir dan status kompetensi untuk semua siswa di kelas ini.</p>
                        <div class="flex gap-4">
                            <a href="?action=view_class_scores&class_id=<?php echo $class_id; ?>" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded-lg transition">📊 Lihat Nilai Semua Siswa</a>
                            <form method="POST" action="?action=generate_sample_scores&class_id=<?php echo $class_id; ?>" onsubmit="return confirm('Apakah Anda yakin ingin mengisi nilai acak untuk semua siswa? Nilai yang ada akan ditimpa.');">
                                <button type="submit" class="bg-orange-500 hover:bg-orange-600 text-white font-bold py-2 px-4 rounded-lg transition">🎲 Generate Data Acak</button>
                            </form>
                        </div>
                    <?php else: ?>
                        <p class="text-gray-500 italic">Anda harus mengkonfigurasi asesmen terlebih dahulu sebelum dapat melihat rekap nilai.</p>
                    <?php endif; ?>
                </div>
                <?php
                break;
            
            case 'add_student_form':
                if (isset($_SESSION['is_viewer']) && $_SESSION['is_viewer']) { header("Location: ?"); exit; }
                $class_id = $_GET['class_id'];
                $class = getClass($conn, $class_id);
                ?>
                <div class="mb-6"><a href="?action=view_class_dashboard&class_id=<?php echo $class_id; ?>" class="text-blue-600 hover:text-blue-800">&larr; Kembali</a></div>
                <h2 class="text-2xl font-bold text-gray-800 mb-6">Tambah Siswa Baru di <?php echo htmlspecialchars($class['name']); ?></h2>
                <form method="POST" class="space-y-4">
                    <input type="hidden" name="class_id" value="<?php echo $class_id; ?>">
                    <div>
                        <label for="student_name" class="block text-sm font-medium text-gray-700">Nama Siswa</label>
                        <input type="text" id="student_name" name="student_name" required class="mt-1 p-2 block w-full border-gray-300 rounded-md">
                    </div>
                    <div>
                        <label for="student_number" class="block text-sm font-medium text-gray-700">NIS / NISN</label>
                        <input type="text" id="student_number" name="student_number" required class="mt-1 p-2 block w-full border-gray-300 rounded-md">
                    </div>
                    <div class="flex gap-4">
                        <button type="submit" name="add_student" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">Simpan</button>
                        <a href="?action=view_class_dashboard&class_id=<?php echo $class_id; ?>" class="bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded text-center">Batal</a>
                    </div>
                </form>
                <?php
                break;

            case 'configure_assessment':
                if (isset($_SESSION['is_viewer']) && $_SESSION['is_viewer']) { header("Location: ?"); exit; }
                $class_id = $_GET['class_id'];
                $class = getClass($conn, $class_id);
                $assessment = getAssessment($conn, $class_id);
                if ($assessment) {
                    $conn->begin_transaction();
                    try {
                        $tp_scores = $conn->prepare("DELETE ts FROM tp_scores ts JOIN student_scores ss ON ts.student_score_id = ss.id JOIN chapters c ON ss.chapter_id = c.id WHERE c.assessment_id = ?");
                        $tp_scores->bind_param("i", $assessment['id']);
                        $tp_scores->execute();
                        $student_scores = $conn->prepare("DELETE ss FROM student_scores ss JOIN chapters c ON ss.chapter_id = c.id WHERE c.assessment_id = ?");
                        $student_scores->bind_param("i", $assessment['id']);
                        $student_scores->execute();
                        $learning_objectives = $conn->prepare("DELETE lo FROM learning_objectives lo JOIN chapters c ON lo.chapter_id = c.id WHERE c.assessment_id = ?");
                        $learning_objectives->bind_param("i", $assessment['id']);
                        $learning_objectives->execute();
                        $chapters = $conn->prepare("DELETE FROM chapters WHERE assessment_id = ?");
                        $chapters->bind_param("i", $assessment['id']);
                        $chapters->execute();
                        $assessments = $conn->prepare("DELETE FROM assessments WHERE id = ?");
                        $assessments->bind_param("i", $assessment['id']);
                        $assessments->execute();
                        $conn->commit();
                    } catch (Exception $e) { $conn->rollback(); }
                }
                if (!isset($_SESSION['assessment_config'])) $_SESSION['assessment_config'] = [];
                $step = $_GET['step'] ?? 1;
                $config = &$_SESSION['assessment_config'];
                if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                    if (isset($_POST['submit_step_1'])) {
                        $config['chapter_count'] = (int)$_POST['chapter_count'];
                        header("Location: ?action=configure_assessment&class_id=$class_id&step=2"); exit;
                    } elseif (isset($_POST['submit_step_2'])) {
                        $config['chapters'] = [];
                        for ($i = 0; $i < $config['chapter_count']; $i++) {
                            $config['chapters'][] = ['name' => $_POST["chapter_name_$i"], 'topic' => $_POST["chapter_topic_$i"], 'tp_count' => (int)$_POST["tp_count_$i"]];
                        }
                        header("Location: ?action=configure_assessment&class_id=$class_id&step=3"); exit;
                    } elseif (isset($_POST['submit_step_3'])) {
                        $config['pg_total'] = (int)$_POST['pg_total'];
                        $config['isian_total'] = (int)$_POST['isian_total'];
                        $config['essay_total'] = (int)$_POST['essay_total'];
                        for ($i = 0; $i < $config['chapter_count']; $i++) {
                            for ($j = 0; $j < $config['chapters'][$i]['tp_count']; $j++) {
                                $config['chapters'][$i]['tps'][$j]['topic'] = $_POST["tp_topic_{$i}_{$j}"];
                            }
                        }
                        $conn->begin_transaction();
                        try {
                            $stmt = $conn->prepare("INSERT INTO assessments (class_id, name, pg_total, isian_total, essay_total) VALUES (?, ?, ?, ?, ?)");
                            $assessment_name = "Asesmen " . htmlspecialchars($class['name']) . " " . date('Y');
                            $stmt->bind_param("isiii", $class_id, $assessment_name, $config['pg_total'], $config['isian_total'], $config['essay_total']);
                            $stmt->execute();
                            $assessment_id = $conn->insert_id;
                            foreach ($config['chapters'] as $i => $chapter) {
                                $stmt_ch = $conn->prepare("INSERT INTO chapters (assessment_id, name, description) VALUES (?, ?, ?)");
                                $stmt_ch->bind_param("iss", $assessment_id, $chapter['name'], $chapter['topic']);
                                $stmt_ch->execute();
                                $chapter_id = $conn->insert_id;
                                foreach ($chapter['tps'] as $j => $tp) {
                                    $tp_name = "TP " . ($i + 1) . "." . ($j + 1);
                                    $stmt_tp = $conn->prepare("INSERT INTO learning_objectives (chapter_id, name, description) VALUES (?, ?, ?)");
                                    $stmt_tp->bind_param("iss", $chapter_id, $tp_name, $tp['topic']);
                                    $stmt_tp->execute();
                                }
                            }
                            $conn->commit();
                            $_SESSION['message'] = "Konfigurasi Asesmen berhasil disimpan!";
                            $_SESSION['message_type'] = "success";
                            unset($_SESSION['assessment_config']);
                            header("Location: ?action=view_class_dashboard&class_id=$class_id");
                            exit;
                        } catch (mysqli_sql_exception $exception) { $conn->rollback(); }
                    }
                }
                ?>
                <div class="mb-6">
                    <a href="?action=view_class_dashboard&class_id=<?php echo $class_id; ?>" class="text-blue-600 hover:text-blue-800">&larr; Kembali ke Dashboard Kelas</a>
                    <h2 class="text-2xl font-bold text-gray-800 mt-2">Konfigurasi Asesmen untuk: <?php echo htmlspecialchars($class['name']); ?></h2>
                    <p class="text-gray-600">KKM: <?php echo $class['kktp']; ?></p>
                </div>
                <div class="mb-8 p-4 bg-gray-50 rounded-xl shadow-inner border border-gray-200">
                    <div class="flex justify-between items-center mb-2">
                        <span class="text-sm font-medium text-gray-700">Langkah <?php echo $step; ?> dari 3</span>
                        <span class="text-sm font-medium text-gray-700"><?php echo ($step == 1) ? 'Jumlah Bab' : (($step == 2) ? 'Detail Bab & TP' : 'Detail TP & Soal'); ?></span>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-2.5">
                        <div class="bg-red-600 h-2.5 rounded-full transition-all duration-300" style="width: <?php echo ($step / 3) * 100; ?>%"></div>
                    </div>
                </div>
                <?php if ($message): ?>
                    <div class="bg-<?php echo ($message_type === 'success') ? 'green' : 'red'; ?>-100 border border-<?php echo ($message_type === 'success') ? 'green' : 'red'; ?>-400 text-<?php echo ($message_type === 'success') ? 'green' : 'red'; ?>-700 px-4 py-3 rounded relative mb-4" role="alert">
                        <span class="block sm:inline"><?php echo htmlspecialchars($message); ?></span>
                    </div>
                <?php endif; ?>
                <?php if ($step == 1): ?>
                    <form method="POST" class="space-y-6">
                        <div class="bg-blue-50 p-6 rounded-xl">
                            <h3 class="text-lg font-bold text-blue-800 mb-4">1. Tentukan Jumlah Bab/Unit</h3>
                            <div>
                                <label for="chapter_count" class="block text-sm font-medium text-gray-700">Berapa jumlah Bab yang akan Anda nilai?</label>
                                <input type="number" id="chapter_count" name="chapter_count" min="1" max="10" value="<?php echo $config['chapter_count'] ?? 2; ?>" required class="mt-1 p-3 block w-full border-gray-300 rounded-md text-xl font-semibold">
                            </div>
                        </div>
                        <div class="flex justify-end">
                            <button type="submit" name="submit_step_1" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-6 rounded-lg">Lanjut ke Langkah 2 &rarr;</button>
                        </div>
                    </form>
                <?php elseif ($step == 2): ?>
                    <form method="POST" class="space-y-6">
                        <div class="bg-yellow-50 p-6 rounded-xl">
                            <h3 class="text-lg font-bold text-yellow-800 mb-4">2. Detail untuk Setiap Bab</h3>
                            <?php for ($i = 0; $i < $config['chapter_count']; $i++): ?>
                                <div class="p-4 bg-white rounded-lg shadow mb-4">
                                    <h4 class="font-bold text-md text-gray-700 mb-3">Bab <?php echo $i + 1; ?></h4>
                                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700">Nama Bab</label>
                                            <input type="text" name="chapter_name_<?php echo $i; ?>" value="<?php echo $config['chapters'][$i]['name'] ?? "Bab " . ($i+1); ?>" required class="mt-1 p-2 block w-full border-gray-300 rounded-md">
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700">Lingkup Materi Bab</label>
                                            <input type="text" name="chapter_topic_<?php echo $i; ?>" value="<?php echo $config['chapters'][$i]['topic'] ?? "Deskripsi Bab " . ($i+1); ?>" required class="mt-1 p-2 block w-full border-gray-300 rounded-md">
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700">Jumlah TP</label>
                                            <input type="number" name="tp_count_<?php echo $i; ?>" value="<?php echo $config['chapters'][$i]['tp_count'] ?? 3; ?>" min="1" max="10" required class="mt-1 p-2 block w-full border-gray-300 rounded-md">
                                        </div>
                                    </div>
                                </div>
                            <?php endfor; ?>
                        </div>
                        <div class="flex justify-between">
                            <a href="?action=configure_assessment&class_id=<?php echo $class_id; ?>&step=1" class="bg-gray-500 hover:bg-gray-600 text-white font-bold py-3 px-6 rounded-lg">&larr; Kembali</a>
                            <button type="submit" name="submit_step_2" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-6 rounded-lg">Lanjut ke Langkah 3 &rarr;</button>
                        </div>
                    </form>
                <?php elseif ($step == 3): ?>
                    <form method="POST" class="space-y-6">
                        <div class="bg-green-50 p-6 rounded-xl">
                            <h3 class="text-lg font-bold text-green-800 mb-4">3a. Masukkan Total Soal Global</h3>
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div><label class="block text-sm font-medium text-gray-700">Total Pilihan Ganda (PG)</label><input type="number" name="pg_total" value="<?php echo $config['pg_total'] ?? 25; ?>" min="0" required class="mt-1 p-2 block w-full border-gray-300 rounded-md"></div>
                                <div><label class="block text-sm font-medium text-gray-700">Total Isian Singkat</label><input type="number" name="isian_total" value="<?php echo $config['isian_total'] ?? 10; ?>" min="0" required class="mt-1 p-2 block w-full border-gray-300 rounded-md"></div>
                                <div><label class="block text-sm font-medium text-gray-700">Total Essay</label><input type="number" name="essay_total" value="<?php echo $config['essay_total'] ?? 5; ?>" min="0" required class="mt-1 p-2 block w-full border-gray-300 rounded-md"></div>
                            </div>
                        </div>
                        <div class="bg-purple-50 p-6 rounded-xl">
                            <h3 class="text-lg font-bold text-purple-800 mb-4">3b. Masukkan Lingkup Materi untuk Setiap TP</h3>
                            <?php foreach ($config['chapters'] as $i => $chapter): ?>
                                <div class="p-4 bg-white rounded-lg shadow mb-4">
                                    <h4 class="font-bold text-md text-purple-700 mb-3"><?php echo htmlspecialchars($chapter['name']); ?></h4>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                        <?php for ($j = 0; $j < $chapter['tp_count']; $j++): ?>
                                            <div>
                                                <label class="block text-sm font-medium text-gray-700">TP <?php echo ($i+1) . "." . ($j+1); ?></label>
                                                <input type="text" name="tp_topic_<?php echo "{$i}_{$j}"; ?>" value="<?php echo $config['chapters'][$i]['tps'][$j]['topic'] ?? "Deskripsi TP " . ($i+1) . "." . ($j+1); ?>" required class="mt-1 p-2 block w-full border-gray-300 rounded-md">
                                            </div>
                                        <?php endfor; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <div class="flex justify-between">
                            <a href="?action=configure_assessment&class_id=<?php echo $class_id; ?>&step=2" class="bg-gray-500 hover:bg-gray-600 text-white font-bold py-3 px-6 rounded-lg">&larr; Kembali</a>
                            <button type="submit" name="submit_step_3" class="bg-green-600 hover:bg-green-700 text-white font-bold py-3 px-6 rounded-lg">Simpan Konfigurasi</button>
                        </div>
                    </form>
                <?php endif; ?>
                <?php
                break;

            case 'grade_student':
                if (isset($_SESSION['is_viewer']) && $_SESSION['is_viewer']) { header("Location: ?"); exit; }
                $student_id = $_GET['student_id'];
                $student = getStudent($conn, $student_id);
                $class_id = $student['class_id'];
                $assessment = getAssessment($conn, $class_id);
                if (!$assessment) {
                    $_SESSION['message'] = "Asesmen untuk kelas ini belum dikonfigurasi.";
                    $_SESSION['message_type'] = "error";
                    header("Location: ?action=view_class_dashboard&class_id=$class_id");
                    exit;
                }
                $assessment_config = ['kktp' => $student['kktp'], 'pg_total' => $assessment['pg_total'], 'isian_total' => $assessment['isian_total'], 'essay_total' => $assessment['essay_total'], 'chapters' => []];
                $stmt_chapters = $conn->prepare("SELECT * FROM chapters WHERE assessment_id = ? ORDER BY id");
                $stmt_chapters->bind_param("i", $assessment['id']);
                $stmt_chapters->execute();
                $chapters_result_set = $stmt_chapters->get_result();
                while($chapter = $chapters_result_set->fetch_assoc()){
                    $stmt_tps = $conn->prepare("SELECT * FROM learning_objectives WHERE chapter_id = ? ORDER BY id");
                    $stmt_tps->bind_param("i", $chapter['id']);
                    $stmt_tps->execute();
                    $tps_result_set = $stmt_tps->get_result();
                    $chapter['tps'] = $tps_result_set->fetch_all(MYSQLI_ASSOC);
                    $assessment_config['chapters'][] = $chapter;
                    $stmt_tps->close();
                }
                $stmt_chapters->close();
                if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_grades'])) {
                    $student_answers = ['pg_correct' => (int)$_POST['pg_benar'], 'isian_correct' => (int)$_POST['isian_benar'], 'essay_correct' => (int)$_POST['essay_benar']];
                    $slm_scores = $_POST['slm_scores'];
                    $chapters_with_scores = [];
                    $nilai_rapor_akhir = calculateFinalScores($assessment_config, $student_answers, $slm_scores, $chapters_with_scores);
                    $conn->query("DELETE FROM student_global_answers WHERE student_id = $student_id AND assessment_id = " . $assessment['id']);
                    $stmt = $conn->prepare("INSERT INTO student_global_answers (student_id, assessment_id, pg_correct, isian_correct, essay_correct) VALUES (?, ?, ?, ?, ?)");
                    $stmt->bind_param("iiiii", $student_id, $assessment['id'], $student_answers['pg_correct'], $student_answers['isian_correct'], $student_answers['essay_correct']);
                    $stmt->execute();
                    foreach($chapters_with_scores as $chapter_id => $chapter_data) {
                        $slm_score = $slm_scores[$chapter_id];
                        $final_score = $chapter_data['final_score'];
                        $status = $chapter_data['status'];
                        $stmt = $conn->prepare("INSERT INTO student_scores (student_id, chapter_id, slm_score, final_score, status) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE slm_score=VALUES(slm_score), final_score=VALUES(final_score), status=VALUES(status)");
                        $stmt->bind_param("iidss", $student_id, $chapter_id, $slm_score, $final_score, $status);
                        $stmt->execute();
                        $student_score_id = $conn->insert_id ?: $conn->query("SELECT id FROM student_scores WHERE student_id=$student_id AND chapter_id=$chapter_id")->fetch_assoc()['id'];
                        foreach($chapter_data['tps'] as $tp){
                            $stmt = $conn->prepare("INSERT INTO tp_scores (student_score_id, learning_objective_id, score) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE score=VALUES(score)");
                            $stmt->bind_param("iid", $student_score_id, $tp['id'], $tp['score_100']);
                            $stmt->execute();
                        }
                    }
                    $_SESSION['message'] = "Nilai berhasil disimpan!";
                    $_SESSION['message_type'] = "success";
                    header("Location: ?action=grade_student&student_id=$student_id");
                    exit;
                }
                ?>
                <div class="mb-6">
                    <a href="?action=view_class_dashboard&class_id=<?php echo $class_id; ?>" class="text-blue-600 hover:text-blue-800">&larr; Kembali ke Dashboard Kelas</a>
                    <h2 class="text-2xl font-bold text-gray-800 mb-2">Input Nilai untuk: <?php echo htmlspecialchars($student['name']); ?></h2>
                    <p class="text-gray-600 mb-6">Kelas: <?php echo htmlspecialchars($student['class_name']); ?> | KKM: <?php echo $student['kktp']; ?></p>
                </div>
                <form method="POST" class="space-y-8">
                    <div class="space-y-4 bg-green-50 p-6 rounded-xl border-l-4 border-green-500">
                        <p class="text-xl font-bold text-green-800 mb-4">1. Input Jawaban Benar Siswa (Tes Global)</p>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div><label>PG Benar (Max <?php echo $assessment['pg_total']; ?>)</label><input type="number" name="pg_benar" min="0" max="<?php echo $assessment['pg_total']; ?>" required class="p-2 w-full border rounded"></div>
                            <div><label>Isian Benar (Max <?php echo $assessment['isian_total']; ?>)</label><input type="number" name="isian_benar" min="0" max="<?php echo $assessment['isian_total']; ?>" required class="p-2 w-full border rounded"></div>
                            <div><label>Essay Benar (Max <?php echo $assessment['essay_total']; ?>)</label><input type="number" name="essay_benar" min="0" max="<?php echo $assessment['essay_total']; ?>" required class="p-2 w-full border rounded"></div>
                        </div>
                    </div>
                    <div class="space-y-4 bg-purple-50 p-6 rounded-xl border-l-4 border-purple-500">
                        <p class="text-xl font-bold text-purple-800 mb-4">2. Input Nilai SLM/UH per Bab</p>
                        <?php foreach($assessment_config['chapters'] as $chapter): ?>
                            <div class="flex items-center gap-4">
                                <label for="slm_<?php echo $chapter['id']; ?>" class="flex-1">Nilai SLM <?php echo htmlspecialchars($chapter['name']); ?>:</label>
                                <input type="number" name="slm_scores[<?php echo $chapter['id']; ?>]" id="slm_<?php echo $chapter['id']; ?>" min="0" max="100" required class="p-2 w-32 border rounded">
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <button type="submit" name="submit_grades" class="w-full bg-red-600 hover:bg-red-700 text-white font-bold py-4 rounded-lg text-lg">Hitung & Simpan Nilai</button>
                </form>
                <?php
                break;

            case 'generate_sample_scores':
                if (isset($_SESSION['is_viewer']) && $_SESSION['is_viewer']) { header("Location: ?"); exit; }
                $class_id = $_GET['class_id'];
                $class = getClass($conn, $class_id);
                $assessment = getAssessment($conn, $class_id);
                $assessment_config = ['kktp' => $class['kktp'], 'pg_total' => $assessment['pg_total'], 'isian_total' => $assessment['isian_total'], 'essay_total' => $assessment['essay_total'], 'chapters' => []];
                $stmt_chapters = $conn->prepare("SELECT * FROM chapters WHERE assessment_id = ? ORDER BY id");
                $stmt_chapters->bind_param("i", $assessment['id']);
                $stmt_chapters->execute();
                $chapters_result_set = $stmt_chapters->get_result();
                while($chapter = $chapters_result_set->fetch_assoc()){
                    $stmt_tps = $conn->prepare("SELECT * FROM learning_objectives WHERE chapter_id = ? ORDER BY id");
                    $stmt_tps->bind_param("i", $chapter['id']);
                    $stmt_tps->execute();
                    $tps_result_set = $stmt_tps->get_result();
                    $chapter['tps'] = $tps_result_set->fetch_all(MYSQLI_ASSOC);
                    $assessment_config['chapters'][] = $chapter;
                    $stmt_tps->close();
                }
                $stmt_chapters->close();
                $students_result = $conn->prepare("SELECT id FROM students WHERE class_id = ?");
                $students_result->bind_param("i", $class_id);
                $students_result->execute();
                $students = $students_result->get_result();
                $conn->begin_transaction();
                try {
                    while($student_row = $students->fetch_assoc()){
                        $student_id = $student_row['id'];
                        $student_answers = ['pg_correct' => rand(0, $assessment['pg_total']), 'isian_correct' => rand(0, $assessment['isian_total']), 'essay_correct' => rand(0, $assessment['essay_total'])];
                        $slm_scores = [];
                        foreach($assessment_config['chapters'] as $chapter) {
                            $slm_scores[$chapter['id']] = rand(65, 100);
                        }
                        $chapters_with_scores = [];
                        $nilai_rapor_akhir = calculateFinalScores($assessment_config, $student_answers, $slm_scores, $chapters_with_scores);
                        $conn->query("DELETE FROM student_global_answers WHERE student_id = $student_id AND assessment_id = " . $assessment['id']);
                        $stmt = $conn->prepare("INSERT INTO student_global_answers (student_id, assessment_id, pg_correct, isian_correct, essay_correct) VALUES (?, ?, ?, ?, ?)");
                        $stmt->bind_param("iiiii", $student_id, $assessment['id'], $student_answers['pg_correct'], $student_answers['isian_correct'], $student_answers['essay_correct']);
                        $stmt->execute();
                        foreach($chapters_with_scores as $chapter_id => $chapter_data) {
                            $slm_score = $slm_scores[$chapter_id];
                            $final_score = $chapter_data['final_score'];
                            $status = $chapter_data['status'];
                            $stmt = $conn->prepare("INSERT INTO student_scores (student_id, chapter_id, slm_score, final_score, status) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE slm_score=VALUES(slm_score), final_score=VALUES(final_score), status=VALUES(status)");
                            $stmt->bind_param("iidss", $student_id, $chapter_id, $slm_score, $final_score, $status);
                            $stmt->execute();
                            $student_score_id = $conn->insert_id ?: $conn->query("SELECT id FROM student_scores WHERE student_id=$student_id AND chapter_id=$chapter_id")->fetch_assoc()['id'];
                            foreach($chapter_data['tps'] as $tp){
                                $stmt = $conn->prepare("INSERT INTO tp_scores (student_score_id, learning_objective_id, score) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE score=VALUES(score)");
                                $stmt->bind_param("iid", $student_score_id, $tp['id'], $tp['score_100']);
                                $stmt->execute();
                            }
                        }
                    }
                    $conn->commit();
                    $_SESSION['message'] = "Data acak untuk semua siswa berhasil dibuat!";
                    $_SESSION['message_type'] = "success";
                } catch (Exception $e) { $conn->rollback(); }
                header("Location: ?action=view_class_scores&class_id=$class_id");
                exit;
                break;

            case 'view_class_scores':
                $class_id = $_GET['class_id'];
                $class = getClass($conn, $class_id);
                $assessment = getAssessment($conn, $class_id);
                if (!$assessment) {
                    $_SESSION['message'] = "Asesmen untuk kelas ini belum dikonfigurasi.";
                    $_SESSION['message_type'] = "error";
                    header("Location: ?action=view_class_dashboard&class_id=$class_id");
                    exit;
                }
                $all_classes_result = $conn->prepare("SELECT id, name FROM classes WHERE school_id = ? ORDER BY name");
                $all_classes_result->bind_param("i", $class['school_id']);
                $all_classes_result->execute();
                $all_classes = $all_classes_result->get_result()->fetch_all(MYSQLI_ASSOC);
                $students_result = $conn->prepare("SELECT id, name, student_number FROM students WHERE class_id = ? ORDER BY name");
                $students_result->bind_param("i", $class_id);
                $students_result->execute();
                $students = $students_result->get_result()->fetch_all(MYSQLI_ASSOC);
                $chapters_tps = [];
                $stmt_ch = $conn->prepare("SELECT id, name FROM chapters WHERE assessment_id = ? ORDER BY id");
                $stmt_ch->bind_param("i", $assessment['id']);
                $stmt_ch->execute();
                $chapters_result = $stmt_ch->get_result();
                while($chapter = $chapters_result->fetch_assoc()){
                    $stmt_tp = $conn->prepare("SELECT id, name FROM learning_objectives WHERE chapter_id = ? ORDER BY id");
                    $stmt_tp->bind_param("i", $chapter['id']);
                    $stmt_tp->execute();
                    $chapter['tps'] = $stmt_tp->get_result()->fetch_all(MYSQLI_ASSOC);
                    $chapters_tps[] = $chapter;
                }
                $all_scores = [];
                if(!empty($students)) {
                    $student_ids = array_column($students, 'id');
                    $student_ids_str = implode(',', $student_ids);
                    $chapter_scores_res = $conn->query("SELECT student_id, chapter_id, final_score, slm_score FROM student_scores WHERE student_id IN ($student_ids_str)");
                    while($row = $chapter_scores_res->fetch_assoc()){
                        $all_scores['chapter'][$row['student_id']][$row['chapter_id']] = $row['final_score'];
                        $all_scores['slm'][$row['student_id']][$row['chapter_id']] = $row['slm_score'];
                    }
                    $tp_scores_res = $conn->query("SELECT tps.score, lo.id as tp_id, ss.student_id FROM tp_scores tps JOIN learning_objectives lo ON tps.learning_objective_id = lo.id JOIN student_scores ss ON tps.student_score_id = ss.id WHERE ss.student_id IN ($student_ids_str)");
                    while($row = $tp_scores_res->fetch_assoc()){
                        $all_scores['tp'][$row['student_id']][$row['tp_id']] = $row['score'];
                    }
                }
                $total_tp_count = 0; foreach ($chapters_tps as $chapter) { $total_tp_count += count($chapter['tps']); }
                $total_chapter_count = count($chapters_tps);
                $colspan_value = 1 + $total_tp_count + $total_chapter_count + 1 + 1 + 1;
                $selected_student_id = $_GET['student_id'] ?? null;
                $selected_student_details = null;
                if ($selected_student_id) {
                    $stmt_student = $conn->prepare("SELECT name FROM students WHERE id = ?");
                    $stmt_student->bind_param("i", $selected_student_id);
                    $stmt_student->execute();
                    $selected_student_details['name'] = $stmt_student->get_result()->fetch_assoc()['name'];
                    $stmt_global = $conn->prepare("SELECT pg_correct, isian_correct, essay_correct FROM student_global_answers WHERE student_id = ? AND assessment_id = ?");
                    $stmt_global->bind_param("ii", $selected_student_id, $assessment['id']);
                    $stmt_global->execute();
                    $selected_student_details['global_answers'] = $stmt_global->get_result()->fetch_assoc();
                    $stmt_lm_desc = $conn->prepare("SELECT c.name, c.description FROM chapters c WHERE c.assessment_id = ? ORDER BY c.id");
                    $stmt_lm_desc->bind_param("i", $assessment['id']);
                    $stmt_lm_desc->execute();
                    $selected_student_details['lm_descriptions'] = $stmt_lm_desc->get_result()->fetch_all(MYSQLI_ASSOC);
                    $stmt_tp_desc = $conn->prepare("SELECT lo.name, lo.description FROM learning_objectives lo JOIN chapters c ON lo.chapter_id = c.id WHERE c.assessment_id = ? ORDER BY c.id, lo.id");
                    $stmt_tp_desc->bind_param("i", $assessment['id']);
                    $stmt_tp_desc->execute();
                    $selected_student_details['tp_descriptions'] = $stmt_tp_desc->get_result()->fetch_all(MYSQLI_ASSOC);
                }
                ?>
                <div class="mb-6">
                    <?php if (isset($_SESSION['is_viewer']) && $_SESSION['is_viewer']): ?>
                        <a href="?action=viewer_exit_to_admin" class="text-red-600 hover:text-red-800 font-semibold">&larr; Keluar ke Mode Admin</a>
                        <h2 class="text-2xl font-bold text-gray-800 mt-2">Laporan Nilai: <?php echo htmlspecialchars($class['name']); ?></h2>
                        <p class="text-gray-600">Mode Viewer (Read-Only) | KKM: <?php echo $class['kktp']; ?></p>
                    <?php else: ?>
                        <a href="?action=view_class_dashboard&class_id=<?php echo $class_id; ?>" class="text-blue-600 hover:text-blue-800">&larr; Kembali ke Dashboard Kelas</a>
                        <h2 class="text-2xl font-bold text-gray-800 mt-2">Rekapitulasi Nilai Kelas: <?php echo htmlspecialchars($class['name']); ?></h2>
                        <p class="text-gray-600">KKM: <?php echo $class['kktp']; ?></p>
                    <?php endif; ?>
                </div>
                <div class="mb-6 p-4 bg-gray-50 rounded-lg border no-print">
                    <form method="GET" action="" class="flex items-center gap-4">
                        <input type="hidden" name="action" value="view_class_scores">
                        <label for="class_filter" class="font-semibold text-gray-700">Pindah ke Kelas:</label>
                        <select name="class_id" id="class_filter" onchange="this.form.submit()" class="p-2 border border-gray-300 rounded-md">
                            <?php foreach($all_classes as $c): ?>
                                <option value="<?php echo $c['id']; ?>" <?php echo ($c['id'] == $class_id) ? 'selected' : ''; ?>><?php echo htmlspecialchars($c['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </form>
                </div>
                <div class="flex justify-end mb-6 no-print">
                    <button onclick="window.print()" class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg transition">🖨️ Cetak Laporan</button>
                </div>
                <div class="overflow-x-auto shadow-lg rounded-lg border border-gray-200">
                    <table class="min-w-full divide-y divide-gray-200 text-xs table-print">
                        <thead class="bg-gray-50 sticky top-0">
                            <tr>
                                <th rowspan="2" class="px-2 py-2 text-left font-medium text-gray-500 uppercase">Nama Siswa</th>
                                <?php foreach($chapters_tps as $chapter): ?>
                                    <th colspan="<?php echo count($chapter['tps']); ?>" class="px-2 py-2 text-center font-medium text-gray-700 uppercase border-l"><?php echo htmlspecialchars($chapter['name']); ?></th>
                                <?php endforeach; ?>
                                <th colspan="<?php echo count($chapters_tps); ?>" class="px-2 py-2 text-center font-medium text-blue-700 uppercase border-l bg-blue-100">Nilai LM (Inputan Guru)</th>
                                <th rowspan="2" class="px-2 py-2 text-center font-bold text-red-700 uppercase border-l">Nilai Akhir</th>
                                <th rowspan="2" class="px-2 py-2 text-center font-medium text-gray-500 uppercase">Status</th>
                                <th rowspan="2" class="px-2 py-2 text-center font-medium text-gray-500 uppercase border-l">Aksi</th>
                            </tr>
                            <tr>
                                <?php foreach($chapters_tps as $chapter): ?>
                                    <?php foreach($chapter['tps'] as $tp): ?>
                                        <th class="px-1 py-1 text-center font-medium text-gray-600 uppercase border-l border-t" title="<?php echo htmlspecialchars($tp['name']); ?>"><?php $tp_name_parts = explode(' ', $tp['name']); echo end($tp_name_parts); ?></th>
                                    <?php endforeach; ?>
                                <?php endforeach; ?>
                                <?php $lm_counter = 0; foreach($chapters_tps as $chapter): $lm_counter++; ?>
                                    <th class="px-2 py-1 text-center font-medium text-blue-600 uppercase border-l border-t bg-blue-50">LM <?php echo $lm_counter; ?></th>
                                <?php endforeach; ?>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php if(empty($students)): ?>
                                <tr><td colspan="<?php echo $colspan_value; ?>" class="px-6 py-4 text-center text-gray-500">Tidak ada siswa di kelas ini.</td></tr>
                            <?php else: ?>
                                <?php foreach($students as $student): ?>
                                    <?php
                                    $final_average = 0;
                                    $chapter_finals = $all_scores['chapter'][$student['id']] ?? [];
                                    if(!empty($chapter_finals)){
                                        $final_average = array_sum($chapter_finals) / count($chapter_finals);
                                    }
                                    $status = ($final_average >= $class['kktp']) ? 'KOMPETEN' : 'BELUM KOMPETEN';
                                    ?>
                                    <tr class="hover:bg-gray-50 <?php echo ($selected_student_id == $student['id']) ? 'bg-indigo-50' : ''; ?>">
                                        <td class="px-2 py-2 font-medium text-gray-900" title="<?php echo htmlspecialchars($student['student_number']); ?>"><?php echo htmlspecialchars($student['name']); ?></td>
                                        <?php foreach($chapters_tps as $chapter): ?>
                                            <?php foreach($chapter['tps'] as $tp): ?>
                                                <td class="px-1 py-1 text-center border-l"><?php echo isset($all_scores['tp'][$student['id']][$tp['id']]) ? number_format($all_scores['tp'][$student['id']][$tp['id']], 1) : '-'; ?></td>
                                            <?php endforeach; ?>
                                        <?php endforeach; ?>
                                        <?php foreach($chapters_tps as $chapter): ?>
                                            <td class="px-2 py-1 text-center font-semibold text-blue-700 border-l"><?php echo isset($all_scores['slm'][$student['id']][$chapter['id']]) ? number_format($all_scores['slm'][$student['id']][$chapter['id']], 2) : '-'; ?></td>
                                        <?php endforeach; ?>
                                        <td class="px-2 py-2 text-center font-bold text-red-900 border-l"><?php echo ($final_average > 0) ? number_format($final_average, 2) : '-'; ?></td>
                                        <td class="px-2 py-2 text-center border-l">
                                            <?php if($final_average > 0): ?>
                                                <span class="px-1 py-0.5 inline-flex text-xs leading-4 font-semibold rounded-full <?php echo ($status === 'KOMPETEN') ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>"><?php echo $status; ?></span>
                                            <?php else: ?>
                                                <span class="px-1 py-0.5 inline-flex text-xs leading-4 font-semibold rounded-full bg-gray-100 text-gray-800">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="px-2 py-2 text-center border-l">
                                            <?php if($selected_student_id == $student['id']): ?>
                                                <a href="?action=view_class_scores&class_id=<?php echo $class_id; ?>" class="text-gray-500 hover:text-gray-700 font-semibold">Tutup</a>
                                            <?php else: ?>
                                                <a href="?action=view_class_scores&class_id=<?php echo $class_id; ?>&student_id=<?php echo $student['id']; ?>" class="text-indigo-600 hover:text-indigo-900 font-semibold">Detail</a>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <?php if ($selected_student_id && $selected_student_details['name']): ?>
                    <div class="mt-8 p-6 bg-blue-50 rounded-xl border border-blue-200 shadow-md no-print">
                        <div class="flex justify-between items-center mb-4">
                            <h3 class="text-lg font-bold text-blue-800">Deskripsi Materi Asesmen: <?php echo htmlspecialchars($selected_student_details['name']); ?></h3>
                            <a href="?action=view_class_scores&class_id=<?php echo $class_id; ?>" class="text-gray-600 hover:text-gray-800 text-sm font-semibold">Tutup Detail</a>
                        </div>
                        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                            <div class="bg-white p-4 rounded-lg shadow">
                                <h4 class="font-semibold text-gray-700 mb-2 border-b pb-1">Jawaban Tes Global (SAS)</h4>
                                <?php if ($selected_student_details['global_answers']): ?>
                                    <ul class="text-sm text-gray-600 space-y-1">
                                        <li>PG Benar: <span class="font-bold"><?php echo $selected_student_details['global_answers']['pg_correct']; ?></span> dari <?php echo $assessment['pg_total']; ?></li>
                                        <li>Isian Benar: <span class="font-bold"><?php echo $selected_student_details['global_answers']['isian_correct']; ?></span> dari <?php echo $assessment['isian_total']; ?></li>
                                        <li>Essay Benar: <span class="font-bold"><?php echo $selected_student_details['global_answers']['essay_correct']; ?></span> dari <?php echo $assessment['essay_total']; ?></li>
                                    </ul>
                                <?php else: ?>
                                    <p class="text-sm text-gray-500 italic">Belum ada data jawaban tes global.</p>
                                <?php endif; ?>
                            </div>
                            <div class="bg-white p-4 rounded-lg shadow lg:col-span-2">
                                <h4 class="font-semibold text-gray-700 mb-2 border-b pb-1">Deskripsi Lingkup Materi (LM)</h4>
                                <?php if ($selected_student_details['lm_descriptions']): ?>
                                    <ul class="text-sm text-gray-600 space-y-2">
                                        <?php foreach ($selected_student_details['lm_descriptions'] as $lm): ?>
                                            <li>
                                                <span class="font-semibold text-blue-700"><?php echo htmlspecialchars($lm['name']); ?>:</span>
                                                <p class="text-gray-500 mt-1"><?php echo htmlspecialchars($lm['description']); ?></p>
                                            </li>
                                        <?php endforeach; ?>
                                    </ul>
                                <?php else: ?>
                                    <p class="text-sm text-gray-500 italic">Belum ada deskripsi LM.</p>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="bg-white p-4 rounded-lg shadow mt-6">
                            <h4 class="font-semibold text-gray-700 mb-2 border-b pb-1">Deskripsi Tujuan Pembelajaran (TP)</h4>
                            <?php if ($selected_student_details['tp_descriptions']): ?>
                                <ul class="text-sm text-gray-600 space-y-2">
                                    <?php foreach ($selected_student_details['tp_descriptions'] as $tp): ?>
                                        <li>
                                            <span class="font-semibold text-indigo-700"><?php echo htmlspecialchars($tp['name']); ?>:</span>
                                            <p class="text-gray-500 mt-1"><?php echo htmlspecialchars($tp['description']); ?></p>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            <?php else: ?>
                                <p class="text-sm text-gray-500 italic">Belum ada deskripsi TP.</p>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>
                <?php
                break;
        }
        ?>
    </div>
</body>
</html>