<?php
session_start();
include "../../inc/config.php";
require_once '../../lib/Writer.php';
$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;
    }

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

      $id_sms = "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 = "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 = "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 = "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_sms";

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


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

        $temp_rec = json_decode($db->run($temp_data_kelas,$url));

        if ($temp_rec->data) {
          foreach ($temp_rec->data 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(
                            'nilai_huruf' => convert_ascii($key->nilai_huruf),
                            'nilai_indeks' => convert_ascii($key->nilai_indeks),
                            'bobot_minimum' => convert_ascii($key->bobot_nilai_min),
                            'bobot_maksimum' => convert_ascii($key->bobot_nilai_maks),
                            'tanggal_mulai_efektif' => tgl_english(convert_ascii($key->tanggal_mulai_efektif)),
                            'tanggal_akhir_efektif' => tgl_english(convert_ascii($key->tanggal_akhir_efektif)),
                            'kode_jur' => $kode_jur
                          );
            }
        }
    
   
$file_name = $_POST['random_number'];
//write temp file
$filename = SITE_ROOT."upload/temp/$file_name.json";

write_data($filename,$data_rec);

    //        }
if ($_POST['last']=='yes') {
    $data_file = file_get_contents($filename);
    $final_decode = json_decode($data_file,true);
    //echo "<pre>";
    //print_r($data_file);
   // print_r($final_decode);
    foreach ($final_decode as $key => $value) {
          $final[] = array(
              $value['nilai_huruf'],
              $value['nilai_indeks'],
              $value['bobot_minimum'],
              $value['bobot_maksimum'],
              $value['tanggal_mulai_efektif'],
              $value['tanggal_akhir_efektif'],
              $value['kode_jur']
          );
    }

$jumlah_total = count($final);
unlink($filename);

$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'
                    ),
                'border' => array(
                    'style' => 'thin',
                    'color' => '000000'
                    ),
                'verticalAlign' => 'center',
                'horizontalAlign' => 'center',
            )
            );

//column width
$col_width = array(
  1 => 15,
  2 => 15,
  3 => 19,
  4 => 19,
  5 => 18,
  6 => 18,
  7 => 15
  );
$writer->setColWidth($col_width);


$header = array(
  'Nilai Huruf'=>'string',
  'Nilai Indeks'=>'string',
  'Bobot Nilai Minimum' => 'string',
  'Bobot Nilai Maksimum' =>'string',
  'Tanggal Mulai Efektif' =>'string',
  'Tanggal Akhir Efektif' =>'string',
  'Kode Prodi' =>'string'
);

$filename = 'skala_nilai.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,'Skala Nilai', $header, $style);
$writer->writeToFile(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\">".$jumlah_total." data Skala Nilai berhasil di generate</font><br />";
        $msg .= "<a class='btn btn-block btn-primary btn-xs' href='".base_admin()."modul/".$modul_name[$index_modul]."/".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."admina/modul/".$modul_name[$index_modul]."/".XLSXWriter::sanitize_filename(str_replace(' ','_',$filename));

        $jumlah['last_notif'] = $msg;
}



array_push($json_response, $jumlah);

echo json_encode($json_response);
exit();
?>