<?php
session_start();
include "../../inc/config.php";
$json_response = array();
$token = get_token();

$config_feeder = $db->fetch_single_row('config_user','id',1);
$id_sp = $config_feeder->id_sp;
$user_id = $config_feeder->id_user;
if ($_POST['total_data']>0) {
		$url_rest = get_service_url('rest');
		$error_kelas = "";
        $sukses_count = 0;
        $error_count = 0;
        $error_count_in = 0;
        $error_msg = array();
        $update_data = array();
        $update_data_status = array();
        $update_data_er =array();
        $update_data_er_status =array();
        $error_mk = "";
        $data_id_sukses = array();
        $data_id_error= array();
        $all_errors = array();
        $all_error = array();
        $query_not_in = "";
        $id_mk = "";
        $error_mk = "";
        $msg = "";
        $array_aktivitas = array();
        $query_jenis = '';
        $query_jurusan = '';
        $all_id = array();
        $final_up = array();
        $sem = "";
        $data_kls_deleted = array();
        $data_ids_deleted = array();
        $array_aktivitas = array();
        $data_kls = array();
        $data_ids = array();
        $restore_key = array();
        $periode_concat = array();
        $final_up_deleted = array();
        $periode_data = array();
        $error_update_data = array();
        $data_id_error = array();
        $error_code = "";
		if ($_POST['sem']!='all') {
			$sem = "and periode_perkuliahan.semester='".$_POST['sem']."'";
		}

		if ($_POST['jurusan']!='all') {
			$query_jurusan = "and periode_perkuliahan.kode_jurusan='".trim($_POST['jurusan'])."'";
		} else {
			if ($_SESSION['level']!=1) {
				$query_jurusan = "and periode_perkuliahan.kode_jurusan='".$_SESSION['jurusan']."'";
			} else {
				$query_jurusan = "";
			}
		}


		$query_not_in = "and unik_id not in(".$_POST['random_number'].")";
		$data = $db->fetch_custom("select periode_perkuliahan.*,id_sms,periode_perkuliahan.id as id_krs from periode_perkuliahan
 inner join jurusan on periode_perkuliahan.kode_jurusan=jurusan.kode_jurusan where periode_perkuliahan.id is not null $sem $query_jurusan and status_error!=1 $query_not_in limit 11");

		foreach ($data as $dt_loop) {
			$periode_concat[] = "('".$dt_loop->id_sms."','".$dt_loop->semester."')";
			$data_loop[] = $dt_loop;
		}

		$periode_concat_where = implode(",", $periode_concat);
		$filter_periode = "(id_prodi,trim(id_semester)) in ($periode_concat_where)";

		$data_req_periode = [
			'act' => 'GetListPeriodePerkuliahan',
		    'token' => $token,
		    'filter' => $filter_periode,
		    'order' => "",
		    'limit' => "",
		    'offset' => ""

		];
		$check_periode_exist = json_decode($db->run($data_req_periode,$url_rest));
		if (!empty($check_periode_exist->data)) {
			foreach ($check_periode_exist->data as $periode) {
				$periode_data[] = convert_ascii($periode->id_prodi).convert_ascii($periode->id_semester);
			}
		}

function responseCheck($data) {
	$return_array = array();
	$return_array['data'] = array();
	$return_array['is_error'] = 1;
		if (is_object($data)) {
		$value_data = addslashes($data->error_desc);
		if ($value_data!='') {
			$return_array['data'] = array(
				'keterangan' => $value_data,
				'status_error' => 2
			);
		} else {
			//dump($data);
			if ($data->data->id_prodi=="") {
				$return_array['is_error'] = 1;
				$return_array['data'] = array(
					'keterangan' => 'Gagal di Import',
					'status_error' => 2
				);
			} else {
				$return_array['is_error'] = 0;
				$return_array['data'] = array(
					'keterangan' => '',
					'status_error' => 1
				);
			}

		}
	} else {
		$return_array['data'] = array(
				'keterangan' => $data,
				'status_error' => 2
			);
	}

	//dump($return_array);

	return $return_array;
}


		foreach ($data_loop as $dt) {
		$id_sms = $dt->id_sms;
		$filter_deleted = "id_sms='$id_sms' and id_smt='".$dt->semester."'";

		if ($_POST['metode']=='insert') {
	
			if (in_array($dt->id_sms.$dt->semester, $periode_data)) {
				$error_update_data[] = array(
					'keterangan' => "Periode Perkuliahan Sudah Ada",
					'status_error' => 2
				);
				$data_id_error[] = $dt->id_krs;
			} else {
				$array_periode = array(
		              'id_semester' => $dt->semester,
		              'id_prodi' => $id_sms,
		              'jumlah_target_mahasiswa_baru' => $dt->target_mhs_baru,
		              'jumlah_pendaftar_ikut_seleksi' => $dt->calon_ikut_seleksi,
		              'jumlah_pendaftar_lulus_seleksi' => $dt->calon_lulus_seleksi,
		              'jumlah_daftar_ulang' => $dt->daftar_sbg_mhs,
		              'jumlah_mengundurkan_diri' => $dt->pst_undur_diri,
		              'tanggal_awal_perkuliahan' => $dt->tgl_awal_kul,
		              'tanggal_akhir_perkuliahan' => $dt->tgl_akhir_kul,
		              'jumlah_minggu_pertemuan' => $dt->jml_mgu_kul
		            );
				$param = array(
					'act' => 'InsertPeriodePerkuliahan',
					'token' => $token,
					'record' => $array_periode
					);
				$insert_periode = service_request($param);
				$check_responses = responseCheck($insert_periode);
		    	if ($check_responses['is_error']==0) {
		    		$update_data[] = $check_responses['data'];
		    		$data_id_sukses[] = $dt->id;
		    	} else {
		    		$error_update_data[] = $check_responses['data'];
		    		$data_id_error[] = $dt->id;
		    	}
			}

		} else {
			$key_update['id_semester'] =  $dt->semester;
			$key_update['id_prodi'] = $id_sms;
			$record_update = array(
				'jumlah_target_mahasiswa_baru' => $dt->target_mhs_baru,
				'jumlah_pendaftar_ikut_seleksi' => $dt->calon_ikut_seleksi,
				'jumlah_pendaftar_lulus_seleksi' => $dt->calon_lulus_seleksi,
				'jumlah_daftar_ulang' => $dt->daftar_sbg_mhs,
				'jumlah_mengundurkan_diri' => $dt->pst_undur_diri,
				'tanggal_awal_perkuliahan' => $dt->tgl_awal_kul,
				'tanggal_akhir_perkuliahan' => $dt->tgl_akhir_kul,
				'jumlah_minggu_pertemuan' => $dt->jml_mgu_kul
			);
		  	$data_dic = [
		      'act' => 'UpdatePeriodePerkuliahan',
		      'key' => $key_update,
		        'token' => $token,
		        'record' => $record_update,
		    ];
			$update_nilai = service_request($data_dic);
			/*dump($data_dic);
			dump($update_nilai);*/
			$value_data = addslashes($update_nilai->error_desc);
			if ($value_data!='') {
				$error_update_data[] = array(
					'keterangan' => $value_data,
					'status_error' => 2
				);
				$data_id_error[] = $dt->id;
			} else {
				$update_data[] = array(
					'keterangan' => '',
					'status_error' => 1
				);
				$data_id_sukses[] = $dt->id;
			}
		}
		$all_id[] = $dt->id;
	}

		//update error
		if (!empty($error_update_data)) {
			updateMulti('periode_perkuliahan',$error_update_data,'id',$data_id_error);
		}
		$error_update_data = array();
		$data_id_error = array();
		//update sukses
		if (!empty($update_data)) {
			updateMulti('periode_perkuliahan',$update_data,'id',$data_id_sukses);
		}
		$update_data = array();
		$data_id_sukses = array();
	
	$implode_id = implode(",", $all_id);
	

	$db->fetch_custom("update periode_perkuliahan set unik_id=".$_POST['random_number']." where id in (".$implode_id.")");

	//$jumlah['not_in'] = $query_not_in;
	$jumlah['all_id'] = $all_id;
	$jumlah['error_msg'] = $error_msg;
	$jumlah['token'] = $token;



	if (isset($_POST['id_data'])) {

		$jml_error_sukses = $db->fetch_custom_single("SELECT COUNT(IF(status_error='1',1,NULL)) AS jml_sukses,COUNT(IF(status_error='2',1,NULL)) AS jml_error FROM periode_perkuliahan where unik_id=".$_POST['random_number']);

		$jumlah_sukses = $jml_error_sukses->jml_sukses;
		$jumlah_error = $jml_error_sukses->jml_error;

	
		$msg =  "<div class=\"alert alert-warning \" role=\"alert\">
		<font color=\"#3c763d\">".$jumlah_sukses." data Periode Perkuliahan berhasil Di Import Ke Feeder DIKTI</font><br />
		<font color=\"#ce4844\" >".$jumlah_error." data tidak bisa Di Import </font>";
		
		if (!$jumlah_error==0) {
			$msg .= "<a data-toggle=\"collapse\" href=\"#collapseExample\" aria-expanded=\"false\" aria-controls=\"collapseExample\">Detail error</a>";
			//pesan error 

			if (!empty($_POST['error_msg'])) {
				$trim_error = rtrim($_POST['error_msg'], ',');
			
				$all_error = explode(",", $trim_error);
			}
			

			$all_errors = array_merge($all_error,$error_msg);
			
		}
		//echo "<br />Total: ".$i." baris data";
		$msg .= "<div class=\"collapse\" id=\"collapseExample\">";
				$i=1;
				foreach ($all_errors as $pesan) {
						$msg .= "<div class=\"bs-callout bs-callout-danger\">".$i.". ".$pesan."</div><br />";
					$i++;
					}
		$msg .= "</div>
		</div>";


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


} else {
	$msg =  "Tidak ada data yang bisa diproses<p>";
		$jumlah['last_notif'] = $msg;
}

array_push($json_response, $jumlah);
echo json_encode($json_response);
//echo convert(memory_get_usage(true)); // 123 kb