<?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');


$data_rec = array();

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

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

$no = $offset;

if ($offset==0) {
$token = get_token();
    $jumlah['token'] = $token;
}




//require_once '../../lib/php-export-data.class.php';


$header = array(
            'Semester'=> 'string',
            'NIDN'=> 'string',
            'Nama Dosen'=> 'string',
            'Kode Matakuliah'=> 'string',
            'Nama Kelas'=> 'string',
            'Rencana Tatap Muka'=> 'string',
            'Tatap Muka Real'=> 'string',
            'Kode Prodi'=> 'string',
            'SKS Ajar' => 'string',
            'Jenis Evaluasi' => 'string',
            'Matakuliah' => 'string',
            'ID Dosen NEO' => 'string',
            'ID Substansi Kuliah' => 'string'
);

$id_sms = '';
            $semester = "where id_smt='".$_POST['sem_filter']."'";
           if ($_POST['matkul']=='all') {
              $matkul = '';
            } else {
              $matkul = "and id_mk='".$_POST['matkul']."'";
            }
           if ($_POST['jurusan']=='all') {
              $id_sms = '';
            } else {
              $id_sms = "and id_sms='".$_POST['jurusan']."' ";
            }
            
            $filter_kelas = "id_kelas_kuliah in(select id_kls from kelas_kuliah $semester $id_sms $matkul)";


           if ($_POST['jurusan']=='all') {
              $nama_jurusan = 'Semua_Prodi';
            } else {
             $prodi = $_POST['jurusan'];
                $jurusan = $db->fetch_custom_single("select id_sms,nama_jurusan,kode_jurusan from jurusan where id_sms='$prodi'");
                $nama_jurusan = $jurusan->nama_jurusan;
                $kode_prodi = $jurusan->kode_jurusan;
            }


            $prodi = $_POST['jurusan'];

              if ($prodi=='all') {
                  $jurusan = "";
                   $id_sms = "";

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


              } else {
                $jurusan = $db->fetch_custom_single("select id_sms,nama_jurusan,kode_jurusan from jurusan where id_sms='$prodi'");
                $id_sms = "and id_prodi='".$prodi."'";
                $nama_jurusan = "_".$jurusan->nama_jurusan;
                $data_array_jur[$jurusan->id_sms] =  $jurusan->kode_jurusan;
              }

        if ($_POST['total_data']<=59) {
            $limit = $_POST['total_data'];
        } else {
            $limit = 59;
        }
        $order_by = "kode_mk ASC";
                      $temp_data_kelas = [
                        'act' => 'GetDosenPengajarKelasKuliah',
                      'token' => $token,
                      'filter' => $filter_kelas,
                      'order' => 'id_aktivitas_mengajar asc',
                      'limit' => $limit,
                      'offset' => $offset

                  ];

              $temp_rec = json_decode($db->run($temp_data_kelas,$url));
     
               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_kelas = "'" . implode("','", $id_kls) . "'";

                  $temp_data_ajar = [
                        'act' => 'GetDetailKelasKuliah',
                          'token' => $token,
                          'filter' => "id_kelas_kuliah in($id_kelas)",
                          'order' => "",
                          'limit' => "",
                          'offset' => ""
                      ];
                      $temp_data = json_decode($db->run($temp_data_ajar,$url));
                      $id_kelas_dosen = array();
                      $second_merge = array();

                  foreach ($temp_data->data as $dts) {
                    $data_kelas[$dts->id_kelas_kuliah] = $dts;
                  }


                if (!empty($temp_rec->data)) {
                foreach ($temp_rec->data as $key) {

                    if (in_array($key->id_kelas_kuliah, array_keys($data_kelas))) {
                        if (in_array($key->id_prodi, array_keys($data_array_jur))) { 
                          $kode_jur = $data_array_jur[$key->id_prodi];
                        } else {
                          $kode_jur = '';
                        }
                          $data_rec = array(
                              convert_ascii($key->id_semester),
                              convert_ascii($key->nidn),
                              convert_ascii($key->nama_dosen),
                              convert_ascii($data_kelas[$key->id_kelas_kuliah]->kode_mata_kuliah),
                              convert_ascii($key->nama_kelas_kuliah),
                              convert_ascii($key->rencana_minggu_pertemuan),
                              convert_ascii($key->realisasi_minggu_pertemuan),
                              $kode_jur,
                              convert_ascii($key->sks_substansi_total),
                              $key->id_jenis_evaluasi,
                              $data_kelas[$key->id_kelas_kuliah]->nama_mata_kuliah,
                              $key->id_dosen,
                              $key->id_substansi
                          ); 
                           $merge_key_val[] = array_combine(array_keys($header), $data_rec);
                           $id_kelas_dosen[$key->id_kelas_kuliah] = $key->id_kelas_kuliah;
                    }


                }
                }
              }

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


//column width
$col_width = array(
  1 => 19,
  2 => 19,
  3 => 27,
  4 => 35,
  5 => 19,
  6 => 19,
  7 => 19,
  8 => 19,
  9 => 15,
  10 => 15,
  11 => 45,
  12 => 50,
  13 => 50
  );

$writer->setColWidth($col_width);



$filename = "Dosen_Ajar_".$_POST['sem_filter'].$nama_jurusan.'.xlsx';
/*header('Content-disposition: attachment; filename="'.XLSXWriter::sanitize_filename($filename).'"');
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');

$writer->writeToFile('xlsx-simple.xlsx');*/
$writer->writeSheet($final,'Data Dosen Ajar', $header, $style);
$writer->writeToFile(SITE_ROOT."upload/temp/".XLSXWriter::sanitize_filename(str_replace(' ','_',$filename)));

$msg =  "<div class=\"alert alert-warning \" role=\"alert\">
        <font color=\"#3c763d\">".$jml_akhir." data Dosen Ajar 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();
?>