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

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

    $url = $db->get_service_url('rest');
    $offset = $_POST['offset'];
    $token = $_POST['token'];

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

    if ($offset==0) {
        $token = $db->get_token();
        $jumlah['token'] = $token;
    }
    $merge_key_val = array();
    $header = array(
  'Semester' => 'string',
  'Kelas' => 'string',
  'Kode Matakuliah'=>'string',
  'Nama Matakuliah'=>'string',
  'Basis Evaluasi'=>'string',
  'Komponen Evaluasi'=>'string',
  'Bobot (%)'=>'string',
  'Nama (Inggris)' =>'string',
  'Kode Prodi'=>'string'
);

        $id_sms = '';
          
        $semester = "and id_semester='".$_POST['sem_filter']."'";

            if ($_POST['matkul']=='all') {
            $matkul = '';
          } else {
            $matkul = "and id_matkul='".$_POST['matkul']."'";

          }
        
         $prodi = $_POST['jurusan'];

      $id_sms = "and id_prodi='".$_POST['jurusan']."' ";
      if ($prodi=='all') {
          $jurusan = "";
           $id_sms = "";

          $jumlah['jurusan_attribute'] = $_POST['jurusan_attribute'];
          $data_array_jur = json_decode($_POST['jurusan_attribute'],true);  

        if ($offset==0) {
          if ($_SESSION['level']!=1) {
            $id_sms = "and id_prodi='".$_SESSION['id_sms']."'";
              $jurusan = $db->fetch_custom_single("select id_sms,nama_jurusan,kode_jurusan from jurusan where id_sms='".$_SESSION['id_sms']."'");
              $id_sms = "and id_prodi='".$jurusan->id_sms."'";
              $nama_jurusan = $jurusan->nama_jurusan;
              $data_array_jur[$jurusan->id_sms] = $jurusan->kode_jurusan;
          } else {
              $nama_jurusan = "";
              $data_jurusan = $db->fetch_all('jurusan');
              
              $data_array_jur = array();
              foreach ($data_jurusan as $dt) {
                  $data_array_jur[$dt->id_sms] =  $dt->kode_jurusan;  
              }
          }
          $jumlah['jurusan_attribute'] = json_encode($data_array_jur);
        }



      } else {
       
          $jumlah['jurusan_attribute'] = $_POST['jurusan_attribute'];
          $data_array_jur = json_decode($_POST['jurusan_attribute'],true);  

        if ($offset==0) {
          $jurusan = $db->fetch_custom_single("select id_sms,nama_jurusan,kode_jurusan from jurusan where id_sms='$prodi'");
          $id_sms = "and id_prodi='".$jurusan->id_sms."'";
          $nama_jurusan = $jurusan->nama_jurusan;
          $data_array_jur[$jurusan->id_sms] =  $jurusan->kode_jurusan;
          $jumlah['jurusan_attribute'] = json_encode($data_array_jur);
        }
      }

       
        $filter_kelas = "id_kelas_kuliah in(select id_kls from komponen_evaluasi) $semester $id_sms $matkul";




        $order_by = "id_kelas_kuliah ASC";
        if ($_POST['total_data']<=13) {
            $limit = $_POST['total_data'];
        } else {
            $limit = 13;
        }


              $temp_data_kelas = [
                'act' => 'GetDetailKelasKuliah',
                  'token' => $token,
                  'filter' => $filter_kelas,
                  'order' => $order_by,
                  'limit' => $limit,
                  'offset' => $offset
              ];

        $temp_rec = json_decode($db->run($temp_data_kelas,$url));
        $temp_data_rec = $temp_rec;
        if ($temp_data_rec->data) {
          foreach ($temp_data_rec->data as $dt) {
          $id_kelas[$dt->id_kelas_kuliah] = $dt;
        }

        $in_id_kelas = "'" . implode("','", array_keys($id_kelas)) . "'";
        //jumlah pengajar
        $count_kelas = [
          'act' => 'GetListKomponenEvaluasiKelas',
            'token' => $token,
            'filter' => "id_kelas_kuliah in($in_id_kelas)",
        ];
        $temp_recs = json_decode($db->run($count_kelas,$url));
        if ($temp_recs->data) {
          foreach ($temp_recs->data as $key) {
            if (in_array($id_kelas[$key->id_kelas_kuliah]->id_prodi, array_keys($data_array_jur))) { 
                            $kode_jur = $data_array_jur[$id_kelas[$key->id_kelas_kuliah]->id_prodi];
                          } else {
                            $kode_jur = '';
                          }
              $data_rec = array(
                  $id_kelas[$key->id_kelas_kuliah]->id_semester,
                  $id_kelas[$key->id_kelas_kuliah]->nama_kelas_kuliah,
                  $id_kelas[$key->id_kelas_kuliah]->kode_mata_kuliah,
                  $id_kelas[$key->id_kelas_kuliah]->nama_mata_kuliah,
                  $key->id_jenis_evaluasi,
                  $key->nama,
                  $key->bobot_evaluasi*100,
                  $key->nama_inggris,
                  $kode_jur
              );
              $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') {
$data_file = JsonMachine::fromFile($json_filename);
$jml_akhir = 0;
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',
                    'B1',
                    'C1',
                    'E1',
                    'G1',
                    'H1',
                    'I1'
                    ),
                'border' => array(
                    'style' => 'thin',
                    'color' => '000000'
                    ),
                'verticalAlign' => 'center',
                'horizontalAlign' => 'center',
            ),
                        array(
                'fill' => array(
                    'color' => '00ff00'
                    ),
                'cells' => array(
                      'D1'
                    ),
                'border' => array(
                    'style' => 'thin',
                    'color' => '000000'
                    ),
                'verticalAlign' => 'center',
                'horizontalAlign' => 'center',
                ),
                        array(
                'fill' => array(
                    'color' => '00B0F0'
                    ),
                'cells' => array(
                      'F1'
                    ),
                'border' => array(
                    'style' => 'thin',
                    'color' => '000000'
                    ),
                'verticalAlign' => 'center',
                'horizontalAlign' => 'center',
                )
            );

//column width
$col_width = array(
  1 => 10,
  2 => 8,
  3 => 18,
  4 => 23,
  5 => 16,
  6 => 17,
  7 => 9,
  8 => 18,
  9 => 11
  );
$writer->setColWidth($col_width);


$filename = $_POST['sem_filter'].'_evaluasi_kelas_kuliah.xlsx';


$writer->writeSheet($final,'Data KRS', $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." Evaluasi Kelas 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();
?>