<?php
// Samakan variabel jenis_ujian jika dipanggil dari hasil_ujian siswa
if (isset($jenis_ujian_post) && !empty($jenis_ujian_post)) {
    $jenis_ujian = $jenis_ujian_post;
}

require_once __DIR__ . '/../../vendor/autoload.php';

use Sastrawi\Stemmer\StemmerFactory;
use Sastrawi\StopWordRemover\StopWordRemoverFactory;

// ===== FUNGSI PREPROCESSING (SAMA DENGAN cosine.php GURU) =====
function auto_tokenize($text) {
    $tokens = [];
    $words = preg_split('/\s+/', $text);
    foreach ($words as $word) {
        $word = strtolower($word);
        $word = preg_replace('/[^a-z0-9\-]/', '', $word);
        if (!empty($word)) $tokens[] = $word;
    }
    return $tokens;
}

function auto_filter($tokens) {
    $stopwordRemover = (new StopWordRemoverFactory())->createStopWordRemover();
    $result = [];
    foreach ($tokens as $token) {
        $filtered = $stopwordRemover->remove($token);
        if (!empty($filtered)) $result[] = $filtered;
    }
    return $result;
}

function auto_stem($tokens) {
    $stemmer = (new StemmerFactory())->createStemmer();
    $result = [];
    foreach ($tokens as $token) {
        $result[] = $stemmer->stem($token);
    }
    return $result;
}

function auto_getSinonim($kata) {
    $url = "https://www.sinonimkata.com/search.php";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "q=" . urlencode($kata));
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $html = curl_exec($ch);
    curl_close($ch);

    if (!$html) return [$kata];

    if (preg_match("/sinonim<\/td>(.*?)antonim/s", $html, $bagian)) {
        $bagianSinonim = $bagian[1];
    } else if (preg_match("/sinonim<\/td>(.*?)<\/table>/s", $html, $bagian)) {
        $bagianSinonim = $bagian[1];
    } else {
        return [$kata];
    }

    preg_match_all("/>([^<]+)<\/a>/", $bagianSinonim, $matches);
    $sinonim = [];
    foreach ($matches[1] as $s) {
        $bersih = strtolower(trim($s));
        if (!empty($bersih)) $sinonim[] = $bersih;
    }
    $sinonim[] = strtolower($kata);
    return array_unique($sinonim);
}

function auto_applySinonim($tokens_siswa, $tokens_kunci) {
    $hasil = [];
    foreach ($tokens_siswa as $kata) {
        $sinonim = auto_getSinonim($kata);
        $cocok = false;
        foreach ($tokens_kunci as $kata_kunci) {
            if (in_array($kata_kunci, $sinonim)) {
                $hasil[] = $kata_kunci;
                $cocok = true;
                break;
            }
        }
        if (!$cocok) $hasil[] = $kata;
    }
    return $hasil;
}

function auto_preprocess($text, $tokens_kunci = []) {
    $tokens   = auto_tokenize($text);
    $filtered = auto_filter($tokens);
    $stemmed  = auto_stem($filtered);

    $sinonim = $stemmed;
    if (!empty($tokens_kunci)) {
        $sinonim = auto_applySinonim($stemmed, $tokens_kunci);
    }

    return implode(' ', $sinonim);
}

// ===== FUNGSI COSINE SIMILARITY =====
function auto_term_frequency($text) {
    $words = preg_split('/\s+/', strtolower($text), -1, PREG_SPLIT_NO_EMPTY);
    return array_count_values($words);
}

function auto_cosine_similarity($text_a, $text_b) {
    $freq_a    = auto_term_frequency($text_a);
    $freq_b    = auto_term_frequency($text_b);
    $all_terms = array_unique(array_merge(array_keys($freq_a), array_keys($freq_b)));

    $dot = $sum_a = $sum_b = 0;
    foreach ($all_terms as $term) {
        $a = $freq_a[$term] ?? 0;
        $b = $freq_b[$term] ?? 0;
        $dot   += $a * $b;
        $sum_a += $a * $a;
        $sum_b += $b * $b;
    }
    if ($sum_a == 0 || $sum_b == 0) return 0;
    return $dot / (sqrt($sum_a) * sqrt($sum_b));
}

// ===== FUNGSI LEVENSHTEIN SIMILARITY =====
function auto_levenshtein_similarity($s1, $s2) {
    $d   = levenshtein($s1, $s2);
    $max = max(strlen($s1), strlen($s2));
    return ($max == 0) ? 0 : (1 - ($d / $max));
}

// ===== AMBIL DATA JAWABAN =====
$q = mysqli_query($koneksi, "
    SELECT j.id, j.jawaban, s.knc_jawaban, s.bobot
    FROM jawaban_essay j
    JOIN soal_essay s ON j.id_soal = s.id_soal
    WHERE j.nis='$nis'
      AND j.kode_kelas='$kode_kelas'
      AND j.kode_mapel='$kode_mapel'
      AND j.jenis_ujian='$jenis_ujian'
    ORDER BY s.id_soal
");

$total_nilai_akhir   = 0;
$total_cosine        = 0;
$total_levenshtein   = 0;
$index               = 0;

while ($row = mysqli_fetch_assoc($q)) {
    $id_jawaban = $row['id'];
    $bobot      = $row['bobot'];

    // Preprocessing sama persis dengan cosine.php guru (termasuk sinonim)
    $tokens_kunci  = auto_stem(auto_filter(auto_tokenize($row['knc_jawaban'])));
    $final_kunci   = auto_preprocess($row['knc_jawaban']);
    $final_jawaban = auto_preprocess($row['jawaban'], $tokens_kunci);

    // Cosine & Levenshtein
    $cosine_raw = auto_cosine_similarity($final_kunci, $final_jawaban);
    $lev_raw    = auto_levenshtein_similarity($final_kunci, $final_jawaban);

    // Final Score per soal
    $final_score = ($cosine_raw + $lev_raw) / 2;
    $nilai_soal  = round($final_score * $bobot, 2);

    // Update skor per jawaban
    mysqli_query($koneksi, "
        UPDATE jawaban_essay
        SET skor = '$nilai_soal'
        WHERE id = '$id_jawaban'
    ");

    $total_cosine      += $cosine_raw;
    $total_levenshtein += $lev_raw;
    $total_nilai_akhir += $nilai_soal;
    $index++;
}

$nilai_cosine_total      = $index > 0 ? number_format($total_cosine / $index, 2) : 0;
$nilai_levenshtein_total = $index > 0 ? number_format($total_levenshtein / $index, 2) : 0;
$nilai_akhir_total       = round($total_nilai_akhir, 2);

// Simpan ke database
$cek = mysqli_query($koneksi, "
    SELECT id FROM nilai_essay
    WHERE nis='$nis'
      AND kode_kelas='$kode_kelas'
      AND kode_mapel='$kode_mapel'
      AND jenis_ujian='$jenis_ujian'
");

if (mysqli_num_rows($cek) > 0) {
    mysqli_query($koneksi, "
        UPDATE nilai_essay
        SET nilai_cosine      = '$nilai_cosine_total',
            nilai_levenshtein = '$nilai_levenshtein_total',
            nilai_akhir       = '$nilai_akhir_total'
        WHERE nis='$nis'
          AND kode_kelas='$kode_kelas'
          AND kode_mapel='$kode_mapel'
          AND jenis_ujian='$jenis_ujian'
    ");
} else {
    mysqli_query($koneksi, "
        INSERT INTO nilai_essay (nis, kode_kelas, kode_mapel, jenis_ujian, nilai_cosine, nilai_levenshtein, nilai_akhir)
        VALUES ('$nis', '$kode_kelas', '$kode_mapel', '$jenis_ujian', '$nilai_cosine_total', '$nilai_levenshtein_total', '$nilai_akhir_total')
    ");
}