<?php
session_start();

function baseUrl($path = '') {
    // Basic base URL helper
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
    $host = $_SERVER['HTTP_HOST'];
    $uri = str_replace(array('/admin', '/includes', '/config'), '', dirname($_SERVER['SCRIPT_NAME']));
    $uri = rtrim($uri, '/\\');
    return $protocol . "://" . $host . $uri . "/" . ltrim($path, '/');
}

function redirect($url) {
    header("Location: " . $url);
    exit();
}

function setFlash($type, $message) {
    $_SESSION['flash'] = array(
        'type' => $type,
        'message' => $message
    );
}

function getFlash() {
    if (isset($_SESSION['flash'])) {
        $flash = $_SESSION['flash'];
        unset($_SESSION['flash']);
        return $flash;
    }
    return null;
}

function checkAdmin() {
    if (!isset($_SESSION['admin_auth'])) {
        setFlash('error', 'Silahkan login terlebih dahulu.');
        redirect(baseUrl('admin/login.php'));
    }
}

function checkSiswa() {
    if (!isset($_SESSION['siswa_auth'])) {
        setFlash('error', 'Silahkan login terlebih dahulu.');
        redirect(baseUrl('login-siswa.php'));
    }
}

/**
 * Certainty Factor Calculation
 * $inputs: array of [id_gejala => cf_user]
 */
function calculateCertaintyFactor($pdo, $inputs) {
    if (empty($inputs)) return array();

    // 1. Ambil semua aturan yang gejalanya ada di input
    $gejalaIds = array_keys($inputs);
    $placeholders = implode(',', array_fill(0, count($gejalaIds), '?'));
    
    $stmt = $pdo->prepare("
        SELECT a.id_diagnosa, da.id_gejala, da.cf_rule, d.nama as diagnosa_nama, d.tipe as diagnosa_tipe
        FROM detail_aturan da
        JOIN aturan a ON da.id_aturan = a.id
        JOIN diagnosa d ON a.id_diagnosa = d.id
        WHERE da.id_gejala IN ($placeholders)
    ");
    $stmt->execute($gejalaIds);
    $rules = $stmt->fetchAll();

    $results = array(); 

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

    // 2. Hitung CF per Diagnosa (Tahap 1: PT & AD)
    $groupedRules = array();
    foreach ($rules as $rule) {
        $id_diagnosa = $rule['id_diagnosa'];
        $id_gejala = $rule['id_gejala'];
        $cf_user = isset($inputs[$id_gejala]) ? $inputs[$id_gejala] : 0;
        
        $cf_calc = $cf_user * $rule['cf_rule'];
        
        if (!isset($groupedRules[$id_diagnosa])) {
            $groupedRules[$id_diagnosa] = array(
                'nama' => $rule['diagnosa_nama'],
                'tipe' => $rule['diagnosa_tipe'],
                'cfs' => array()
            );
        }
        $groupedRules[$id_diagnosa]['cfs'][] = $cf_calc;
    }

    $primary_results = array();
    foreach ($groupedRules as $id_diag => $data) {
        $cfs = $data['cfs'];
        $combined_cf = 0;
        if (count($cfs) > 0) {
            $combined_cf = $cfs[0];
            for ($i = 1; $i < count($cfs); $i++) {
                $combined_cf = $combined_cf + ($cfs[$i] * (1 - $combined_cf));
            }
        }
        
        $cf_rata = 0;
        if (isset($total_symptoms[$id_diag]) && $total_symptoms[$id_diag] > 0) {
            $cf_rata = array_sum($cfs) / $total_symptoms[$id_diag];
        }

        $primary_results[$id_diag] = array(
            'id' => $id_diag,
            'nama' => $data['nama'],
            'tipe' => $data['tipe'],
            'cf' => $combined_cf,
            'cf_rata' => $cf_rata
        );
    }

    // 3. Tahap 2: Gabungkan ke FINAL jika KEDUA tipe ada (PT dan AD)
    $pt_cf = 0;
    $ad_cf = 0;
    $has_pt = false;
    $has_ad = false;

    $pt_cf_rata = 0;
    $ad_cf_rata = 0;

    foreach ($primary_results as $pr) {
        if ($pr['tipe'] === 'PT' && $pr['cf'] > 0) {
            $pt_cf = $pr['cf'];
            $pt_cf_rata = $pr['cf_rata'];
            $has_pt = true;
        }
        if ($pr['tipe'] === 'AD' && $pr['cf'] > 0) {
            $ad_cf = $pr['cf'];
            $ad_cf_rata = $pr['cf_rata'];
            $has_ad = true;
        }
    }

    // Jika keduanya ada, tambahkan hasil FINAL (R9-R11)
    if ($has_pt && $has_ad) {
        $final_diag = $pdo->query("SELECT * FROM diagnosa WHERE tipe = 'FINAL' LIMIT 1")->fetch();
        if ($final_diag) {
            $final_cf = $pt_cf + ($ad_cf * (1 - $pt_cf));
            $final_cf_rata = ($pt_cf_rata + $ad_cf_rata) / 2;
            $primary_results[$final_diag['id']] = array(
                'id' => $final_diag['id'],
                'nama' => $final_diag['nama'],
                'tipe' => 'FINAL',
                'cf' => $final_cf,
                'cf_rata' => $final_cf_rata
            );
        }
    }

    // Sort: FINAL always top if exists, then by CF descending
    uasort($primary_results, function($a, $b) {
        if ($a['tipe'] === 'FINAL') return -1;
        if ($b['tipe'] === 'FINAL') return 1;
        if ($b['cf'] == $a['cf']) return 0;
        return ($b['cf'] > $a['cf']) ? 1 : -1;
    });

    return $primary_results;
}

function getKategoriCF($pdo, $id_diagnosa, $cf) {
    $stmt = $pdo->prepare("SELECT nama FROM kategori_cf WHERE id_diagnosa = ? AND ? >= min_cf AND ? <= max_cf LIMIT 1");
    $stmt->execute(array($id_diagnosa, $cf, $cf));
    $res = $stmt->fetch();
    return $res ? $res['nama'] : "Tidak Terdefinisi";
}

function renderPagination($currentPage, $totalPages, $baseUrl) {
    if ($totalPages <= 1) return "";
    
    $html = '<div class="flex justify-center items-center gap-2 mt-8">';
    
    // Previous button
    if ($currentPage > 1) {
        $html .= '<a href="' . $baseUrl . 'page=' . ($currentPage - 1) . '" class="w-10 h-10 flex items-center justify-center rounded-xl bg-white border border-slate-200 text-slate-600 hover:bg-primary hover:text-white transition-all">&laquo;</a>';
    }
    
    // Page numbers
    for ($i = 1; $i <= $totalPages; $i++) {
        $activeClass = $i == $currentPage ? 'bg-primary text-white border-primary' : 'bg-white text-slate-600 border-slate-200 hover:bg-slate-50';
        $html .= '<a href="' . $baseUrl . 'page=' . $i . '" class="w-10 h-10 flex items-center justify-center rounded-xl border ' . $activeClass . ' font-bold transition-all">' . $i . '</a>';
    }
    
    // Next button
    if ($currentPage < $totalPages) {
        $html .= '<a href="' . $baseUrl . 'page=' . ($currentPage + 1) . '" class="w-10 h-10 flex items-center justify-center rounded-xl bg-white border border-slate-200 text-slate-600 hover:bg-primary hover:text-white transition-all">&raquo;</a>';
    }
    
    $html .= '</div>';
    return $html;
}
?>
