<?php

session_start();

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

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

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

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;
}


// Fungsi untuk melakukan filtering teks
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;
}

// Fungsi untuk melakukan stemming teks
function stem($tokens)
{
  $stemmedTokens = [];
  $stemmerFactory = new StemmerFactory();
  $stemmer = $stemmerFactory->createStemmer();

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

  return $stemmedTokens;
}

// Fungsi untuk menghitung bobot TF-IDF

function calculateTFIDF($tokens, $corpus)
{
  $tfidf = [];
  $totalDocuments = count($corpus);

  // Menghitung Term Frequency ( TF )
  $tf = array_count_values($tokens);
  $totalWords = count($tokens);

  // Menghitung Inverse Document Frequency ( IDF )
  $idf = [];
  foreach ($tf as $word => $frequency) {
    $documentCount = 0;
    foreach ($corpus as $documentTokens) {
      if (in_array($word, $documentTokens)) {
        $documentCount++;
      }
    }
    $idf[$word] = log10($totalDocuments / $documentCount);
  }

  // Menghitung TF-IDF
  foreach ($tf as $word => $frequency) {
    $tfidf[$word] = ($frequency / $totalWords) * $idf[$word];
  }

  return $tfidf;
}

// Fungsi untuk menghitung cosine similarity

function calculateCosineSimilarity($tfidf1, $tfidf2)
{
  $dotProduct = 0;
  $magnitude1 = 0;
  $magnitude2 = 0;

  foreach ($tfidf1 as $word => $tfidfValue1) {
    $tfidfValue2 = isset($tfidf2[$word]) ? $tfidf2[$word] : 0;

    $dotProduct += $tfidfValue1 * $tfidfValue2;
    $magnitude1 += pow($tfidfValue1, 2);
    $magnitude2 += pow($tfidfValue2, 2);
  }

  $magnitude1 = sqrt($magnitude1);
  $magnitude2 = sqrt($magnitude2);

  if ($magnitude1 == 0 || $magnitude2 == 0) {
    return 0;
  }

  return round($dotProduct / ($magnitude1 * $magnitude2),3);
}

// Fungsi untuk menghitung nilai akhir siswa


include '../../koneksi.php';
// Mendapatkan nilai parameter dari URL
$nis = $_GET['nis'];
$kode_kelas = $_GET['kode_kelas'];
$kode_mapel = $_GET['kode_mapel'];
$jenis_ujian = $_GET['jenis_ujian'];

// get data jawaban_essay tabel
$query = "SELECT * FROM jawaban_essay WHERE nis='$nis' AND kode_kelas='$kode_kelas' AND kode_mapel='$kode_mapel' AND jenis_ujian='$jenis_ujian'";
$hasil = mysqli_query($koneksi, $query);
$data_jawaban_essay = array();

while ($row = mysqli_fetch_assoc($hasil)) {
  $data_jawaban_essay[] = $row;
}
// get data soal_essay
$query = "SELECT * FROM soal_essay WHERE kode_kelas='$kode_kelas' AND kode_mapel='$kode_mapel' AND jenis_ujian='$jenis_ujian'";
$hasil = mysqli_query($koneksi, $query);
$data_soal_essay = array();

while ($row = mysqli_fetch_assoc($hasil)) {
  $data_soal_essay[] = $row;
}

// Data soal, kunci jawaban, dan bobot
$questions = [];
$answerKeys = [];
$weights = [];

// Jawaban siswa
$studentAnswers = [];

// Preprocessing, pembobotan, dan perhitungan similarity
$corpus = [];
$preprocessedCorpus = [];
$tfidfAnswerKeys = [];
$tfidfStudentAnswers = [];

foreach ($data_soal_essay as $soal) {
  $questions[] = $soal['soal'];
  $answerKeys[] = $soal['knc_jawaban'];
  $weights[] = $soal['bobot'];
}

foreach ($data_jawaban_essay as $jawaban) {
  $studentAnswers[] = $jawaban['jawaban'];
}

// Preprocessing, pembobotan, dan perhitungan similarity
$corpus = array_merge($answerKeys, $studentAnswers);


foreach ($corpus as $document) {
  $tokens = tokenize($document);
  $filteredTokens = filter($tokens);
  $stemmedTokens = stem($filteredTokens);
  $preprocessedCorpus[] = $stemmedTokens;
}

for ($i = 0; $i < count($answerKeys); $i++) {
  $tokens = $preprocessedCorpus[$i];
  $tfidfAnswerKeys[$i] = calculateTFIDF($tokens, $preprocessedCorpus);
}

for ($i = count($answerKeys); $i < count($corpus); $i++) {
  $tokens = $preprocessedCorpus[$i];
  $tfidfStudentAnswers[$i - count($answerKeys)] = calculateTFIDF($tokens, $preprocessedCorpus);
}


// soal
$questionsData = [];
for ($i = 0; $i < count($questions); $i++) {
  $questionsData[] = [
    'index' => $i,
    'question' => $questions[$i],
    'answerKey' => $answerKeys[$i],
    'weight' => $weights[$i]
  ];
}

// jawaban 
$studentAnswersData = [];
for ($i = 0; $i < count($studentAnswers); $i++) {
  $studentAnswersData[] = [
    'index' => $i,
    'answer' => $studentAnswers[$i]
  ];
}

// soal,jawaban, bobot dan jawaban
$questionsAndAnswersData = [];
for ($i = 0; $i < count($questions); $i++) {
  $questionsAndAnswersData[] = [
    'index' => $i,
    'question' => $questions[$i],
    'answerKey' => $answerKeys[$i],
    'weight' => $weights[$i],
    'answer' => $studentAnswers[$i]
  ];
}

// Menampilkan TF dan IDF
$tfidfData = [];
for ($i = 0; $i < count($answerKeys); $i++) {
  $tfidfData[] = [
    'type' => 'Kunci Jawaban',
    'index' => $i,
    'tfidf' => $tfidfAnswerKeys[$i],
    'soal' => $questions[$i],
    'kunci_jawaban' => $answerKeys[$i],
  'tokenizing' => tokenize($answerKeys[$i]),
    'filtering' => filter(tokenize($answerKeys[$i])),
    'stemming' => stem(filter(tokenize($answerKeys[$i]))),
    
  ];
}

for ($i = count($answerKeys); $i < count($corpus); $i++) {
  $studentAnswerIndex = $i - count($answerKeys);
  $tfidfData[] = [
    'type' => 'Jawaban Siswa',
    'index' => $studentAnswerIndex,
    'tfidf' => $tfidfStudentAnswers[$studentAnswerIndex],
    'soal' => '',
    'kunci_jawaban' => '',
    'tokenizing' => tokenize($studentAnswers[$studentAnswerIndex]),
    'filtering' => filter(tokenize($studentAnswers[$studentAnswerIndex])),
    'stemming' => stem(filter(tokenize($studentAnswers[$studentAnswerIndex]))),
  ];
}


$tableData = [];


// Jumlah Term
$termCounts = [];
foreach ($preprocessedCorpus as $documentTokens) {
  $documentUniqueTerms = [];
  foreach ($documentTokens as $token) {
    if (!isset($documentUniqueTerms[$token])) {
      $documentUniqueTerms[$token] = true;
      if (!isset($termCounts[$token])) {
        $termCounts[$token] = 1;
      } else {
        $termCounts[$token]++;
      }
    }
  }
}

foreach ($tfidfData as $data) {
  $type = $data['type'];
  $index = $data['index'];
  $tfidf = $data['tfidf'];
  $soal = $data['soal'];
  $kunci_jawaban = $data['kunci_jawaban'];
  $tokenizing = $data['tokenizing'];
  $filtering = $data['filtering'];
  $stemming = $data['stemming'];


  $row = [
    'Type' => $type,
    'Index' => $index,
    'TF-IDF' => '',
    'soal' => $soal,
    'kunci_jawaban' => $kunci_jawaban,
    'tokenizing' => implode(", ", $tokenizing),
    'filtering' => implode(", ", $filtering),
    'stemming' => implode(", ", $stemming)

  ];

  $tf = array_count_values($stemming);
  foreach ($tf as $word => $tffrequency){
    $hasiltf[$word] = $tffrequency / count($stemming);
  }

  $tfidfValues = [];
  $akhirtfidf = [];
  foreach ($tfidf as $word => $value) {
    $termFrequency = round($hasiltf[$word],3);
    $inverseDocumentFrequency = round(log10(count($corpus) / $termCounts[$word]),3);
    $termFrequency_inverseDocumentFrequency = round($value,3);
    $tfidfValues[] = "$word: TF = $termFrequency IDF = $inverseDocumentFrequency";
    $akhirtfidf[] = "$word: TF-IDF = $termFrequency_inverseDocumentFrequency";

  }

  $row['TF-IDF'] = implode(", ", $tfidfValues);
  $row['TF_IDF'] = implode(", ", $akhirtfidf);
  $tableData[] = $row;
}


// Menampilkan jumlah Term
$termCountTableData = [];
foreach ($termCounts as $term => $count) {
  $termCountTableData[] = [
    'Term' => $term,
    'Count' => $count
  ];
}

// Perhitungan similarity dan nilai akhir siswa
$dataScoreSimilarity = [];
$totalSimilarity = 0;

for ($i = 0; $i < count($answerKeys); $i++) {
  $similarity = calculateCosineSimilarity(
    $tfidfAnswerKeys[$i],
    $tfidfStudentAnswers[$i]
  );

  $totalSimilarity += $similarity;

  $dataScoreSimilarity[] = [
    'soal' => $i + 1,
    'similarity' => $similarity
  ];
}

// rata-rata cosine
$avgCosine = round($totalSimilarity / count($answerKeys), 4);

mysqli_query($koneksi, "
  INSERT INTO nilai_cosine 
  (nis, kode_kelas, kode_mapel, jenis_ujian, cosine_similarity)
  VALUES 
  ('$nis', '$kode_kelas', '$kode_mapel', '$jenis_ujian', '$avgCosine')
  ON DUPLICATE KEY UPDATE cosine_similarity='$avgCosine'
");


// ===============================
// HASIL COSINE SIMILARITY (MURNI)
// ===============================

$scoreTableData = [];
$totalSimilarity = 0;

for ($i = 0; $i < count($dataScoreSimilarity); $i++) {
  $similarity = $dataScoreSimilarity[$i]['similarity'];
  $totalSimilarity += $similarity;

  $scoreTableData[] = [
    'Question' => 'Soal ' . ($i + 1),
    'Similarity' => $similarity
  ];
}

// Rata-rata cosine similarity
$avgCosine = round($totalSimilarity / count($dataScoreSimilarity), 4);

// SIMPAN KE DATABASE (COSINE SAJA)
mysqli_query($koneksi, "
  INSERT INTO nilai_cosine
  (nis, kode_kelas, kode_mapel, jenis_ujian, cosine_similarity)
  VALUES
  ('$nis', '$kode_kelas', '$kode_mapel', '$jenis_ujian', '$avgCosine')
  ON DUPLICATE KEY UPDATE cosine_similarity='$avgCosine'
");


?>

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="Start your development with a Dashboard for Bootstrap 4.">
  <meta name="author" content="Creative Tim">
  <title>Sistem Penilaian Esai Otomatis</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 rel="stylesheet" href="../../assets/css/style.css">
  <link href="../../assets/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">
</head>

<body>
  <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">
    <nav class="navbar navbar-top navbar-expand navbar-dark bg-warning border-bottom">
      <div class="container-fluid">
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <form class="navbar-search navbar-search-light form-inline mr-sm-3" id="navbar-search-main">
            <div class="form-group mb-0">
              <div class="input-group input-group-alternative input-group-merge">
                <div class="input-group-prepend">
                </div>
              </div>
            </div>
            <button type="button" class="close" data-action="search-close" data-target="#navbar-search-main" aria-label="Close">
              <span aria-hidden="true">×</span>
            </button>
          </form>
          <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 siswa WHERE nis='$nis'");
                    $tampil_profil = mysqli_fetch_array($profil);
                    ?>
                    <img alt="Image placeholder" src="../../assets/img/profil_siswa/<?= $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="card  card-stats">
                <div class="card-header">
                  <h1 class="fw-bold color-primary">Penilaian Esai Otomatis</h1>
                </div>
                <div class="card-body">
                  <div class="table-responsive">
                    <h2>Soal, Kunci Jawaban dan Jawab :</h2>
                    <table class="table table-bordered" width="100%" cellspacing="0">
                      <tr>
                        <th>No</th>
                        <th>Index Soal</th>
                        <th>Soal</th>
                        <th>Kunci Jawaban</th>
                        <th>Jawaban</th>
                        <th>Bobot</th>
                      </tr>
                      <?php
                      $no = 1;
                      usort($questionsAndAnswersData, function ($a, $b) {
                        return $a['index'] - $b['index'];
                      });
                      foreach ($questionsAndAnswersData as $row) :
                      ?>
                        <tr>
                          <td><?= $no++; ?></td>
                          <td><?= $row['index'] + 1; ?></td>
                          <td>
                            <textarea class="form-control" readonly><?= $row['question']; ?></textarea>
                          </td>
                          <td>
                            <textarea class="form-control" readonly><?= $row['answerKey']; ?></textarea>
                          </td>
                          <td>
                            <textarea class="form-control" readonly><?= $row['answer']; ?></textarea>
                          </td>
                          <td>
                            <input class="form-control" value="<?= $row['weight']; ?>" readonly>
                          </td>
                        </tr>
                      <?php endforeach; ?>
                    </table>
                  </div>

                  <div class="table-responsive mt-4">
                    <h2>Preprocessing Kalimat Kunci Jawaban dan Jawaban :</h2>
                    <table class="table table-bordered" width="100%" cellspacing="0">
                      <tr>
                        <th>No</th>
                        <th>Index Soal</th>
                        <th>Type</th>
                        <th>Tokenize</th>
                        <th>Filtering</th>
                        <th>Stemming</th>
                      </tr>
                      <?php
                      $no = 1;
                      usort($tableData, function ($a, $b) {
                        return $a['Index'] - $b['Index'];
                      });
                      foreach ($tableData as $row) :
                      ?>
                        <tr>
                          <td><?= $no++; ?></td>
                          <td><?= $row['Index'] + 1; ?></td>
                          <td><?= $row['Type']; ?></td>
                          <td>
                            <input type="text" class="form-control" value="<?= $row['tokenizing']; ?>" readonly>
                          </td>
                          <td>
                            <input type="text" class="form-control" value="<?= $row['filtering']; ?>" readonly>
                          </td>
                          <td>
                            <input type="text" class="form-control" value="<?= $row['stemming']; ?>" readonly>
                          </td>
                        </tr>
                      <?php endforeach; ?>
                    </table>
                  </div>

                  <div class="table-responsive mt-4">
                    <h2>Jumlah kemunculan Term:</h2>
                    <div class="table-responsive">
                      <table class="table table-bordered" id="example" width="100%" cellspacing="0">
                        <thead>
                          <tr>
                            <th>Term</th>
                            <th>Count</th>
                          </tr>
                        </thead>
                        <tbody>
                          <?php foreach ($termCountTableData as $row) : ?>
                            <tr>
                              <td><?= $row['Term']; ?></td>
                              <td><?= $row['Count']; ?></td>
                            </tr>
                          <?php endforeach; ?>
                        </tbody>
                      </table>
                    </div>

                    <div class="table-responsive mt-4">
                      <h2>Nilai TF dan IDF:</h2>
                      <table class="table table-bordered" width="100%" cellspacing="0">
                        <tr>
                          <th>Type</th>
                          <th>Index</th>
                          <th>TF-IDF</th>
                        </tr>
                        <?php
                        usort($tableData, function ($a, $b) {
                          return $a['Index'] - $b['Index'];
                        });

                        foreach ($tableData as $row) :
                        ?>
                          <tr>
                            <td><?= $row['Type']; ?></td>
                            <td><?= $row['Index'] + 1; ?></td>
                            <td><?= $row['TF-IDF']; ?></td>
                          </tr>
                        <?php endforeach; ?>
                      </table>
                    </div>

                    <h2>Nilai TF-IDF:</h2>
                    <table class="table table-bordered" width="100%" cellspacing="0">
                      <tr>
                        <th>Type</th>
                        <th>Index</th>
                        <th>Hasil TF-IDF</th>
                      </tr>
                      <?php
                      usort($tableData, function ($a, $b) {
                        return $a['Index'] - $b['Index'];
                      });

                      foreach ($tableData as $row) :
                      ?>
                        <tr>
                          <td><?= $row['Type']; ?></td>
                          <td><?= $row['Index'] + 1; ?></td>
                          <td><?= $row['TF_IDF']; ?></td>
                        </tr>
                      <?php endforeach; ?>
                    </table>
                  </div>

                  <div class="table-responsive mt-4">
                    <h2>Score Similarity:</h2>
                    <table class="table table-bordered" width="100%" cellspacing="0">
                      <tr>
                        <th>Soal</th>
                        <th>Similarity</th>
                        <th>Nilai Akhir</th>
                      </tr>
                      <?php foreach ($scoreTableData as $row) : ?>
                        <tr>
                          <td><?= $row['Question']; ?></td>
                          <td><?= $row['Similarity']; ?></td>
                          <td><?= $row['Final Score']; ?></td>
                        </tr>
                      <?php endforeach; ?>
                    </table>
                  </div>

                  <div class="row mt-5 justify-content-center">
                    <div class="card">
                      <div class="card-header">
                        <h3 class="mb-0">Nilai Essay Siswa</h3>
                      </div>
                      <div class="card-body">
                        <h1 class="text-center"><?= $nilai_essay_siswa; ?></h1>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="container-fluid mt--6">
        <div class="row">
        </div>
        <div class="row">
          <div class="col-xl-12">
          </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>
      $(document).ready(function() {
        $('#example').DataTable();
      });
    </script>

    <script src="../../assets/datatables/jquery.dataTables.min.js"></script>
    <script src="../../assets/datatables/dataTables.bootstrap4.min.js"></script>
    <script src="../../assets/vendor/chart.js/dist/Chart.min.js"></script>
    <script src="../../assets/vendor/chart.js/dist/Chart.extension.js"></script>
    <script src="../../assets/js/argon.js?v=1.2.0"></script>
</body>

</html>