<?php
session_start();

if (!isset($_SESSION["login"])) {
    header("location: ../../login.php");
    exit;
}

$nip = $_SESSION['nip'];

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../../vendor/autoload.php';
include "../../koneksi.php";

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

/* ===========================
   FUNGSI PREPROCESSING
=========================== */

function 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 filter($tokens)
{
    $filteredTokens = [];
    $stopwordRemoverFactory = new StopWordRemoverFactory();
    $stopwordRemover = $stopwordRemoverFactory->createStopWordRemover();

    foreach ($tokens as $token) {
        $filteredToken = $stopwordRemover->remove($token);
        if (!empty($filteredToken)) {
            $filteredTokens[] = $filteredToken;
        }
    }
    return $filteredTokens;
}

function stem($tokens)
{
    $stemmedTokens = [];
    $stemmerFactory = new StemmerFactory();
    $stemmer = $stemmerFactory->createStemmer();

    foreach ($tokens as $token) {
        $stemmedTokens[] = $stemmer->stem($token);
    }

    return $stemmedTokens;
}

/* ===========================
   FUNGSI SINONIM
=========================== */

function 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 [];

    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 applySinonim($tokens_siswa, $tokens_kunci) {
    $hasil = [];
    foreach ($tokens_siswa as $kata) {
        $sinonim = 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 preprocessing_text($text, $tokens_kunci = [])
{
    $tokens   = tokenize($text);
    $filtered = filter($tokens);
    $stemmed  = stem($filtered);

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

    $final = implode(' ', $sinonim);

    return [
        'original' => $text,
        'tokens'   => $tokens,
        'filtered' => $filtered,
        'stemmed'  => $stemmed,
        'sinonim'  => $sinonim,
        'final'    => $final
    ];
}

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

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

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

    $dot_product    = 0;
    $sum_a_squared  = 0;
    $sum_b_squared  = 0;

    foreach ($all_terms as $term) {
        $count_a = $freq_a[$term] ?? 0;
        $count_b = $freq_b[$term] ?? 0;
        $dot_product   += $count_a * $count_b;
        $sum_a_squared += $count_a * $count_a;
        $sum_b_squared += $count_b * $count_b;
    }

    if ($sum_a_squared == 0 || $sum_b_squared == 0) return 0;

    return $dot_product / (sqrt($sum_a_squared) * sqrt($sum_b_squared));
}

function cosine_similarity_detail($text_a, $text_b) {
    $freq_a    = term_frequency($text_a);
    $freq_b    = term_frequency($text_b);
    $all_terms = array_unique(array_merge(array_keys($freq_a), array_keys($freq_b)));
    sort($all_terms);

    $term_table = [];
    foreach ($all_terms as $term) {
        $term_table[] = [
            'term'   => $term,
            'freq_a' => $freq_a[$term] ?? 0,
            'freq_b' => $freq_b[$term] ?? 0
        ];
    }

    $dot_product   = 0;
    $sum_a_squared = 0;
    $sum_b_squared = 0;

    foreach ($all_terms as $term) {
        $count_a = $freq_a[$term] ?? 0;
        $count_b = $freq_b[$term] ?? 0;
        $dot_product   += ($count_a * $count_b);
        $sum_a_squared += ($count_a * $count_a);
        $sum_b_squared += ($count_b * $count_b);
    }

    $similarity_raw = 0;
    if ($sum_a_squared > 0 && $sum_b_squared > 0) {
        $similarity_raw = $dot_product / (sqrt($sum_a_squared) * sqrt($sum_b_squared));
    }

    return [
        'term_table'    => $term_table,
        'dot_product'   => $dot_product,
        'sum_a_squared' => $sum_a_squared,
        'sum_b_squared' => $sum_b_squared,
        'sqrt_a'        => sqrt($sum_a_squared),
        'sqrt_b'        => sqrt($sum_b_squared),
        'similarity_raw' => round($similarity_raw, 4),
    ];
}

/* ===========================
   FUNGSI LEVENSHTEIN
=========================== */

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

function levenshtein_matrix($s, $t) {
    $m = strlen($s);
    $n = strlen($t);
    $d = [];

    for ($i = 0; $i <= $m; $i++) $d[$i][0] = $i;
    for ($j = 0; $j <= $n; $j++) $d[0][$j] = $j;

    for ($i = 1; $i <= $m; $i++) {
        for ($j = 1; $j <= $n; $j++) {
            $cost       = ($s[$i-1] == $t[$j-1]) ? 0 : 1;
            $d[$i][$j]  = min(
                $d[$i-1][$j] + 1,
                $d[$i][$j-1] + 1,
                $d[$i-1][$j-1] + $cost
            );
        }
    }
    return $d;
}

/* ===========================
   PARAMETER
=========================== */

$nis         = $_GET['nis'];
$kode_kelas  = $_GET['kode_kelas'];
$kode_mapel  = $_GET['kode_mapel'];
$jenis_ujian = $_GET['jenis_ujian'];

/* ===========================
   AMBIL DATA DARI DATABASE
=========================== */

$q = mysqli_query($koneksi, "
    SELECT j.id, j.jawaban, s.knc_jawaban, s.bobot, s.soal
    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
");

if (!$q) {
    die("Error query data: " . mysqli_error($koneksi));
}

$total_nilai_cosine      = 0;
$total_nilai_levenshtein = 0;
$total_nilai_akhir       = 0;

$scoreTableData          = [];
$detailCosineData        = [];
$detailLevenshteinData   = [];
$questionsAndAnswersData = [];
$preprocessingData       = [];

/* ===========================
   PROSES PER SOAL
=========================== */

$index = 0;
while ($row = mysqli_fetch_assoc($q)) {

    $id_jawaban = $row['id'];
    $bobot      = $row['bobot'];

    // ===== PREPROCESSING =====
    $prep_kunci   = preprocessing_text($row['knc_jawaban']);
    $prep_jawaban = preprocessing_text($row['jawaban'], $prep_kunci['stemmed']);

    $final_kunci   = $prep_kunci['final'];
    $final_jawaban = $prep_jawaban['final'];

    // ===== COSINE SIMILARITY =====
    $cosine_raw = cosine_similarity($final_kunci, $final_jawaban);

    // ===== LEVENSHTEIN SIMILARITY =====
    $lev_raw  = levenshtein_similarity($final_kunci, $final_jawaban);
    $lev_dist = levenshtein($final_kunci, $final_jawaban);

    // ===== FORMULA BARU =====
    // Langkah 1: Final Score = (Cosine + Levenshtein) / 2
    $final_score = ($cosine_raw + $lev_raw) / 2;

    // Langkah 2: Nilai Soal = Final Score × Bobot
    $nilai_soal = round($final_score * $bobot, 2);

    // Format 2 angka desimal (skala 0-1)
    $cosine_fmt      = number_format($cosine_raw, 2);
    $levenshtein_fmt = number_format($lev_raw, 2);
    $final_score_fmt = number_format($final_score, 2);

    // ===== UPDATE SKOR DI DATABASE =====
    mysqli_query($koneksi, "
        UPDATE jawaban_essay
        SET skor = '$nilai_soal'
        WHERE id = '$id_jawaban'
    ");

    // ===== AKUMULASI TOTAL =====
    $total_nilai_cosine      += $cosine_raw;
    $total_nilai_levenshtein += $lev_raw;
    $total_nilai_akhir       += $nilai_soal;

    // ===== SIMPAN DATA SCORE =====
    $scoreTableData[] = [
        'Question'        => 'Soal ' . ($index + 1),
        'Cosine_Raw'      => $cosine_fmt,
        'Levenshtein_Raw' => $levenshtein_fmt,
        'Final_Score'     => $final_score_fmt,
        'Bobot'           => $bobot,
        'Nilai_Soal'      => $nilai_soal,
    ];

    // ===== SIMPAN DATA SOAL =====
    $questionsAndAnswersData[] = [
        'index'     => $index,
        'question'  => $row['soal'],
        'answerKey' => $row['knc_jawaban'],
        'weight'    => $bobot,
        'answer'    => $row['jawaban']
    ];

    // ===== SIMPAN DATA PREPROCESSING =====
    $preprocessingData[] = [
        'index'      => $index,
        'type'       => 'Kunci Jawaban',
        'tokenizing' => implode(", ", $prep_kunci['tokens']),
        'filtering'  => implode(", ", $prep_kunci['filtered']),
        'stemming'   => implode(", ", $prep_kunci['stemmed']),
        'sinonim'    => implode(", ", $prep_kunci['sinonim'])
    ];
    $preprocessingData[] = [
        'index'      => $index,
        'type'       => 'Jawaban Siswa',
        'tokenizing' => implode(", ", $prep_jawaban['tokens']),
        'filtering'  => implode(", ", $prep_jawaban['filtered']),
        'stemming'   => implode(", ", $prep_jawaban['stemmed']),
        'sinonim'    => implode(", ", $prep_jawaban['sinonim'])
    ];

    // ===== SIMPAN DETAIL COSINE =====
    $detailCosineData[] = [
        'index'        => $index,
        'detail'       => cosine_similarity_detail($final_kunci, $final_jawaban),
        'prep_kunci'   => $prep_kunci,
        'prep_jawaban' => $prep_jawaban,
    ];

    // ===== SIMPAN DETAIL LEVENSHTEIN =====
    $detailLevenshteinData[] = [
        'index'        => $index,
        'distance'     => $lev_dist,
        'sim_raw'      => round($lev_raw, 4),
        'sim_persen'   => number_format($lev_raw, 2),
        'max_len'      => max(strlen($final_kunci), strlen($final_jawaban)),
        'matrix'       => levenshtein_matrix($final_kunci, $final_jawaban),
        'prep_kunci'   => $prep_kunci,
        'prep_jawaban' => $prep_jawaban,
    ];

    $index++;
}

// ===== NILAI AKHIR =====
$nilai_cosine_total      = number_format($total_nilai_cosine / max($index, 1), 2);
$nilai_levenshtein_total = number_format($total_nilai_levenshtein / max($index, 1), 2);
$nilai_akhir_total       = round($total_nilai_akhir, 2);

/* ===========================
   SIMPAN KE DATABASE
=========================== */

$nis_safe          = mysqli_real_escape_string($koneksi, $nis);
$kode_kelas_safe   = mysqli_real_escape_string($koneksi, $kode_kelas);
$kode_mapel_safe   = mysqli_real_escape_string($koneksi, $kode_mapel);
$jenis_ujian_safe  = mysqli_real_escape_string($koneksi, $jenis_ujian);

$cek = mysqli_query($koneksi, "
    SELECT id FROM nilai_essay
    WHERE nis='$nis_safe'
      AND kode_kelas='$kode_kelas_safe'
      AND kode_mapel='$kode_mapel_safe'
      AND jenis_ujian='$jenis_ujian_safe'
");

if (!$cek) die("Error query cek: " . mysqli_error($koneksi));

if (mysqli_num_rows($cek) > 0) {
    $update = 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_safe'
          AND kode_kelas='$kode_kelas_safe'
          AND kode_mapel='$kode_mapel_safe'
          AND jenis_ujian='$jenis_ujian_safe'
    ");
    if (!$update) die("Gagal update: " . mysqli_error($koneksi));
} else {
    $insert = mysqli_query($koneksi, "
        INSERT INTO nilai_essay (nis, kode_kelas, kode_mapel, jenis_ujian, nilai_cosine, nilai_levenshtein, nilai_akhir)
        VALUES ('$nis_safe', '$kode_kelas_safe', '$kode_mapel_safe', '$jenis_ujian_safe', $nilai_cosine_total, $nilai_levenshtein_total, $nilai_akhir_total)
    ");
    if (!$insert) die("Gagal insert: " . mysqli_error($koneksi));
}

// ===== DATA HEADER =====
$siswa_query = mysqli_query($koneksi, "SELECT * FROM siswa WHERE nis='$nis_safe'");
$siswa       = mysqli_fetch_array($siswa_query);

$kelas_query = mysqli_query($koneksi, "SELECT * FROM kelas WHERE kode_kelas='$kode_kelas_safe'");
$kelas       = mysqli_fetch_array($kelas_query);

$mapel_query = mysqli_query($koneksi, "SELECT * FROM mapel WHERE kode_mapel='$kode_mapel_safe'");
$mapel       = mysqli_fetch_array($mapel_query);

?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Penilaian Esai Otomatis - Cosine & Levenshtein</title>
  <link rel="icon" href="../../assets/img/brand/favicon.png" type="image/png">
  <link rel="stylesheet" href="../../https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700">
  <link rel="stylesheet" href="../../assets/vendor/nucleo/css/nucleo.css" type="text/css">
  <link rel="stylesheet" href="../../assets/vendor/@fortawesome/fontawesome-free/css/all.min.css" type="text/css">
  <link rel="stylesheet" href="../../assets/css/argon.css?v=1.2.0" type="text/css">
  <link href="../../assets/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">
  <style>
    body { background: #f5f7fa; font-family: 'Open Sans', sans-serif; }
    .main-card { background: white; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin-bottom: 20px; }
    .section-header { background: #f8f9fa; border-bottom: 2px solid #e9ecef; padding: 15px 20px; font-weight: 600; color: #2c3e50; }
    .content-box { padding: 20px; }
    .info-row { padding: 10px 0; border-bottom: 1px solid #e9ecef; }
    .info-row:last-child { border-bottom: none; }
    .info-label { font-weight: 600; color: #495057; min-width: 150px; display: inline-block; }
    .soal-card { background: white; border: 1px solid #dee2e6; border-radius: 6px; margin-bottom: 25px; overflow: hidden; }
    .soal-header { background: #e9ecef; padding: 12px 20px; border-bottom: 1px solid #dee2e6; display: flex; justify-content: space-between; align-items: center; }
    .soal-title { font-weight: 600; color: #2c3e50; margin: 0; }
    .text-box { background: #f8f9fa; border: 1px solid #dee2e6; padding: 12px; border-radius: 4px; margin-bottom: 15px; }
    .text-box-label { font-weight: 600; color: #495057; margin-bottom: 8px; display: block; }
    .preprocessing-table { width: 100%; margin-bottom: 20px; }
    .preprocessing-table td { padding: 10px; border: 1px solid #dee2e6; word-wrap: break-word; vertical-align: top; }
    .preprocessing-table td:first-child { background: #f8f9fa; font-weight: 600; width: 150px; }
    .hasil-row { background: #e9ecef; font-weight: 600; }
    .calculation-box { background: #f8f9fa; border: 1px solid #dee2e6; padding: 15px; border-radius: 4px; margin: 10px 0; }
    .calc-label { font-weight: 600; color: #495057; }
    .calc-value { color: #2c3e50; font-weight: 600; }
    .formula-box { background: white; border-left: 3px solid #6c757d; padding: 12px; margin: 15px 0; }
    .step-item { background: #f8f9fa; padding: 12px; margin: 8px 0; border-radius: 4px; border-left: 3px solid #6c757d; }
    .step-number { display: inline-block; background: #6c757d; color: white; width: 25px; height: 25px; text-align: center; line-height: 25px; border-radius: 50%; font-weight: 600; margin-right: 10px; }
    .result-box { background: #2c3e50; color: white; padding: 30px; text-align: center; border-radius: 8px; margin: 30px 0; }
    .result-value { font-size: 3rem; font-weight: 700; margin: 15px 0; }
    .summary-table { width: 100%; border-collapse: collapse; }
    .summary-table th, .summary-table td { padding: 12px; border: 1px solid #dee2e6; text-align: left; }
    .summary-table th { background: #f8f9fa; font-weight: 600; }
    .summary-table tfoot td { background: #2c3e50; color: white; font-weight: 700; font-size: 1.1rem; }
    .matrix-wrapper { background: #f8f9fa; padding: 15px; border-radius: 6px; overflow-x: auto; margin-top: 20px; }
    .matrix-table { font-size: 11px; background: white; border-collapse: collapse; }
    .matrix-table td { padding: 6px 10px; text-align: center; border: 1px solid #dee2e6; }
    .algo-divider { border-top: 2px dashed #dee2e6; margin: 25px 0; padding-top: 20px; }
    .badge-cosine { background: #17a2b8; color: white; padding: 3px 10px; border-radius: 4px; font-size: 12px; }
    .badge-lev { background: #6f42c1; color: white; padding: 3px 10px; border-radius: 4px; font-size: 12px; }
    .btn-back { background: #6c757d; color: white; padding: 12px 30px; border-radius: 4px; text-decoration: none; display: inline-block; margin-top: 20px; }
    .btn-back:hover { background: #5a6268; color: white; text-decoration: none; }
    .final-score-box { background: #e8f4f8; border: 2px solid #17a2b8; border-radius: 6px; padding: 15px; margin-top: 15px; }
  </style>
</head>
<body>

  <!-- SIDENAV -->
  <nav class="sidenav navbar navbar-vertical fixed-left navbar-expand-xs navbar-light bg-white" id="sidenav-main">
    <div class="scrollbar-inner">
      <div class="sidenav-header align-items-center">
        <a class="navbar-brand" href="javascript:void(0)">
          <img src="../../assets/img/logo3.jpg" class="navbar-brand-img" alt="...">
        </a>
      </div>
      <div class="navbar-inner">
        <div class="collapse navbar-collapse" id="sidenav-collapse-main">
          <ul class="navbar-nav">
            <li class="nav-item">
              <a class="nav-link" href="beranda.php">
                <i class="ni ni-tv-2 text-warning"></i>
                <span class="nav-link-text">Dashboard</span>
              </a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="daftar_siswa.php">
                <i class="ni ni-archive-2 text-warning"></i>
                <span class="nav-link-text">Daftar Siswa</span>
              </a>
            </li>
            <li class="nav-item">
              <a class="nav-link active" href="kelas.php">
                <i class="ni ni-paper-diploma text-info"></i>
                <span class="nav-link-text">Room Kelas</span>
              </a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="../../logout.php">
                <i class="ni ni-button-power text-dark"></i>
                <span class="nav-link-text">Log Out</span>
              </a>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </nav>

  <div class="main-content" id="panel">

    <!-- TOPNAV -->
    <nav class="navbar navbar-top navbar-expand navbar-dark bg-warning border-bottom">
      <div class="container-fluid">
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav align-items-center ml-md-auto">
            <li class="nav-item d-xl-none">
              <div class="pr-3 sidenav-toggler sidenav-toggler-dark" data-action="sidenav-pin" data-target="#sidenav-main">
                <div class="sidenav-toggler-inner">
                  <i class="sidenav-toggler-line"></i>
                  <i class="sidenav-toggler-line"></i>
                  <i class="sidenav-toggler-line"></i>
                </div>
              </div>
            </li>
          </ul>
          <ul class="navbar-nav align-items-center ml-auto ml-md-0">
            <li class="nav-item dropdown">
              <a class="nav-link pr-0" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <div class="media align-items-center">
                  <span class="avatar avatar-sm rounded-circle">
                    <?php
                    $profil = mysqli_query($koneksi, "SELECT * FROM guru WHERE nip='$nip'");
                    $tampil_profil = mysqli_fetch_array($profil);
                    ?>
                    <img alt="Image placeholder" src="../../assets/img/profil_guru/<?= $tampil_profil['foto']; ?>">
                  </span>
                  <div class="media-body ml-2 d-none d-lg-block">
                    <span class="mb-0 text-sm font-weight-bold">NIP : <?= $_SESSION['nip']; ?></span>
                  </div>
                </div>
              </a>
              <div class="dropdown-menu dropdown-menu-right">
                <a href="../../logout.php" class="dropdown-item">
                  <i class="ni ni-user-run"></i>
                  <span>Logout</span>
                </a>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </nav>

    <div class="header bg-warning pb-6">
      <div class="container-fluid">
        <div class="header-body">
          <div class="row">
            <div class="col-xl-12">

              <div class="main-card">
                <div class="section-header">
                  <h3 class="mb-0">Penilaian Esai Otomatis - Cosine Similarity &amp; Levenshtein Distance</h3>
                </div>
                <div class="content-box">

                  <!-- INFO UJIAN -->
                  <div class="main-card">
                    <div class="section-header">Informasi Ujian</div>
                    <div class="content-box">
                      <div class="row">
                        <div class="col-md-6">
                          <div class="info-row"><span class="info-label">NIS:</span> <?= $nis; ?></div>
                          <div class="info-row"><span class="info-label">Nama Siswa:</span> <?= $siswa['nama_siswa']; ?></div>
                          <div class="info-row"><span class="info-label">Kelas:</span> <?= $kelas['nama_kelas']; ?></div>
                        </div>
                        <div class="col-md-6">
                          <div class="info-row"><span class="info-label">Mata Pelajaran:</span> <?= $mapel['nama_mapel']; ?></div>
                          <div class="info-row"><span class="info-label">Jenis Ujian:</span> <?= $jenis_ujian; ?></div>
                          <div class="info-row"><span class="info-label">Jumlah Soal:</span> <?= count($questionsAndAnswersData); ?> soal</div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- DETAIL PER SOAL -->
                  <?php foreach ($questionsAndAnswersData as $i => $qa) : ?>
                  <div class="soal-card">
                    <div class="soal-header">
                      <h5 class="soal-title">Soal <?= ($i + 1); ?></h5>
                      <span style="font-weight:600;">Bobot: <?= $qa['weight']; ?></span>
                    </div>
                    <div class="content-box">

                      <!-- PERTANYAAN -->
                      <div class="text-box">
                        <span class="text-box-label">Pertanyaan:</span>
                        <?= $qa['question']; ?>
                      </div>

                      <!-- KUNCI & JAWABAN -->
                      <div class="row">
                        <div class="col-md-6">
                          <div class="text-box">
                            <span class="text-box-label">Kunci Jawaban:</span>
                            <?= $qa['answerKey']; ?>
                          </div>
                        </div>
                        <div class="col-md-6">
                          <div class="text-box">
                            <span class="text-box-label">Jawaban Siswa:</span>
                            <?= $qa['answer']; ?>
                          </div>
                        </div>
                      </div>

                      <!-- PREPROCESSING KUNCI -->
                      <h6 style="margin-top:25px;margin-bottom:12px;font-weight:600;">Preprocessing Kunci Jawaban</h6>
                      <table class="preprocessing-table">
                        <tr><td>Tokenizing</td><td><?= $preprocessingData[$i*2]['tokenizing']; ?></td></tr>
                        <tr><td>Filtering</td><td><?= $preprocessingData[$i*2]['filtering']; ?></td></tr>
                        <tr><td>Stemming</td><td><?= $preprocessingData[$i*2]['stemming']; ?></td></tr>
                        <tr><td>Sinonim</td><td><?= $preprocessingData[$i*2]['sinonim']; ?></td></tr>
                        <tr class="hasil-row"><td>Hasil Akhir</td><td><?= $detailCosineData[$i]['prep_kunci']['final']; ?></td></tr>
                      </table>

                      <!-- PREPROCESSING JAWABAN -->
                      <h6 style="margin-top:25px;margin-bottom:12px;font-weight:600;">Preprocessing Jawaban Siswa</h6>
                      <table class="preprocessing-table">
                        <tr><td>Tokenizing</td><td><?= $preprocessingData[$i*2+1]['tokenizing']; ?></td></tr>
                        <tr><td>Filtering</td><td><?= $preprocessingData[$i*2+1]['filtering']; ?></td></tr>
                        <tr><td>Stemming</td><td><?= $preprocessingData[$i*2+1]['stemming']; ?></td></tr>
                        <tr><td>Sinonim</td><td><?= $preprocessingData[$i*2+1]['sinonim']; ?></td></tr>
                        <tr class="hasil-row"><td>Hasil Akhir</td><td><?= $detailCosineData[$i]['prep_jawaban']['final']; ?></td></tr>
                      </table>

                      <!-- ===== COSINE SIMILARITY ===== -->
                      <div class="algo-divider">
                        <h6 style="font-weight:600;"><span class="badge-cosine">Cosine Similarity</span> &nbsp; Detail Perhitungan</h6>

                        <p style="font-weight:600;margin-top:15px;">Term Frequency:</p>
                        <table class="summary-table" style="margin-bottom:20px;">
                          <thead>
                            <tr>
                              <th>Term</th>
                              <th>Kunci (A)</th>
                              <th>Jawaban (B)</th>
                            </tr>
                          </thead>
                          <tbody>
                            <?php foreach ($detailCosineData[$i]['detail']['term_table'] as $term) : ?>
                            <tr>
                              <td><?= $term['term']; ?></td>
                              <td><?= $term['freq_a']; ?></td>
                              <td><?= $term['freq_b']; ?></td>
                            </tr>
                            <?php endforeach; ?>
                          </tbody>
                        </table>

                        <div class="row">
                          <div class="col-md-6">
                            <div class="calculation-box">
                              <span class="calc-label">Σ A.B (Dot Product):</span>
                              <span class="calc-value float-right"><?= $detailCosineData[$i]['detail']['dot_product']; ?></span>
                            </div>
                            <div class="calculation-box">
                              <span class="calc-label">Σ (A)²:</span>
                              <span class="calc-value float-right"><?= $detailCosineData[$i]['detail']['sum_a_squared']; ?></span>
                            </div>
                            <div class="calculation-box">
                              <span class="calc-label">Σ (B)²:</span>
                              <span class="calc-value float-right"><?= $detailCosineData[$i]['detail']['sum_b_squared']; ?></span>
                            </div>
                          </div>
                          <div class="col-md-6">
                            <div class="calculation-box">
                              <span class="calc-label">√Σ(A)²:</span>
                              <span class="calc-value float-right"><?= round($detailCosineData[$i]['detail']['sqrt_a'], 4); ?></span>
                            </div>
                            <div class="calculation-box">
                              <span class="calc-label">√Σ(B)²:</span>
                              <span class="calc-value float-right"><?= round($detailCosineData[$i]['detail']['sqrt_b'], 4); ?></span>
                            </div>
                            <div class="calculation-box">
                              <span class="calc-label">Cosine Similarity:</span>
                              <span class="calc-value float-right"><?= number_format($detailCosineData[$i]['detail']['similarity_raw'], 2); ?></span>
                            </div>
                          </div>
                        </div>

                        <div class="formula-box">
                          <strong>Formula:</strong> <code>Cosine = Σ(A.B) / (√Σ(A)² × √Σ(B)²)</code>
                        </div>
                      </div>

                      <!-- ===== LEVENSHTEIN DISTANCE ===== -->
                      <div class="algo-divider">
                        <h6 style="font-weight:600;"><span class="badge-lev">Levenshtein Distance</span> &nbsp; Detail Perhitungan</h6>

                        <div class="row" style="margin-top:15px;">
                          <div class="col-md-6">
                            <div class="calculation-box">
                              <span class="calc-label">Edit Distance:</span>
                              <span class="calc-value float-right"><?= $detailLevenshteinData[$i]['distance']; ?></span>
                            </div>
                            <div class="calculation-box">
                              <span class="calc-label">Max Length:</span>
                              <span class="calc-value float-right"><?= $detailLevenshteinData[$i]['max_len']; ?></span>
                            </div>
                          </div>
                          <div class="col-md-6">
                            <div class="calculation-box">
                              <span class="calc-label">Levenshtein Similarity:</span>
                              <span class="calc-value float-right"><?= number_format($detailLevenshteinData[$i]['sim_raw'], 2); ?></span>
                            </div>
                            <div class="formula-box">
                              <strong>Formula:</strong> <code>1 - (Distance / Max_Length)</code>
                            </div>
                          </div>
                        </div>

                        <!-- MATRIKS -->
                        <div class="matrix-wrapper">
                          <h6 style="margin-bottom:12px;font-weight:600;">Matriks Levenshtein Distance</h6>
                          <table class="matrix-table">
                            <?php foreach ($detailLevenshteinData[$i]['matrix'] as $row_matrix) : ?>
                            <tr>
                              <?php foreach ($row_matrix as $cell) : ?>
                              <td><?= $cell; ?></td>
                              <?php endforeach; ?>
                            </tr>
                            <?php endforeach; ?>
                          </table>
                        </div>
                      </div>

                      <!-- ===== PERHITUNGAN FINAL PER SOAL ===== -->
                      <div class="algo-divider">
                        <h6 style="font-weight:600;">Langkah Perhitungan Nilai Akhir Soal <?= ($i+1); ?></h6>

                        <div class="step-item">
                          <span class="step-number">1</span>
                          <strong>Final Score = (Cosine + Levenshtein) / 2:</strong><br>
                          <code>
                            (<?= $scoreTableData[$i]['Cosine_Raw']; ?> + <?= $scoreTableData[$i]['Levenshtein_Raw']; ?>) / 2
                            = <?= $scoreTableData[$i]['Final_Score']; ?>
                          </code>
                        </div>

                        <div class="step-item">
                          <span class="step-number">2</span>
                          <strong>Nilai Soal = Final Score × Bobot:</strong><br>
                          <code>
                            <?= $scoreTableData[$i]['Final_Score']; ?> × <?= $qa['weight']; ?>
                            = <?= $scoreTableData[$i]['Nilai_Soal']; ?>
                          </code>
                        </div>

                        <div class="final-score-box">
                          <strong>Nilai Soal <?= ($i+1); ?>: <?= $scoreTableData[$i]['Nilai_Soal']; ?></strong>
                        </div>
                      </div>

                    </div>
                  </div>
                  <?php endforeach; ?>

                  <!-- RINGKASAN -->
                  <div class="main-card">
                    <div class="section-header">Ringkasan Nilai per Soal</div>
                    <div class="content-box" style="padding:0;">
                      <table class="summary-table">
                        <thead>
                          <tr>
                            <th>Soal</th>
                            <th>Cosine (0-1)</th>
                            <th>Levenshtein (0-1)</th>
                            <th>Final Score (0-1)</th>
                            <th>Bobot</th>
                            <th>Nilai Soal</th>
                          </tr>
                        </thead>
                        <tbody>
                          <?php foreach ($scoreTableData as $row) : ?>
                          <tr>
                            <td><?= $row['Question']; ?></td>
                            <td><?= $row['Cosine_Raw']; ?></td>
                            <td><?= $row['Levenshtein_Raw']; ?></td>
                            <td><?= $row['Final_Score']; ?></td>
                            <td><?= $row['Bobot']; ?></td>
                            <td><strong><?= $row['Nilai_Soal']; ?></strong></td>
                          </tr>
                          <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                          <tr>
                            <td colspan="5">TOTAL NILAI AKHIR</td>
                            <td><?= $nilai_akhir_total; ?></td>
                          </tr>
                        </tfoot>
                      </table>
                    </div>
                  </div>

                  <!-- HASIL AKHIR -->
                  <div class="result-box">
                    <h4 style="margin-bottom:10px;opacity:0.9;">NILAI AKHIR ESAI</h4>
                    <div class="result-value"><?= $nilai_akhir_total; ?></div>
                    <p style="margin:0;opacity:0.9;">
                      Total dari <?= count($scoreTableData); ?> soal
                      &nbsp;|&nbsp; Formula: (Cosine + Levenshtein) / 2 × Bobot
                    </p>
                  </div>

                  <!-- TOMBOL KEMBALI -->
                  <div class="text-center">
                    <a href="hasil_ujian.php?kode_mapel=<?= $kode_mapel; ?>&jenis_ujian=<?= $jenis_ujian; ?>" class="btn-back">
                      <i class="fas fa-arrow-left"></i> Kembali ke Hasil Ujian
                    </a>
                  </div>

                </div>
              </div>

            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script src="../../assets/vendor/jquery/dist/jquery.min.js"></script>
  <script src="../../assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
  <script src="../../assets/vendor/js-cookie/js.cookie.js"></script>
  <script src="../../assets/vendor/jquery.scrollbar/jquery.scrollbar.min.js"></script>
  <script src="../../assets/vendor/jquery-scroll-lock/dist/jquery-scrollLock.min.js"></script>
  <script src="../../assets/js/argon.js?v=1.2.0"></script>
</body>
</html>