<?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();
$data_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',
  'Semester' => 'string',
  'Kurikulum' => 'string',
  'Wajib' => '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_mk_kur= [
                          'act' => 'GetMatkulKurikulum',
                            'token' => $token,
                            'filter' => "id_matkul='".$_POST['matkul']."'",
                            'order' => '',
                            'limit' => $limit,
                            'offset' => $offset
                        ];
                    $temp_data_mk_kur = json_decode($db->run($temp_mk_kur,$url));
                    if(!empty($temp_data_mk_kur->data)) {
                      $datas = $temp_data_mk_kur->data;

                      $temp_data_mk = [
                            'act' => 'GetDetailMataKuliah',
                              'token' => $token,
                              'filter' => "id_matkul='".$_POST['matkul']."'",
                              'order' => '',
                              'limit' => $limit,
                              'offset' => $offset
                          ];
                      $temp_mk_data = json_decode($db->run($temp_data_mk,$url));
                      foreach ($temp_mk_data as $dt) {
                        $data_mk[$dt->id_matkul] = $dt;
                      }

                    }

                  } 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));
                    //dump($temp_count_mk_kur_data);
                    if(!empty($temp_count_mk_kur_data->data)) {
                      $datas = $temp_count_mk_kur_data->data;
                      foreach ($temp_count_mk_kur_data->data as $dt) {
                        $temp_count_mk = [
                              'act' => 'GetDetailMataKuliah',
                                'token' => $token,
                                'filter' => "id_matkul='$dt->id_matkul'",
                                '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) {
                            $data_mk[$dt_mk->id_matkul] = $dt_mk;
                          }
                        }
                      }

                    }
                  }
              } else {

            $dic_mk = [
                  'act' => 'GetMatkulKurikulum',
                    'token' => $token,
                    'filter' => "id_prodi='".$_POST['jurusan']."'",
                    'order' => '',
                    'limit' => $limit,
                    'offset' => $offset
                ];
            $temp_data_matkur = json_decode($db->run($dic_mk,$url));
            //dump($temp_data_matkur);
            $ids_mk = array();
            if(!empty($temp_data_matkur->data)) {
              $datas = $temp_data_matkur->data;
              foreach ($temp_data_matkur->data as $dt) {
                  $ids_mk[] = "'".$dt->id_matkul."'";
              }
            }

                $implode_ids = implode(",", $ids_mk);
                $temp_count_mk = [
                      'act' => 'GetDetailMataKuliah',
                        'token' => $token,
                        'filter' => "id_matkul in ($implode_ids)",
                        'order' => '',
                        'limit' => "",
                        'offset' => ""
                    ];
                $temp_count_data_mk = json_decode($db->run($temp_count_mk,$url));

                /*dump($temp_count_mk);
                 dump($temp_count_data_mk);*/
                
                if(!empty($temp_count_data_mk->data)) {
                  foreach ($temp_count_data_mk->data as $dt_mk) {
                    $data_mk[$dt_mk->id_matkul] = $dt_mk;
                  }
                }
                
             

              }
          
          } else {
            $dic_mk = [
                  'act' => 'GetMatkulKurikulum',
                    'token' => $token,
                    'filter' => "",
                    'order' => '',
                    'limit' => $limit,
                    'offset' => $offset
                ];
            $temp_data_matkur = json_decode($db->run($dic_mk,$url));
            //dump($temp_data_matkur);
            $ids_mk = array();
            if(!empty($temp_data_matkur->data)) {
              $datas = $temp_data_matkur->data;
              foreach ($temp_data_matkur->data as $dt) {
                  $ids_mk[] = "'".$dt->id_matkul."'";
              }
            }

                $implode_ids = implode(",", $ids_mk);
                $temp_count_mk = [
                      'act' => 'GetDetailMataKuliah',
                        'token' => $token,
                        'filter' => "id_matkul in ($implode_ids)",
                        'order' => '',
                        'limit' => "",
                        'offset' => ""
                    ];
                $temp_count_data_mk = json_decode($db->run($temp_count_mk,$url));

                /*dump($temp_count_mk);
                 dump($temp_count_data_mk);*/
                
                if(!empty($temp_count_data_mk->data)) {
                  foreach ($temp_count_data_mk->data as $dt_mk) {
                    $data_mk[$dt_mk->id_matkul] = $dt_mk;
                  }
                }


          }



        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 = '';
                  }
                  if (in_array($key->id_matkul, array_keys($data_mk))) {
                    $data_rec = array(
                         convert_ascii($data_mk[$key->id_matkul]->kode_mata_kuliah),
                         convert_ascii($data_mk[$key->id_matkul]->nama_mata_kuliah),
                         convert_ascii($data_mk[$key->id_matkul]->id_jenis_mata_kuliah),
                         convert_ascii($data_mk[$key->id_matkul]->sks_tatap_muka),
                         convert_ascii($data_mk[$key->id_matkul]->sks_praktek),
                         convert_ascii($data_mk[$key->id_matkul]->sks_praktek_lapangan),
                         convert_ascii($data_mk[$key->id_matkul]->sks_simulasi),
                         convert_ascii($data_mk[$key->id_matkul]->metode_kuliah),
                         convert_ascii($data_mk[$key->id_matkul]->tanggal_mulai_efektif),
                         convert_ascii($data_mk[$key->id_matkul]->tanggal_selesai_efektif),
                         convert_ascii($key->semester),
                         convert_ascii($key->id_semester),
                         convert_ascii($key->apakah_wajib),
                         $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',
                    'L1',
                    'M1',
                    'N1',
                    'P1'
                    ),
                'border' => array(
                    'style' => 'thin',
                    'color' => '000000'
                    ),
                'verticalAlign' => 'center',
                'horizontalAlign' => 'center',
            ),
                        array(
                'fill' => array(
                    'color' => '00ff00'
                    ),
                'cells' => array(
                  'H1',
                  'I1',
                  'J1',
                  'O1'
                    ),
                '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,
  12 => 15,
  13 => 25,
  14 => 30,
  15 => 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();

?>
