<?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();
		$id_kelas_feeder = array();
	
		$update_data_er =array();
		$update_data_er_status =array();
		$error_mk = "";

		$data_id_sukses = array();
		$data_id_error= array();
		$check_akt_kelas = array();
		$check_akt_kelas_merdeka = 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_kelas = array();
		$data_kls = array();
		$data_ids = array();
		$filter_mk_where = array();
		$filter_mk_where_cross = array();
		$filter_mk_kur = array();

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

		//merdeka
		$data_kelas_merdeka = array();
		$data_ids_merdeka = array();
		$check_ids = array();
		$data_kelas_id_exist = array();

	
		$sem = "";
		if ($_POST['sem']!='all') {
			$sem = "and kelas_kuliah.semester='".$_POST['sem']."'";
		}

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

		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 kelas_kuliah.id as id_kelas,kelas_kuliah.*,jurusan.kode_jurusan,id_sms from kelas_kuliah inner join jurusan on kelas_kuliah.kode_jurusan=jurusan.kode_jurusan where kelas_kuliah.id is not null $sem $query_jurusan and status_error!=1 $query_matkul $query_kelas $query_not_in limit 10");

		foreach ($data as $dt_id) {
			$filter_mk_kur[$dt_id->id_sms.convert_ascii($dt_id->kode_mk)] = "('".$dt_id->id_sms."','".convert_ascii($dt_id->kode_mk)."')";
			$filter_mk_kur_cross[convert_ascii($dt_id->kode_mk)] = "('".convert_ascii($dt_id->kode_mk)."')";
			$data_kelas_kuliah[] = $dt_id;
			$id_kelas_where[$dt_id->id_sms.trim($dt_id->kode_mk).trim($dt_id->nama_kelas).$dt_id->semester] = "('".$dt_id->id_sms."','".trim($dt_id->kode_mk)."','".trim($dt_id->nama_kelas)."','".trim($dt_id->semester)."')";
		}


		$array_id_mk_kur = array();
		$array_id_mk_cross = array();
		if ($_POST['jenis_method']=='1') {
		if (!empty($filter_mk_kur)) {
			$implode_id_mk = implode(",", $filter_mk_kur);
			$filter_mk = "(id_prodi,trim(kode_mata_kuliah)) IN ($implode_id_mk)";
			$data_req_mat = [
				'act' => 'GetMatkulKurikulum',
			    'token' => $token,
			    'filter' => $filter_mk,
			    'order' => "",
			    'limit' => "",
			    'offset' => ""

			];
			$check_matkul_exist = json_decode($db->run($data_req_mat,$url_rest));

/*			dump($data_req_mat);
			dump($check_matkul_exist);*/

			if (!empty($check_matkul_exist->data)) {
				foreach ($check_matkul_exist->data as $dts) {
					//dump($dts);
					$array_id_mk_kur[$dts->id_prodi.convert_ascii($dts->kode_mata_kuliah)] =  $dts;
					$array_id_mk[] = $dts->id_matkul;
				}				
			}

			$implode_id_mk_cross = implode(",", $filter_mk_kur_cross);
			$filter_mk_cross = "(trim(kode_mata_kuliah)) IN ($implode_id_mk_cross)";
			$data_req_mat = [
				'act' => 'GetMatkulKurikulum',
			    'token' => $token,
			    'filter' => $filter_mk_cross,
			    'order' => "",
			    'limit' => "",
			    'offset' => ""

			];
			$check_matkul_exist_cross = json_decode($db->run($data_req_mat,$url_rest));

/*			dump($data_req_mat);
			dump($check_matkul_exist);*/

			if (!empty($check_matkul_exist_cross->data)) {
				foreach ($check_matkul_exist_cross->data as $dts) {
					$array_id_mk_cross[convert_ascii($dts->kode_mata_kuliah)] = $dts;
					$array_id_mk[] = $dts->id_matkul;
				}				
			}
		}

	}


		if ($_POST['jenis_method']=='2') {
			$matkul_id_kelas = array();
			$implode_id_kelas = implode(",", $id_kelas_where);
			$kelas_filter = "(id_prodi,trim(kode_mata_kuliah),trim(nama_kelas_kuliah),id_semester) IN ($implode_id_kelas)";

			$data_req_kelas = [
				'act' => 'GetDetailKelasKuliah',
			    'token' => $token,
			    'filter' => $kelas_filter,
			    'order' => "",
			    'limit' => "",
			    'offset' => ""

			];
			$check_kelas_exist = json_decode($db->run($data_req_kelas,$url_rest));
/*			dump($data_req_kelas);
			dump($check_kelas_exist);*/
			if (!empty($check_kelas_exist->data)) {
				foreach ($check_kelas_exist->data as $dt_id_kelas) {
				$id_kelas_feeder[$dt_id_kelas->id_prodi.convert_ascii($dt_id_kelas->kode_mata_kuliah).convert_ascii($dt_id_kelas->nama_kelas_kuliah).convert_ascii($dt_id_kelas->id_semester)] = $dt_id_kelas;
				$matkul_id_kelas[] = "'".$dt_id_kelas->id_matkul."'";
				}
			}

			if (!empty($matkul_id_kelas)) {
				$filter_id_mk = implode(',', $matkul_id_kelas);
				$data_req_mat_kelas = [
					'act' => 'GetMatkulKurikulum',
				    'token' => $token,
				    'filter' => "id_matkul in($filter_id_mk)"
				];
				$check_matkul_kelas = json_decode($db->run($data_req_mat_kelas,$url_rest));

				if (!empty($check_matkul_kelas->data)) {
					foreach ($check_matkul_kelas->data as $dts) {
						$array_sks[convert_ascii($dts->id_matkul)] = $dts;
					}				
				}
			}



		}

$status_kuliah = $db->fetch_custom("select * from status_mahasiswa_akm");
foreach ($status_kuliah as $st) {
	$stat_kuliah[$st->id_status] = $st->nama_status;
}

function checkValid($data) {
	$lingkup = array(
		1,2,3
	);
	$mode_kuliah = array(
		'O','F','M'
	);
	$has_error = "";
	$error = array();
	if ($data->lingkup!="" && !in_array($data->lingkup, $lingkup)) {
		$error[] = "Id Lingkup Salah";
	}
	if ($data->mode_kuliah!="" && !in_array($data->mode_kuliah, $mode_kuliah)) {
		$error[] = "Id Mode Kuliah Salah";
	}
	if (!empty($error)) {
		$has_error = implode(",", $error);
	}
	return $has_error;
}


		if (!empty($data_kelas_kuliah)) {
			foreach ($data_kelas_kuliah as $dt) {
				$kode_mk = convert_ascii($dt->kode_mk);
				$kelas = convert_ascii($dt->nama_kelas);
				$semester = $dt->semester;
				$id_sms = convert_ascii($dt->id_sms);
				$matkul_id = "";
				if (strlen($dt->nama_kelas)>5) {
						$error_update_data[] = array(
							'keterangan' => 'Nama Kelas tidak boleh lebih dari 5 Karakter',
							'status_error' => 2
						);
						$data_id_error[] = $dt->id_kelas;
				} elseif (checkValid($dt)!="") {
						$error_update_data[] = array(
							'keterangan' => checkValid($dt),
							'status_error' => 2
						);
						$data_id_error[] = $dt->id_kelas;
				} else {
					if ($_POST['jenis_method']=='1') {
						if (in_array($dt->id_sms.convert_ascii($dt->kode_mk), array_keys($array_id_mk_kur))) {
							$matkul_id = $array_id_mk_kur[$dt->id_sms.convert_ascii($dt->kode_mk)]->id_matkul;
						} elseif (in_array(convert_ascii($dt->kode_mk), array_keys($array_id_mk_cross))) {
							$matkul_id = $array_id_mk_cross[convert_ascii($dt->kode_mk)]->id_matkul;
						}
				}
				if ($_POST['jenis_method']=='1') {
				if ($matkul_id!="") {
					if ($dt->kampus_merdeka==0) {
						$data_kelas[] = array(
							'id_prodi' => $dt->id_sms,
							'id_semester' => $dt->semester,
							'id_matkul' => $matkul_id,
							'nama_kelas_kuliah' => $dt->nama_kelas,
							'bahasan' => $dt->bahasan_case,
							'lingkup' => $dt->lingkup,
							'mode' => $dt->mode_kuliah,
							'tanggal_mulai_efektif' => ($dt->tgl_mulai_koas=='1970-01-01')?'':$dt->tgl_mulai_koas,
							'tanggal_akhir_efektif' => ($dt->tgl_selesai_koas=='1970-01-01')?'':$dt->tgl_selesai_koas
						);
						$data_ids[] = $dt->id_kelas;
					} else {
						$data_kelas_merdeka[] = array(
							'id_prodi' => $dt->id_sms,
							'id_semester' => $dt->semester,
							'id_matkul' => $matkul_id,
							'nama_kelas_kuliah' => $dt->nama_kelas,
							'bahasan' => $dt->bahasan_case,
							'lingkup' => $dt->lingkup,
							'mode' => $dt->mode_kuliah,
							'kapasitas' => $dt->kapasitas,
							'apa_untuk_pditt' => 1,
							'tanggal_tutup_daftar' => $dt->tgl_tutup,
							'tanggal_mulai_efektif' => ($dt->tgl_mulai_koas=='1970-01-01')?'':$dt->tgl_mulai_koas,
							'tanggal_akhir_efektif' => ($dt->tgl_selesai_koas=='1970-01-01')?'':$dt->tgl_selesai_koas
						);
						$data_ids_merdeka[] = $dt->id_kelas;
					}
				} else {
						$error_update_data[] = array(
							'keterangan' => 'Matakuliah tidak ditemukan di kurikulum',
							'status_error' => 2
						);
						$data_id_error[] = $dt->id_kelas;
				}
			} else {
				$matkul_id_kur = "";
				if (in_array($id_sms.$kode_mk.$kelas.$semester, array_keys($id_kelas_feeder))) {
					$id_kls = $id_kelas_feeder[$id_sms.$kode_mk.$kelas.$semester]->id_kelas_kuliah;
					$matkul_id = $id_kelas_feeder[$id_sms.$kode_mk.$kelas.$semester]->id_matkul;
					if (in_array($matkul_id, array_keys($array_sks))) {
							$matkul_id_kur = $array_sks[$matkul_id]->id_matkul;
					}
					if ($matkul_id_kur!="") {
					if ($dt->kampus_merdeka==0) {
						$data_kelas_update[] = array(
							'id_prodi' => $dt->id_sms,
							'id_semester' => $dt->semester,
							'id_matkul' => $matkul_id,
							'nama_kelas_kuliah' => $dt->nama_kelas,
							'bahasan' => $dt->bahasan_case,
							'lingkup' => $dt->lingkup,
							'mode' => $dt->mode_kuliah,
							'tanggal_mulai_efektif' => ($dt->tgl_mulai_koas=='1970-01-01')?'':$dt->tgl_mulai_koas,
							'tanggal_akhir_efektif' => ($dt->tgl_selesai_koas=='1970-01-01')?'':$dt->tgl_selesai_koas,
							'sks_mata_kuliah' => $array_sks[$matkul_id]->sks_mata_kuliah,
						    'sks_tatap_muka' => $array_sks[$matkul_id]->sks_tatap_muka,
						    'sks_praktek' => $array_sks[$matkul_id]->sks_praktek,
						    'sks_praktek_lapangan' => $array_sks[$matkul_id]->sks_praktek_lapangan,
						    'sks_simulasi' => $array_sks[$matkul_id]->sks_simulasi
						);
						$id_kls_neo_update[] = $id_kls;
						$data_ids[] = $dt->id_kelas;
					} else {
						$data_kelas_merdeka_update[] = array(
							'id_prodi' => $dt->id_sms,
							'id_semester' => $dt->semester,
							'id_matkul' => $matkul_id,
							'nama_kelas_kuliah' => $dt->nama_kelas,
							'bahasan' => $dt->bahasan_case,
							'lingkup' => $dt->lingkup,
							'mode' => $dt->mode_kuliah,
							'kapasitas' => $dt->kapasitas,
							'apa_untuk_pditt' => 1,
							'tanggal_mulai_efektif' => ($dt->tgl_mulai_koas=='1970-01-01')?'':$dt->tgl_mulai_koas,
							'tanggal_akhir_efektif' => ($dt->tgl_selesai_koas=='1970-01-01')?'':$dt->tgl_selesai_koas,
							'tanggal_akhir_efektif' => $dt->tgl_selesai_koas,
							'sks_mata_kuliah' => $array_sks[$matkul_id]->sks_mata_kuliah,
						    'sks_tatap_muka' => $array_sks[$matkul_id]->sks_tatap_muka,
						    'sks_praktek' => $array_sks[$matkul_id]->sks_praktek,
						    'sks_praktek_lapangan' => $array_sks[$matkul_id]->sks_praktek_lapangan,
						    'sks_simulasi' => $array_sks[$matkul_id]->sks_simulasi
						);
						$id_kls_neo[] = $id_kls;
						$data_ids_merdeka[] = $dt->id_kelas;
					}

					} else {
						$error_update_data[] = array(
							'keterangan' => 'Matakuliah tidak ditemukan di kurikulum',
							'status_error' => 2
						);
						$data_id_error[] = $dt->id_kelas;
						}
				} else {
					$error_update_data[] = array(
						'keterangan' => "Tidak bisa update karena kelas belum ada di NEO",
						'status_error' => 2
					);
					$data_id_error[] = $dt->id_kelas;
				}


			}
				

			}
					$all_id[] = $dt->id_kelas;
					$matkul_id = "";
		}

	}

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

		if (!empty($data_kelas)) {	
			foreach ($data_kelas as $key => $kls) {
						  $data_dic = [
						      'act' => 'InsertKelasKuliah',
						        'token' => $token,
						        'record' => $kls,
						    ];

						   // exit();
							$temp_recs = json_decode($db->run($data_dic,$url_rest));

/*							dump($data_dic);
							dump($temp_recs);*/
							
							//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;
									}	
				}
			
				
		}

		if (!empty($data_kelas_update)) {	
			foreach ($data_kelas_update as $key => $kls) {

						  $key_update['id_kelas_kuliah'] = $id_kls_neo_update[$key];
						  $data_dic = [
						      'act' => 'UpdateKelasKuliah',
						      'key' => $key_update,
						        'token' => $token,
						        'record' => $kls,
						    ];

						   // exit();
							$temp_recs = json_decode($db->run($data_dic,$url_rest));

/*							dump($data_dic);
							dump($temp_recs);*/
							
							//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('kelas_kuliah',$error_update_data,'id',$data_id_error);
		}

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

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

		if (!empty($data_kelas_merdeka)) {
			foreach ($data_kelas_merdeka as $key => $km) {
			  $data_dic = [
			      'act' => 'InsertKelasKuliah',
			        'token' => $token,
			        '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_merdeka[$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;
						}

			}
				
		}

		if (!empty($data_kelas_merdeka_update)) {	
			foreach ($data_kelas_merdeka_update as $key => $kls) {

						 $key_update['id_kelas_kuliah'] = $id_kls_neo[$key];
						  $data_dic = [
						      'act' => 'UpdateKelasKuliah',
						      'key' => $key_update,
						        'token' => $token,
						        'record' => $kls,
						    ];

						   // exit();
							$temp_recs = json_decode($db->run($data_dic,$url_rest));

/*							dump($data_dic);
							dump($temp_recs);*/
							
							//print_r($temp_recs);
									$value_data = addslashes($temp_recs->error_desc);
									$data_key = $data_ids_merdeka[$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('kelas_kuliah',$error_update_data,'id',$data_id_error);
		}
		//update sukses
		if (!empty($update_data)) {
			updateMulti('kelas_kuliah',$update_data,'id',$data_id_sukses);
		}


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

		$implode_id = implode(",", $all_id);
		
		$jumlah['offset'] = $implode_id;

		$db->fetch_custom("update kelas_kuliah 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 kelas_kuliah where unik_id=".$_POST['random_number']);

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

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

	
		$msg =  "<div class=\"alert alert-warning \" role=\"alert\">
		<font color=\"#3c763d\">".$jumlah_sukses." data Kelas 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