<?php

namespace PHPMaker2021\rdigital21;

use PHPMaker2021\rdigital21\{UserProfile, Language, AdvancedSecurity, Timer, HttpErrorHandler};
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Container\ContainerInterface;
use DI\Container as Container;
use DI\ContainerBuilder;
use Selective\SameSiteCookie\SameSiteCookieConfiguration;
use Selective\SameSiteCookie\SameSiteCookieMiddleware;
use Selective\SameSiteCookie\SameSiteSessionMiddleware;
use Slim\Factory\AppFactory;
use Slim\Factory\ServerRequestCreatorFactory;
use Slim\Exception\HttpInternalServerErrorException;
use Nyholm\Psr7\Factory\Psr17Factory;
use Nyholm\Psr7Server\ServerRequestCreator;

// Relative path
$RELATIVE_PATH = "";

// Require files
require_once "vendor/autoload.php";
require_once "src/constants.php";
require_once "src/config.php";
require_once "src/phpfn.php";
require_once "src/userfn.php";
?>
<!DOCTYPE html>
<html>

<head>
  <title>Action Tool</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<style>
  body,
  html {
    height: 100%;
    margin: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f0f0f0;
  }

  .loader {
    position: relative;
    width: 100px;
    height: 100px;
  }

  .loader img {
    width: 100%;
    height: auto;
    animation: fadeInOut 1s infinite;
  }

  @keyframes fadeInOut {

    0%,
    100% {
      opacity: 0;
    }

    50% {
      opacity: 1;
    }
  }
</style>
</head>



<?php
if (isset($_GET['act'])) {
  $kode_tapel = $_GET['ktp'];
  if ($_GET['act'] === 'no') {
    //$update = ExecuteUpdate("UPDATE tahun_pelajaran SET status='Tidak' WHERE kode_tapel='$kode_tapel'");
    echo '<meta http-equiv="refresh" content="3;url=TahunPelajaranList" />';
    exit;
  }

  if ($_GET['act'] === 'yes') {
    $update = ExecuteUpdate("UPDATE tahun_pelajaran SET status='Aktif' WHERE kode_tapel='$kode_tapel'");
    $update = ExecuteUpdate("UPDATE tahun_pelajaran SET status='Tidak' WHERE kode_tapel!='$kode_tapel'");
    echo '<meta http-equiv="refresh" content="3;url=TahunPelajaranList" />';
    exit;
  }
}
?>


<?php
if (isset($_GET['p5'])) {
  $penilaian = base64_decode($_GET['p5']);
  $txt = explode("|", $penilaian);
  $project_id = $txt[0];
  $tahun_pelajaran = $txt[1];
  $proyek = $txt[2];
  $gdimensi_id = $txt[3];
  $kelas = $txt[4];
  $dimensi_id = explode(",", $txt[3]);
  $kode_tapel = kode_tapel();

  for ($i = 0; $i < count($dimensi_id); $i++) {

    $pd = ExecuteQuery("SELECT nis, nama from peserta_didik where kelas='$kelas' and kode_tapel='$kode_tapel' order by nama");
    while ($pdlist = $pd->fetch()) {
      $nis = $pdlist['nis'];
      $dimensi = ExecuteScalar("SELECT dimensi FROM dimensi WHERE dimensi_id=$dimensi_id[$i]");
      $sub_elemen = ExecuteScalar("SELECT sub_elemen FROM dimensi WHERE dimensi_id=$dimensi_id[$i]");

      $cek = ExecuteScalar("SELECT COUNT(*) FROM nilai_p5 WHERE project_id='$project_id' AND kelas='$kelas'");
      $insert = ExecuteUpdate("INSERT INTO nilai_p5 (project_id, nis, kelas, proyek, dimensi, sub_elemen, nilai, tapel_id) VALUES ('$project_id', '$nis', '$kelas', '$proyek', '$dimensi', '$sub_elemen', 'BSH', '$tahun_pelajaran')");
      echo '<meta http-equiv="refresh" content="3;url=ProyekList" />';
    }
  }
}
?>


<?php
if (isset($_GET['absensi'])) {
  $gabsensi = $_GET['absensi'];
  $txt = explode("|", $gabsensi);
  $kelas = $txt[0];
  $kode_tapel = $txt[1];

  $pd = ExecuteQuery("SELECT nis, nisn, nama, jk FROM peserta_didik WHERE kelas='$kelas' AND kode_tapel='$kode_tapel' ORDER BY nama");
  while ($pdlist = $pd->fetch()) {
    $nis = $pdlist['nis'];
    $nisn = $pdlist['nisn'];
    $nama = str_replace("'", "`", $pdlist['nama']);
    $jk = $pdlist['jk'];

    $cek = ExecuteScalar("SELECT COUNT(*) FROM extra_absensi WHERE kelas='$kelas' AND kode_tapel='$kode_tapel'");
    $insert = ExecuteUpdate("INSERT INTO extra_absensi (kode_tapel, kelas, nisn, nis, nama, jk, s, i, a, ekstra1, deskripsi1) VALUES ('$kode_tapel', '$kelas', '$nisn', '$nis', '$nama', '$jk', '-', '-', '-','Pramuka','Aktif')");
    echo '<meta http-equiv="refresh" content="3;url=ExtraAbsensiList" />';
  }
}
?>

<?php
if (isset($_GET['pis'])) {
  $penilaian_id = base64_decode($_GET['pis']);
  $guru_id = ExecuteScalar("SELECT guru_id FROM nilai_sumatif WHERE penilaian_id='$penilaian_id'");
  $kode_mapel = ExecuteScalar("SELECT kode_mapel FROM nilai_sumatif WHERE penilaian_id='$penilaian_id'");
  $kelas = ExecuteScalar("SELECT kelas FROM nilai_sumatif WHERE penilaian_id='$penilaian_id'");
?>
  <div class="card" style="width:35rem;">
    <div class="card-body shadow">
      <h4>Generate Nilai Sumatif</h4>
      <li>Guru : <?= $guru_id ?></li>
      <li>Kode Mapel : <?= $kode_mapel ?></li>
      <li>Kelas : <?= $kelas ?></li>
      <div class="row bg-light p-3 mt-3">
        <div class="col-3">
          <a href="NilaiSumatifList?showmaster=penilaian&fk_penilaian_id=<?= $penilaian_id ?>" class="btn btn-success" style="width:100%;">Kembali</a>
        </div>
        <div class="col-9">
          <div class="btn btn-light" style="width:100%;"><i>Ubah Jumlah Persentase Nilai jika diperlukan</i></>
          </div>
        </div>
      </div>
      <form class="py-3" action="act.php">
        <input class="form-control" type="hidden" id="penilaian_id" name="penilaian_id" value="<?= $penilaian_id ?>">
        <div class="py-1">
          <label for="persentase_nas">Persentase Nilai Akhir Sumatif (NAS)</label>
          <input class="form-control" type="number" id="persentase_nas" name="persentase_nas" value="40" required>
        </div>
        <div class="py-1">
          <label for="persentase_nas">Persentase Sumatif Tengah Semester (STS)</label>
          <input class="form-control" type="number" id="persentase_sts" name="persentase_sts" value="20" required>
        </div>
        <div class="py-1">
          <label for="persentase_nas">Persentase Sumatif Akhir Semester (SAS)</label>
          <input class="form-control" type="number" id="persentase_sas" name="persentase_sas" value="40" required>
        </div>
        <div class="py-1">
          <input type="submit" class="btn btn-warning" id="generate-nilai" name="generate-nilai" value="Generate Nilai" style="width:100%;">
        </div>
      </form>
    </div>
  </div>
<?php } ?>

<?php
if (isset($_GET['generate-nilai'])) { ?>
  <?php
  $penilaian_id = $_GET['penilaian_id'];
  $persentase_nas = $_GET['persentase_nas'] / 100;
  $persentase_sts = $_GET['persentase_sts'] / 100;
  $persentase_sas = $_GET['persentase_sas'] / 100;

  $nilai_sumatif = ExecuteQuery("SELECT * FROM nilai_sumatif WHERE penilaian_id='$penilaian_id'");
  while ($nilai_sumatiflist = $nilai_sumatif->fetch()) {
    $nilai_s_id = $nilai_sumatiflist['nilai_s_id'];
    $values = [
      number_format($nilai_sumatiflist['s1']),
      number_format($nilai_sumatiflist['s2']),
      number_format($nilai_sumatiflist['s3']),
      number_format($nilai_sumatiflist['s4']),
      number_format($nilai_sumatiflist['s5']),
      number_format($nilai_sumatiflist['s6']),
      number_format($nilai_sumatiflist['s7']),
      number_format($nilai_sumatiflist['s8'])
    ];

    // Filter out the zeros and calculate the sum
    $nonZeroValues = array_filter($values, function ($value) {
      return $value != '0'; // Only keep values that are not zero
    });

    // Calculate the sum and average of the non-zero values
    $sum = array_sum($nonZeroValues);
    $count = count($nonZeroValues);
    $nas = ($count > 0) ? $sum / $count : 0;
    $sts = $nilai_sumatiflist['sts'];
    $sas = $nilai_sumatiflist['sas'];
    $hnr1 = number_format((($persentase_nas * $nas) + ($persentase_sts * $sts) + ($persentase_sas * $sas)), 2) . "<br>";
    $hnr2 = number_format((($persentase_nas * $nas) + ($persentase_sts * $sts) + ($persentase_sas * $sas)), 0);
    $myResult = ExecuteUpdate("UPDATE nilai_sumatif SET nas='$nas', nr1='$hnr1', nr2='$hnr2' WHERE nilai_s_id='$nilai_s_id'");
  ?>
  <?php } ?>

  <body>
    <div class="loader"> <img src="../kurmer.png" alt="Loading"> </div>
  </body>

  <meta http-equiv="refresh" content="2;url=NilaiSumatifList?showmaster=penilaian&fk_penilaian_id=<?= $penilaian_id ?>" />
<?php } ?>

<?php
if (isset($_GET['pif'])) {
  $penilaian_id = base64_decode($_GET['pif']);
  $guru_id = ExecuteScalar("SELECT guru_id FROM nilai_formatif WHERE penilaian_id='$penilaian_id'");
  $kode_mapel = ExecuteScalar("SELECT kode_mapel FROM nilai_formatif WHERE penilaian_id='$penilaian_id'");
  $kelas = ExecuteScalar("SELECT kelas FROM nilai_formatif WHERE penilaian_id='$penilaian_id'");
?>
  <div class="card" style="width:30rem;">
    <div class="card-body shadow">
      <h4>Generate Nilai Formatif</h4>
      <li>Guru : <?= $guru_id ?></li>
      <li>Kode Mapel : <?= $kode_mapel ?></li>
      <li>Kelas : <?= $kelas ?></li>

      <form class="py-3" action="act.php">

        <input class="form-control" type="hidden" id="penilaian_id" name="penilaian_id" value="<?= $penilaian_id ?>">
        <div class="py-1">
          <div class="row">
            <div class="col-md-4">
              <a href="NilaiFormatifList?showmaster=penilaian&fk_penilaian_id=<?= $penilaian_id ?>" class="btn btn-success" style="width:100%;">Kembali</a>
            </div>
            <div class="col-md-8">
              <input type="submit" class="btn btn-warning" id="rata-sumatif" name="rata-sumatif" value="Generate Rata Nilai Formatif" style="width:100%;">
            </div>
          </div>

        </div>
      </form>
    </div>
  </div>
<?php } ?>

<?php
if (isset($_GET['rata-sumatif'])) { ?>
  <?php
  $penilaian_id = $_GET['penilaian_id'];

  $nilai_formatif = ExecuteQuery("SELECT * FROM nilai_formatif WHERE penilaian_id='$penilaian_id'");
  while ($nilai_formatiflist = $nilai_formatif->fetch()) {
    $nilai_f_id = $nilai_formatiflist['nilai_f_id'];
    $naf = $nilai_formatiflist['naf'];
    // Initialize an array to hold the values
    $values = [
      number_format($nilai_formatiflist['f1']),
      number_format($nilai_formatiflist['f2']),
      number_format($nilai_formatiflist['f3']),
      number_format($nilai_formatiflist['f4']),
      number_format($nilai_formatiflist['f5']),
      number_format($nilai_formatiflist['f6']),
      number_format($nilai_formatiflist['f7']),
      number_format($nilai_formatiflist['f8']),
      number_format($nilai_formatiflist['f9']),
      number_format($nilai_formatiflist['f10']),
      number_format($nilai_formatiflist['f11']),
      number_format($nilai_formatiflist['f12']),
      number_format($nilai_formatiflist['f13']),
      number_format($nilai_formatiflist['f14']),
      number_format($nilai_formatiflist['f15'])
    ];

    // Filter out the zeros and calculate the sum
    $nonZeroValues = array_filter($values, function ($value) {
      return $value != '0'; // Only keep values that are not zero
    });

    // Calculate the sum and average of the non-zero values
    $sum = array_sum($nonZeroValues);
    $count = count($nonZeroValues);

    $average = ($count > 0) ? $sum / $count : 0; // Avoid division by zero
    if ($average != $naf) {
      $update = ExecuteUpdate("UPDATE nilai_formatif SET naf='$average' WHERE nilai_f_id='$nilai_f_id'");
    }
  ?>
  <?php } ?>

  <body>
    <div class="loader"> <img src="../kurmer.png" alt="Loading"> </div>
  </body>

  <meta http-equiv="refresh" content="2;url=NilaiFormatifList?showmaster=penilaian&fk_penilaian_id=<?= $penilaian_id ?>" />
<?php } ?>