<?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();
    }

$header = array(
             'NIM' =>'string',
             'Nama Mahasiswa' =>'string',
             'Kode Matakuliah' =>'string',
             'Nama Matakuliah' =>'string',
             'Semester' =>'string',
             'Kelas' =>'string',
             'Nilai Huruf' =>'string',
             'Nilai Indeks' =>'string',
             'Nilai Angka' =>'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) {
              $jur_array[] = "'".$jur->id_sms."'";
              $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['nim']=='all') {
               if ($_POST['jurusan']=='all') {
                  $offset = $offset;
                  $jur = $db->fetch_custom_single("select id_sms from jurusan limit $offset,1");
                  $id_sms = $jur->id_sms;
                         $data_dic = array(
                        'act' => 'GetDetailNilaiPerkuliahanKelas',
                        'token' => $token,
                        'filter' => "id_semester='".$_POST['sem_filter']."' and id_prodi='$id_sms'",
                        'order' => 'nim asc'
                          );
                      
                         $temp_data = json_decode($db->run($data_dic,$url));
                } else {
                  if ($_POST['total_data']<=500) {
                      $limit = $_POST['total_data'];
                  } else {
                      $limit = 500;
                  }
                 
              $kode_mk = "";
              if ($_POST['matkul']!='all') {
                $kode_mk = "and id_matkul='".$_POST['matkul']."'";
              }

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

                    $data_dic = array(
                        'act' => 'GetDetailNilaiPerkuliahanKelas',
                        'token' => $token,
                        'filter' => $filter_kelas,
                        'order' => 'nim asc',
                        'limit' => $limit,
                        'offset' => $offset,
                        //'fungsi' => 'InsertPeriodePerkuliahan'
                    );
                    $temp_data = json_decode($db->run($data_dic,$url));
            }


               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($nilai->id_prodi, array_keys($data_array_jur))) { 
                    $kode_jur_kelas = $data_array_jur[$nilai->id_prodi]['kode_jurusan'];
                  } else {
                    $kode_jur_kelas = '';
                  }
                   $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),
                      convert_ascii($nilai->nilai_huruf),
                      convert_ascii($nilai->nilai_indeks),
                      convert_ascii($nilai->nilai_angka),
                      $kode_jur,
                      $kode_jur_kelas,
                      convert_ascii($nilai->sks_mata_kuliah)
                  );

                   $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_peserta = [
              'act' => 'GetPesertaKelasKuliah',
                'token' => $token,
                'filter' => "id_registrasi_mahasiswa='$id_reg' $sem_filter"
            ];
            
            $temp_data = json_decode($db->run($temp_peserta,$url));
            if (!empty($temp_data->data)) {
              foreach ($temp_data->data as $dt_peserta) {
                $id_kelas_array[] = "'".$dt_peserta->id_kelas_kuliah."'";
              }
           
            $kelas_id = implode(",", $id_kelas_array);
            $temp_kelas = [
              'act' => 'GetListKelasKuliah',
                'token' => $token,
                'filter' => "id_kelas_kuliah in($kelas_id)"
            ];
            
            $temp_data_kelas = json_decode($db->run($temp_kelas,$url));
            if (!empty($temp_data_kelas->data)) {
              foreach ($temp_data_kelas->data as $dt_kelas) {
                $id_prodi_array[$dt_kelas->id_prodi] = $dt_kelas->id_prodi;
              }
            }

            foreach ($id_prodi_array as $id_prodi) {
                $temp_nilai = [
                  'act' => 'GetDetailNilaiPerkuliahanKelas',
                    'token' => $token,
                    'filter' => "id_registrasi_mahasiswa='$id_reg' $sem_filter and id_prodi='$id_prodi'"
                ];
                //dump($temp_nilai);
                $temp_data = json_decode($db->run($temp_nilai,$url));
                if (!empty($temp_data->data)) {
            foreach ($temp_data->data 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 = '';
                  }
                     $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),
                        convert_ascii($nly->nilai_huruf),
                        convert_ascii($nly->nilai_indeks),
                        convert_ascii($nly->nilai_angka),
                        $kode_jur,
                        $kode_jur_kelas,
                        convert_ascii($nly->sks_mata_kuliah),
                    );

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

          }

        }


$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',
                    'D1',
                   'E1',
                    'F1',
                    'G1',
                    'H1',
                    'I1',
                    'J1',
                    'K1'
                    ),
                'border' => array(
                    'style' => 'thin',
                    'color' => '000000'
                    ),
                'verticalAlign' => 'center',
                'horizontalAlign' => 'center',
            ),
                        array(
                'fill' => array(
                    'color' => '00ff00'
                    ),
                'cells' => array(
                  'B1',
                    'D1',
                    'L1'
                    
                    ),
                'border' => array(
                    'style' => 'thin',
                    'color' => '000000'
                    ),
                'verticalAlign' => 'center',
                'horizontalAlign' => 'center',
                )
            );

//column width
$col_width = array(
  1 => 19,
  2 => 27,
  3 => 20,
  4 => 30,
  5 => 20,
  6 => 15,
  7 => 19,
  8 => 19,
  9 => 19,
  10 => 22,
  11 => 20,
  12 => 11
  );

$writer->setColWidth($col_width);

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

    if ($_POST['nim']!='all') {
      $filename = $_POST['value_nim'].'_NILAI.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();
?>