<?php
require_once __DIR__ . '/../../vendor/autoload.php';
// pastikan koneksi.php sudah di-include sebelumnya

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

/* ===========================
   PREPROCESSING (SAMA PERSIS)
=========================== */

function tokenize($text) {
    $words = preg_split('/\s+/', strtolower($text));
    return array_values(array_filter(array_map(
        fn($w) => preg_replace('/[^a-z0-9]/', '', $w),
        $words
    )));
}

function filtering($tokens) {
    $stopwordRemover = (new StopWordRemoverFactory())->createStopWordRemover();
    return array_values(array_filter(array_map(
        fn($t) => $stopwordRemover->remove($t),
        $tokens
    )));
}

function stemming($tokens) {
    $stemmer = (new StemmerFactory())->createStemmer();
    return array_map(fn($t) => $stemmer->stem($t), $tokens);
}

function preprocessing_detail($text) {
    $token  = tokenize($text);
    $filter = filtering($token);
    $stem   = stemming($filter);

    return [
        'final' => implode(' ', $stem)
    ];
}

/* ===========================
   FUNGSI SIMILARITY
=========================== */

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

/* ===========================
   AMBIL DATA
=========================== */

$q = mysqli_query($koneksi, "
SELECT j.jawaban, s.knc_jawaban
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_ld = 0;

/* ===========================
   PROSES PER SOAL (IDENTIK)
=========================== */

while ($row = mysqli_fetch_assoc($q)) {

    $prep_kunci   = preprocessing_detail($row['knc_jawaban']);
    $prep_jawaban = preprocessing_detail($row['jawaban']);

    $sim_murni = levenshtein_similarity(
        $prep_kunci['final'],
        $prep_jawaban['final']
    );

    // ===== IDENTIK DENGAN FILE GURU =====

    $similarity_murni  = round($sim_murni, 2);
    $similarity_persen = round($similarity_murni * 100);
    $nilai_levenshtein = round($similarity_persen * 0.2, 1);

    $total_nilai_ld += $nilai_levenshtein;
}

/* ===========================
   TOTAL AKHIR
=========================== */

$nilai_levenshtein_total = round($total_nilai_ld, 1);

/* ===========================
   UPDATE DATABASE
=========================== */

mysqli_query($koneksi, "
UPDATE nilai_essay 
SET nilai_levenshtein='$nilai_levenshtein_total'
WHERE nis='$nis'
AND kode_kelas='$kode_kelas'
AND kode_mapel='$kode_mapel'
AND jenis_ujian='$jenis_ujian'
");