<?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 = get_service_url('url_rest');

$data_rec = array();
$final = array();
$id_reg_pd_smt = array();
$offset = $_POST['offset'];
$token = $_POST['token'];

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

$no = $offset;

if ($offset==0) {

$token = $db->get_token();


    $jumlah['token'] = get_token();
}




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



        $id_sms = '';
        $semester = "";
        $nim = "";
          
        if ($_POST['sem_filter']!='') {
          $semester = "and id_semester='".$_POST['sem_filter']."'";
        }

        if ($_POST['nim']!='all') {
          $nim = "and nim='".$_POST['value_nim']."'";
        }


            if ($_POST['status']=='all') {
            $status = '';
          } else {
            $status = "and id_status_mahasiswa='".$_POST['status']."'";

          }
        $filter_angkatan = "and (angkatan BETWEEN '".$_POST['angkatan_awal']."' and '".$_POST['angkatan_akhir']."')";
         $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;
      }

       
        $filter_kelas = "nim is not null $nim $filter_angkatan $semester $id_sms $status";

       // echo $filter_kelas;

        $order_by = "id_semester asc,nim ASC";


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

        //$jumlah['limit'] = $limit;

    $temp_data_akm = [
      'act' => 'GetListPerkuliahanMahasiswa',
        'token' => $token,
        'filter' => $filter_kelas,
        'order' => $order_by,
        'limit' => $limit,
        'offset' => $offset

    ];

$header = array(
             'NIM' => 'String',
             'Nama' => 'String',
             'Semester' =>'string',
             'SKS' =>'string',
             'IP Semester' =>'string',
             'SKS Kumulatif' =>'string',
             'IP Kumulatif' =>'string',
             'Status' =>'string',
             'Kode Prodi' => 'string',
             'Biaya Semester' => 'string',
             'Jenis Pembiayaan' => 'string'
);
    $temp_data = json_decode($db->run($temp_data_akm,$url));

     //dump($temp_data); 

    foreach ($temp_data->data as $data_akm) {
            if (in_array($data_akm->id_prodi, array_keys($data_array_jur))) { 
              $kode_jur = $data_array_jur[$data_akm->id_prodi];
            } else {
              $kode_jur = '';
            }
            $data_rec = array(
               convert_ascii($data_akm->nim),
               convert_ascii($data_akm->nama_mahasiswa),
               convert_ascii($data_akm->id_semester),
               convert_ascii($data_akm->sks_semester),
               convert_ascii($data_akm->ips),
               convert_ascii($data_akm->sks_total),
               convert_ascii($data_akm->ipk),
               convert_ascii($data_akm->id_status_mahasiswa),
               convert_ascii($kode_jur),
               convert_ascii(number_format($data_akm->biaya_kuliah_smt, 0, '.', '')),
               $data_akm->id_pembiayaan
            );
            $merge_key_val[] = array_combine(array_keys($header), $data_rec);
    }

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

//column width
$col_width = array(
  1 => 19,
  2 => 27,
  3 => 30,
  4 => 20,
  5 => 20,
  6 => 20,
  7 => 20,
  8 => 15,
  9 => 20,
  10 => 15,
  11 => 20
  );

$writer->setColWidth($col_width);      


$filename = 'Akm'.$_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 Akm', $header, $style);
$writer->writeToFile(SITE_ROOT."upload/temp/".XLSXWriter::sanitize_filename(str_replace(' ','_',$filename)));
//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\">".$_POST['total_data']." data Akm 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();
?>