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

if (!isset($_SESSION['riwayat_id'])) {
    redirect('diagnosa.php');
}

$riwayat_id = $_SESSION['riwayat_id'];

// Get session data
$stmt = $pdo->prepare("
    SELECT g.kode as gejala_kode, g.nama as gejala_nama, j.cf_user, da.cf_rule, d.nama as diagnosa_nama, d.tipe as diagnosa_tipe, d.id as id_diagnosa
    FROM jawaban_user j
    JOIN gejala g ON j.id_gejala = g.id
    JOIN detail_aturan da ON g.id = da.id_gejala
    JOIN aturan a ON da.id_aturan = a.id
    JOIN diagnosa d ON a.id_diagnosa = d.id
    WHERE j.id_riwayat = ?
    ORDER BY d.tipe ASC, g.kode ASC
");
$stmt->execute(array($riwayat_id));
$details = $stmt->fetchAll();

// Group by diagnosis
$grouped = array();
foreach ($details as $row) {
    if (!isset($grouped[$row['diagnosa_nama']])) {
        $grouped[$row['diagnosa_nama']] = array(
            'tipe' => $row['diagnosa_tipe'],
            'items' => array()
        );
    }
    $grouped[$row['diagnosa_nama']]['items'][] = $row;
}

// Get total symptoms per diagnosa for average calculation
$total_symptoms = array();
$stmt_tot = $pdo->query("SELECT a.id_diagnosa, COUNT(da.id_gejala) as total FROM detail_aturan da JOIN aturan a ON da.id_aturan = a.id GROUP BY a.id_diagnosa");
while ($row = $stmt_tot->fetch()) {
    $total_symptoms[$row['id_diagnosa']] = $row['total'];
}
?>

<div class="container mx-auto px-6 py-12">
    <div class="max-w-4xl mx-auto">
        <div class="mb-12">
            <a href="hasil.php" class="inline-flex items-center gap-2 text-sm font-bold text-slate-400 hover:text-primary transition-all mb-4">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path></svg>
                Kembali ke Hasil
            </a>
            <h2 class="text-3xl font-extrabold text-slate-800">Detail Perhitungan Matematika</h2>
            <p class="text-slate-500">Transparansi perhitungan Certainty Factor (CF) berdasarkan aturan sistem pakar.</p>
        </div>

        <div class="space-y-12">
            <?php 
            $cf_pt_final = 0;
            $cf_ad_final = 0;
            $cf_pt_rata = 0;
            $cf_ad_rata = 0;
            
            foreach ($grouped as $diag_nama => $data): 
                $cfs = array();
                echo '<div class="card p-0 overflow-hidden">';
                echo '<div class="bg-slate-50 px-8 py-5 border-b border-slate-200">';
                echo '<h4 class="text-lg font-bold text-slate-800">Tahap 1: Perhitungan CF ' . $diag_nama . '</h4>';
                echo '</div>';
                echo '<div class="p-8">';
                echo '<table class="w-full text-left bg-slate-50 rounded-2xl overflow-hidden mb-8">';
                echo '<thead class="bg-slate-200/50 text-[10px] font-bold text-slate-500 uppercase tracking-widest">';
                echo '<tr><th class="px-6 py-4">Kode</th><th class="px-6 py-4">Nama Gejala</th><th class="px-6 py-4 text-center">CF User</th><th class="px-6 py-4 text-center">CF Pakar</th><th class="px-6 py-4 text-right">CF[H,E]</th></tr>';
                echo '</thead>';
                echo '<tbody>';
                
                foreach ($data['items'] as $item) {
                    $cf_he = $item['cf_user'] * $item['cf_rule'];
                    $cfs[] = $cf_he;
                    echo '<tr class="text-sm border-b border-white last:border-none">';
                    echo '<td class="px-6 py-4 font-bold text-primary">' . $item['gejala_kode'] . '</td>';
                    echo '<td class="px-6 py-4 text-slate-600">' . $item['gejala_nama'] . '</td>';
                    echo '<td class="px-6 py-4 text-center font-mono">' . $item['cf_user'] . '</td>';
                    echo '<td class="px-6 py-4 text-center font-mono">' . $item['cf_rule'] . '</td>';
                    echo '<td class="px-6 py-4 text-right font-bold text-slate-800">' . number_format($cf_he, 2) . '</td>';
                    echo '</tr>';
                }
                echo '</tbody></table>';

                // Combination Steps
                echo '<h5 class="font-bold text-slate-800 mb-4 flex items-center gap-2"><svg class="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path></svg> Langkah Kombinasi (CF Combine)</h5>';
                echo '<div class="space-y-3 font-mono text-xs bg-slate-900 text-slate-300 p-6 rounded-2xl">';
                
                $combined_cf = 0;
                if (count($cfs) > 0) {
                    $combined_cf = $cfs[0];
                    echo '<p class="text-slate-500">// Penyakit awal</p>';
                    echo '<p>CF Combine 1 = CF[1] = <span class="text-accent underline">' . number_format($combined_cf, 4) . '</span></p>';
                    
                    for ($i = 1; $i < count($cfs); $i++) {
                        $old = $combined_cf;
                        $new = $cfs[$i];
                        $combined_cf = $old + ($new * (1 - $old));
                        echo '<p class="mt-4 text-slate-500">// Iterasi ke-' . ($i + 1) . '</p>';
                        echo '<p>CF Combine ' . ($i + 1) . ' = ' . number_format($old, 4) . ' + (' . number_format($new, 4) . ' * (1 - ' . number_format($old, 4) . '))</p>';
                        echo '<p>CF Combine ' . ($i + 1) . ' = <span class="text-accent underline">' . number_format($combined_cf, 4) . '</span></p>';
                    }
                }
                
                // Track for final
                if ($data['tipe'] === 'PT') $cf_pt_final = $combined_cf;
                if ($data['tipe'] === 'AD') $cf_ad_final = $combined_cf;

                echo '</div>';
                
                // Calculate Average CF
                $id_diag = $data['items'][0]['id_diagnosa'];
                $tot_symptom = isset($total_symptoms[$id_diag]) ? $total_symptoms[$id_diag] : 1;
                $cf_rata = array_sum($cfs) / $tot_symptom;
                
                if ($data['tipe'] === 'PT') $cf_pt_rata = $cf_rata;
                if ($data['tipe'] === 'AD') $cf_ad_rata = $cf_rata;
                
                echo '<div class="mt-8 grid grid-cols-1 gap-6 max-w-sm mx-auto">';
                echo '<div class="bg-slate-50 p-5 rounded-2xl border border-slate-200 shadow-sm flex flex-col justify-center items-center text-center">';
                echo '<p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">CF Murni (Tingkat Keyakinan)</p>';
                echo '<p class="text-3xl font-black text-slate-700">' . number_format($combined_cf * 100, 2) . '%</p>';
                echo '</div>';
                echo '</div>';
                
                echo '</div></div>';
            endforeach; 
            ?>

            <?php if ($cf_pt_final > 0 && $cf_ad_final > 0): 
                $final_cf = $cf_pt_final + ($cf_ad_final * (1 - $cf_pt_final));
            ?>
                <div class="card p-0 overflow-hidden border-2 border-primary">
                    <div class="bg-primary px-8 py-5 flex justify-between items-center">
                        <h4 class="text-lg font-bold text-white">Tahap 2: Diagnosis Akhir (Mental Health Level)</h4>
                        <span class="bg-white/20 text-white text-[10px] font-bold px-3 py-1 rounded-full uppercase tracking-widest">Final Calculation</span>
                    </div>
                    <div class="p-8">
                        <div class="bg-slate-50 rounded-2xl p-8 mb-8">
                            <p class="text-slate-500 text-sm mb-6 leading-relaxed">
                                Pada tahap ini, sistem menggabungkan hasil CF dari gangguan Pola Tidur dan dampak Aktivitas Digital untuk mendapatkan tingkat kesehatan mental secara keseluruhan.
                            </p>
                            <div class="flex flex-col md:flex-row gap-8 items-center justify-center">
                                <div class="text-center">
                                    <p class="text-[10px] font-bold text-slate-400 uppercase mb-1">CF Pola Tidur</p>
                                    <p class="text-xl font-bold text-slate-700"><?= number_format($cf_pt_final, 4) ?></p>
                                </div>
                                <div class="text-2xl text-slate-300 font-light">+</div>
                                <div class="text-center">
                                    <p class="text-[10px] font-bold text-slate-400 uppercase mb-1">CF Aktivitas Digital</p>
                                    <p class="text-xl font-bold text-slate-700"><?= number_format($cf_ad_final, 4) ?></p>
                                </div>
                            </div>
                        </div>

                        <h5 class="font-bold text-slate-800 mb-4">Rumus Gabungan Akhir:</h5>
                        <div class="bg-slate-900 text-slate-300 p-8 rounded-2xl font-mono text-sm leading-loose">
                            <p class="text-slate-500 mb-4">// CF_Final = CF_PT + CF_AD * (1 - CF_PT)</p>
                            <p>CF Final = <?= number_format($cf_pt_final, 4) ?> + (<?= number_format($cf_ad_final, 4) ?> * (1 - <?= number_format($cf_pt_final, 4) ?>))</p>
                            <p>CF Final = <?= number_format($cf_pt_final, 4) ?> + (<?= number_format($cf_ad_final, 4) ?> * <?= number_format(1 - $cf_pt_final, 4) ?>)</p>
                            <p>CF Final = <?= number_format($cf_pt_final, 4) ?> + <?= number_format($cf_ad_final * (1 - $cf_pt_final), 4) ?></p>
                            <p class="text-xl mt-4">CF Final = <span class="text-accent underline"><?= number_format($final_cf, 4) ?></span></p>
                        </div>

                        <div class="mt-10 grid grid-cols-1 gap-6 max-w-sm mx-auto">
                            <?php 
                            $final_cf_rata = ($cf_pt_rata + $cf_ad_rata) / 2;
                            ?>
                            <div class="bg-slate-50 p-6 rounded-2xl border border-slate-200 flex flex-col justify-center items-center text-center">
                                <p class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-2">Interpretasi CF Murni</p>
                                <p class="text-4xl font-black text-slate-800"><?= number_format($final_cf * 100, 2) ?>%</p>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <div class="mt-12 pt-8 border-t border-slate-200 flex justify-center">
            <a href="hasil.php" class="btn-primary py-4 px-12">Selesai</a>
        </div>
    </div>
</div>

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