<?php
session_start();

// Include file yang diperlukan
require_once 'config.php';
require_once 'functions.php';

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

// --- PROSES POST REQUEST ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Proses Tambah Sekolah
    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: index.php");
        exit;
    }

    // Proses Tambah Kelas
    if (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: index.php?action=view_class&school_id=" . $_POST['school_id']);
        exit;
    }

    // Proses Tambah Siswa
    if (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: index.php?action=view_class_dashboard&class_id=" . $_POST['class_id']);
        exit;
    }

    // Proses Login Viewer
    if (isset($_POST['viewer_key'])) {
        $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: index.php");
            exit;
        } else {
            $_SESSION['message'] = "Kunci Viewer salah. Akses ditolak.";
            $_SESSION['message_type'] = "error";
            header("Location: index.php?action=viewer_login_form");
            exit;
        }
    }

    // Proses Keluar ke Admin
    if (isset($_POST['admin_key'])) {
        $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: index.php");
            exit;
        } else {
            $_SESSION['message'] = "Kunci Admin salah. Anda tetap di Mode Viewer.";
            $_SESSION['message_type'] = "error";
            header("Location: index.php?action=viewer_exit_to_admin");
            exit;
        }
    }

    // Proses Konfigurasi Asesmen (Multi-step)
    if (isset($_POST['submit_step_1'])) {
        $_SESSION['assessment_config']['chapter_count'] = (int)$_POST['chapter_count'];
        $class_id = $_GET['class_id'];
        header("Location: index.php?action=configure_assessment&class_id={$class_id}&step=2");
        exit;
    }
    if (isset($_POST['submit_step_2'])) {
        $config = &$_SESSION['assessment_config'];
        $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"]];
        }
        $class_id = $_GET['class_id'];
        header("Location: index.php?action=configure_assessment&class_id={$class_id}&step=3");
        exit;
    }
    if (isset($_POST['submit_step_3'])) {
        $class_id = $_GET['class_id'];
        $class = getClass($conn, $class_id);
        if (!$class) {
            $_SESSION['message'] = "Kelas tidak ditemukan saat menyimpan konfigurasi.";
            $_SESSION['message_type'] = "error";
            header("Location: index.php");
            exit;
        }
        $config = &$_SESSION['assessment_config'];
        $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_db = $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_db, $tp_name, $tp['topic']);
                    $stmt_tp->execute();
                }
            }
            $conn->commit();
            $_SESSION['message'] = "Konfigurasi Asesmen berhasil disimpan!";
            $_SESSION['message_type'] = "success";
            unset($_SESSION['assessment_config']);
        } catch (mysqli_sql_exception $exception) { 
            $conn->rollback(); 
            $_SESSION['message'] = "Gagal menyimpan konfigurasi: " . $exception->getMessage();
            $_SESSION['message_type'] = "error";
        }
        header("Location: index.php?action=view_class_dashboard&class_id=$class_id");
        exit;
    }

    // Proses Input Nilai Siswa (BLOK YANG BENAR DAN LENGKAP)
    if (isset($_POST['submit_grades'])) {
    // --- PERBAIKAN AKHIR: Ambil student_id dari URL (GET) ---
    $student_id = $_GET['student_id'] ?? null;
    if (!$student_id || !filter_var($student_id, FILTER_VALIDATE_INT, ["options" => ["min_range" => 1]])) {
        $_SESSION['message'] = "ID Siswa tidak valid saat menyimpan nilai.";
        $_SESSION['message_type'] = "error";
        header("Location: index.php");
        exit;
    }
    // ------------------------------------------------------------
    
    $student = getStudent($conn, $student_id);
    if (!$student) {
        $_SESSION['message'] = "Siswa tidak ditemukan saat menyimpan nilai.";
        $_SESSION['message_type'] = "error";
        header("Location: index.php");
        exit;
    }
   
        if (!$student) {
            $_SESSION['message'] = "Siswa tidak ditemukan saat menyimpan nilai.";
            $_SESSION['message_type'] = "error";
            header("Location: index.php");
            exit;
        }
        $class_id = $student['class_id'];
        $assessment = getAssessment($conn, $class_id);
        $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();

        $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->begin_transaction();
        try {
            $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'] = "Nilai berhasil disimpan!";
            $_SESSION['message_type'] = "success";
        } catch (Exception $e) { $conn->rollback(); $_SESSION['message'] = "Gagal menyimpan nilai."; $_SESSION['message_type'] = "error"; }
        
        header("Location: index.php?action=grade_student&student_id=$student_id");
        exit;
    }
}


// --- ROUTER ---
switch ($action) {
    case 'list_schools':
        if (isset($_SESSION['is_viewer']) && $_SESSION['is_viewer']) {
            $first_school_with_class = $conn->query("SELECT s.id FROM schools s JOIN classes c ON s.id = c.school_id LIMIT 1")->fetch_assoc();
            if ($first_school_with_class) {
                header("Location: index.php?action=view_class&school_id=" . $first_school_with_class['id']);
                exit;
            } else {
                include 'views/viewer_no_classes.php';
                break;
            }
        }
        $schools = $conn->query("SELECT * FROM schools ORDER BY name");
        include 'views/list_schools.php';
        break;

    case 'viewer_login_form':
        include 'views/viewer_login_form.php';
        break;

    case 'viewer_exit_to_admin':
        if (!isset($_SESSION['is_viewer']) || !$_SESSION['is_viewer']) { header("Location: index.php"); exit; }
        include 'views/viewer_exit_to_admin.php';
        break;

    case 'viewer_logout':
        unset($_SESSION['is_viewer']);
        $_SESSION['message'] = "Anda telah keluar dari Mode Viewer.";
        $_SESSION['message_type'] = "info";
        header("Location: index.php");
        exit;
        break;

    case 'add_school_form':
        if (isset($_SESSION['is_viewer']) && $_SESSION['is_viewer']) { header("Location: index.php"); exit; }
        include 'views/add_school_form.php';
        break;

    case 'view_class':
        $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();
        include 'views/view_class.php';
        break;
            
    case 'add_class_form':
        if (isset($_SESSION['is_viewer']) && $_SESSION['is_viewer']) { header("Location: index.php"); exit; }
        $school_id = $_GET['school_id'];
        $school = getSchool($conn, $school_id);
        include 'views/add_class_form.php';
        break;

    case 'view_class_dashboard':
        if (isset($_SESSION['is_viewer']) && $_SESSION['is_viewer']) { header("Location: index.php"); exit; }
        $class_id = $_GET['class_id'];
        $class = getClass($conn, $class_id);
        if (!$class) {
            $_SESSION['message'] = "Kelas tidak ditemukan.";
            $_SESSION['message_type'] = "error";
            header("Location: index.php");
            exit;
        }
        $school = getSchool($conn, $class['school_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();
        include 'views/view_class_dashboard.php';
        break;
            
    case 'add_student_form':
        if (isset($_SESSION['is_viewer']) && $_SESSION['is_viewer']) { header("Location: index.php"); exit; }
        $class_id = $_GET['class_id'];
        $class = getClass($conn, $class_id);
        if (!$class) {
            $_SESSION['message'] = "Kelas tidak ditemukan.";
            $_SESSION['message_type'] = "error";
            header("Location: index.php");
            exit;
        }
        $school = getSchool($conn, $class['school_id']);
        include 'views/add_student_form.php';
        break;

    case 'configure_assessment':
        if (isset($_SESSION['is_viewer']) && $_SESSION['is_viewer']) { header("Location: index.php"); exit; }
        $class_id = $_GET['class_id'];
        $class = getClass($conn, $class_id);
        if (!$class) {
            $_SESSION['message'] = "Kelas tidak ditemukan.";
            $_SESSION['message_type'] = "error";
            header("Location: index.php");
            exit;
        }
        $school = getSchool($conn, $class['school_id']);
        if (!$school) {
            $_SESSION['message'] = "Sekolah untuk kelas ini tidak ditemukan. Ada masalah integritas data.";
            $_SESSION['message_type'] = "error";
            header("Location: index.php");
            exit;
        }
        $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'];
        include 'views/configure_assessment.php';
        break;

    case 'grade_student':
        if (isset($_SESSION['is_viewer']) && $_SESSION['is_viewer']) { header("Location: index.php"); exit; }
        $student_id = $_GET['student_id'] ?? null;
        if (!$student_id || !filter_var($student_id, FILTER_VALIDATE_INT, ["options" => ["min_range" => 1]])) {
            $_SESSION['message'] = "ID Siswa tidak valid.";
            $_SESSION['message_type'] = "error";
            header("Location: index.php");
            exit;
        }
        $student = getStudent($conn, $student_id);
        if (!$student) {
            $_SESSION['message'] = "Siswa dengan ID tersebut tidak ditemukan di database.";
            $_SESSION['message_type'] = "error";
            header("Location: index.php");
            exit;
        }
        $class_id = $student['class_id'];
        $class = getClass($conn, $class_id);
        $school = getSchool($conn, $class['school_id']);
        $assessment = getAssessment($conn, $class_id);
        if (!$assessment) {
            $_SESSION['message'] = "Asesmen untuk kelas ini belum dikonfigurasi.";
            $_SESSION['message_type'] = "error";
            header("Location: index.php?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();
        include 'views/grade_student.php';
        break;

    case 'generate_sample_scores':
        if (isset($_SESSION['is_viewer']) && $_SESSION['is_viewer']) { header("Location: index.php"); exit; }
        $class_id = $_GET['class_id'];
        $class = getClass($conn, $class_id);
        if(!$class){
            $_SESSION['message'] = "Kelas tidak ditemukan.";
            $_SESSION['message_type'] = "error";
            header("Location: index.php");
            exit;
        }
        $assessment = getAssessment($conn, $class_id);
        if (!$assessment) {
            $_SESSION['message'] = "Asesmen untuk kelas ini belum dikonfigurasi.";
            $_SESSION['message_type'] = "error";
            header("Location: index.php?action=view_class_dashboard&class_id=$class_id");
            exit;
        }
        $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(); 
            $_SESSION['message'] = "Gagal membuat data acak: " . $e->getMessage();
            $_SESSION['message_type'] = "error";
        }
        header("Location: index.php?action=view_class_scores&class_id=$class_id");
        exit;
        break;

    case 'view_class_scores':
        $class_id = $_GET['class_id'];
        $class = getClass($conn, $class_id);
        if(!$class){
            $_SESSION['message'] = "Kelas tidak ditemukan.";
            $_SESSION['message_type'] = "error";
            header("Location: index.php");
            exit;
        }
        $school = getSchool($conn, $class['school_id']);
        $assessment = getAssessment($conn, $class_id);
        if (!$assessment) {
            $_SESSION['message'] = "Asesmen untuk kelas ini belum dikonfigurasi.";
            $_SESSION['message_type'] = "error";
            header("Location: index.php?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);
        }
        include 'views/view_class_scores.php';
        break;

    default:
        http_response_code(404);
        include 'views/header.php';
        echo '<h1 class="text-4xl text-center">Halaman Tidak Ditemukan</h1>';
        include 'views/footer.php';
        break;
}