<?php
session_start();
include "../../../inc/config.php";


require_once '../../../lib/Writer.php';
include "../../../lib/vendor/autoload.php";
use \JsonMachine\JsonMachine;

$json_response = array();
$final = array();
$data_rec = array();
$data_array_jur = array();
$merge_key_val = 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_rest = get_service_url('rest');

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

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

$filter_aktivitas = $_POST['filter'];
$jumlah['filter'] = $filter_aktivitas;

if ($offset==0) {
    $jumlah['token'] = get_token();
    $token = $jumlah['token'];



$filter_sms = "";
$filter_semester = "";
$filter_jenis = "";


  if ($_POST['jurusan']!='all') {
    $filter_sms = "and id_prodi='".$_POST['jurusan']."'";
  }
  if ($_POST['semester']!='all') {
    $filter_semester = "and id_semester='".$_POST['semester']."'";
  }
  if ($_POST['jenis']!='all') {
    $filter_jenis = "and id_jenis_aktivitas='".$_POST['jenis']."'";
  }  

    $filter_aktivitas = "id_aktivitas is not null $filter_semester $filter_sms $filter_jenis";

    $jumlah['filter'] = $filter_aktivitas;
}

if ($_POST['semester']!='all') {
  $order_by = "id_aktivitas DESC";
} else {
  $order_by = "id_semester DESC";
}

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

$temp_rec = array();


$header = array(
  'Semester'=>'string',
  'Jenis Aktivitas'=>'string',
  'Judul'=>'string',
  'Lokasi'=>'string',
  'Nomor SK Tugas' => 'string',
  'Tanggal SK Tugas' => 'date',
  'Jenis Anggota' => 'string',
  'ID AKTIVITAS'=>'string',
  'Kode Prodi' => 'string',
  'ID Aktivitas NEO' => 'string'
);

$index_header = count($header);
for ($i=0; $i < $index_header; $i++) { 
  $index_head[] = 'h'.$i;
}

/*dump(array_keys($header));
dump($index_head);*/
$data_req_aktivitas = [
    'act' => 'GetListAktivitasMahasiswa',
      'token' => $token,
      'filter' => trim($filter_aktivitas),
      'order' => $order_by,
      'limit' => $limit,
      'offset' => $offset

];

$check_aktivitas = json_decode($db->run($data_req_aktivitas,$url_rest));


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

        }

            // print_r($check_aktivitas);
            if (!empty($check_aktivitas->data)) {
              foreach ($check_aktivitas->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(
                       convert_ascii($key->id_semester),
                       convert_ascii($key->id_jenis_aktivitas),
                       convert_ascii($key->judul),
                       convert_ascii($key->lokasi),
                       convert_ascii($key->sk_tugas),
                       convert_ascii($key->tanggal_sk_tugas),
                       convert_ascii($key->jenis_anggota),
                       convert_ascii($key->keterangan),
                       $kode_jur,
                       convert_ascii($key->id_aktivitas)
                       );
                  $merge_key_val[] = array_combine(array_values($index_head), $data_rec);

              }

            }


//dump($merge_key_val);

$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') {
  if (file_exists($json_filename)) {
      $data_file = JsonMachine::fromFile($json_filename);

      foreach ($data_file as $key => $value) {
            $final[] = array_values($value);
          //dump($final);     
      }
  }

  if (count($final)<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();
  } else {
$writer = new XLSXWriter();
$style =
        array (
                      array(
              'border' => array(
                'style' => 'thin',
                'color' => '000000'
                ),
            'allfilleddata' => true
            ),
            array(
                'fill' => array(
                    'color' => 'ff0000'
                    ),
                'cells' => array(
                    'A1',
                    'B1',
                    'C1',
                    'G1',
                    'H1',
                    'I1'
                   
                    ),
                'border' => array(
                    'style' => 'thin',
                    'color' => '000000'
                    ),
                'verticalAlign' => 'center',
                'horizontalAlign' => 'center',
            ),
                        array(
                'fill' => array(
                    'color' => '00ff00'
                    ),
                'cells' => array(
                      'D1',
                      'E1',
                      'F1',
                      'J1'
                    ),
                'border' => array(
                    'style' => 'thin',
                    'color' => '000000'
                    ),
                'verticalAlign' => 'center',
                'horizontalAlign' => 'center',
                )
            );

//column width
$col_width = array(
  1 => 19,
  2 => 20,
  3 => 42,
  4 => 19,
  5 => 23,
  6 => 19,
  7 => 19,
  8 => 19,
  9 => 19,
  10 => 38
  );

$writer->setColWidth($col_width);
    //unlink($filename);
    $filename = 'Data_Aktivitas.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 Aktivitas', $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\">".count($final)." 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();

?>