<?php
include "../../inc/config.php";
require_once '../../lib/Writer.php';
include "../../lib/vendor/autoload.php";
use \JsonMachine\JsonMachine;
$json_response = array();


function normalizeString($string) {
    // Step 1: Trim leading and trailing whitespaces
    $string = trim($string);
    
    // Step 2: Replace non-breaking spaces with regular spaces
    $string = str_replace("\u{00A0}", ' ', $string);  // Non-breaking space

    // Step 3: Remove invisible characters (like zero-width space)
    $string = preg_replace('/\p{Cf}+/u', '', $string);  // Unicode "Other, Format" chars

    // Step 4: Convert to UTF-8 encoding (if not already)
    $string = mb_convert_encoding($string, 'UTF-8', 'UTF-8');

    // Step 5: Remove double spaces to avoid subtle differences
    $string = preg_replace('/\s+/', ' ', $string);

    return $string;
}

if ($_POST['total_data']<1) {
    $msg =  "<div class=\"alert alert-warning \" role=\"alert\">
        <font color=\"#3c763d\">Tidak ada data berhasil di generate</font><br />
        </div>";

    $jumlah['last_notif'] = $msg;
    array_push($json_response, $jumlah);

    echo json_encode($json_response);
    exit();
}

$merge_key_val = array();
    $url = get_service_url('rest');

    $data_rec = array();

    $offset = $_POST['offset'];
    $token = $_POST['token'];

    $jumlah['offset'] = $offset;
    $jumlah['token'] = $_POST['token'];

    $no = $offset;

    if ($offset==0) {

        $jumlah['token'] = get_token();
        $token = get_token();
    }
    if ($_POST['nim']!='all') {
      $offset = ($offset/5) * 30;
    }


$header = array(
  'NIM'=>'string',
  'Nama'=>'string',
  'Kode Matakuliah'=>'string',
  'Nama Matakuliah'=>'string',
  'Semester'=>'string',
  'Kelas' => 'string',
  'Aktivitas Partisipatif'=>'string',
  'Hasil proyek' => 'string',
  'QUIZ' => 'string',
  'TUGAS' => 'string',
  'UTS' => 'string',
  'UAS' => 'string',
  'Kode Prodi Mahasiswa'=>'string',
  'Kode Prodi Kelas'=>'string',
  'SKS'=>'string'
);

            $array_jur_name = array();
            $jurusan = $db->fetch_custom("select id_sms,concat(jurusan.jenjang,' ',jurusan.nama_jurusan) as nama_jurusan,kode_jurusan from jurusan");
            foreach ($jurusan as $jur) {
              $array_jur_name[normalizeString($jur->nama_jurusan)] = $jur->kode_jurusan;
              $data_array_jur[$jur->id_sms] = array(
                'kode_jurusan' => $jur->kode_jurusan,
                'nama_jurusan' => $jur->nama_jurusan
              );

            }

        $nim = "";
        $value_nim = "";
        $id_sms = '';
                      $id_prodi = "";
            $id_matkul = "";
            $id_kelas_kuliah = "";
            $nama_jurusan = "";
            $sem_filter = "";
            if ($_POST['total_data']<=11) {
                $limit = $_POST['total_data'];
            } else {
                $limit = 11;
            }
           

$partisipasi_id = array();
$proyek_id = array();
$quiz_id = array();
$tugas_id = array();
$uts_id = array();
$uas_id = array();
  $array_komponen = array(
    1 => 'partisipatif',2 => 'proyek',3 => 'quiz',4 => 'tugas',5 => 'uts',6 => 'uas'
  );
        if ($_POST['nim']=='all') {


          $old_kode_mk = "";
          $kode_mk = "";
          if ($_POST['matkul']!='all') {
            $kode_mk = "and id_matkul='".$_POST['matkul']."'";
            $old_kode_mk = "and id_mk='".$_POST['matkul']."'";
          }


        if ($_POST['nama_kelas']!='all') {
              $filter_kelas = "id_kelas_kuliah='".$_POST['nama_kelas']."'";
            } else {
              $filter_kelas = "id_semester='".$_POST['sem_filter']."' and id_prodi='".$_POST['jurusan']."' $kode_mk";
            }

              $data_dic = [
                    'act' => 'GetDetailKelasKuliah',
                      'token' => $token,
                      'filter' => $filter_kelas,
                      'order' => 'id_kelas_kuliah desc',
                      'limit' => $limit,
                      'offset' => $offset

                  ];
                  $data_kls = array();
                  $temp_rec = service_request($data_dic);
/*                  dump($data_dic);
                  dump($temp_rec);*/
                  if(!empty($temp_rec->data)) {
                    foreach ($temp_rec->data as $dt) {
                      $id_kls[$dt->id_kelas_kuliah] = $dt->id_kelas_kuliah;
                      $data_kls[$dt->id_kelas_kuliah] = $dt->id_prodi;
                    }
                  $id_kelas = "'" . implode("','", $id_kls) . "'";

                 // dump($id_kelas);

              $data_dic = array(
                'act' => 'GetDetailNilaiPerkuliahanKelas',
                'token' => $token,
                'filter' => "id_kelas_kuliah in($id_kelas) and id_prodi='".$_POST['jurusan']."'",
                'order' => 'nim asc',
                'limit' => '',
                'offset' => '',
                //'fungsi' => 'InsertPeriodePerkuliahan'
              );
             
              $temp_data = json_decode($db->run($data_dic,$url));
              //get komponen nilai
              $data_dic_kom = array(
                'act' => 'GetRiwayatNilaiMahasiswaKomponenEvaluasi',
                'token' => $token,
                'filter' => "id_kelas in($id_kelas) and id_prodi='".$_POST['jurusan']."'"
              );
             $nilai_kom_mahasiswa = array();
              $temp_data_kom = json_decode($db->run($data_dic_kom,$url));
              if (!empty($temp_data_kom->data)) {
                //dump($temp_data_kom);
                foreach ($temp_data_kom->data as $kom_kelas) {

                  if ($kom_kelas->id_jns_eval==2) {
                    $partisipasi_id[$kom_kelas->id_kelas.$kom_kelas->id_registrasi_mahasiswa.'1'] = $kom_kelas->nilai_komp_eval;
                  } elseif ($kom_kelas->id_jns_eval==3) {
                    $proyek_id[$kom_kelas->id_kelas.$kom_kelas->id_registrasi_mahasiswa.'2'] = $kom_kelas->nilai_komp_eval;
                  } elseif ($kom_kelas->id_jns_eval==4 && $kom_kelas->nama=='QIZ') {
                    $quiz_id[$kom_kelas->id_kelas.$kom_kelas->id_registrasi_mahasiswa.'3'] = $kom_kelas->nilai_komp_eval;
                  } elseif ($kom_kelas->id_jns_eval==4 && $kom_kelas->nama=='TGS') {
                    $tugas_id[$kom_kelas->id_kelas.$kom_kelas->id_registrasi_mahasiswa.'4'] = $kom_kelas->nilai_komp_eval;
                  } elseif ($kom_kelas->id_jns_eval==4 && $kom_kelas->nama=='UTS') {
                    $uts_id[$kom_kelas->id_kelas.$kom_kelas->id_registrasi_mahasiswa.'5'] = $kom_kelas->nilai_komp_eval;
                  } elseif ($kom_kelas->id_jns_eval==4 && $kom_kelas->nama=='UAS') {
                    $uas_id[$kom_kelas->id_kelas.$kom_kelas->id_registrasi_mahasiswa.'6'] = $kom_kelas->nilai_komp_eval;
                  }
                }


              }





/*dump($data_dic);
            dump($temp_data);*/
              if (!empty($temp_data->data)) {
                foreach ($temp_data->data as $nilai) {
                  $juran_mhs = normalizeString($nilai->jurusan);
                  if (in_array($juran_mhs, array_keys($array_jur_name))) { 
                    $kode_jur = $array_jur_name[$juran_mhs];
                  } else {
                    $kode_jur = '';
                  }
                  if (in_array($data_kls[$nilai->id_kelas_kuliah], array_keys($data_array_jur))) { 
                    $kode_jur_kelas = $data_array_jur[$data_kls[$nilai->id_kelas_kuliah]]['kode_jurusan'];
                  } else {
                    $kode_jur_kelas = '';
                  }

                  $partisipasi = "";
                  $proyek = "";
                  $quiz = "";
                  $tugas = "";
                  $uts = "";
                  $uas = "";
                  foreach ($array_komponen as $key => $value) {
                    if (in_array($nilai->id_kelas_kuliah.$nilai->id_registrasi_mahasiswa.$key, array_keys($partisipasi_id))) {
                      $partisipasi = $partisipasi_id[$nilai->id_kelas_kuliah.$nilai->id_registrasi_mahasiswa.$key];
                       //dump($partisipasi);
                    }

                    if (in_array($nilai->id_kelas_kuliah.$nilai->id_registrasi_mahasiswa.$key, array_keys($proyek_id))) {
                      $proyek = $proyek_id[$nilai->id_kelas_kuliah.$nilai->id_registrasi_mahasiswa.$key];
                    }
                    if (in_array($nilai->id_kelas_kuliah.$nilai->id_registrasi_mahasiswa.$key, array_keys($quiz_id))) {
                      $quiz = $quiz_id[$nilai->id_kelas_kuliah.$nilai->id_registrasi_mahasiswa.$key];
                    }
                    if (in_array($nilai->id_kelas_kuliah.$nilai->id_registrasi_mahasiswa.$key, array_keys($tugas_id))) {
                      $tugas = $tugas_id[$nilai->id_kelas_kuliah.$nilai->id_registrasi_mahasiswa.$key];
                    }
                    if (in_array($nilai->id_kelas_kuliah.$nilai->id_registrasi_mahasiswa.$key, array_keys($uts_id))) {
                      $uts = $uts_id[$nilai->id_kelas_kuliah.$nilai->id_registrasi_mahasiswa.$key];
                    }
                    if (in_array($nilai->id_kelas_kuliah.$nilai->id_registrasi_mahasiswa.$key, array_keys($uas_id))) {
                      $uas = $uas_id[$nilai->id_kelas_kuliah.$nilai->id_registrasi_mahasiswa.$key];
                    }
                  }
                   $data_rec = array(
                      convert_ascii($nilai->nim),
                      convert_ascii($nilai->nama_mahasiswa),
                      convert_ascii($nilai->kode_mata_kuliah),
                      convert_ascii($nilai->nama_mata_kuliah),
                      convert_ascii($nilai->id_semester),
                      convert_ascii($nilai->nama_kelas_kuliah),
                      $partisipasi,
                      $proyek,
                      $quiz,
                      $tugas,
                      $uts,
                      $uas,
                      $kode_jur,
                      $kode_jur_kelas,
                      convert_ascii($nilai->sks_mata_kuliah)
                  );

                 /* if ($partisipasi!="") {
                    dump($data_rec);
                  }*/

                   $merge_key_val[] = array_combine(array_keys($header), $data_rec);

                }         
              }
              }
              

        } else {

            $filter_nim = "nim='".$_POST['value_nim']."'";
            $data_req_mhs = [
              'act' => 'GetListMahasiswa',
                'token' => $token,
                'filter' => $filter_nim
            ];

            $check_nim_exist = service_request($data_req_mhs);
            //dump($check_nim_exist);
            if (!empty($check_nim_exist->data)) {
              $id_reg = $check_nim_exist->data[0]->id_registrasi_mahasiswa;
              $prodi_mhs = $check_nim_exist->data[0]->id_prodi;

            if ($_POST['sem_filter']!='') {
                $sem_filter = "and id_kelas_kuliah in(select id_kls from kelas_kuliah where id_smt='".$_POST['sem_filter']."')";
            } 



            $temp_count = [
              'act' => 'GetDetailNilaiPerkuliahanKelas',
                'token' => $token,
                'filter' => "id_registrasi_mahasiswa='$id_reg' $sem_filter and id_prodi='$prodi_mhs'",
                'limit' => 30,
                'offset' => $offset
            ];

            $temp_data = json_decode($db->run($temp_count,$url));


            $data_nilai = array();
            foreach ($temp_data->data as $nilai) {
              $data_nilai[] = $nilai;
              $id_kls[] = $nilai->id_kelas_kuliah;
            }

//nilai komponen
           $implode_id_kelas = "";
           if (!empty($id_kls)) {
             $implode_id_kelas = "'" . implode("','", $id_kls) . "'";
           }
         
              $data_dic_kom = array(
                'act' => 'GetRiwayatNilaiMahasiswaKomponenEvaluasi',
                'token' => $token,
                'filter' =>  "id_registrasi_mahasiswa='$id_reg' and id_kelas in($implode_id_kelas) and id_prodi='$prodi_mhs'"
              );
             $nilai_kom_mahasiswa = array();
              $temp_data_kom = json_decode($db->run($data_dic_kom,$url));
              if (!empty($temp_data_kom->data)) {
                //dump($temp_data_kom);
                foreach ($temp_data_kom->data as $kom_kelas) {

                  if ($kom_kelas->id_jns_eval==2) {
                    $partisipasi_id[$kom_kelas->id_kelas.$kom_kelas->id_registrasi_mahasiswa.'1'] = $kom_kelas->nilai_komp_eval;
                  } elseif ($kom_kelas->id_jns_eval==3) {
                    $proyek_id[$kom_kelas->id_kelas.$kom_kelas->id_registrasi_mahasiswa.'2'] = $kom_kelas->nilai_komp_eval;
                  } elseif ($kom_kelas->id_jns_eval==4 && $kom_kelas->nama=='QIZ') {
                    $quiz_id[$kom_kelas->id_kelas.$kom_kelas->id_registrasi_mahasiswa.'3'] = $kom_kelas->nilai_komp_eval;
                  } elseif ($kom_kelas->id_jns_eval==4 && $kom_kelas->nama=='TGS') {
                    $tugas_id[$kom_kelas->id_kelas.$kom_kelas->id_registrasi_mahasiswa.'4'] = $kom_kelas->nilai_komp_eval;
                  } elseif ($kom_kelas->id_jns_eval==4 && $kom_kelas->nama=='UTS') {
                    $uts_id[$kom_kelas->id_kelas.$kom_kelas->id_registrasi_mahasiswa.'5'] = $kom_kelas->nilai_komp_eval;
                  } elseif ($kom_kelas->id_jns_eval==4 && $kom_kelas->nama=='UAS') {
                    $uas_id[$kom_kelas->id_kelas.$kom_kelas->id_registrasi_mahasiswa.'6'] = $kom_kelas->nilai_komp_eval;
                  }
                }


              }

            foreach ($data_nilai as $nly) {
              $juran_mhs = normalizeString($nly->jurusan);
              if (in_array($juran_mhs, array_keys($array_jur_name))) { 
                $kode_jur = $array_jur_name[$juran_mhs];
              } else {
                $kode_jur = '';
              }

              if (in_array($nly->id_prodi, array_keys($data_array_jur))) { 
                $kode_jur_kelas = $data_array_jur[$nly->id_prodi]['kode_jurusan'];
              } else {
                $kode_jur_kelas = '';
              }

              $partisipasi = "";
                  $proyek = "";
                  $quiz = "";
                  $tugas = "";
                  $uts = "";
                  $uas = "";
                  foreach ($array_komponen as $key => $value) {
                    if (in_array($nly->id_kelas_kuliah.$nly->id_registrasi_mahasiswa.$key, array_keys($partisipasi_id))) {
                      $partisipasi = $partisipasi_id[$nly->id_kelas_kuliah.$nly->id_registrasi_mahasiswa.$key];
                       //dump($partisipasi);
                    }

                    if (in_array($nly->id_kelas_kuliah.$nly->id_registrasi_mahasiswa.$key, array_keys($proyek_id))) {
                      $proyek = $proyek_id[$nly->id_kelas_kuliah.$nly->id_registrasi_mahasiswa.$key];
                    }
                    if (in_array($nly->id_kelas_kuliah.$nly->id_registrasi_mahasiswa.$key, array_keys($quiz_id))) {
                      $quiz = $quiz_id[$nly->id_kelas_kuliah.$nly->id_registrasi_mahasiswa.$key];
                    }
                    if (in_array($nly->id_kelas_kuliah.$nly->id_registrasi_mahasiswa.$key, array_keys($tugas_id))) {
                      $tugas = $tugas_id[$nly->id_kelas_kuliah.$nly->id_registrasi_mahasiswa.$key];
                    }
                    if (in_array($nly->id_kelas_kuliah.$nly->id_registrasi_mahasiswa.$key, array_keys($uts_id))) {
                      $uts = $uts_id[$nly->id_kelas_kuliah.$nly->id_registrasi_mahasiswa.$key];
                    }
                    if (in_array($nly->id_kelas_kuliah.$nly->id_registrasi_mahasiswa.$key, array_keys($uas_id))) {
                      $uas = $uas_id[$nly->id_kelas_kuliah.$nly->id_registrasi_mahasiswa.$key];
                    }
                  }

              $data_rec = array(
                  convert_ascii($nly->nim),
                  convert_ascii($nly->nama_mahasiswa),
                  convert_ascii($nly->kode_mata_kuliah),
                  convert_ascii($nly->nama_mata_kuliah),
                  convert_ascii($nly->id_semester),
                  convert_ascii($nly->nama_kelas_kuliah),
                  $partisipasi,
                  $proyek,
                  $quiz,
                  $tugas,
                  $uts,
                  $uas,
                  $kode_jur,
                  $kode_jur_kelas,
                  convert_ascii($nly->sks_mata_kuliah)
                );

               $merge_key_val[] = array_combine(array_keys($header), $data_rec);
            }
            
            //dump($merge_key_val);

          }

        }


$file_name = $_POST['random_number'];
//write temp file
$json_filename = SITE_ROOT."upload/temp/$file_name.json";

if (!empty($merge_key_val)) {

    write_data($json_filename,$merge_key_val);
}

    //        }
if ($_POST['last']=='yes') {
$final = array();
$jml_akhir = 0;
if (is_file($json_filename)) {
  $data_file = JsonMachine::fromFile($json_filename);
  
  foreach ($data_file as $key => $value) {
        $final[] = array_values($value);
        $jml_akhir++;
  }

}





 
$writer = new XLSXWriter();
$style =
        array (
                      array(
              'border' => array(
                'style' => 'thin',
                'color' => '000000'
                ),
            'allfilleddata' => true
            ),
            array(
                'fill' => array(
                    'color' => 'ff0000'
                    ),
                'cells' => array(
                    'A1',
                    'C1',
                    'E1',
                    'F1',
                    'G1',
                    'H1',
                    'I1',
                    'J1',
                    'K1',
                    'L1',
                    'M1',
                    'N1'
                    ),
                'border' => array(
                    'style' => 'thin',
                    'color' => '000000'
                    ),
                'verticalAlign' => 'center',
                'horizontalAlign' => 'center',
            ),
                        array(
                'fill' => array(
                    'color' => '00ff00'
                    ),
                'cells' => array(
                      'B1',
                      'D1',
                      'O1'
                    ),
                'border' => array(
                    'style' => 'thin',
                    'color' => '000000'
                    ),
                'verticalAlign' => 'center',
                'horizontalAlign' => 'center',
                )
            );

//column width
$col_width = array(
  1 => 12,
  2 => 28,
  3 => 16,
  4 => 19,
  5 => 9,
  6 => 9,
  7 => 17,
  8 => 11,
  9 => 7,
  10 => 7,
  11 => 7,
  12 => 7,
  13 => 19,
  14 => 16,
  15 => 30
  );
$writer->setColWidth($col_width);

$filename = $_POST['sem_filter'].$nama_jurusan.'_NILAI_KOMPONEN.xlsx';

    if ($_POST['nim']!='all') {
      $filename = $_POST['value_nim'].'_NILAI_KOMPONEN.xlsx';
    } 


$writer->writeSheet($final,'Data Nilai', $header, $style);
$writer->writeToFile(SITE_ROOT."upload/temp/".XLSXWriter::sanitize_filename(str_replace(' ','_',$filename)));
//$writer->writeToStdOut();
//exit(0);
$modul_name = explode("/", $_SERVER['REQUEST_URI']);

$total_length = count($modul_name);
$index_modul = $total_length-2;

$msg =  "<div class=\"alert alert-warning \" role=\"alert\">
        <font color=\"#3c763d\">".$jml_akhir."  Nilai berhasil di generate</font><br />";
        $msg .= "<a class='btn btn-block btn-primary btn-xs' href='".base_url()."upload/temp/".XLSXWriter::sanitize_filename(str_replace(' ','_',$filename))."' target='_blank'><i class='fa  fa-cloud-download'></i> Download File</a></div>
        </div>";

        $jumlah['data_uri'] = SITE_ROOT."upload/temp/".XLSXWriter::sanitize_filename(str_replace(' ','_',$filename));

        $jumlah['json_file'] = $json_filename;

        $jumlah['last_notif'] = $msg;
}



array_push($json_response, $jumlah);

echo json_encode($json_response);
exit();
?>