<?php
error_reporting(0);
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 = '';
          
        $semester = "id_semester='".$_POST['sem_filter']."'";
        
         $prodi = $_POST['jurusan'];

      $id_sms = "and 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 = "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;  
              }
          }
          $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 = "and 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 = "$semester $id_sms and
EXISTS (
    SELECT 1
    FROM daya_tampung_jalur_masuk
    WHERE id_semester = daya_tampung_jalur_masuk.id_smt
      AND id_prodi = daya_tampung_jalur_masuk.id_sms
  )";

      //  echo $filter_kelas;




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

        

         $temp_data_periode = [
                'act' => 'GetListPeriodePerkuliahan',
                  'token' => $token,
                  'filter' => $filter_kelas,
                  'order' => 'id_prodi desc',
                  'limit' => $limit,
                  'offset' => $offset
              ];

        $temp_rec_periode = json_decode($db->run($temp_data_periode,$url));
        $filter_periode_jalur = array();
        if (!empty($temp_rec_periode->data)) {
          foreach ($temp_rec_periode->data as $dt_periode) {
            $filter_periode_jalur[$dt_periode->id_prodi.$dt_periode->id_semester] = "('".$dt_periode->id_prodi."','".$dt_periode->id_semester."')";
          }
        }
        $order_by = "id_prodi,id_jalur_daftar ASC";
        $implode_periode = implode(",", $filter_periode_jalur);
              $temp_data_kelas = [
                'act' => 'GetListPeriodeJalurPendaftaranPerkuliahan',
                  'token' => $token,
                  'filter' => "(id_prodi,trim(id_semester)) IN ($implode_periode)",
                  'order' => $order_by
              ];

        $temp_rec = json_decode($db->run($temp_data_kelas,$url));
        $data_rec = array();
        if (!empty($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(
                            'id_semester' => $key->id_semester,
                            'kode_jur' => $kode_jur,
                            'id_jalur_daftar' => $key->id_jalur_daftar,
                            'nm_jalur_daftar' => $key->nm_jalur_daftar,
                            'jumlah_target_mahasiswa_baru' => $key->jumlah_target_mahasiswa_baru,
                            'calon_ikut_seleksi' => $key->calon_ikut_seleksi,
                            'calon_lulus_seleksi' => $key->calon_lulus_seleksi,
                            'daftar_sbg_mhs' => $key->daftar_sbg_mhs,
                            'pst_undur_diri' => $key->pst_undur_diri
                          );
            }
        }
    
   
$file_name = $_POST['random_number'];
//write temp file
$filename = SITE_ROOT."upload/temp/$file_name.json";

if (!empty($data_rec)) {

  write_data($filename,$data_rec);
}


    //        }
if ($_POST['last']=='yes') {
  $final = array();
    if (file_exists($filename)) {
    $data_file = file_get_contents($filename);
    $final_decode = json_decode($data_file,true);
    foreach ($final_decode as $key => $value) {
          $final[] = array(
              $value['id_semester'],
              $value['kode_jur'],
              $value['id_jalur_daftar'],
              $value['nm_jalur_daftar'],
              $value['jumlah_target_mahasiswa_baru'],
              $value['calon_ikut_seleksi'],
              $value['calon_lulus_seleksi'],
              $value['daftar_sbg_mhs'],
              $value['pst_undur_diri']
          );
    }
      unlink($filename);
}
$jumlah_total = count($final);

if ($jumlah_total<1) {
    $msg =  "<div class=\"alert alert-warning \" role=\"alert\">
        <font color=\"#3c763d\">Tidak ada data berhasil di Download</font><br />
        </div>";

    $jumlah['last_notif'] = $msg;
    array_push($json_response, $jumlah);

    echo json_encode($json_response);
    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',
                        'E1',
                        'F1',
                        'G1',
                        'H1',
                        'I1'
                        ),
                    'border' => array(
                        'style' => 'thin',
                        'color' => '000000'
                        ),
                    'verticalAlign' => 'center',
                    'horizontalAlign' => 'center',
                ),
                            array(
                    'fill' => array(
                        'color' => '91d24a'
                        ),
                    'cells' => array(
                        'D1'
                        ),
                    'border' => array(
                        'style' => 'thin',
                        'color' => '000000'
                        ),
                    'verticalAlign' => 'center',
                    'horizontalAlign' => 'center',
                    )
            );

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

$header = array(
  'Semester'=> 'string',
  'Kode Prodi'=> 'string',
  'Id  Jalur Pendaftaran'=> 'string',
  'Nama Jalur Pendaftaran'=> 'string',
  'Jml Target Mhs Baru'=> 'string',
  'Jml Pendaftar Ikut Seleksi'=> 'string',
  'Jml Pendaftar Lulus Seleksi'=> 'string',
  'Jml Daftar Ulang'=> 'string',
  'Jml Mengundurkan Diri'=> 'string'
);

$filename = $_POST['sem_filter'].'_Daya_tampung_periode_perkuliahan.xlsx';



$writer->writeSheet($final,'Daya Tampung', $header, $style);
$writer->writeToFile(XLSXWriter::sanitize_filename(str_replace(' ','_',$filename)));
$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 Daya Tampung berhasil di generate</font><br />";
        $msg .= "<a class='btn btn-block btn-primary btn-xs' href='".base_admin()."modul/download_daya_tampung/".$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/download_daya_tampung/".$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();
?>