<?php
// pastikan koneksi.php sudah di-include sebelumnya
// dan variabel berikut sudah ada:
// $nis, $kode_kelas, $kode_mapel, $jenis_ujian

/* =========================
   HITUNG JUMLAH SOAL ESSAY
========================= */
$soal_query = mysqli_query(
    $koneksi,
    "SELECT id_soal 
     FROM soal_essay 
     WHERE kode_kelas='$kode_kelas'
       AND kode_mapel='$kode_mapel'
       AND jenis_ujian='$jenis_ujian'"
);

$jumlah_soal = mysqli_num_rows($soal_query);

if ($jumlah_soal == 0) {
    return; // hentikan jika tidak ada soal
}

/* =========================
   AMBIL NILAI COSINE & LEVENSHTEIN
========================= */
$q = mysqli_query($koneksi, "
    SELECT nilai_cosine, nilai_levenshtein
    FROM nilai_essay
    WHERE nis='$nis'
      AND kode_kelas='$kode_kelas'
      AND kode_mapel='$kode_mapel'
      AND jenis_ujian='$jenis_ujian'
");

$data = mysqli_fetch_assoc($q);

if (!$data) {
    return;
}

$total_cosine       = (float)$data['nilai_cosine'];
$total_levenshtein  = (float)$data['nilai_levenshtein'];

/* =========================
   HITUNG NILAI AKHIR (IDENTIK)
========================= */

// Total gabungan
$total_nilai = $total_cosine + $total_levenshtein;

// Rata-rata per soal
$nilai_akhir = $total_nilai / $jumlah_soal;

// Pembulatan 2 angka desimal (SAMA PERSIS)
$nilai_akhir = round($nilai_akhir, 2);

/* =========================
   UPDATE DATABASE
========================= */
mysqli_query($koneksi, "
    UPDATE nilai_essay
    SET nilai_akhir='$nilai_akhir'
    WHERE nis='$nis'
      AND kode_kelas='$kode_kelas'
      AND kode_mapel='$kode_mapel'
      AND jenis_ujian='$jenis_ujian'
");