<?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();
$merge_key_val = array();
$filter_aktivitas = "";
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_angkatan = "";



$angkatan = "";

   $semester = '';
  if ($_POST['semester']=='all') {
      $semester = '';
      if ($_POST['jurusan']=='all') {
    $id_sms = '';
      if ($_SESSION['level']!=1) {
      $id_sms = "id_prodi='".$_SESSION['id_sms']."'";
    }

    } else {
      $id_sms = "and id_prodi='".$_POST['jurusan']."'";
    }
  } else {
    $semester = "and id_semester='".$_POST['semester']."'";
      if ($_POST['jurusan']=='all') {
        $id_sms = '';
        if ($_SESSION['level']!=1) {
      $id_sms = "and id_prodi='".$_SESSION['id_sms']."'";
    }
    } else {
      $id_sms = "and id_prodi='".$_POST['jurusan']."'";
    }
  }


    $filter_aktivitas = "id_aktivitas is not null $semester $id_sms";

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

  if ($_POST['jenis_peran']=='bimbing') {
    $jenis = "1 ";
    $peran_ke = "Pembimbing ke ";
    $table = "GetListBimbingMahasiswa";
    $table_soap = 'bimbing_mahasiswa';
    $filter_count = "and jns_peran_mhs='".$_POST['jenis_peran']."' ";
  } else {
    $table = "GetListUjiMahasiswa";
    $jenis = "2 ";
    $table_soap = 'uji_mahasiswa';
    $peran_ke = "Penguji ke ";
  }

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

$temp_rec = array();
$id_akt = array();
$id_aktivitas = "";
$data_akt = array();

if ($_POST['nidn']!='all') {

            $data_anggotas = [
              'act' => $table,
                'token' => $token,
                'filter' => "nidn like '%".$_POST['value_nidn']."%'",
                'order' => "",
                'limit' => $limit,
                'offset' => $offset

            ];
            
            $check_anggota_datas = json_decode($db->run($data_anggotas,$url_rest));

            $check_anggota_data = $check_anggota_datas;

            //dump($check_anggota_datas);
            if (!empty($check_anggota_datas->data)) {
              foreach ($check_anggota_datas->data as $dt) {
                $id_anggota_aktivitas[] = "'".$dt->id_aktivitas."'";
              }
              $id_aktivitas_filter = implode(",", $id_anggota_aktivitas);

              $order_by = "";
                $data_req_aktivitas = [
                    'act' => 'GetListAktivitasMahasiswa',
                      'token' => $token,
                      'filter' => "id_aktivitas in($id_aktivitas_filter)",
                      'order' => $order_by,
                      'limit' => "",
                      'offset' => ""

                ];

                $check_aktivitas = json_decode($db->run($data_req_aktivitas,$url_rest));
                if (!empty($check_aktivitas->data)) {
                  foreach ($check_aktivitas->data as $key) {
                    $id_akt[] = "'".$key->id_aktivitas."'";
                    $data_akt[$key->id_aktivitas] = $key;
                  }
                  $id_aktivitas = implode(",", $id_akt);
                }
            }



} else {
  $order_by = "";
    $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));
    if (!empty($check_aktivitas->data)) {
      foreach ($check_aktivitas->data as $key) {
        $id_akt[] = "'".$key->id_aktivitas."'";
        $data_akt[$key->id_aktivitas] = $key;
      }
      $id_aktivitas = implode(",", $id_akt);
    }


                $data_anggota = [
              'act' => $table,
                'token' => $token,
                'filter' => "id_aktivitas in($id_aktivitas)",
                'order' => "",
                'limit' => "",
                'offset' => ""

            ];
            
            $check_anggota_data = json_decode($db->run($data_anggota,$url_rest));

}
/*echo "<pre>";
print_r($data_akt);*/
//print_r($data_req_aktivitas);
$header = array(
  'Semester'=>'string',
  'ID AKTIVITAS'=>'string',
  'NIDN'=>'string',
  'NAMA'=>'string',
  'Jenis Peran' => 'string',
  $peran_ke => 'string',
  'Kategori Kegiatan' => 'string',
  'Kode Prodi' => 'string',
  'ID Aktivitas NEO' => 'string'
);
$index_header = count($header);
for ($i=0; $i < $index_header; $i++) { 
  $index_head[] = 'h'.$i;
}


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

        }
$file_name = $_POST['random_number'];
//write temp file
$json_filename = SITE_ROOT."upload/temp/$file_name.json";

            // print_r($check_anggota_data);
            if (!empty($check_anggota_data->data)) {
              foreach ($check_anggota_data->data as $key) {
                   if (in_array($data_akt[$key->id_aktivitas]->id_prodi, array_keys($data_array_jur))) {
                    $kode_jur = $data_array_jur[$data_akt[$key->id_aktivitas]->id_prodi];
                   } else {
                     $kode_jur = "";
                   }
                  if ($_POST['jenis_peran']=='bimbing') {
                    $id = $key->id_bimbing_mahasiswa;
                    $urutan = $key->pembimbing_ke;
                  } else {
                    $id = $key->id_uji;
                    $urutan = $key->penguji_ke;
                  }
                  $data_rec = array(
                       convert_ascii($data_akt[$key->id_aktivitas]->id_semester),
                       convert_ascii($data_akt[$key->id_aktivitas]->keterangan),
                       convert_ascii($key->nidn),
                       convert_ascii($key->nama_dosen),
                       $jenis,
                       $urutan,
                       convert_ascii($key->id_kategori_kegiatan),
                       $kode_jur,
                       $key->id_aktivitas
                       );
                  $merge_key_val[] = array_combine(array_values($index_head), $data_rec);

              }

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

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

//column width
$col_width = array(
  1 => 15,
  2 => 17,
  3 => 15,
  4 => 20,
  5 => 17,
  6 => 17,
  7 => 17,
  8 => 17,
  9 => 40
  );

$writer->setColWidth($col_width);
    //unlink($filename);
    $filename = 'Data_Peserta_Akt.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', $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();

?>