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

// --- DEFINISI VARIABEL DAN FUNGSI UTAMA ---
$tp_count = 0;
$kktp = 75; 
$tp_details = []; 
$tahap = 1; // 1: Input Jumlah TP, 2: Input Detail TP, 3: Input Global Score, 4: Tampilkan Hasil
$error_message = null;

// Mengambil data dari hidden fields jika ada
if (isset($_POST['tp_details_json'])) {
    $tp_details = json_decode($_POST['tp_details_json'], true);
    $tp_count = count($tp_details);
    // Mengambil tahap dari post, atau tetap di 2 jika details ada tapi tidak ada aksi submit
    $tahap = (isset($_POST['submit_details']) || isset($_POST['submit_global_score'])) ? $tahap : 2; 
}
$kktp = (int)($_POST['kktp_hidden'] ?? 75);

// --- SETTING DEFAULT: Langsung ke Tahap 2 dengan 4 TP jika belum ada input ---
if (!isset($_POST['submit_tp_count']) && !isset($_POST['submit_details']) && !isset($_POST['submit_global_score']) && $tp_count === 0) {
    $tp_count = 4; // Default ke 4 TP
    $tahap = 2; // Langsung ke Tahap 2 untuk konfigurasi TP
    $kktp = 75;
    
    // Distribusi default (Total 4 TP, Bobot masing-masing 25)
    $tp_details = [];
    $default_pg = 5; 
    $default_isian = 2; 
    $default_esai = 1; 
    $default_weight = 25; // Bobot default 25 (Total 100)
    
    for ($i = 1; $i <= $tp_count; $i++) {
        $tp_details[] = [
            'bab_name' => "TP " . $i,
            'weight' => $default_weight,
            'pg_count' => $default_pg,
            'isian_count' => $default_isian,
            'esai_count' => $default_esai,
            'total_soal' => $default_pg + $default_isian + $default_esai,
        ];
    }
} 

// --- TAHAP 1: INPUT JUMLAH TP ---
elseif (isset($_POST['submit_tp_count'])) {
    $tp_count = max(1, (int)($_POST['tp_count'] ?? 0));
    $kktp = max(0, min(100, (int)($_POST['kktp'] ?? 75)));
    
    // Inisialisasi detail TP default untuk Tahap 2
    $tp_details = [];
    $default_weight = floor(100 / $tp_count);
    $remaining_weight = 100 - ($default_weight * $tp_count);
    
    for ($i = 1; $i <= $tp_count; $i++) {
        $weight = ($i == 1) ? ($default_weight + $remaining_weight) : $default_weight;
        $tp_details[] = [
            'bab_name' => "TP " . $i,
            'weight' => $weight,
            'pg_count' => 5,
            'isian_count' => 2,
            'esai_count' => 1,
        ];
    }

    if ($tp_count > 0) {
        $tahap = 2;
    } else {
        $tahap = 1;
        $error_message = "Jumlah Tujuan Pembelajaran (TP) harus lebih dari 0.";
    }
} 

// --- TAHAP 2: INPUT DETAIL TP (Bobot & Distribusi Soal) ---
elseif (isset($_POST['submit_details'])) {
    $tp_count = (int)($_POST['tp_count_hidden'] ?? 0);
    $kktp = (int)($_POST['kktp_hidden'] ?? 75);
    $total_bobot_check = 0;
    
    $global_pg_total = 0;
    $global_isian_total = 0;
    $global_esai_total = 0;
    
    $tp_details_new = [];

    // Proses input TP yang dinamis
    for ($i = 1; $i <= $tp_count; $i++) {
        $bab_name = htmlspecialchars($_POST["bab_name_$i"] ?? "TP $i");
        $tp_weight = max(0, (int)($_POST["tp_weight_$i"] ?? 0));
        $pg_count = max(0, (int)($_POST["pg_count_$i"] ?? 0));
        $isian_count = max(0, (int)($_POST["isian_count_$i"] ?? 0));
        $esai_count = max(0, (int)($_POST["esai_count_$i"] ?? 0));
        
        $total_bobot_check += $tp_weight;
        $global_pg_total += $pg_count;
        $global_isian_total += $isian_count;
        $global_esai_total += $esai_count;
        
        $tp_details_new[] = [
            'bab_name' => $bab_name,
            'weight' => $tp_weight,
            'pg_count' => $pg_count,
            'isian_count' => $isian_count,
            'esai_count' => $esai_count,
            'total_soal' => $pg_count + $isian_count + $esai_count,
        ];
    }
    
    if ($total_bobot_check !== 100) {
        $tahap = 2; 
        $tp_details = $tp_details_new; // Kembalikan data agar tidak hilang
        $error_message = "Kesalahan: Total Bobot semua Tujuan Pembelajaran (TP) harus berjumlah 100. Saat ini total bobot Anda adalah " . $total_bobot_check . ".";
    } elseif ($global_pg_total + $global_isian_total + $global_esai_total == 0) {
        $tahap = 2;
        $tp_details = $tp_details_new;
        $error_message = "Kesalahan: Total jumlah soal dari semua TP tidak boleh 0.";
    } else {
        $tp_details = $tp_details_new;
        $tahap = 3;
    }
}

// --- TAHAP 3: INPUT GLOBAL SCORE (Jawaban Benar PG, Isian, Esai) ---
elseif (isset($_POST['submit_global_score'])) {
    
    // Pastikan data TP details sudah di-load
    if (!empty($_POST['tp_details_json'])) {
        $tp_details = json_decode($_POST['tp_details_json'], true);
    } else {
        $tahap = 2; 
        $error_message = "Kesalahan data: Detail TP hilang. Silakan ulangi Langkah 2.";
        goto render_html;
    }

    $pg_benar = max(0, (int)($_POST['pg_benar'] ?? 0));
    $isian_benar = max(0, (int)($_POST['isian_benar'] ?? 0));
    $esai_benar = max(0, (int)($_POST['esai_benar'] ?? 0));
    
    $global_pg_total = (int)($_POST['global_pg_total'] ?? 0);
    $global_isian_total = (int)($_POST['global_isian_total'] ?? 0);
    $global_esai_total = (int)($_POST['global_esai_total'] ?? 0);
    $kktp = (int)($_POST['kktp_hidden'] ?? 75);

    // Validasi Jawaban Benar tidak melebihi total soal
    if ($pg_benar > $global_pg_total || $isian_benar > $global_isian_total || $esai_benar > $global_esai_total) {
        $tahap = 3;
        $error_message = "Kesalahan: Jumlah jawaban benar tidak boleh melebihi jumlah soal total pada kategori tersebut.";
    } else {
        // --- LOGIKA PERHITUNGAN AKHIR ---
        $nilai_akhir = 0;
        
        // 1. Hitung Global Achievement Rate (GAR)
        // GAR = Jawaban Benar / Total Soal (Untuk setiap jenis soal)
        $pg_gar = ($global_pg_total > 0) ? $pg_benar / $global_pg_total : 0;
        $isian_gar = ($global_isian_total > 0) ? $isian_benar / $global_isian_total : 0;
        $esai_gar = ($global_esai_total > 0) ? $esai_benar / $global_esai_total : 0;

        // 2. Hitung kontribusi score per TP (Proportional Weighted Score)
        foreach ($tp_details as &$tp) {
            $tp_score = 0;
            $tp_total_soal = $tp['total_soal']; // Total soal (PG+Isian+Esai) di TP ini
            
            if ($tp_total_soal > 0) {
                // Proporsi soal PG/Isian/Esai dalam TP tersebut
                $prop_pg = $tp['pg_count'] / $tp_total_soal;
                $prop_isian = $tp['isian_count'] / $tp_total_soal;
                $prop_esai = $tp['esai_count'] / $tp_total_soal;

                // Kontribusi Keberhasilan di TP ini
                // (Proporsi soal * GAR global) + (Proporsi soal * GAR global) ...
                $achievement_contribution = 
                    ($prop_pg * $pg_gar) +
                    ($prop_isian * $isian_gar) +
                    ($prop_esai * $esai_gar);

                // Score TP = Bobot Maksimum TP * Kontribusi Keberhasilan
                $tp_score = $tp['weight'] * $achievement_contribution;
            }
            
            // Tambahkan data GAR ke setiap TP untuk tujuan debugging/analisis
            // Note: GARs are the same for all TPs in this model because the achievement rate is global.
            $tp['pg_gar'] = $pg_gar; 
            $tp['isian_gar'] = $isian_gar;
            $tp['esai_gar'] = $esai_gar;

            // Hitung Capaian TP (nilai TP skala 100)
            // Ini adalah Achivement Contribution * 100
            $tp['capaian_skala_100'] = $achievement_contribution * 100;
            
            $nilai_akhir += $tp_score;
        }
        unset($tp); // Putuskan referensi
        
        $tahap = 4;
    }
}

// --- TAHAP 4: TAMPILKAN HASIL ---
// Jika langsung akses Tahap 4 tanpa submit, tidak ada data, jadi perlu dicek
elseif ($tahap === 4) {
    // Data di Tahap 4 diasumsikan sudah ada dari submit_global_score
    // Jika tidak ada data, kembalikan ke Tahap 1
    if (empty($tp_details)) {
        $tahap = 1;
    }
}

render_html:
// --- 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 K-Merdeka (Bobot TP)</title>
</head>
<body class="p-4 md:p-8 flex justify-center items-start min-h-screen">

    <div class="w-full max-w-3xl bg-white p-6 md:p-10 shadow-xl rounded-xl">
        <h1 class="text-3xl font-bold text-center text-red-700 mb-2">Kalkulator Nilai Kurikulum Merdeka</h1>
        <p class="text-center text-md text-gray-500 mb-6">Penilaian Proporsional Berbasis Tujuan Pembelajaran (TP)</p>
        
        <?php if ($error_message): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                <span class="block sm:inline"><?php echo htmlspecialchars($error_message); ?></span>
            </div>
        <?php endif; ?>

        <?php if ($tahap === 1): ?>
            <!-- TAHAP 1: INPUT JUMLAH TP DAN KKTP GLOBAL -->
            <p class="text-lg text-gray-600 mb-4 text-center font-semibold">Langkah 1/4: Setup Awal</p>
            <form method="POST" action="hitung_nilai.php" class="space-y-6">
                
                <!-- Input KKTP -->
                <div class="bg-blue-50 border-l-4 border-blue-500 p-4 rounded-lg">
                    <label for="kktp" class="text-blue-800 font-bold mb-2 block">KKTP (Kriteria Ketuntasan Tujuan Pembelajaran):</label>
                    <input type="number" id="kktp" name="kktp" required min="0" max="100" value="<?php echo htmlspecialchars($kktp); ?>"
                           class="p-3 w-full border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-150">
                    <p class="text-sm text-blue-600 mt-1">Nilai minimal yang harus dicapai siswa untuk dikatakan **Kompeten** (Skala 100).</p>
                </div>

                <!-- Input Jumlah TP -->
                <div class="flex flex-col">
                    <label for="tp_count" class="text-gray-700 font-bold mb-1">Total Jumlah Tujuan Pembelajaran (TP) yang Diujikan:</label>
                    <input type="number" id="tp_count" name="tp_count" required min="1" value="<?php echo htmlspecialchars($tp_count > 0 ? $tp_count : 4); ?>"
                           class="p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 transition duration-150">
                    <p class="text-sm text-gray-500 mt-1">Masukkan total TP/unit yang akan dinilai.</p>
                </div>
                
                <button type="submit" name="submit_tp_count" 
                        class="w-full bg-red-600 hover:bg-red-700 text-white font-bold py-3 rounded-lg transition duration-200 shadow-md transform hover:scale-[1.01]">
                    Lanjut ke Detail Bobot TP
                </button>
            </form>

        <?php elseif ($tahap === 2): ?>
            <!-- TAHAP 2: INPUT DETAIL TP (Bobot & Distribusi Soal) -->
            <p class="text-lg text-gray-600 mb-4 text-center font-semibold">Langkah 2/4: Distribusi Bobot dan Soal per TP</p>

            <div class="bg-yellow-50 border border-yellow-200 p-4 rounded-lg mb-6 text-sm text-yellow-800">
                <p class="font-semibold mb-1">Ketentuan Penting:</p>
                <ul class="list-disc list-inside space-y-1">
                    <li>Total kolom **Bobot Nilai Maksimal** harus berjumlah **100**. (Saat ini defaultnya 4 TP @ 25).</li>
                    <li>Tentukan **jumlah soal PG, Isian, dan Esai** yang mewakili TP tersebut.</li>
                </ul>
                <p class="mt-2 text-sm text-red-700 font-bold">KKTP Global: <?php echo $kktp; ?></p>
            </div>

            <form method="POST" action="hitung_nilai.php" class="space-y-4">
                <!-- Data tersembunyi -->
                <input type="hidden" name="tp_count_hidden" value="<?php echo $tp_count; ?>">
                <input type="hidden" name="kktp_hidden" value="<?php echo $kktp; ?>">
                
                <div class="grid grid-cols-12 gap-2 text-xs md:text-sm font-bold text-gray-700 bg-gray-100 p-2 rounded-lg">
                    <div class="col-span-3">Bab/TP</div>
                    <div class="col-span-2 text-center">Bobot (Max 100)</div>
                    <div class="col-span-2 text-center">Soal PG</div>
                    <div class="col-span-2 text-center">Soal Isian</div>
                    <div class="col-span-3 text-center">Soal Esai</div>
                </div>

                <?php for ($i = 0; $i < $tp_count; $i++): 
                    $tp = $tp_details[$i] ?? [];
                ?>
                    <div class="grid grid-cols-12 gap-2 items-center">
                        <!-- Bab/TP Name -->
                        <div class="col-span-3">
                            <input type="text" name="bab_name_<?php echo $i+1; ?>" value="<?php echo htmlspecialchars($tp['bab_name'] ?? "TP " . ($i+1)); ?>" required
                                class="p-2 w-full border border-gray-300 rounded-lg text-xs md:text-sm">
                        </div>
                        
                        <!-- Bobot Nilai Maksimal -->
                        <div class="col-span-2">
                            <input type="number" name="tp_weight_<?php echo $i+1; ?>" required min="0" max="100" value="<?php echo htmlspecialchars($tp['weight'] ?? 0); ?>"
                                class="p-2 w-full border border-gray-300 rounded-lg text-center text-xs md:text-sm focus:ring-red-500">
                        </div>

                        <!-- PG Count -->
                        <div class="col-span-2">
                            <input type="number" name="pg_count_<?php echo $i+1; ?>" required min="0" value="<?php echo htmlspecialchars($tp['pg_count'] ?? 0); ?>"
                                class="p-2 w-full border border-gray-300 rounded-lg text-center text-xs md:text-sm focus:ring-red-500">
                        </div>

                        <!-- Isian Count -->
                        <div class="col-span-2">
                            <input type="number" name="isian_count_<?php echo $i+1; ?>" required min="0" value="<?php echo htmlspecialchars($tp['isian_count'] ?? 0); ?>"
                                class="p-2 w-full border border-gray-300 rounded-lg text-center text-xs md:text-sm focus:ring-red-500">
                        </div>

                        <!-- Esai Count -->
                        <div class="col-span-3">
                            <input type="number" name="esai_count_<?php echo $i+1; ?>" required min="0" value="<?php echo htmlspecialchars($tp['esai_count'] ?? 0); ?>"
                                class="p-2 w-full border border-gray-300 rounded-lg text-center text-xs md:text-sm focus:ring-red-500">
                        </div>
                    </div>
                <?php endfor; ?>
                
                <button type="submit" name="submit_details" 
                        class="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-3 rounded-lg transition duration-200 shadow-md transform hover:scale-[1.01] mt-6">
                    Lanjut ke Input Jawaban Benar Global
                </button>
            </form>

        <?php elseif ($tahap === 3): 
            // Hitung total soal dari data yang sudah disubmit di Tahap 2
            $global_pg_total = array_sum(array_column($tp_details, 'pg_count'));
            $global_isian_total = array_sum(array_column($tp_details, 'isian_count'));
            $global_esai_total = array_sum(array_column($tp_details, 'esai_count'));
            $global_total_soal = $global_pg_total + $global_isian_total + $global_esai_total;
        ?>
            <!-- TAHAP 3: INPUT GLOBAL SCORE (Jawaban Benar PG, Isian, Esai) -->
            <p class="text-lg text-gray-600 mb-4 text-center font-semibold">Langkah 3/4: Input Hasil Siswa (Global)</p>

            <div class="bg-blue-50 border border-blue-200 p-4 rounded-lg mb-6 text-sm text-blue-800">
                <p class="font-semibold mb-1">Total Soal Keseluruhan:</p>
                <ul class="list-disc list-inside space-y-1">
                    <li>Pilihan Ganda (PG): **<?php echo $global_pg_total; ?>** soal</li>
                    <li>Isian Singkat: **<?php echo $global_isian_total; ?>** soal</li>
                    <li>Esai: **<?php echo $global_esai_total; ?>** soal</li>
                    <li class="font-bold">Total: **<?php echo $global_total_soal; ?>** soal</li>
                </ul>
            </div>

            <form method="POST" action="hitung_nilai.php" class="space-y-4">
                <!-- Data tersembunyi untuk perhitungan -->
                <input type="hidden" name="tp_details_json" value="<?php echo htmlspecialchars(json_encode($tp_details)); ?>">
                <input type="hidden" name="kktp_hidden" value="<?php echo $kktp; ?>">
                <input type="hidden" name="global_pg_total" value="<?php echo $global_pg_total; ?>">
                <input type="hidden" name="global_isian_total" value="<?php echo $global_isian_total; ?>">
                <input type="hidden" name="global_esai_total" value="<?php echo $global_esai_total; ?>">

                <div class="flex flex-col">
                    <label for="pg_benar" class="text-gray-700 font-medium mb-1">Jawaban Benar Pilihan Ganda (Max: <?php echo $global_pg_total; ?>):</label>
                    <input type="number" id="pg_benar" name="pg_benar" required min="0" max="<?php echo $global_pg_total; ?>" value="" placeholder="Jumlah benar PG"
                           class="p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 transition duration-150">
                </div>
                
                <div class="flex flex-col">
                    <label for="isian_benar" class="text-gray-700 font-medium mb-1">Jawaban Benar Isian Singkat (Max: <?php echo $global_isian_total; ?>):</label>
                    <input type="number" id="isian_benar" name="isian_benar" required min="0" max="<?php echo $global_isian_total; ?>" value="" placeholder="Jumlah benar Isian Singkat"
                           class="p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 transition duration-150">
                </div>

                <div class="flex flex-col">
                    <label for="esai_benar" class="text-gray-700 font-medium mb-1">Jawaban Benar Esai (Max: <?php echo $global_esai_total; ?>):</label>
                    <input type="number" id="esai_benar" name="esai_benar" required min="0" max="<?php echo $global_esai_total; ?>" value="" placeholder="Jumlah benar Esai"
                           class="p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 transition duration-150">
                </div>
                
                <button type="submit" name="submit_global_score" 
                        class="w-full bg-red-600 hover:bg-red-700 text-white font-bold py-3 rounded-lg transition duration-200 shadow-md transform hover:scale-[1.01] mt-6">
                    Lihat Laporan Akhir
                </button>
            </form>

        <?php elseif ($tahap === 4): ?>
            <!-- TAHAP 4: TAMPILKAN HASIL DAN KETUNTASAN TP -->
            <?php
                $nilai_akhir = array_sum(array_column($tp_details, 'score'));
                $status_kompetensi = ($nilai_akhir >= $kktp) ? 'Kompeten' : 'Belum Kompeten';
                $status_color = ($nilai_akhir >= $kktp) ? 'bg-green-600' : 'bg-red-600';
            ?>

            <div class="text-center">
                <h2 class="text-2xl font-semibold text-gray-800 mb-4">Laporan Hasil Penilaian TP Siswa</h2>
                
                <!-- Nilai Utama -->
                <div class="bg-red-100 p-6 rounded-xl shadow-inner mb-4">
                    <p class="text-lg text-red-700 mb-2">Total Nilai Akhir (Skala 100):</p>
                    <p class="text-6xl font-extrabold text-red-900"><?php echo number_format($nilai_akhir, 2); ?></p>
                </div>

                <!-- Status Ketuntasan KKTP -->
                <div class="<?php echo $status_color; ?> text-white font-bold text-2xl py-3 rounded-lg shadow-lg mb-6">
                    STATUS KETUNTASAN TP: <?php echo $status_kompetensi; ?>
                </div>

                <div class="space-y-3 text-left text-gray-700 border-t pt-4">
                    <p class="text-xl font-bold text-gray-800 mb-3">Rincian Nilai Per Tujuan Pembelajaran (TP):</p>
                    
                    <div class="grid grid-cols-12 gap-2 text-sm font-bold text-gray-700 bg-gray-100 p-2 rounded-lg">
                        <div class="col-span-4">Bab/TP</div>
                        <div class="col-span-3 text-center">Bobot (Max)</div>
                        <div class="col-span-3 text-center">Capaian TP (Skala 100)</div>
                        <div class="col-span-2 text-center">Kontribusi Nilai</div>
                    </div>
                    
                    <?php foreach ($tp_details as $tp): ?>
                        <div class="grid grid-cols-12 gap-2 items-center border-b border-gray-100 py-1">
                            <div class="col-span-4 font-semibold text-gray-800"><?php echo $tp['bab_name']; ?></div>
                            <div class="col-span-3 text-center text-red-600 font-bold"><?php echo $tp['weight']; ?> Poin</div>
                            <div class="col-span-3 text-center text-blue-700 font-extrabold"><?php echo number_format($tp['capaian_skala_100'], 2); ?></div>
                            <div class="col-span-2 text-center text-green-700 font-extrabold"><?php echo number_format($tp['score'], 2); ?></div>
                            
                            <div class="col-span-12 text-xs text-gray-500 pl-4">
                                <span class="font-medium">Distribusi Soal:</span> PG (<?php echo $tp['pg_count']; ?>), Isian (<?php echo $tp['isian_count']; ?>), Esai (<?php echo $tp['esai_count']; ?>) | Total: <?php echo $tp['total_soal']; ?> soal.
                            </div>
                        </div>
                    <?php endforeach; ?>

                    <p class="pt-4"><span class="font-bold text-blue-700">KKTP Global yang Ditetapkan:</span> <?php echo $kktp; ?></p>
                    <p class="text-xs text-gray-500 italic pt-2">Perhitungan didasarkan pada Tingkat Ketercapaian Global (GAR) untuk setiap jenis soal (PG, Isian, Esai), kemudian proporsi soal tersebut di dalam TP diterapkan pada bobot maksimum TP.</p>
                </div>
                
                <a href="hitung_nilai.php" 
                   class="mt-6 inline-block w-full bg-gray-500 hover:bg-gray-600 text-white font-bold py-3 rounded-lg transition duration-200 shadow-md transform hover:scale-[1.01]">
                    Hitung Ulang (Kembali ke Langkah 1)
                </a>
            </div>

        <?php endif; ?>

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