<?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 = '';
          
        $semester = "id_semester='".$_POST['sem_filter']."'";

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

          }
        
         $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 $matkul";




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


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

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

        $temp_data_rec = $temp_rec;

        if ($temp_data_rec->data) {
          foreach ($temp_data_rec->data as $dt) {
          $id_kelas[] = $dt->id_kelas_kuliah;
        }



        $dosen_name = array();
        $jml_siswa = array();
        $in_id_kelas = "'" . implode("','", $id_kelas) . "'";
        //jumlah pengajar
        $count_kelas = [
          'act' => 'GetDosenPengajarKelasKuliah',
            'token' => $token,
            'filter' => "id_kelas_kuliah in($in_id_kelas)",
        ];
        $temp_recs = json_decode($db->run($count_kelas,$url));
        if ($temp_recs->data) {
          foreach ($temp_recs->data as $count) {
              $dosen_name[$count->id_kelas_kuliah][] = $count->nama_dosen;
          }
        }

        $sks_kelas = array();
        $count_kelas = [
          'act' => 'GetListKelasKuliah',
            'token' => $token,
            'filter' => "id_kelas_kuliah in($in_id_kelas)",
        ];
        $temp_recs = json_decode($db->run($count_kelas,$url));
        if ($temp_recs->data) {
          foreach ($temp_recs->data as $sks) {
              $sks_kelas[$sks->id_kelas_kuliah][] = $sks->sks;
          }
        }


        //jumlah mahasiswa kelas
        $count_kelas_mhs = [
          'act' => 'GetKRSMahasiswa',
            'token' => $token,
            'filter' => "id_kelas in($in_id_kelas)",
        ];

        $temp_recs_mhs = json_decode($db->run($count_kelas_mhs,$url));
          foreach ($temp_recs_mhs->data as $key => $dt) {
            $data[$dt->id_kelas][] = $dt;
            $jml_siswa[$dt->id_kelas] = count($data[$dt->id_kelas]);
          }
    }

        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 = '';
                          }
                          /*if ($key->prodi_penyelenggara=="") {
                            $kampus_merdeka = '0';
                          } else {
                            $kampus_merdeka = '1';
                          }*/
                          if (in_array($key->id_kelas_kuliah, array_keys($sks_kelas))) {
                            $sks_kls = implode(",", $sks_kelas[$key->id_kelas_kuliah]) ;
                          } else {
                            $sks_kls = 0;
                          }
                          if (in_array($key->id_kelas_kuliah, array_keys($dosen_name))) {
                            $nm_dosen = implode(",", $dosen_name[$key->id_kelas_kuliah]) ;
                          } else {
                            $nm_dosen = '';
                          }
                          if (in_array($key->id_kelas_kuliah, array_keys($jml_siswa))) {
                            $jumlah_peserta = $jml_siswa[$key->id_kelas_kuliah];
                          } else {
                            $jumlah_peserta = 0;
                          }

                           $data_rec[] = array(
                            'id_smt' => convert_ascii($key->id_semester),
                            'kode_mata_kuliah' => convert_ascii($key->kode_mata_kuliah),
                            'nama_mata_kuliah' => convert_ascii($key->nama_mata_kuliah),
                            'nama_kelas_kuliah' => convert_ascii($key->nama_kelas_kuliah),
                            'bahasan' => convert_ascii($key->bahasan),
                            //'kampus_merdeka' => $kampus_merdeka,
                            //'lingkup' => convert_ascii($key->lingkup),
                            'lingkup' => '',
                            //'mode' => convert_ascii($key->mode),
                             'mode' => '',
                            //'tanggal_tutup_daftar' => convert_ascii($key->tanggal_tutup_daftar),
                            //'kapasitas' => convert_ascii($key->kapasitas),
                            '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,
                            'sks' => $sks_kls,
                            'nm_dosen' => $nm_dosen,
                            'jumlah_peserta' => convert_ascii($jumlah_peserta),
                            'id_kelas_kuliah' => $key->id_kelas_kuliah
                          );
            }
        }

   
$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['id_smt'],
              $value['kode_mata_kuliah'],
              $value['nama_mata_kuliah'],
              $value['nama_kelas_kuliah'],
              $value['bahasan'],
              //$value['kampus_merdeka'],
              $value['lingkup'],
              $value['mode'],
              //$value['tanggal_tutup_daftar'],
              //$value['kapasitas'],
              $value['tanggal_mulai_efektif'],
              $value['tanggal_akhir_efektif'],
              $value['kode_jur'],
              $value['sks'],
              $value['nm_dosen'],
              $value['jumlah_peserta'],
               $value['id_kelas_kuliah']
          );
    }

$jumlah_total = count($final);

    /*if ($_POST['total_data']>97) {
            $final_array = array();
        foreach ($_POST['data_rec'] as $dat) {
             $data = json_decode($dat);
             foreach ($data as $dt) {
                 $final_array[]=$dt;
             }
             
        }

        $final = array_merge($final_array,$data_rec);
        $jumlah_total = count($final);

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

//column width
$col_width = array(
  1 => 16,
  2 => 18,
  3 => 35,
  4 => 10,
  5 => 35,
  6 => 11,
  7 => 14,
  8 => 21,
  9 => 21,
  10 => 15,
  11 => 10,
  12 => 25,
  13 => 25,
  14 => 25,
  15 => 40
  );
$writer->setColWidth($col_width);


$header = array(
  'Semester'=>'string',
  'Kode Matakuliah'=>'string',
  'Nama Matakuliah'=>'string',
  'Kelas'=>'string',
  'Bahasan' => 'string',
  //'Kelas Kampus Merdeka' =>'string',
  'Lingkup' =>'string',
  'Mode Kuliah' =>'string',
  //'Tanggal Tutup Pendaftaran' => 'date',
  //'Kapasitas' =>'string',
  'Tanggal Mulai Efektif' => 'date',
  'Tanggal Akhir Efektif' => 'date',
  'Kode Prodi'=>'string',
  'Bobos SKS'=>'string',
  'Dosen Kelas' => 'string',
  'Jml Peserta Kelas' => 'string',
  'Id Kelas NEO FEEDER' => 'string'
);

$filename = $_POST['sem_filter'].'kelas_kuliah.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 Kelas', $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 Kelas 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();
?>