<?php
// Mengaktifkan Tailwind CSS melalui CDN
echo '<script src="https://cdn.tailwindcss.com"></script>';
// Mengatur font default
echo '<style>
    body { font-family: "Inter", sans-serif; background-color: #f4f7f9; }
    /* Menyesuaikan tampilan math/LaTeX agar terlihat rapi */
    .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>';

// --- DEFINISI VARIABEL DAN FUNGSI UTAMA ---
$tahap = 1; 
$error_message = null;
$kktp = 75; // Kriteria Ketuntasan minimum

// Global Soal Inputs (Digunakan untuk menghitung Nilai TP Proporsional)
$pg_total_soal = 0;
$isian_total_soal = 0;
$essay_total_soal = 0;

// Global Jawaban Benar (Digunakan untuk menghitung Nilai TP Proporsional)
$pg_benar = 0;
$isian_benar = 0;
$essay_benar = 0;

// Structure: [['bab_name' => 'Bab X', 'bab_topic' => 'Materi Bab', 'slm_score_100' => 90, 'bab_score_100' => 0 (Final Score), 'tp_count' => N, 'tp_list' => [TP1.1: {tp_topic, score_data}, ...]], ...]
$bab_details = []; 

// Fungsi utilitas untuk menghitung total TP
function getTotalTPCount($bab_details) {
    $total_tp_count = 0;
    foreach ($bab_details as $bab) {
        $total_tp_count += $bab['tp_count'] ?? 0;
    }
    return $total_tp_count;
}

// Fungsi untuk membuat struktur data Bab/TP awal
function createBabDetails($bab_count_input, $existing_details = []) {
    $details = [];
    for ($i = 1; $i <= $bab_count_input; $i++) {
        $bab_name = $existing_details[$i - 1]['bab_name'] ?? "Bab $i";
        $bab_topic = $existing_details[$i - 1]['bab_topic'] ?? "Lingkup Materi Bab $i";
        $tp_count = $existing_details[$i - 1]['tp_count'] ?? 0;
        
        $details[] = [
            'bab_name' => $bab_name,
            'bab_topic' => $bab_topic, 
            'tp_count' => $tp_count, 
            'slm_score_100' => $existing_details[$i - 1]['slm_score_100'] ?? 0, // NEW: Direct SLM/UH Score
            'bab_score_100' => $existing_details[$i - 1]['bab_score_100'] ?? 0, 
            'tp_list' => $existing_details[$i - 1]['tp_list'] ?? []
        ];
    }
    return $details;
}

// Fungsi untuk menyimpan data state ke hidden field
function getBabDetailsJson($bab_details, $pg_total, $isian_total, $essay_total, $pg_b, $isian_b, $essay_b, $kktp_val) {
    $state = [
        'bab_details' => $bab_details,
        'pg_total_soal' => $pg_total,
        'isian_total_soal' => $isian_total,
        'essay_total_soal' => $essay_total,
        'pg_benar' => $pg_b,
        'isian_benar' => $isian_b,
        'essay_benar' => $essay_b,
        'kktp' => $kktp_val, 
    ];
    return htmlspecialchars(json_encode($state));
}

// Fungsi untuk memuat data state dari hidden field
function loadBabDetailsState() {
    global $bab_details, $pg_total_soal, $isian_total_soal, $essay_total_soal, $pg_benar, $isian_benar, $essay_benar, $kktp;
    if (isset($_POST['state_json']) && !empty($_POST['state_json'])) {
        $state = json_decode($_POST['state_json'], true);
        $bab_details = $state['bab_details'] ?? [];
        $pg_total_soal = $state['pg_total_soal'] ?? 0;
        $isian_total_soal = $state['isian_total_soal'] ?? 0;
        $essay_total_soal = $state['essay_total_soal'] ?? 0;
        $pg_benar = $state['pg_benar'] ?? 0;
        $isian_benar = $state['isian_benar'] ?? 0;
        $essay_benar = $state['essay_benar'] ?? 0;
        $kktp = $state['kktp'] ?? 75; 
    }
}

// --- MEMPROSES INPUT DATA ANTAR TAHAP ---

loadBabDetailsState();

if (isset($_POST['submit_reset_state'])) {
    // --- RESET SEMUA STATE ---
    $bab_details = [];
    $pg_total_soal = 0;
    $isian_total_soal = 0;
    $essay_total_soal = 0;
    $pg_benar = 0;
    $isian_benar = 0;
    $essay_benar = 0;
    $kktp = 75; 
    $tahap = 1;
} elseif (isset($_POST['submit_recalculate'])) {
    // --- KEMBALI KE TAHAP 4 UNTUK GANTI JAWABAN BENAR ---
    // State sudah dimuat oleh loadBabDetailsState()
    
    // ** PERUBAHAN DISINI: Mereset input Jawaban Benar Siswa menjadi 0 **
    $pg_benar = 0;
    $isian_benar = 0;
    $essay_benar = 0;
    
    $tahap = 4;
} elseif (isset($_POST['submit_bab_count'])) {
    // --- TAHAP 1 -> TAHAP 2 ---
    $bab_count = max(1, min(5, (int)($_POST['bab_count'] ?? 0)));
    $kktp = max(0, min(100, (int)($_POST['kktp'] ?? 75)));

    if ($bab_count > 0) {
        $bab_details = createBabDetails($bab_count, $bab_details);
        $tahap = 2;
    } else {
        $error_message = "Jumlah Bab minimal adalah 1 dan maksimal 5.";
        $tahap = 1;
    }
} elseif (isset($_POST['submit_tp_count_and_bab_topic'])) {
    // --- TAHAP 2 -> TAHAP 3 ---
    $total_tp_check = 0;
    $bab_details_new = [];
    
    for ($i = 0; $i < count($bab_details); $i++) {
        $tp_count = max(0, (int)($_POST["tp_count_$i"] ?? 0));
        $bab_name = htmlspecialchars($_POST["bab_name_$i"] ?? "Bab " . ($i+1));
        $bab_topic = htmlspecialchars($_POST["bab_topic_$i"] ?? "Lingkup Materi Bab " . ($i+1));
        
        $tp_list = [];
        for ($j = 1; $j <= $tp_count; $j++) { 
             $tp_name_key = "TP " . ($i+1) . "." . $j; 
             $existing_tp_topic = $bab_details[$i]['tp_list'][$tp_name_key]['tp_topic'] ?? "Materi TP " . ($i+1) . "." . $j;
             $tp_list[$tp_name_key] = [
                'tp_topic' => $existing_tp_topic, 
                'pg_max' => 0, 'isian_max' => 0, 'essay_max' => 0
             ]; 
        }

        $bab_details_new[] = [
            'bab_name' => $bab_name,
            'bab_topic' => $bab_topic, 
            'tp_count' => $tp_count,
            'slm_score_100' => $bab_details[$i]['slm_score_100'] ?? 0, // Preserve SLM Score
            'bab_score_100' => 0,
            'tp_list' => $tp_list
        ];
        $total_tp_check += $tp_count;
    }

    if ($total_tp_check > 0) {
        $bab_details = $bab_details_new;
        $tahap = 3;
    } else {
        $error_message = "Total semua Tujuan Pembelajaran (TP) harus lebih dari 0.";
        $tahap = 2;
        $bab_details = $bab_details_new; 
    }
} elseif (isset($_POST['submit_total_soal'])) {
    // --- TAHAP 3 -> TAHAP 4 (Mengisi Lingkup Materi TP & Global Soal) ---

    // 1. Ambil data Lingkup Materi TP yang baru diisi
    $total_tp_check = 0;
    foreach ($bab_details as $i => &$bab) {
        foreach ($bab['tp_list'] as $tp_name => &$tp_data) {
            $tp_topic_key = "tp_topic_" . $i . "_" . str_replace('TP ', '', $tp_name); 
            $tp_data['tp_topic'] = htmlspecialchars($_POST[$tp_topic_key] ?? $tp_data['tp_topic']);
            $total_tp_check++;
        }
        unset($tp_data);
    }
    unset($bab);
    
    // 2. Ambil data Total Soal Global
    $pg_total_soal = max(0, (int)($_POST['pg_total_soal'] ?? 0));
    $isian_total_soal = max(0, (int)($_POST['isian_total_soal'] ?? 0));
    $essay_total_soal = max(0, (int)($_POST['essay_total_soal'] ?? 0));

    if ($pg_total_soal + $isian_total_soal + $essay_total_soal == 0) {
        $error_message = "Total semua soal (PG, Isian, Essay) harus lebih dari 0.";
        $tahap = 3;
    } elseif ($total_tp_check == 0) {
         $error_message = "Tidak ada TP yang terdaftar. Kembali ke Langkah 2.";
        $tahap = 2;
    } else {
        $tahap = 4;
    }
} elseif (isset($_POST['submit_jawaban_benar'])) {
    // --- TAHAP 4 -> TAHAP 5 (Perhitungan) ---

    // 1. Ambil data Global Jawaban Benar
    $pg_benar = max(0, min($pg_total_soal, (int)($_POST['pg_benar'] ?? 0)));
    $isian_benar = max(0, min($isian_total_soal, (int)($_POST['isian_benar'] ?? 0)));
    $essay_benar = max(0, min($essay_total_soal, (int)($_POST['essay_benar'] ?? 0)));

    // 2. Ambil data Nilai SLM/UH Langsung per Bab (NEW)
    foreach ($bab_details as $i => &$bab) {
        $slm_score_input = max(0, min(100, (int)($_POST["slm_score_$i"] ?? 0)));
        $bab['slm_score_100'] = $slm_score_input;
    }
    unset($bab);
    
    if ($pg_total_soal == 0 && $isian_total_soal == 0 && $essay_total_soal == 0) {
        $error_message = "Tidak ada soal yang terdaftar. Kembali ke Langkah 3.";
        $tahap = 3;
    } else {
        $tahap = 5;
    }
} 

// --- FUNGSI ALGORITMA DISTRIBUSI & PERHITUNGAN FINAL ---

function calculateFinalScores(&$bab_details, $pg_total_soal, $isian_total_soal, $essay_total_soal, $pg_benar, $isian_benar, $essay_benar, &$total_tp_count) {
    
    $total_tp_count = getTotalTPCount($bab_details);

    if ($total_tp_count === 0) return 0;

    // 1. Hitung Persentase Capaian Global per Jenis Soal (Achievement Rate)
    $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;

    // 2. Distribusikan Soal (Poin Maksimal) secara Merata ke Semua TP
    $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 ($bab_details as $bab_index => &$bab) {
        $bab_score_sum_tp_normalized = 0; // Akumulator untuk nilai TP (dari Tes Global)
        
        foreach ($bab['tp_list'] as $tp_name => &$tp_data) {
            $tp_counter++;

            // 3. Alokasikan Poin Maksimal per TP (termasuk sisa)
            $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_data['pg_max'] = $tp_pg_max;
            $tp_data['isian_max'] = $tp_isian_max;
            $tp_data['essay_max'] = $tp_essay_max;

            // 4. Hitung Poin Didapat (Siswa) - Proporsional
            $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;

            $tp_data['pg_achieved'] = $tp_pg_achieved;
            $tp_data['isian_achieved'] = $tp_isian_achieved;
            $tp_data['essay_achieved'] = $tp_essay_achieved;

            // 5. Normalisasi Nilai TP ke Skala 100 (Dari Tes Global SAS)
            $nilai_akhir_tp_100 = 0;
            if ($total_max_raw > 0) {
                $nilai_akhir_tp_100 = ($total_achieved_raw / $total_max_raw) * 100;
            }
            $tp_data['score_100'] = $nilai_akhir_tp_100;
            
            $bab_score_sum_tp_normalized += $nilai_akhir_tp_100; // Akumulasi untuk Bab Score TP
        }
        unset($tp_data); 
        
        // 6. Hitung Rata-rata TP (Normalized dari Tes Global)
        $bab_score_normalized_tp = 0;
        if ($bab['tp_count'] > 0) {
            $bab_score_normalized_tp = $bab_score_sum_tp_normalized / $bab['tp_count'];
        }
        $bab['bab_score_normalized_tp'] = $bab_score_normalized_tp; 

        // 7. Hitung Nilai Bab Akhir (Gabungan SLM/UH dan TP Normalized)
        $slm_score = $bab['slm_score_100'] ?? 0;
        
        $final_bab_score = 0;
        if ($slm_score > 0) {
            // Gabungan 50% TP Normalized (Global Test) + 50% SLM Score (Direct Input)
            $final_bab_score = ($bab_score_normalized_tp + $slm_score) / 2;
            $bab['bab_final_score_source'] = 'Kombinasi (50:50)';
        } else {
            // Jika SLM/UH tidak diisi (nilai 0), gunakan murni Nilai TP Normalized
            $final_bab_score = $bab_score_normalized_tp;
            $bab['bab_final_score_source'] = 'Hanya TP Normalized';
        }

        $bab['bab_score_100'] = $final_bab_score; 
        $total_final_bab_score_sum += $final_bab_score; // Akumulasi untuk Nilai Rapor Akhir
    }
    unset($bab); 

    // 8. Hitung Nilai Rapor Akhir (Rata-rata dari semua Nilai Bab Akhir)
    $total_bab_count = count($bab_details);
    if ($total_bab_count > 0) {
        $nilai_rapor_akhir = $total_final_bab_score_sum / $total_bab_count;
        return $nilai_rapor_akhir;
    }
    return 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>Kalkulator Nilai Normalisasi Otomatis</title>
</head>
<body class="p-4 md:p-8 flex justify-center items-start min-h-screen">

    <div class="w-full max-w-4xl 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-2">Kalkulator Nilai Otomatis Berbasis TP</h1>
        <p class="text-center text-md text-gray-500 mb-6">Sistem kini mendukung gabungan nilai Sumatif Lingkup Materi (SLM) dan Tes Global.</p>
        
        <?php $total_tp_count = getTotalTPCount($bab_details); ?>

        <?php if ($error_message): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4 font-semibold" role="alert">
                <span class="block sm:inline">⚠️ <?php echo htmlspecialchars($error_message); ?></span>
            </div>
        <?php endif; ?>

        <!-- Progress Bar & Indicator -->
        <?php 
            $tahap_data = [
                1 => ["Setup Awal & KKM", "Tentukan KKM dan jumlah Bab/Unit."], 
                2 => ["Detail Bab & TP", "Tentukan nama Bab, Lingkup Materi Bab, dan jumlah TP."], 
                3 => ["Detail Materi TP & Soal", "Tentukan Lingkup Materi setiap TP dan total soal global."], 
                4 => ["Input Nilai SLM/UH & Jawaban Global", "Masukkan nilai SLM/UH langsung per Bab dan total jawaban benar siswa di Tes Global."],
                5 => ["Hasil Rapor", "Lihat Nilai Akhir yang sudah dinormalisasi."],
            ];
            $progress_width = (($tahap > 4 ? 4 : $tahap) - 1) / 3 * 100; 
        ?>
        <div class="mb-8 p-4 bg-gray-50 rounded-xl shadow-inner border border-gray-200">
            <div class="text-lg font-bold text-gray-800 mb-2">Langkah <?php echo $tahap; ?>/5: <?php echo $tahap_data[$tahap][0]; ?></div>
            <p class="text-sm text-gray-600 mb-4"><?php echo $tahap_data[$tahap][1]; ?></p>
            <div class="w-full bg-gray-200 rounded-full h-3">
                <div class="bg-red-600 h-3 rounded-full transition-all duration-500" style="width: <?php echo $progress_width; ?>%"></div>
            </div>
        </div>

        <?php if ($tahap === 1): ?>
            <!-- TAHAP 1: INPUT JUMLAH BAB & KKM -->
            <form method="POST" action="kalkulator_bab_tp.php" class="space-y-6">
                <input type="hidden" name="state_json" value="<?php echo getBabDetailsJson($bab_details, $pg_total_soal, $isian_total_soal, $essay_total_soal, $pg_benar, $isian_benar, $essay_benar, $kktp); ?>">
                
                <div class="bg-blue-50 border-l-4 border-blue-500 p-6 rounded-xl space-y-4">
                    <h2 class="text-blue-800 font-bold text-xl border-b pb-2">Pengaturan Awal</h2>
                    
                    <!-- KKM Input -->
                    <div class="flex flex-col">
                        <label for="kktp" class="text-blue-800 font-bold mb-1 block text-lg">Kriteria Ketuntasan Minimal (KKM/KKTP):</label>
                        <input type="number" id="kktp" name="kktp" required min="0" max="100" value="<?php echo htmlspecialchars($kktp); ?>"
                            class="p-4 w-full border border-gray-300 rounded-lg text-2xl font-bold focus:outline-none focus:ring-4 focus:ring-blue-300 transition duration-150 shadow-inner text-center">
                        <p class="text-sm text-blue-600 mt-2">Nilai ini digunakan sebagai batas minimal status "Kompeten". (Skala 0-100)</p>
                    </div>

                    <!-- Jumlah Bab Input -->
                    <div class="flex flex-col pt-4 border-t border-blue-200">
                        <label for="bab_count" class="text-blue-800 font-bold mb-1 block text-lg">Jumlah Bab/Unit yang Dinilai:</label>
                        <input type="number" id="bab_count" name="bab_count" required min="1" max="5" value="<?php echo htmlspecialchars(count($bab_details) > 0 ? count($bab_details) : 2); ?>"
                           class="p-4 w-full border border-gray-300 rounded-lg text-2xl font-bold focus:outline-none focus:ring-4 focus:ring-blue-300 transition duration-150 shadow-inner text-center">
                        <p class="text-sm text-blue-600 mt-2">Masukkan jumlah Bab yang akan Anda nilai TP-nya (Maks. 5 Bab).</p>
                    </div>
                </div>
                
                <button type="submit" name="submit_bab_count" 
                        class="w-full bg-red-600 hover:bg-red-700 text-white font-bold py-4 rounded-lg transition duration-200 shadow-xl transform hover:scale-[1.01] text-lg">
                    Lanjut ke Langkah 2
                </button>
            </form>

        <?php elseif ($tahap === 2): ?>
            <!-- TAHAP 2: INPUT NAMA BAB, LINGKUP MATERI BAB, & TP COUNT PER BAB -->
            <form method="POST" action="kalkulator_bab_tp.php" class="space-y-8">
                <input type="hidden" name="state_json" value="<?php echo getBabDetailsJson($bab_details, $pg_total_soal, $isian_total_soal, $essay_total_soal, $pg_benar, $isian_benar, $essay_benar, $kktp); ?>">
                
                <p class="text-lg text-gray-700 font-semibold mb-4">Isi detail dan jumlah TP untuk setiap Bab:</p>
                <div class="grid grid-cols-1 gap-6">
                    <?php foreach ($bab_details as $i => $bab): ?>
                        <div class="flex flex-col bg-gray-50 p-6 rounded-xl border border-red-300 shadow-md hover:shadow-lg transition space-y-3">
                            <h3 class="text-xl font-extrabold text-red-700 border-b pb-2">Bab <?php echo $i+1; ?></h3>
                            
                            <!-- Nama Bab -->
                            <div class="flex flex-col">
                                <label for="bab_name_<?php echo $i; ?>" class="text-gray-700 font-bold mb-1 text-md">Nama Bab:</label>
                                <input type="text" name="bab_name_<?php echo $i; ?>" id="bab_name_<?php echo $i; ?>" value="<?php echo htmlspecialchars($bab['bab_name']); ?>" required
                                    class="p-2 border border-gray-300 rounded-lg text-md focus:ring-red-500">
                            </div>
                            
                            <!-- Lingkup Materi Bab -->
                            <div class="flex flex-col">
                                <label for="bab_topic_<?php echo $i; ?>" class="text-gray-700 font-bold mb-1 text-md">Lingkup Materi Bab:</label>
                                <input type="text" name="bab_topic_<?php echo $i; ?>" id="bab_topic_<?php echo $i; ?>" value="<?php echo htmlspecialchars($bab['bab_topic']); ?>" required
                                    class="p-2 border border-gray-300 rounded-lg text-md focus:ring-red-500">
                                <p class="text-xs text-gray-500 mt-1 italic">Contoh: "Algoritma Pemrograman Dasar"</p>
                            </div>

                            <!-- Jumlah TP -->
                            <div class="flex flex-col pt-2">
                                <label for="tp_count_<?php echo $i; ?>" class="text-gray-700 font-bold mb-1 text-md">Jumlah Tujuan Pembelajaran (TP):</label>
                                <input type="number" name="tp_count_<?php echo $i; ?>" id="tp_count_<?php echo $i; ?>" required min="0" value="<?php echo htmlspecialchars($bab['tp_count']); ?>"
                                    class="p-3 border border-gray-300 rounded-lg text-xl font-semibold focus:outline-none focus:ring-2 focus:ring-red-500 transition duration-150 shadow-inner">
                                <p class="text-sm text-gray-500 mt-1 italic">Contoh: 3 TP (TP 1.1, TP 1.2, TP 1.3).</p>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <button type="submit" name="submit_tp_count_and_bab_topic" 
                        class="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-4 rounded-lg transition duration-200 shadow-xl transform hover:scale-[1.01] mt-6 text-lg">
                    Lanjut ke Langkah 3
                </button>
            </form>
        
        <?php elseif ($tahap === 3): ?>
            <!-- TAHAP 3: INPUT LINGKUP MATERI TP & TOTAL SOAL GLOBAL -->
            <form method="POST" action="kalkulator_bab_tp.php" class="space-y-8">
                <input type="hidden" name="state_json" value="<?php echo getBabDetailsJson($bab_details, $pg_total_soal, $isian_total_soal, $essay_total_soal, $pg_benar, $isian_benar, $essay_benar, $kktp); ?>">

                <p class="text-center text-lg font-semibold text-gray-700 mb-4">Total TP yang akan dinilai: <span class="text-red-600 font-extrabold"><?php echo $total_tp_count; ?> TP</span></p>

                <!-- Input Lingkup Materi TP -->
                <div class="space-y-6 bg-blue-50 p-6 rounded-xl border-l-4 border-blue-500">
                    <h3 class="text-xl font-bold text-blue-800 mb-4">Lingkup Materi untuk Setiap TP</h3>
                    <?php 
                    $bab_index_counter = 0;
                    foreach ($bab_details as $i => $bab): 
                        if (count($bab['tp_list']) > 0):
                    ?>
                        <div class="p-4 bg-white rounded-lg shadow-inner border border-blue-200">
                            <h4 class="font-bold text-lg text-blue-600 mb-3"><?php echo htmlspecialchars($bab['bab_name']); ?>: <span class="text-sm text-gray-500 font-normal italic"><?php echo htmlspecialchars($bab['bab_topic']); ?></span></h4>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                <?php 
                                $tp_index_counter = 0;
                                foreach ($bab['tp_list'] as $tp_name => $tp_data): 
                                    $tp_index_counter++;
                                    // Generate key for input (e.g., tp_topic_0_1.1)
                                    $tp_key = "tp_topic_" . $i . "_" . str_replace('TP ', '', $tp_name); 
                                ?>
                                <div class="flex flex-col">
                                    <label for="<?php echo $tp_key; ?>" class="text-gray-700 font-medium mb-1 text-sm"><?php echo $tp_name; ?> - Lingkup Materi:</label>
                                    <input type="text" name="<?php echo $tp_key; ?>" id="<?php echo $tp_key; ?>" value="<?php echo htmlspecialchars($tp_data['tp_topic']); ?>" required
                                        class="p-2 border border-gray-300 rounded-lg text-sm focus:ring-blue-500 shadow-inner">
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; endforeach; ?>
                </div>

                <!-- Input Total Soal Global -->
                <div class="space-y-4 bg-yellow-50 p-6 rounded-xl border-l-4 border-yellow-500">
                    <p class="text-xl font-bold text-yellow-800 mb-3">Masukkan Total Soal Keseluruhan (Tes Global/SAS)</p>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div class="flex flex-col">
                            <label for="pg_total_soal" class="text-gray-700 font-medium mb-1">Total Pilihan Ganda (PG):</label>
                            <input type="number" name="pg_total_soal" id="pg_total_soal" value="<?php echo htmlspecialchars($pg_total_soal > 0 ? $pg_total_soal : 25); ?>" min="0" required
                                class="p-3 border border-gray-300 rounded-lg text-xl font-semibold focus:ring-red-500 shadow-inner">
                        </div>
                        <div class="flex flex-col">
                            <label for="isian_total_soal" class="text-gray-700 font-medium mb-1">Total Isian Singkat:</label>
                            <input type="number" name="isian_total_soal" id="isian_total_soal" value="<?php echo htmlspecialchars($isian_total_soal > 0 ? $isian_total_soal : 10); ?>" min="0" required
                                class="p-3 border border-gray-300 rounded-lg text-xl font-semibold focus:ring-red-500 shadow-inner">
                        </div>
                        <div class="flex flex-col">
                            <label for="essay_total_soal" class="text-gray-700 font-medium mb-1">Total Essay:</label>
                            <input type="number" name="essay_total_soal" id="essay_total_soal" value="<?php echo htmlspecialchars($essay_total_soal > 0 ? $essay_total_soal : 5); ?>" min="0" required
                                class="p-3 border border-gray-300 rounded-lg text-xl font-semibold focus:ring-red-500 shadow-inner">
                        </div>
                    </div>
                    <p class="text-sm text-yellow-700 mt-3 italic">Soal ini akan dibagi rata secara proporsional ke $\mathbf{<?php echo $total_tp_count; ?>}$ TP.</p>
                </div>
                
                <button type="submit" name="submit_total_soal" 
                        class="w-full bg-red-600 hover:bg-red-700 text-white font-bold py-4 rounded-lg transition duration-200 shadow-xl transform hover:scale-[1.01] mt-6 text-lg">
                    Lanjut ke Langkah 4
                </button>
            </form>

        <?php elseif ($tahap === 4): ?>
            <!-- TAHAP 4: INPUT NILAI SLM/UH LANGSUNG & JAWABAN BENAR GLOBAL -->
            <form method="POST" action="kalkulator_bab_tp.php" class="space-y-8">
                <input type="hidden" name="state_json" value="<?php echo getBabDetailsJson($bab_details, $pg_total_soal, $isian_total_soal, $essay_total_soal, $pg_benar, $isian_benar, $essay_benar, $kktp); ?>">

                <p class="text-center text-lg font-semibold text-gray-700 mb-4">KKM: <span class="text-red-600 font-extrabold"><?php echo $kktp; ?></span> | Total Soal Global: <span class="text-blue-600 font-extrabold"><?php echo $pg_total_soal + $isian_total_soal + $essay_total_soal; ?></span></p>

                <!-- Bagian 1: Input Nilai SLM/UH Langsung -->
                <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-3">1. Input Nilai Sumatif Lingkup Materi (SLM) / Ulangan Harian (UH)</p>
                    <p class="text-sm text-purple-700 italic mb-4">Masukkan nilai $0-100$ yang didapat siswa dari tes spesifik Bab ini. Nilai ini akan di-rata-rata $\mathbf{50:50}$ dengan hasil Tes Global Bab tersebut. **Nilai ini sama untuk satu siswa, tidak berubah saat menghitung ulang.**</p>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <?php foreach ($bab_details as $i => $bab): ?>
                            <div class="flex flex-col p-3 border border-purple-300 rounded-lg bg-white shadow-sm">
                                <label for="slm_score_<?php echo $i; ?>" class="text-gray-700 font-medium mb-1">Nilai SLM/UH $\mathbf{<?php echo htmlspecialchars($bab['bab_name']); ?>}$:</label>
                                <input type="number" name="slm_score_<?php echo $i; ?>" id="slm_score_<?php echo $i; ?>" 
                                       value="<?php echo htmlspecialchars($bab['slm_score_100']); ?>" min="0" max="100" required
                                       class="p-2 border border-gray-300 rounded-lg text-2xl font-bold text-center focus:ring-purple-500 shadow-inner">
                                <p class="text-xs text-gray-500 mt-1">Skala 0-100. (Isi $\mathbf{0}$ jika tidak ada UH/SLM).</p>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Bagian 2: Input Jawaban Benar 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 mb-3">2. Input Total Jawaban Benar Siswa (Tes Global/SAS)</p>
                    <p class="text-sm text-green-700 italic mb-4">Ubah nilai ini untuk siswa yang berbeda. Siswa $\mathbf{A}$ mendapat 20 PG Benar, Siswa $\mathbf{B}$ mendapat 18 PG Benar.</p>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div class="flex flex-col">
                            <label for="pg_benar" class="text-gray-700 font-medium mb-1">PG Benar (Max <?php echo $pg_total_soal; ?>):</label>
                            <input type="number" name="pg_benar" id="pg_benar" value="<?php echo htmlspecialchars($pg_benar); ?>" min="0" max="<?php echo $pg_total_soal; ?>" required
                                class="p-3 border border-gray-300 rounded-lg text-2xl font-bold focus:ring-red-500 shadow-inner">
                        </div>
                        <div class="flex flex-col">
                            <label for="isian_benar" class="text-gray-700 font-medium mb-1">Isian Benar (Max <?php echo $isian_total_soal; ?>):</label>
                            <input type="number" name="isian_benar" id="isian_benar" value="<?php echo htmlspecialchars($isian_benar); ?>" min="0" max="<?php echo $isian_total_soal; ?>" required
                                class="p-3 border border-gray-300 rounded-lg text-2xl font-bold focus:ring-red-500 shadow-inner">
                        </div>
                        <div class="flex flex-col">
                            <label for="essay_benar" class="text-gray-700 font-medium mb-1">Essay Benar (Max <?php echo $essay_total_soal; ?>):</label>
                            <input type="number" name="essay_benar" id="essay_benar" value="<?php echo htmlspecialchars($essay_benar); ?>" min="0" max="<?php echo $essay_total_soal; ?>" required
                                class="p-3 border border-gray-300 rounded-lg text-2xl font-bold focus:ring-red-500 shadow-inner">
                        </div>
                    </div>
                </div>
                
                <div class="flex flex-col sm:flex-row gap-4 mt-6">
                    <button type="submit" name="submit_jawaban_benar" 
                            class="flex-1 w-full bg-red-600 hover:bg-red-700 text-white font-bold py-4 rounded-lg transition duration-200 shadow-xl transform hover:scale-[1.01] text-lg">
                        Lanjut ke Langkah 5: Lihat Laporan
                    </button>
                    <!-- Tombol Reset -->
                    <button type="submit" name="submit_reset_state"
                            formmethod="POST" 
                            class="w-full sm:w-auto bg-gray-500 hover:bg-gray-600 text-white font-bold py-4 px-6 rounded-lg transition duration-200 shadow-md">
                        Ulang dari Awal (Reset)
                    </button>
                </div>
            </form>

        <?php elseif ($tahap === 5): ?>
            <!-- TAHAP 5: TAMPILKAN HASIL NORMALISASI -->
            <?php
                $nilai_rapor_akhir = calculateFinalScores($bab_details, $pg_total_soal, $isian_total_soal, $essay_total_soal, $pg_benar, $isian_benar, $essay_benar, $total_tp_count);
                $total_raw_max_score = $pg_total_soal + $isian_total_soal + $essay_total_soal;

                $status_kompetensi = ($nilai_rapor_akhir >= $kktp) ? 'KOMPETEN' : 'BELUM KOMPETEN';
                $status_color = ($nilai_rapor_akhir >= $kktp) ? 'border-green-600 bg-green-50' : 'border-red-600 bg-red-50';
                $status_text_color = ($nilai_rapor_akhir >= $kktp) ? 'text-green-700' : 'text-red-700';
            ?>

            <div class="text-center">
                <h2 class="text-3xl font-extrabold text-gray-800 mb-6">Laporan Nilai Rapor Akhir Siswa</h2>
                
                <!-- Nilai Utama & Status (VERSI RINGKAS) -->
                <div class="p-6 rounded-xl shadow-xl border-2 <?php echo $status_color; ?> mb-8">
                    <div class="flex flex-col md:flex-row items-center justify-between gap-4">
                        <!-- Nilai Rapor Akhir (Paling Menonjol) -->
                        <div class="flex flex-col items-center md:items-start flex-1">
                            <p class="text-md text-red-700 mb-1 font-semibold uppercase tracking-wider">Nilai Rapor Akhir (Rata-Rata Seluruh Bab)</p>
                            <p class="text-6xl font-extrabold text-red-900 leading-none"><?php echo number_format($nilai_rapor_akhir, 2); ?></p>
                            <p class="text-sm text-gray-500 mt-2">KKTP yang Ditetapkan: $\mathbf{<?php echo $kktp; ?>}$</p>
                        </div>
                        
                        <!-- Status Kompetensi -->
                        <div class="w-full md:w-auto p-3 rounded-lg border-2 border-dashed <?php echo ($nilai_rapor_akhir >= $kktp) ? 'border-green-500 bg-green-100' : 'border-red-500 bg-red-100'; ?>">
                            <p class="text-sm font-bold mb-1 uppercase tracking-wider">Status</p>
                            <p class="text-3xl font-extrabold <?php echo $status_text_color; ?>"><?php echo $status_kompetensi; ?></p>
                        </div>
                    </div>
                </div>

                <!-- Ringkasan Perhitungan -->
                <div class="text-left mb-8">
                    <h3 class="text-xl font-bold text-gray-800 mb-3 border-b pb-1">Ringkasan Data & Proporsi</h3>
                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 text-sm">
                        <!-- Box 1: Total Soal -->
                        <div class="bg-blue-50 p-4 rounded-lg border border-blue-200">
                            <p class="text-blue-700 font-bold mb-1">Tes Global (SAS) Soal / Benar</p>
                            <ul class="text-gray-700 space-y-0.5">
                                <li>PG: $\mathbf{<?php echo $pg_total_soal; ?>}$ / $\mathbf{<?php echo $pg_benar; ?>}$</li>
                                <li>Isian: $\mathbf{<?php echo $isian_total_soal; ?>}$ / $\mathbf{<?php echo $isian_benar; ?>}$</li>
                                <li>Essay: $\mathbf{<?php echo $essay_total_soal; ?>}$ / $\mathbf{<?php echo $essay_benar; ?>}$</li>
                            </ul>
                        </div>
                         <!-- Box 2: Total Metrik -->
                        <div class="bg-gray-100 p-4 rounded-lg border border-gray-200">
                            <p class="text-gray-700 font-bold mb-1">Bab & TP</p>
                            <p class="text-2xl font-extrabold text-gray-800"><?php echo $total_tp_count; ?> TP</p>
                            <p class="text-sm text-gray-500">Dari $\mathbf{<?php echo count($bab_details); ?>}$ Bab. Total Soal Global: $\mathbf{<?php echo $total_raw_max_score; ?>}$</p>
                        </div>
                        <!-- Box 3: Rumus -->
                        <div class="bg-purple-50 p-4 rounded-lg border border-purple-200 col-span-1 sm:col-span-2 lg:col-span-1">
                            <p class="text-purple-700 font-bold mb-1">Konsep Perhitungan Bab Akhir</p>
                            <div class="math-display">
                                $$ \text{Nilai Bab Final} = \frac{\text{SLM} + \text{Rata-rata TP (Norm.)}}{2} $$
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Rincian Nilai Per BAB & TP (Menggunakan Tabel) -->
                <div class="text-left overflow-x-auto shadow-md rounded-lg border border-gray-200">
                    <h3 class="text-xl font-bold text-gray-800 p-4 bg-gray-50 border-b">Rincian Nilai Per Bab dan Tujuan Pembelajaran (TP)</h3>
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-100">
                            <tr>
                                <th scope="col" class="px-3 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider w-1/4">Bab / TP</th>
                                <th scope="col" class="px-3 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Lingkup Materi</th>
                                <th scope="col" class="px-3 py-3 text-center text-xs font-semibold text-gray-600 uppercase tracking-wider">Nilai SLM/UH</th>
                                <th scope="col" class="px-3 py-3 text-center text-sm font-bold text-red-700 uppercase tracking-wider">Nilai Bab Final (100)</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php 
                            foreach ($bab_details as $bab): 
                                $bab_score_100 = $bab['bab_score_100'] ?? 0;
                                $bab_slm_score = $bab['slm_score_100'] ?? 0;
                                $bab_score_normalized_tp = $bab['bab_score_normalized_tp'] ?? 0;
                                $bab_status_color = ($bab_score_100 >= $kktp) ? 'bg-green-100 text-green-800' : 'bg-orange-100 text-orange-800';
                            ?>
                                <!-- Baris Nilai Rata-rata Bab -->
                                <tr class="border-t-4 border-red-200">
                                    <td class="px-3 py-3 whitespace-nowrap align-top font-extrabold text-red-700">
                                        <?php echo htmlspecialchars($bab['bab_name']); ?>
                                    </td>
                                    <td class="px-3 py-3 whitespace-nowrap align-top text-xs font-bold text-red-500 italic">
                                        <?php echo htmlspecialchars($bab['bab_topic']); ?>
                                        <p class="text-gray-500 font-normal italic mt-1 text-xs">Norm. TP: <?php echo number_format($bab_score_normalized_tp, 2); ?>. Sumber: <?php echo $bab['bab_final_score_source']; ?></p>
                                    </td>
                                    <td class="px-3 py-3 whitespace-nowrap text-center text-lg font-bold text-purple-700">
                                        <?php echo $bab_slm_score; ?>
                                    </td>
                                    <td class="px-3 py-3 whitespace-nowrap text-center text-xl font-extrabold <?php echo $bab_status_color; ?> rounded-lg">
                                        <?php echo number_format($bab_score_100, 2); ?>
                                    </td>
                                </tr>

                                <?php 
                                foreach ($bab['tp_list'] as $tp_name => $tp_data): 
                                    $total_max_tp = ($tp_data['pg_max'] ?? 0) + ($tp_data['isian_max'] ?? 0) + ($tp_data['essay_max'] ?? 0);
                                    $tp_score_100 = $tp_data['score_100'] ?? 0;
                                    $tp_status_color = ($tp_score_100 >= $kktp) ? 'text-green-600' : 'text-orange-600';
                                ?>
                                    <!-- Baris Rincian TP -->
                                    <tr class="text-sm">
                                        <td class="px-3 py-2 whitespace-nowrap align-top pl-6 text-gray-500">
                                            <?php echo $tp_name; ?>
                                        </td>
                                        <!-- Lingkup Materi TP -->
                                        <td class="px-3 py-2 align-top text-gray-800 italic max-w-sm overflow-hidden text-ellipsis">
                                            <?php echo htmlspecialchars($tp_data['tp_topic']); ?>
                                            <div class="text-gray-400 mt-1 text-xs font-mono">
                                                Alokasi Soal: (PG: <?php echo $tp_data['pg_max']; ?> | Isian: <?php echo $tp_data['isian_max']; ?> | Essay: <?php echo $tp_data['essay_max']; ?>)
                                            </div>
                                        </td>
                                        <td class="px-3 py-2 whitespace-nowrap text-center text-gray-500 italic">
                                            Tidak berlaku
                                        </td>
                                        <td class="px-3 py-2 whitespace-nowrap text-center text-sm font-extrabold <?php echo $tp_status_color; ?>">
                                            <?php echo number_format($tp_score_100, 2); ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <div class="flex flex-col sm:flex-row gap-4 mt-8">
                    <!-- Tombol Recalculate -->
                    <form method="POST" action="kalkulator_bab_tp.php" class="flex-1 w-full">
                        <input type="hidden" name="state_json" value="<?php echo getBabDetailsJson($bab_details, $pg_total_soal, $isian_total_soal, $essay_total_soal, $pg_benar, $isian_benar, $essay_benar, $kktp); ?>">
                        <button type="submit" name="submit_recalculate" 
                                class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-4 rounded-lg transition duration-200 shadow-md transform hover:scale-[1.01] text-lg">
                            Kembali ke Input Jawaban (Recalculate)
                        </button>
                    </form>

                    <!-- Tombol Reset -->
                    <form method="POST" action="kalkulator_bab_tp.php" class="w-full sm:w-auto">
                        <button type="submit" name="submit_reset_state"
                                class="w-full bg-gray-500 hover:bg-gray-600 text-white font-bold py-4 px-6 rounded-lg transition duration-200 shadow-md">
                            Ulang dari Awal (Reset)
                        </button>
                    </form>
                </div>
            </div>

        <?php endif; ?>

    </div>
</body>
</html>
