<?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; }
</style>';

// --- KONFIGURASI DATABASE ---
 $db_host = 'localhost';
 $db_user = 'root';
 $db_pass = '';
 $db_name = '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 = '';
 $message_type = 'info'; // info, success, error

// --- 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) {
    // PERBAIKAN: Mengubah 'cl.kktp' menjadi 'c.kktp'
    $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()) {
            $message = "Sekolah berhasil ditambahkan!";
            $message_type = "success";
        } else {
            $message = "Gagal menambahkan sekolah.";
            $message_type = "error";
        }
    } 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()) {
            $message = "Kelas berhasil ditambahkan!";
            $message_type = "success";
        } else {
            $message = "Gagal menambahkan kelas.";
            $message_type = "error";
        }
    } 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()) {
            $message = "Siswa berhasil ditambahkan!";
            $message_type = "success";
        } else {
            $message = "Gagal menambahkan siswa. Mungkin NIS sudah ada.";
            $message_type = "error";
        }
    }
    // Proses lainnya (konfigurasi, penilaian) akan ada di bagian bawah
}

// --- ALGORITMA PERHITUNGAN (SAMA SEPERTI SEBELUMNYA) ---
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 ---
?>
<!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-6xl 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 UNTUK MENAMPILKAN HALAMAN ---
        switch ($action) {
            case 'list_schools':
                $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>
                    <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 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 'add_school_form':
                ?>
                <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':
                $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>
                    <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>
                </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_dashboard&class_id=<?php echo $class['id']; ?>" class="text-indigo-600 hover:text-indigo-900">Kelola</a>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
                <?php
                break;
            
            case 'add_class_form':
                $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':
                $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>

                <!-- Manajemen Siswa -->
                <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>

                <!-- Konfigurasi Asesmen -->
                <div class="bg-yellow-50 p-6 rounded-xl">
                    <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>
                <?php
                break;
            
            case 'add_student_form':
                $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':
                $class_id = $_GET['class_id'];
                $class = getClass($conn, $class_id);
                $assessment = getAssessment($conn, $class_id); // Cek apakah sudah ada

                // Jika sudah ada, arahkan ke mode edit (untuk saat ini, kita akan buat yang baru)
                // Di masa depan, Anda bisa mengembangkan logika edit di sini.
                if ($assessment) {
                    // Opsi 1: Tampilkan error
                    // $message = "Asesmen untuk kelas ini sudah ada. Silakan edit atau hapus terlebih dahulu.";
                    // $message_type = "error";
                    // header("Location: ?action=view_class_dashboard&class_id=$class_id");
                    // exit;

                    // Opsi 2: Hapus yang lama dan buat baru (lebih sederhana untuk sekarang)
                    $conn->begin_transaction();
                    try {
                        // Hapus data lama secara bertahap untuk menjaga integritas referential
                        $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();
                        $message = "Gagal menghapus konfigurasi lama: " . $e->getMessage();
                        $message_type = "error";
                        header("Location: ?action=view_class_dashboard&class_id=$class_id");
                        exit;
                    }
                }

                // Inisialisasi session untuk menyimpan data sementara antar langkah
                if (!isset($_SESSION['assessment_config'])) {
                    $_SESSION['assessment_config'] = [];
                }

                // Tentukan langkah saat ini
                $step = $_GET['step'] ?? 1;
                $config = &$_SESSION['assessment_config']; // Gunakan reference untuk memudahkan

                // Proses POST untuk setiap langkah
                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'])) {
                        // Simpan semua data ke database
                        $config['pg_total'] = (int)$_POST['pg_total'];
                        $config['isian_total'] = (int)$_POST['isian_total'];
                        $config['essay_total'] = (int)$_POST['essay_total'];

                        // Simpan detail TP
                        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}"];
                            }
                        }
                        
                        // --- PROSES SIMPAN KE DATABASE ---
                        $conn->begin_transaction();
                        try {
                            // 1. Insert ke tabel assessments
                            $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;

                            // 2. Insert ke tabel chapters dan learning_objectives
                            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']); // Hapus session config
                            header("Location: ?action=view_class_dashboard&class_id=$class_id");
                            exit;

                        } catch (mysqli_sql_exception $exception) {
                            $conn->rollback();
                            $message = "Terjadi kesalahan saat menyimpan: " . $exception->getMessage();
                            $message_type = "error";
                            // Tetap di langkah 3 untuk menampilkan error
                        }
                    }
                }

                // --- TAMPILAN UNTUK SETIAP LANGKAH ---
                ?>
                <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>

                <!-- Progress Bar -->
                <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): ?>
                    <!-- LANGKAH 1: JUMLAH BAB -->
                    <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): ?>
                    <!-- LANGKAH 2: DETAIL BAB & JUMLAH TP -->
                    <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): ?>
                    <!-- LANGKAH 3: DETAIL TP & TOTAL SOAL -->
                    <form method="POST" class="space-y-6">
                        <!-- Bagian A: Total Soal -->
                        <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>

                        <!-- Bagian B: Detail TP -->
                        <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':
                $student_id = $_GET['student_id'];
                $student = getStudent($conn, $student_id);
                $class_id = $student['class_id'];
                $assessment = getAssessment($conn, $class_id);
                
                if (!$assessment) {
                    echo "<div class='text-center text-red-600'>Asesmen untuk kelas ini belum dikonfigurasi.</div>";
                    break;
                }

           // Load Assessment Config
            $assessment_config = ['kktp' => $student['kktp'], 'pg_total' => $assessment['pg_total'], 'isian_total' => $assessment['isian_total'], 'essay_total' => $assessment['essay_total'], 'chapters' => []];

            // --- PERBAIKAN DIMULAI DI SINI ---
            $stmt_chapters = $conn->prepare("SELECT * FROM chapters WHERE assessment_id = ?");
            $stmt_chapters->bind_param("i", $assessment['id']);
            $stmt_chapters->execute();
            $chapters_result_set = $stmt_chapters->get_result(); // Panggil get_result() SEKALI dan simpan hasilnya

            while($chapter = $chapters_result_set->fetch_assoc()){ // Loop variabel hasilnya
                $stmt_tps = $conn->prepare("SELECT * FROM learning_objectives WHERE chapter_id = ?");
                $stmt_tps->bind_param("i", $chapter['id']);
                $stmt_tps->execute();
                $tps_result_set = $stmt_tps->get_result(); // Lakukan hal yang sama untuk query di dalam
                $chapter['tps'] = $tps_result_set->fetch_all(MYSQLI_ASSOC);
                $assessment_config['chapters'][] = $chapter;
                $stmt_tps->close(); // Praktik baik: tutup statement setelah digunakan
            }
            $stmt_chapters->close(); // Praktik baik: tutup statement utama
            // --- PERBAIKAN SELESAI DI SINI ---
                
                // Proses POST untuk input nilai
                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);

                    // Simpan ke database
                    $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();
                        }
                    }
                    $message = "Nilai berhasil disimpan!";
                    $message_type = "success";
                }

                // Tampilkan Form Input Nilai dan Hasil
                ?>
                <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></div>
                <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>

                <form method="POST" class="space-y-8">
                    <!-- Input Jawaban Global -->
                    <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">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>

                    <!-- Input Nilai SLM per Bab -->
                    <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">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 if (isset($nilai_rapor_akhir)): ?>
                    <hr class="my-8">
                    <h3 class="text-2xl font-extrabold text-center text-gray-800 mb-6">Laporan Nilai Akhir</h3>
                    <div class="text-center p-6 rounded-xl shadow-xl border-2 <?php echo ($nilai_rapor_akhir >= $student['kktp']) ? 'border-green-600 bg-green-50' : 'border-red-600 bg-red-50'; ?> mb-8">
                        <p class="text-6xl font-extrabold text-red-900"><?php echo number_format($nilai_rapor_akhir, 2); ?></p>
                        <p class="text-2xl font-bold mt-2 <?php echo ($nilai_rapor_akhir >= $student['kktp']) ? 'text-green-700' : 'text-red-700'; ?>"><?php echo ($nilai_rapor_akhir >= $student['kktp']) ? 'KOMPETEN' : 'BELUM KOMPETEN'; ?></p>
                    </div>
                    <!-- Tabel detail nilai bisa ditambahkan di sini -->
                <?php endif; ?>
                <?php
                break;
        }
        ?>
    </div>
</body>
</html>