<?php
require_once '../../vendor/autoload.php';
include '../../koneksi.php';

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

/* ================= PREPROCESS ================= */
function preprocess($text)
{
    $text = strtolower($text);
    $text = preg_replace('/[^a-z0-9\s]/', '', $text);
    $tokens = array_filter(explode(' ', $text));

    $stopFactory = new StopWordRemoverFactory();
    $stopword = $stopFactory->createStopWordRemover();

    $stemFactory = new StemmerFactory();
    $stemmer = $stemFactory->createStemmer();

    $hasil = [];
    foreach ($tokens as $t) {
        $t = $stopword->remove($t);
        if (!empty($t)) {
            $hasil[] = $stemmer->stem($t);
        }
    }
    return $hasil;
}

/* ================= TF-IDF ================= */
function tfidf($tokens, $corpus)
{
    $tf = array_count_values($tokens);
    $tfidf = [];
    $N = count($corpus);

    foreach ($tf as $term => $freq) {
        $df = 0;
        foreach ($corpus as $doc) {
            if (in_array($term, $doc)) {
                $df++;
            }
        }
        if ($df == 0) continue;

        $idf = log10($N / $df);
        $tfidf[$term] = ($freq / count($tokens)) * $idf;
    }
    return $tfidf;
}

/* ================= COSINE ================= */
function cosineSimilarity($v1, $v2)
{
    $dot = 0;
    $mag1 = 0;
    $mag2 = 0;

    foreach ($v1 as $term => $value) {
        $dot += $value * ($v2[$term] ?? 0);
        $mag1 += $value * $value;
    }

    foreach ($v2 as $value) {
        $mag2 += $value * $value;
    }

    if ($mag1 == 0 || $mag2 == 0) return 0;
    return $dot / (sqrt($mag1) * sqrt($mag2));
}

/* ================= PARAMETER ================= */
$nis         = $_GET['nis'];
$kode_kelas  = $_GET['kode_kelas'];
$kode_mapel  = $_GET['kode_mapel'];
$jenis_ujian = $_GET['jenis_ujian'];

/* ================= AMBIL DATA ================= */
$q_soal = mysqli_query($koneksi, "
    SELECT knc_jawaban, bobot 
    FROM soal_essay 
    WHERE kode_kelas='$kode_kelas'
    AND kode_mapel='$kode_mapel'
    AND jenis_ujian='$jenis_ujian'
");

$q_jawaban = mysqli_query($koneksi, "
    SELECT jawaban 
    FROM jawaban_essay 
    WHERE nis='$nis'
    AND kode_kelas='$kode_kelas'
    AND kode_mapel='$kode_mapel'
    AND jenis_ujian='$jenis_ujian'
");

$kunci = [];
$jawaban = [];
$bobot = [];

while ($s = mysqli_fetch_assoc($q_soal)) {
    $kunci[] = $s['knc_jawaban'];
    $bobot[] = $s['bobot'];
}

while ($j = mysqli_fetch_assoc($q_jawaban)) {
    $jawaban[] = $j['jawaban'];
}

/* ================= VALIDASI ================= */
if (count($kunci) == 0 || count($jawaban) == 0) {
    die('Data soal atau jawaban tidak ditemukan');
}

/* ================= CORPUS ================= */
$corpus = [];
foreach (array_merge($kunci, $jawaban) as $doc) {
    $corpus[] = preprocess($doc);
}

/* ================= HITUNG COSINE ================= */
$totalCosine = 0;
$totalBobot  = array_sum($bobot);

for ($i = 0; $i < count($kunci); $i++) {
    $tfidf_kunci   = tfidf($corpus[$i], $corpus);
    $tfidf_jawaban = tfidf($corpus[$i + count($kunci)], $corpus);

    $cs = cosineSimilarity($tfidf_kunci, $tfidf_jawaban);
    $totalCosine += ($cs * $bobot[$i]);
}

$nilai_cosine = ($totalBobot > 0) ? round($totalCosine / $totalBobot, 3) : 0;

/* ================= INSERT / UPDATE ================= */
$cek = mysqli_query($koneksi, "
    SELECT * 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, "
        INSERT INTO nilai_essay
        (nis, kode_kelas, kode_mapel, jenis_ujian, nilai_cosine)
        VALUES
        ('$nis', '$kode_kelas', '$kode_mapel', '$jenis_ujian', '$nilai_cosine')
    ");
} else {
    mysqli_query($koneksi, "
        UPDATE nilai_essay
        SET nilai_cosine='$nilai_cosine'
        WHERE nis='$nis'
        AND kode_kelas='$kode_kelas'
        AND kode_mapel='$kode_mapel'
        AND jenis_ujian='$jenis_ujian'
    ");
}

/* ================= REDIRECT ================= */
header("Location: hasil_ujian.php?kode_kelas=$kode_kelas&kode_mapel=$kode_mapel&jenis_ujian=$jenis_ujian");
exit;
