<?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');

$data_rec = array();
$final = array();
$id_reg_pd_smt = array();
$offset = $_POST['offset'];
$token = $_POST['token'];

$jumlah["token"] = $_POST["token"];

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

$no = $offset;
$file_name = $_POST['random_number'];

if ($offset==0) {
$token = $db->get_token();
$jumlah['token'] = $token;
}

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

        $ids_string = $_POST['ids_string'];
		$array_xpl = explode(',', $ids_string);
		$process_data = array_slice($array_xpl, $offset, $limit);
		$array_status = array();

		foreach ($process_data as $id) {
        $xpl_id = explode('#', $id);
        $temp_data_insert = array(
          'id_kelas_kuliah' => $xpl_id[0],
          'id_matkul' => $xpl_id[1]
        );
        $data_dic = [
          'act' => 'SalinKomponenEvaluasiMatkul',
            'token' => get_token(),
            'key' => $temp_data_insert,
        ];
          $temp_recs = service_request($data_dic);
		  $value_data = addslashes($temp_recs->error_desc);
		  if ($value_data!='') {
		     action_response($value_data);
		     $array_status[] = array(
		     	'id_kelas_kuliah' => $xpl_id[0],
		     	'status' => 'error',
		     	'error_message' => $value_data
		     );
		  }
      }

$json_filename = SITE_ROOT."upload/temp/$file_name.json";
if (!empty($array_status)) {
	write_data($json_filename,$array_status);
}
      
if ($_POST['last']=='yes') {
	$error_count = 0;
	$sukses = 0;
	if (file_exists($json_filename)) {
		$data_file = JsonMachine::fromFile($json_filename);
		$id_kelas = array();
		foreach ($data_file as $key => $value) {
				$id_kelas[$value['id_kelas_kuliah']] = $value['error_message'];
				$error_count++;
		}
	

$implode_id_kelas = "'" . implode("','", array_keys($id_kelas)) . "'";
$temp_data_kelas = [
	'act' => 'GetDetailKelasKuliah',
    'token' => $token,
    'filter' => "id_kelas_kuliah in($implode_id_kelas)"
];
$temp_rec = json_decode($db->run($temp_data_kelas,$url));
if (!empty($temp_rec->data)) {
	foreach ($temp_rec->data as $dt) {
		$final[] = array(
			$dt->id_semester,
			$dt->kode_mata_kuliah,
			$dt->nama_mata_kuliah,
			$dt->nama_kelas_kuliah,
			$dt->nama_program_studi,
			$id_kelas[$dt->id_kelas_kuliah]
		);
	}
}

$writer = new XLSXWriter();
$style =
        array (
                      array(
              'border' => array(
                'style' => 'thin',
                'color' => '000000'
                ),
            'allfilleddata' => true
            ),
                        array(
                'fill' => array(
                    'color' => '00ff00'
                    ),
                'cells' => array(
                  'A1',
                  'B1',
                  'C1',
                 	'D1',
                    'E1',
                    'F1'            
                    ),
                'border' => array(
                    'style' => 'thin',
                    'color' => '000000'
                    ),
                'verticalAlign' => 'center',
                'horizontalAlign' => 'center',
                )
            );

$header = array(
  'Semester'=>'string',
  'Kode Matakuliah'=>'string',
  'Nama Matakuliah'=>'string',
  'Kelas'=>'string',
  'Kode Prodi'=>'string',
  'Keterangan'=>'string'
);

//column width
$col_width = array(
  1 => 19,
  2 => 30,
  3 => 30,
  4 => 30,
  5 => 30,
  6 => 40
  );

$writer->setColWidth($col_width);      
$filename = 'data_error_salin_evaluasi.xlsx';
$writer->writeSheet($final,'Data', $header, $style);
$writer->writeToFile(SITE_ROOT."upload/temp/".XLSXWriter::sanitize_filename(str_replace(' ','_',$filename)));

}
$sukses = $_POST['total_data'] - $error_count;
//exit(0);
$modul_name = explode("/", $_SERVER['REQUEST_URI']);

$total_length = count($modul_name);
$index_modul = $total_length-2;

    $msg =  "<div class=\"alert alert-warning alert-dismissible\" role=\"alert\" style=\"margin-bottom: 0;\" >
    <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>
    <font color=\"#3c763d\">".$sukses." data Evaluasi Berhasil di Salin ke Kelas</font><br />
    <font color=\"#ce4844\" >".$error_count." data Evaluasi tidak bisa disalin ke kelas</font><br>";
    
    if ($error_count>0) {
        $msg .= "<a href='".base_url()."upload/temp/".XLSXWriter::sanitize_filename(str_replace(' ','_',$filename))."' target='_blank' class='btn btn-sm btn-primary' style='text-decoration:none;'>Download Data Error</a><br>";
        $jumlah['data_uri'] = SITE_ROOT."upload/temp/".XLSXWriter::sanitize_filename(str_replace(' ','_',$filename));
    } else {
    	$jumlah['data_uri'] = '';
    }

        

        $jumlah['json_file'] = $json_filename;


        $jumlah['last_notif'] = $msg;
}



array_push($json_response, $jumlah);

echo json_encode($json_response);
exit();
?>