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

$jumlah['offset'] = $offset;
$jumlah['token'] = $_POST['token'];
$data_array_jur = 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(
  'NIM'=>'string',
  'NAMA'=>'string',
  'Kode Mk Asal'=>'string',
  'Nama Mk Asal'=>'string',
  'SKS Asal'=>'string',
  'Nilai Huruf Asal'=>'string',
  'Kode Matakuliah Diakui'=>'string',
  'Nama Matakuliah Diakui'=>'string',
  'Nilai Huruf Diakui' => 'string',
  'Nilai Angka Diakui' => 'string',
  'Kode Prodi' => 'string',
  'Semester' => 'string'
);

        $nim = "";
        $filter_prodi = "";

        $filter_transfer = "";
        if ($_POST['nim']!='all') {
            $nim_label = $_POST['value_nim'];
            $nim  = "and nim like '%".$_POST['value_nim']."%'";
        } else {
          if ($_POST['jurusan']!='all') {
            $filter_prodi = "and id_prodi='".$_POST['jurusan']."'";
          }
        }


        $semester = "";

        if ($_POST['sem_filter']!='all') {
          if ($_POST['sem_filter']=='kosong') {
             $semester = "and id_semester is null ";
          } else {
             $semester = "and id_semester='".$_POST['sem_filter']."' ";
          }
         
        }

        $filter_angkatan = "and id_registrasi_mahasiswa in(select id_reg_pd from reg_pd where left(mulai_smt,4) BETWEEN '".$_POST['angkatan_awal']."' and '".$_POST['angkatan_akhir']."')";

        $filter_transfer = "id_registrasi_mahasiswa is not null $filter_angkatan $nim $filter_prodi $semester";



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

        $temp_rec = array();
        $temp_data_akm = [
          'act' => 'GetNilaiTransferPendidikanMahasiswa',
            'token' => $token,
            'filter' => "$filter_transfer",
            'order' => "nim asc",
            'limit' => $limit,
            'offset' => $offset

        ];

        //dump($temp_data_akm);
        $temp_rec = json_decode($db->run($temp_data_akm,$url));

        if ($temp_rec->data) {

          foreach ($temp_rec->data as $key) {

                  $data_rec = array(
                       convert_ascii($key->nim),
                       convert_ascii($key->nama_mahasiswa),
                       convert_ascii($key->kode_mata_kuliah_asal),
                       convert_ascii($key->nama_mata_kuliah_asal),
                       convert_ascii($key->sks_mata_kuliah_asal),
                       convert_ascii($key->nilai_huruf_asal),
                       convert_ascii($key->kode_matkul_diakui),
                       convert_ascii($key->nama_mata_kuliah_diakui),
                       convert_ascii($key->nilai_huruf_diakui),
                       convert_ascii($key->nilai_angka_diakui),
                       $data_array_jur[$key->id_prodi],
                       convert_ascii($key->id_semester)
                       );
                  $merge_key_val[] = array_combine(array_keys($header), $data_rec);

                         $index++;
                    }

        }

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

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

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






//unlink($filename);
$filename = 'Data_Nilai_transfer.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 Nilai', $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();

?>