<?php
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');
$merge_key_val = array();
$data_rec = array();
$offset = $_POST['offset'];
$token = $_POST['token'];
 $nim_data = array();
$jumlah['offset'] = $offset;
$jumlah['token'] = $_POST['token'];
$data_array_jur = array();
$datas = array();
$id_mk = array();
/*if ($_POST['last']=='yes') {
    //echo 'yes';
    $jumlah['last'] = "Yes";
}*/


// open the file "demosaved.csv" for writing
//$file = fopen('demosaved.csv', 'a');

if ($offset==0) {
  
    $token = $db->get_token();

    $jumlah['token'] = $token;


}

        $jurusan = $db->fetch_custom("select id_sms,nama_jurusan,kode_jurusan from jurusan");
        foreach ($jurusan as $jur) {
          $data_array_jur[$jur->id_sms] = $jur->kode_jurusan;

        }



$no=1;
$index = 2;
$nim_label = "Semua";
$data_rec = array();
$header = array(
  'Kode MK'=>'string',
  'Nama MK'=>'string',
  'Jenis MK'=>'string',
  'SKS Tatap Muka'=>'string',
  'SKS Praktek' => 'string',
  'SKS Praktek Lapangan' => 'string',
  'SKS Simulasi' => 'string',
  'Metode Pembelajaran' => 'string',
  'Tgl Mulai Efektif' => 'string',
  'Tgl Akhir Efektif' => 'string',
  'Kode Prodi' => 'string',
  'Id Matkul' => 'string'
);

        if ($_POST['total_data']<=200) {
            $limit = $_POST['total_data'];
        } else {
            $limit = 200;
        }

         if ($_POST['jurusan']!="all") {
            if ($_POST['kurikulum']!='all') {
                  if ($_POST['matkul']!='all') {
                    $jumlah = 1;
                    $temp_count_mk_kur = [
                          'act' => 'GetDetailMataKuliah',
                            'token' => $token,
                            'filter' => "id_matkul='".$_POST['matkul']."'",
                            'order' => '',
                            'limit' => $limit,
                            'offset' => $offset
                        ];
                    $temp_count_mk_kur_data = json_decode($db->run($temp_count_mk_kur,$url));
                    if(!empty($temp_count_mk_kur_data->data)) {
                      $datas = $temp_count_mk_kur_data->data;
                    }

                  } else {
                    $temp_count_mk_kur = [
                          'act' => 'GetMatkulKurikulum',
                            'token' => $token,
                            'filter' => "id_kurikulum='".$_POST['kurikulum']."'",
                            'order' => '',
                            'limit' => $limit,
                            'offset' => $offset
                        ];
                    $temp_count_mk_kur_data = json_decode($db->run($temp_count_mk_kur,$url));
                    if(!empty($temp_count_mk_kur_data->data)) {
                      foreach ($temp_count_mk_kur_data->data as $dt) {
                        $id_mk[$dt->id_matkul] = "'".$dt->id_matkul."'";
                      }
                      $implode_id_mk = implode(",", $id_mk);
                      $temp_count_mk = [
                            'act' => 'GetDetailMataKuliah',
                              'token' => $token,
                              'filter' => "id_matkul in($implode_id_mk)",
                              'order' => '',
                              'limit' => "",
                              'offset' => ""
                          ];
                      $temp_count_data_mk = json_decode($db->run($temp_count_mk,$url));
                      if(!empty($temp_count_data_mk->data)) {
                        foreach ($temp_count_data_mk->data as $dt_mk) {
                          $datas[] = $dt_mk;
                        }
                      }
                    }
                  }
              } else {
                $temp_count_mk = [
                      'act' => 'GetDetailMataKuliah',
                        'token' => $token,
                        'filter' => "id_prodi='".$_POST['jurusan']."'",
                        'order' => '',
                        'limit' => $limit,
                        'offset' => $offset
                    ];
                $temp_count = json_decode($db->run($temp_count_mk,$url));
                if(!empty($temp_count->data)) {
                  $datas = $temp_count->data;
                }

              }
          
          } else {
            $temp_count_mk = [
                  'act' => 'GetDetailMataKuliah',
                    'token' => $token,
                    'filter' => "",
                    'order' => '',
                    'limit' => $limit,
                    'offset' => $offset
                ];
            $temp_count = json_decode($db->run($temp_count_mk,$url));
            if(!empty($temp_count->data)) {
              $datas = $temp_count->data;
            }

          }



        if (!empty($datas)) {

          foreach ($datas as $key) {
                  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->kode_mata_kuliah),
                       convert_ascii($key->nama_mata_kuliah),
                       convert_ascii($key->id_jenis_mata_kuliah),
                       convert_ascii($key->sks_tatap_muka),
                       convert_ascii($key->sks_praktek),
                       convert_ascii($key->sks_praktek_lapangan),
                       convert_ascii($key->sks_simulasi),
                       convert_ascii($key->metode_kuliah),
                       convert_ascii($key->tanggal_mulai_efektif),
                       convert_ascii($key->tanggal_selesai_efektif),
                       $kode_jur,
                       $key->id_matkul
                       );

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

        }

/*echo "<pre>";
print_r($merge_key_val);*/
$file_name = $_POST['random_number'];
//write temp file
$json_filename = SITE_ROOT."upload/temp/$file_name.json";

write_data($json_filename,$merge_key_val);


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

/*echo "<pre>";
print_r($final);

exit();*/



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

//column width
$col_width = array(
  1 => 15,
  2 => 25,
  3 => 10,
  4 => 15,
  5 => 15,
  6 => 19,
  7 => 13,
  8 => 20,
  9 => 20,
  10 => 20,
  11 => 15
  );
$writer->setColWidth($col_width);






//unlink($filename);
$filename = 'Data_Matakuliah.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 Matakuliah', $header, $style);
$writer->writeToFile(SITE_ROOT."upload/temp/".$_POST['random_number']."_".XLSXWriter::sanitize_filename(str_replace(' ','_',$filename)));

ob_end_clean();



$msg =  "<div class=\"alert alert-warning \" role=\"alert\">
        <font color=\"#3c763d\">".$_POST['total_data']." data berhasil di generate</font><br />";
        $msg .= "<a class='btn btn-block btn-primary btn-xs' href='".base_url()."upload/temp/".$_POST['random_number']."_".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/".$_POST['random_number']."_".XLSXWriter::sanitize_filename(str_replace(' ','_',$filename));

        $jumlah['json_file'] = $json_filename; 

        $jumlah['last_notif'] = $msg;
        //unlink($json_filename);
}



array_push($json_response, $jumlah);

echo json_encode($json_response);
exit();

?>