<?php
session_start();
include "../../inc/config.php";
$json_response = array();
$jumlah = array();
if ($_POST['total_data']>0) {
		$url_rest = get_service_url('rest');
		$offset = $_POST['offset'];
		$jumlah['offset'] = $offset;
		$token = $_POST['token'];
		$jumlah['token'] = $_POST['token'];

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

		$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 = "";
		$query_matkul = '';
		$query_kelas = '';
		$query_jurusan = '';
		$all_id = array();
		$data_rencana = array();
		$data_kls = array();
		$data_ids = array();
		$filter_mk_where = array();

		$array_id_mk = array();
		$array_id_mk_cross = array();
		$data_rencana_pembelajaran = array();
		$error_data = "";
		$error_update_data = array();
		$data_id_error = array();
		$array_exist_pembelajaran = array();

		//merdeka
		$data_rencana = array();


		if ($_POST['matkul']!='all') {
			$query_matkul = "and trim(kode_mk)='".trim($_POST['matkul'])."'";
		}

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


 		$query_not_in = "and unik_id not in(".$_POST['random_number'].")";

		$data = $db->fetch_custom("select mat_rencana_pembelajaran.id as id_kelas,mat_rencana_pembelajaran.*,jurusan.kode_jurusan,id_sms from mat_rencana_pembelajaran inner join jurusan on mat_rencana_pembelajaran.kode_jurusan=jurusan.kode_jurusan where mat_rencana_pembelajaran.id is not null $query_jurusan and status_error!=1 $query_matkul $query_not_in limit 11");

		foreach ($data as $dt_id) {
			$filter_mk_where[$dt_id->id_sms.convert_ascii($dt_id->kode_mk)] = "('".$dt_id->id_sms."','".convert_ascii($dt_id->kode_mk)."')";
			$data_rencana_pembelajaran[] = $dt_id;
		}

		if (!empty($filter_mk_where)) {
			$implode_id_mk = implode(",", $filter_mk_where);
			$filter_mk = "(id_prodi,trim(kode_mata_kuliah)) IN ($implode_id_mk)";
			$data_req_mat = [
				'act' => 'GetListMataKuliah',
			    'token' => $token,
			    'filter' => $filter_mk,
			    'order' => "",
			    'limit' => "",
			    'offset' => ""

			];
			$check_matkul_exist = json_decode($db->run($data_req_mat,$url_rest));
			$filter_check_evaluasi = array();
			if (!empty($check_matkul_exist->data)) {
				foreach ($check_matkul_exist->data as $dts) {
					$filter_check_evaluasi[] = "'".$dts->id_matkul."'";
					$array_id_mk[$dts->id_prodi.convert_ascii($dts->kode_mata_kuliah)] = array(
						'id_mk' => $dts->id_matkul,
						'kode_mata_kuliah' => $dts->kode_mata_kuliah,
						'id_prodi' => $dts->id_prodi,
						'sks_mk' => $dts->sks_mata_kuliah,
						'sks_tm' => $dts->sks_tatap_muka,
					    'sks_prak' => $dts->sks_praktek,
				   		'sks_prak_lap' => $dts->sks_praktek_lapangan,
						'sks_sim' => $dts->sks_simulasi
					); 
				}				
			}
		}


		if (!empty($data_rencana_pembelajaran)) {
			foreach ($data_rencana_pembelajaran as $dt) {
				if (in_array($dt->id_sms.convert_ascii($dt->kode_mk), array_keys($array_id_mk))) {
						$temp_data = array(
							'id_matkul' => $array_id_mk[$dt->id_sms.convert_ascii($dt->kode_mk)]['id_mk'],
							'pertemuan' => $dt->pertemuan,
							'materi_indonesia' => $dt->materi_indonesia,
							'materi_inggris' => $dt->materi_inggris
						);
						$matkul_id[$dt->kode_mk.$dt->id_sms.$dt->pertemuan] = "('".$dt->id_sms."','".$array_id_mk[$dt->id_sms.convert_ascii($dt->kode_mk)]['id_mk']."','".$dt->pertemuan."')"; ;
						$data_rencana[$dt->kode_mk.$dt->id_sms.$dt->pertemuan] = $temp_data;
						$data_ids[$dt->kode_mk.$dt->id_sms.$dt->pertemuan] = $dt->id_kelas;
				} else {
						$error_data = "Kode MK $dt->kode_mk tidak ditemukan di Feeder";
						$error_update_data[] = array(
							'keterangan' => $error_data,
							'status_error' => 2
						);
						$data_id_error[] = $dt->id_kelas;
				}
					$error_data = "";
					$all_id[] = $dt->id_kelas;
			}
		}

		//update error
		if (!empty($error_update_data)) {
			updateMulti('mat_rencana_pembelajaran',$error_update_data,'id',$data_id_error);
		}
		$error_update_data = array();
		$data_id_error = array();

		if (!empty($data_rencana)) {
			//check evaluasi if exist
				$implode_matkul_id = implode(",", $matkul_id);
				$data_req_matkul = [
					'act' => 'GetListRencanaPembelajaran',
				    'token' => $token,
				    'filter' => "(id_prodi,id_matkul,pertemuan) IN ($implode_matkul_id)",
				    'order' => "",
				    'limit' => 50,
				    'offset' => 0

				];
				
				$check_exist_evaluasi = json_decode($db->run($data_req_matkul,$url_rest));

/*				echo "<pre>";
				print_r($data_req_matkul);
				print_r($check_exist_evaluasi);
				exit();*/
					if (!empty($check_exist_evaluasi->data)) {
						foreach ($check_exist_evaluasi->data as $akt) {
							$array_exist_pembelajaran[convert_ascii($akt->kode_mata_kuliah).$akt->id_prodi.$akt->pertemuan] = $akt->id_rencana_ajar;
						}
					}

			if ($_POST['method']=='up') {
				foreach ($data_rencana as $key => $km) {
						$data_key = $data_ids[$key];
					if (in_array($key, array_keys($array_exist_pembelajaran))) {
						$key_id['id_rencana_ajar'] = $array_exist_pembelajaran[$key];
						  $data_dic = [
						      'act' => 'UpdateRencanaPembelajaran',
						        'token' => $token,
						        'key' => $key_id,
						        'record' => $km,
						    ];
							$temp_recs = json_decode($db->run($data_dic,$url_rest));
							//print_r($temp_recs);
							$value_data = addslashes($temp_recs->error_desc);
							$data_key = $data_ids[$key];

							if ($value_data!='') {
								$error_update_data[] = array(
									'keterangan' => $value_data,
									'status_error' => 2
								);
								$data_id_error[] = $data_key;
							} else {
								$update_data[] = array(
									'keterangan' => '',
									'status_error' => 1
								);
								$data_id_sukses[] = $data_key;
							}
					} else {
						$error_data = "Rencana tidak ditemukan, silakan lakukan Import Pilih Insert";
						$error_update_data[] = array(
							'keterangan' => $error_data,
							'status_error' => 2
						);
						$data_id_error[] = $data_key;
					}

				}
			} else {
				///echo "<pre>";
				foreach ($data_rencana as $key => $km) {
/*					print_r($km);*/
					$data_key = $data_ids[$key];
					if (in_array($key, array_keys($array_exist_pembelajaran))) {
						$error_data = "Rencana untuk pertemuan ini sudah ada";
						$error_update_data[] = array(
							'keterangan' => $error_data,
							'status_error' => 2
						);
						$data_id_error[] = $data_key;
					} else {
						  $data_dic = [
						      'act' => 'InsertRencanaPembelajaran',
						        'token' => $token,
						        'record' => $km,
						    ];

						   /* echo "<pre>";
						    print_r($data_dic);*/

							$temp_recs = json_decode($db->run($data_dic,$url_rest));
							//print_r($temp_recs);
									$value_data = addslashes($temp_recs->error_desc);
									$data_key = $data_ids[$key];

									if ($value_data!='') {
										$error_update_data[] = array(
											'keterangan' => $value_data,
											'status_error' => 2
										);
										$data_id_error[] = $data_key;
									} else {
										$update_data[] = array(
											'keterangan' => '',
											'status_error' => 1
										);
										$data_id_sukses[] = $data_key;
									}
					}
				}
			}
				
		}

		//update error
		if (!empty($error_update_data)) {
			updateMulti('mat_rencana_pembelajaran',$error_update_data,'id',$data_id_error);
		}
		//update sukses
		if (!empty($update_data)) {
			updateMulti('mat_rencana_pembelajaran',$update_data,'id',$data_id_sukses);
		}


		$update_data = array();
		$data_id_sukses = array();

		$implode_id = implode(",", $all_id);
		

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

	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 mat_rencana_pembelajaran where unik_id=".$_POST['random_number']);

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

		$db->fetch_custom("update mat_rencana_pembelajaran set unik_id=0 where  unik_id=".$_POST['random_number']);

	
		$msg =  "<div class=\"alert alert-warning \" role=\"alert\">
		<font color=\"#3c763d\">".$jumlah_sukses." data Rencana Pembelajaran 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 
			$all_errors = array('Silakan lihat detail error di list data');
			
		}
		//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