<?php
require_once 'includes/header-siswa.php';
checkSiswa();

$gejala = $pdo->query("SELECT * FROM gejala ORDER BY tipe ASC, CAST(SUBSTR(kode, 3) AS UNSIGNED) ASC")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['proses_diagnosa'])) {
    $selected_gejala = isset($_POST['gejala']) ? $_POST['gejala'] : array();
    $beliefs = isset($_POST['belief']) ? $_POST['belief'] : array();
    
    if (empty($selected_gejala)) {
        $error = "Silahkan pilih setidaknya satu gejala.";
    } else {
        $inputs = array();
        foreach ($selected_gejala as $gid) {
            $inputs[$gid] = isset($beliefs[$gid]) ? (float)$beliefs[$gid] : 0;
        }
        
        $results = calculateCertaintyFactor($pdo, $inputs);
        
        if (empty($results)) {
            $error = "Tidak ada diagnosa yang cocok dengan kombinasi gejala tersebut.";
        } else {
            // Save to DB
            $nis = $_SESSION['siswa_auth']['nis'];
            $top_result = reset($results); // Get first (strongest)
            
            $pdo->beginTransaction();
            try {
                // Delete previous history for this student (will cascade to jawaban_user)
                $stmt_del = $pdo->prepare("DELETE FROM riwayat_diagnosa WHERE nis = ?");
                $stmt_del->execute(array($nis));
                
                $stmt = $pdo->prepare("INSERT INTO riwayat_diagnosa (nis, id_diagnosa, total_cf, total_cf_rata) VALUES (?, ?, ?, ?)");
                $stmt->execute(array($nis, $top_result['id'], $top_result['cf'], $top_result['cf_rata']));
                $riwayat_id = $pdo->lastInsertId();
                
                $stmt_detail = $pdo->prepare("INSERT INTO jawaban_user (id_riwayat, nis, id_gejala, cf_user) VALUES (?, ?, ?, ?)");
                foreach ($inputs as $gid => $cfu) {
                    $stmt_detail->execute(array($riwayat_id, $nis, $gid, $cfu));
                }
                
                $pdo->commit();
                $_SESSION['last_result'] = $results;
                $_SESSION['riwayat_id'] = $riwayat_id;
                redirect('hasil.php');
            } catch (Exception $e) {
                $pdo->rollBack();
                $error = "Terjadi kesalahan sistem: " . $e->getMessage();
            }
        }
    }
}
?>

<div class="container mx-auto px-6 py-12">
    <div class="max-w-4xl mx-auto">
        <div class="mb-12 text-center">
            <h2 class="text-3xl font-extrabold text-slate-800 mb-4">Mulai Diagnosa Mandiri</h2>
            <p class="text-slate-500 font-medium">Pilih gejala yang Anda rasakan selama 2 minggu terakhir dan tentukan tingkat keyakinannya.</p>
        </div>

        <?php if (isset($error)): ?>
            <div class="mb-8 p-6 rounded-2xl bg-red-100 text-red-700 border border-red-200 font-bold">
                <?= $error ?>
            </div>
        <?php endif; ?>

        <form action="" method="POST" class="space-y-6">
            <input type="hidden" name="proses_diagnosa" value="1">
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <?php 
                $current_type = '';
                foreach ($gejala as $g): 
                    if ($current_type !== $g['tipe']):
                        $current_type = $g['tipe'];
                        $type_label = ($current_type === 'PT') ? 'Gejala Pola Tidur' : 'Gejala Aktivitas Digital';
                ?>
                    <div class="md:col-span-2 mt-8 mb-4">
                        <h4 class="text-sm font-black text-slate-400 uppercase tracking-[0.2em] flex items-center gap-4">
                            <span class="flex-shrink-0"><?= $type_label ?></span>
                            <div class="h-px bg-slate-200 flex-1"></div>
                        </h4>
                    </div>
                <?php endif; ?>
                    <div class="card p-8 border border-slate-100 flex flex-col justify-between gap-6 hover:border-primary/40 hover:shadow-md transition-all group">
                        <div class="flex items-start gap-5">
                            <div class="flex-shrink-0 pt-1">
                                <label class="relative inline-flex items-center cursor-pointer">
                                    <input type="checkbox" name="gejala[]" value="<?= $g['id'] ?>" class="peer sr-only" onchange="toggleBelief(this, <?= $g['id'] ?>)">
                                    <div class="w-7 h-7 bg-slate-100 border-2 border-slate-200 rounded-xl peer-checked:bg-primary peer-checked:border-primary transition-all flex items-center justify-center">
                                        <svg class="w-5 h-5 text-white opacity-0 peer-checked:opacity-100 transition-opacity" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"></path></svg>
                                    </div>
                                </label>
                            </div>
                            <div class="flex-1">
                                <p class="text-[10px] font-bold text-primary uppercase tracking-[0.1em] mb-1.5"><?= $g['kode'] ?></p>
                                <p class="text-slate-700 font-medium text-sm leading-relaxed"><?= $g['pernyataan'] ?></p>
                            </div>
                        </div>
                        
                        <div id="belief_container_<?= $g['id'] ?>" class="opacity-30 pointer-events-none transition-all duration-300">
                            <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-2">Seberapa sering Anda merasakannya?</label>
                            <select name="belief[<?= $g['id'] ?>]" disabled class="w-full px-4 py-3 rounded-xl border border-slate-100 bg-slate-50 text-sm font-bold text-slate-800 focus:border-primary outline-none transition-all appearance-none">
                                <option value="0.4">Sangat Sering</option>
                                <option value="0.2">Sering</option>
                                <option value="0.1">Jarang</option>
                                <option value="0">Tidak Pernah</option>
                            </select>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="pt-10 sticky bottom-8">
                <button type="submit" class="w-full btn-primary py-5 text-xl font-extrabold shadow-2xl shadow-primary/40 flex items-center justify-center gap-4">
                    Lihat Hasil Diagnosa
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M14 5l7 7m0 0l-7 7m7-7H3"></path></svg>
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function toggleBelief(checkbox, id) {
    const container = document.getElementById('belief_container_' + id);
    const select = container.querySelector('select');
    if (checkbox.checked) {
        container.classList.remove('opacity-30', 'pointer-events-none');
        select.disabled = false;
        select.classList.remove('bg-slate-50', 'border-slate-100');
        select.classList.add('bg-white', 'border-slate-200');
    } else {
        container.classList.add('opacity-30', 'pointer-events-none');
        select.disabled = true;
        select.classList.add('bg-slate-50', 'border-slate-100');
        select.classList.remove('bg-white', 'border-slate-200');
    }
}
</script>

<?php require_once 'includes/footer-siswa.php'; ?>
