<?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');
$merge_key_val = array();
$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 = get_token();
    $jumlah['token'] = $token;
    $filter_nim = "";



        if ($_POST['jurusan']!="all") {
            $filter_sms = "id_registrasi_mahasiswa is not null and id_prodi='".$_POST['jurusan']."'";
        } else {
            $filter_sms = "id_registrasi_mahasiswa is not null";
        }
        
        $filter_angkatan = "and (left(id_periode_masuk,4) BETWEEN '".$_POST['angkatan_awal']."' and '".$_POST['angkatan_akhir']."')";

        $filter_status = " and id_registrasi_mahasiswa in (select id_reg_pd from reg_pd where tgl_keluar is null)";
        $filter_pilihan = "";
        if ($_POST['pilihan_akm']!='all') {
          $filter_pilihan = "and id_registrasi_mahasiswa not in(select id_reg_pd from kuliah_mhs where id_smt='".$_POST['sem_filter']."')";
        }
        $filter_mahasiswa = "$filter_sms $filter_angkatan $filter_status $filter_pilihan";
        $data_rec = array();
        if ($_POST['nim']!='all') {
          $filter_nim = "nim='".$_POST['value_nim']."'";
          $filter_mahasiswa = $filter_nim;
        }
        
        
} else {
  $filter_mahasiswa = $_POST['filter'];
}
$jumlah['filter'] = $filter_mahasiswa;
$order_by = "id_registrasi_mahasiswa ASC";

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

            $jurusan = $db->fetch_custom("select id_sms,nama_jurusan,kode_jurusan from jurusan");
            foreach ($jurusan as $jur) {
              $data_array_jur[$jur->id_sms] = array(
                'kode_jurusan' => $jur->kode_jurusan,
                'nama_jurusan' => $jur->nama_jurusan
              );

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


    $param = [
      'act' => 'GetListRiwayatPendidikanMahasiswa',
        'token' => $token,
        'filter' => $filter_mahasiswa,
        'order' => $order_by,
        'limit' => $limit,
        'offset' => $offset

    ];
    $temp_data_mhs = service_request($param);

    $sem_filter = $_POST['sem_filter'];
    $mhs_data_prodi = array();
    $filter_krs_sec = array();
    if (!empty($temp_data_mhs->data)) {
    foreach ($temp_data_mhs->data as $mhs) {
        $id_reg_pd[] = "'".$mhs->id_registrasi_mahasiswa."'";
        $mhs_data_prodi[$mhs->id_registrasi_mahasiswa] = $mhs->id_prodi;
    }

    $concat_id_reg = implode(",", $id_reg_pd);


    $filter_param = "id_registrasi_mahasiswa in($concat_id_reg) and id_semester<='$sem_filter'";
    if ($_POST['nim']!='all') {
      $filter_nim = "nim='".$_POST['value_nim']."'";
      $filter_mahasiswa = $filter_nim;
      $filter_param = "id_registrasi_mahasiswa='".$mhs->id_registrasi_mahasiswa."' and id_semester<='$sem_filter'";
    }

    $param_krs_nilai = [
      'act' => 'GetDetailNilaiPerkuliahanKelas',
        'token' => $token,
        'filter' => $filter_param
    ];



    $temp_data_krs_nilai = service_request($param_krs_nilai);

    $sks_smt = [];
    $sks_total = [];
    $sks_index = [];
    $sks_index_total = [];
    $nilai_index = [];
    $krs_mhs = [];
    $krs_mhs_current = [];

    if (!empty($temp_data_krs_nilai->data)) {
           foreach ($temp_data_krs_nilai->data as $nilai) {
            $key = $nilai->id_registrasi_mahasiswa;
            $mhs_data[$key] = $nilai;
            $krs_mhs[$nilai->id_registrasi_mahasiswa][] = $db->convert_obj_to_array($nilai);
            if (!array_key_exists($key, $sks_total)) {
                $sks_total[$key] = 0;
                $sks_index_total[$key] = 0;
            }
             $sks_total[$key] = $sks_total[$key] + $nilai->sks_mata_kuliah;
             $sks_index_total[$key]  = $sks_index_total[$key] + ($nilai->nilai_indeks * $nilai->sks_mata_kuliah);
            if ($nilai->id_semester==$sem_filter) {
              if (!array_key_exists($key, $sks_smt)) {
                  $sks_smt[$key] = 0;
                  $nilai_index[$key] = 0;
                  $sks_index[$key] = 0;
              }
              $sks_smt[$key] = $sks_smt[$key] + $nilai->sks_mata_kuliah;
              $nilai_index[$key]  = $nilai_index[$key] + $nilai->nilai_indeks;
              $sks_index[$key]  = $sks_index[$key] + ($nilai->nilai_indeks * $nilai->sks_mata_kuliah);

            }
            

        }
    }



 /*   dump($sks_total);
    dump($sks_index_total);*/


    if (!empty($sks_total)) {
        $ips = [];
        foreach ($sks_total as $key => $nilai_mhs) {
          if (in_array($key, array_keys($sks_smt))) {
            $sks_semester = $sks_smt[$key];
            $ips = number_format($sks_index[$key] / $sks_smt[$key],2);
            $status = 'A';
          } else {
            $sks_semester = 0;
            $ips = 0;
            $status = 'N';
          }
          $ipk = 0;
            $total_sks =  $nilai_mhs;
            if ($nilai_mhs!=0) {
              $ipk = number_format($sks_index_total[$key] / $nilai_mhs,2);
            }
            
            //$ipk = $sks_index_total[$key] / $nilai_mhs,2);
            if (in_array($key, array_keys($mhs_data_prodi))) { 
                $id_prodi = $mhs_data_prodi[$key];
              $kode_jur = $data_array_jur[$id_prodi]['kode_jurusan'];
            } else {
              $kode_jur = '';
            }
            $data_rec = array(
               convert_ascii($mhs_data[$key]->nim),
               convert_ascii($mhs_data[$key]->nama_mahasiswa),
               convert_ascii($sem_filter),
               convert_ascii($sks_semester),
               convert_ascii($ips),
               convert_ascii($total_sks),
               convert_ascii($ipk),
               convert_ascii($status),
               convert_ascii($kode_jur),
               '0',
               '1'
            );
           // dump($data_rec);
            $merge_key_val[] = array_combine(array_keys($header), $data_rec);
        }
    } else {
            if (in_array($mhs->id_prodi, array_keys($data_array_jur))) { 
              $kode_jur = $data_array_jur[$mhs->id_prodi]['kode_jurusan'];
            } else {
              $kode_jur = '';
            }
        $data_rec = array(
               convert_ascii($mhs->nim),
               convert_ascii($mhs->nama_mahasiswa),
               convert_ascii($sem_filter),
               '0',
               '0',
               '0',
               '0',
               'N',
               $kode_jur,
               '0',
               '1'
            );

            
           // dump($data_rec);
            $merge_key_val[] = array_combine(array_keys($header), $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') {


$data_file = JsonMachine::fromFile($json_filename);

$firstItem = current($data_file);

if ($firstItem === false) {
    $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();
}

$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',
                   'J1',   
                   'K1'
                    ),
                'border' => array(
                    'style' => 'thin',
                    'color' => '000000'
                    ),
                'verticalAlign' => 'center',
                'horizontalAlign' => 'center',
            ),
                        array(
                'fill' => array(
                    'color' => '00ff00'
                    ),
                'cells' => array(
                  'B1',  
                               
                    ),
                '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'].'.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-bl+ock 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();
?>