<?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;
		}
		$sukses_count = 0;
	
		$error_count = 0;
		$error_msg = array();
	
		$update_data = array();
		$update_data_status = array();
	
		$matkul_id =array();
		$error_mk = "";

		$data_id_sukses = array();
		$data_id_error= array();
	
		$all_errors = array();
		$all_error = array();
		$query_not_in = "";
		$array_id_dosen = array();
		$error_nim = "";
		$msg = "";
		$sks_mk = "";
		$id_reg_ptk = "";

			$id_kls = "";
			$error_kelas = "";
			$error_sdm = "";
			$error_mk = "";
			$error_ada = "";
			$error_tugas = "";

				$query_matkul = '';
		$query_kelas = '';
		$sem = "";
		$all_id = array();
		$data_dosen = array();
		$data_nidn = array();

		$data_id_penugasan_nidn = array();
		$data_id_penugasan_nuptk = array();
		$data_id_penugasan_id_dosen = array();
		$data_ids = array();

		$data_loop = array();
		$data_nidn = array();
		$data_id_penugasan = array();
		$filter_kelas = array();
		$data_id_kelas = array();
		$error_data = "";
		$error_update_data = array();
		$data_id_error = array();
		$check_dosen_exist = array();

						function is_uuid($string) {
    // Regular expression to match UUID format
    $uuid_regex = '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i';
    // Case-insensitive matching
    return preg_match($uuid_regex, $string) === 1;
}
		
    if ($_POST['sem']!='all') {
      $sem = "and ajar_dosen.semester='".$_POST['sem']."'";
    }

		if ($_POST['matkul']!='all') {
			$query_matkul = "and kode_mk='".$_POST['matkul']."'";
		}
		if ($_POST['kelas']!='all') {
			$query_kelas  = "and nama_kelas='".$_POST['kelas']."'";
		}
		$kode_prodi = $_POST['jurusan'];
		if ($kode_prodi=="all") {
			$jurusan = "";
			if ($_SESSION['level']!=1) {
				$query_jurusan = "and trim(jurusan.kode_jurusan)='".$_SESSION['jurusan']."'";
			}
		} else {
			$jurusan = "and jurusan.kode_jurusan='".$_POST['jurusan']."'";
			
		}
		$id_kelas_where = array();
		$data_nidn_id = array();

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

		$data = $db->fetch_custom("select left(semester,4) as tahun,id_sms,ajar_dosen.id as id_dosen_ajar,ajar_dosen.*,jurusan.kode_jurusan from ajar_dosen inner join jurusan on ajar_dosen.kode_jurusan=jurusan.kode_jurusan where ajar_dosen.id is not null $sem $jurusan and status_error!=1 and nidn!='' $query_matkul $query_kelas $query_not_in limit 11");

		$filter_penugasan_id_sdm = array();
		foreach ($data as $dt_id) {
			if (is_uuid($dt_id->nidn)) {
				$data_nidn_id[] = "'".convert_ascii($dt_id->nidn)."'";
			} else {
				$data_nidn[] = "'".convert_ascii($dt_id->nidn)."'";
			}
			
			$data_loop[] = $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 = array();
		$id_kelas_feeder = array();
		if (!empty($data_nidn) or !empty($data_nidn_id)) {

		$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[] = "'".trim($dt_id_kelas->id_matkul)."'"; 
				}
			}


		if (!empty($matkul_id)) {
			$implode_id_mk = implode(",", $matkul_id);
			$filter_mk = "id_matkul 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));

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

			$filter_nidn = "";
			if (!empty($data_nidn)) {
				$implode_nidn = implode(",", $data_nidn);
				$filter_nidn = "nidn in($implode_nidn) or nuptk in($implode_nidn)";
			}
			if (!empty($data_nidn_id)) {
				$implode_nidn_id = implode(",", $data_nidn_id);
				if ($filter_nidn!="") {
					$filter_nidn.=" or id_dosen in($implode_nidn_id)";
				} else {
					$filter_nidn= "id_dosen in($implode_nidn_id)";
				}
			}
			
      $data_penugasan = [
		      'act' => 'GetListPenugasanDosen',
		        'token' => $token,
		        'filter' => $filter_nidn,
		        'order' => 'id_tahun_ajaran asc',
		        'limit' => '',
		        'offset' => ''
	    	];
			$temp_ptk = json_decode($db->run($data_penugasan,$url_rest));

			/*dump($data_penugasan);
			dump($temp_ptk);*/

			if (!empty($temp_ptk->data)) {
				foreach ($temp_ptk->data as $dt_ptk) {
					$data_id_penugasan_nidn[$dt_ptk->nidn] = $dt_ptk->id_registrasi_dosen;
					$data_id_penugasan_nuptk[$dt_ptk->nuptk] = $dt_ptk->id_registrasi_dosen;
					$data_id_penugasan_id_dosen[$dt_ptk->id_dosen] = $dt_ptk->id_registrasi_dosen;
				}
			}

		}



		$dosen_data = array();
		foreach ($data_loop as $dt) {
			$id_reg_ptk = '';
				if (is_uuid($dt->nidn) && in_array($dt->nidn, array_keys($data_id_penugasan_id_dosen))) {
					$id_reg_ptk = $data_id_penugasan_id_dosen[$dt->nidn];
				} elseif (in_array($dt->nidn, array_keys($data_id_penugasan_nidn))) {
					 $id_reg_ptk = $data_id_penugasan_nidn[$dt->nidn];
				} elseif (in_array($dt->nidn, array_keys($data_id_penugasan_nuptk))) {
					 $id_reg_ptk = $data_id_penugasan_nuptk[$dt->nidn];
				}

				if ($id_reg_ptk!="") {
					if (in_array($dt->id_sms.convert_ascii($dt->kode_mk).convert_ascii($dt->nama_kelas).convert_ascii($dt->semester), array_keys($id_kelas_feeder))) {

						if($dt->sks_ajar!=NULL or $dt->sks_ajar!='') {
							$sks_mk = $dt->sks_ajar;
						} else {
							$sks_mk = $array_id_mk[$id_kelas_feeder[$dt->id_sms.convert_ascii($dt->kode_mk).convert_ascii($dt->nama_kelas).convert_ascii($dt->semester)]->id_matkul]->sks_mata_kuliah;
						}
											//dump($sks_mk);
											//dump($_POST);
								if ($_POST['method']=='up') {
										$id_kls = $id_kelas_feeder[$dt->id_sms.convert_ascii($dt->kode_mk).convert_ascii($dt->nama_kelas).convert_ascii($dt->semester)]->id_kelas_kuliah;
										//check dosen kelas
									  	$data_dic_pengajar = [
									      'act' => 'GetDosenPengajarKelasKuliah',
									        'token' => $token,
									        'filter' => "id_registrasi_dosen='$id_reg_ptk' and id_kelas_kuliah='$id_kls'",
									        'order' => '',
									        'limit' => '',
									        'offset' => ''
									    ];

										$temp_pengajar = service_request($data_dic_pengajar);
									
										if (!empty($temp_pengajar->data)) {
											$dosen_data = array(
														'id_registrasi_dosen' => $id_reg_ptk,
														'id_kelas_kuliah' => $id_kls,
													  	'sks_substansi_total' => $sks_mk,
											  	 		'rencana_minggu_pertemuan' => $dt->rencana_tatap_muka,
											  	 		'realisasi_minggu_pertemuan' => $dt->tatap_muka_real,
											  	 		'id_jenis_evaluasi' => $dt->id_jenis_evaluasi
											);
											if ($dt->id_substansi!="" && is_uuid($dt->id_substansi)) {
												$dosen_data["id_substansi"] = $dt->id_substansi;
											}

											$dosen_key = array(
												'id_aktivitas_mengajar' => $temp_pengajar->data[0]->id_aktivitas_mengajar
											);

										  $data_dic = [
										      'act' => 'UpdateDosenPengajarKelasKuliah',
										        'token' => $token,
										        'key' => $dosen_key,
										        'record' => $dosen_data,
										    ];

											$temp_recs = service_request($data_dic);


											//dump($temp_recs);
											//exit();

											$value_data = addslashes($temp_recs->error_desc);
											if ($value_data!='') {
												$error_update_data[] = array(
													'keterangan' => $value_data,
													'status_error' => 2
												);
												$data_id_error[] = $dt->id_dosen_ajar;
											} else {
												$update_data[] = array(
													'keterangan' => '',
													'status_error' => 1
												);
												$data_id_sukses[] = $dt->id_dosen_ajar;
											}
										} else {
											$error_data = "Dosen tidak ditemukan di Kelas Kuliah";
										}

								} else {
									$id_kls = $id_kelas_feeder[$dt->id_sms.convert_ascii($dt->kode_mk).convert_ascii($dt->nama_kelas).convert_ascii($dt->semester)]->id_kelas_kuliah;
									$data_dic_kelas_dosen = [
								      'act' => 'GetDosenPengajarKelasKuliah',
								        'token' => $token,
								        'filter' => "id_registrasi_dosen='$id_reg_ptk' and id_kelas_kuliah='$id_kls'"
							    	];
									$check_dosen_kelas = service_request($data_dic_kelas_dosen);
/*									dump($data_dic_kelas_dosen);
									dump($check_dosen_kelas);*/
									if (empty($check_dosen_kelas->data)) {
										$data_dosen_ori = array(
													 'id_registrasi_dosen' => $id_reg_ptk,
														 'id_kelas_kuliah' => $id_kls,
												  'sks_substansi_total' => $sks_mk,
	/*											   'sks_tm_subst' => 0,
										  		 'sks_prak_subst' => 0,
										  	 'sks_prak_lap_subst' => 0,
										  	 	  'sks_sim_subst' => 0,*/
										  	 		'rencana_minggu_pertemuan' => $dt->rencana_tatap_muka,
										  	 		'realisasi_minggu_pertemuan' => $dt->tatap_muka_real,
										  	 		'id_jenis_evaluasi' => $dt->id_jenis_evaluasi,
										  	 		'id_substansi' => $dt->id_substansi
											);
										if ($dt->id_substansi!="" && is_uuid($dt->id_substansi)) {
												$data_dosen_ori["id_substansi"] = $dt->id_substansi;
										}
										$data_dosen[] = $data_dosen_ori;
										
										$data_ids[] = $dt->id_dosen_ajar;
									} else {
										$error_update_data[] = array(
											'keterangan' => 'Dosen pengajar ini Sudah ada',
											'status_error' => 2
										);
										$data_id_error[] = $dt->id_dosen_ajar;
									}

								}

						} else {
							$error_data = "Kelas tidak ada di feeder";
						}
				} else {
					$error_data = "Tidak ada penugasan atau NIDN/NUPTK/ID tidak ditemukan";
				}

			if ($error_data!="") {
				$error_update_data[] = array(
					'keterangan' => $error_data,
					'status_error' => 2
				);
				$data_id_error[] = $dt->id_dosen_ajar;
			}

			$all_id[] = $dt->id_dosen_ajar;
			$error_data = "";
		}


		//update sukses
		if (!empty($update_data)) {
			updateMulti('ajar_dosen',$update_data,'id',$data_id_sukses);
		}

		$update_data = array();
		$data_id_sukses = array();
		//update error
		if (!empty($error_update_data)) {
			updateMulti('ajar_dosen',$error_update_data,'id',$data_id_error);
		}
		$error_update_data = array();
		$data_id_error = array();
/*		$data_id_kelas_update = array();

		if (!empty($check_dosen_exist)) {
			$implode_ptk_kls = implode(",", $check_dosen_exist);
			$filter_kls_ptk = "(p.id_reg_ptk,p.id_kls) in ($implode_ptk_kls)";
			$temp_kelas_update = $proxy->GetRecordset($token,'ajar_dosen',$filter_kls_ptk,"","","");
			if (!empty($temp_kelas_update['result'])) {
				foreach ($temp_kelas_update['result'] as $dt_kls_ptk) {
					$data_id_kelas_update[$dt_kls_ptk['id_reg_ptk'].convert_ascii($dt_kls_ptk['id_kls'])] = $dt_kls_ptk['id_ajar'];
				}
			}
		}


		if (!empty($data_id_kelas_update)) {
			foreach ($data_id_kelas_update as $key => $value) {
				$dosen_datas = array(
					  'sks_subst_tot' => $dosen_data[$key]['sks_subst_tot'],
			  	 		'jml_tm_renc' => $dosen_data[$key]['jml_tm_renc'],
			  	 		'jml_tm_real' => $dosen_data[$key]['jml_tm_real']
				);
				$dosen_key = array(
					'id_ajar' => $value
				);
				$data_dosen[] = array('key'=>$dosen_key,'data'=>$dosen_datas);

			}
		}*/




		if (!empty($data_dosen)) {

			//dump($data_dosen);

			foreach ($data_dosen as $key => $dosen_data) {				
			  $data_dic = [
			      'act' => 'InsertDosenPengajarKelasKuliah',
			        'token' => $token,
			        'record' => $dosen_data,
			    ];
				$temp_recs = json_decode($db->run($data_dic,$url_rest));

				//dump($data_dic);
				//dump($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('ajar_dosen',$error_update_data,'id',$data_id_error);
		}
		//update sukses
		if (!empty($update_data)) {
			updateMulti('ajar_dosen',$update_data,'id',$data_id_sukses);
		}

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

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

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

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

		$db->fetch_custom("update ajar_dosen set unik_id=0 where  unik_id=".$_POST['random_number']);
		
		$msg =  "<div class=\"alert alert-warning \" role=\"alert\">
		<font color=\"#3c763d\">".$jumlah_sukses." data Ajar Dosen  berhasil ditambah/diperbaharui</font><br />
		<font color=\"#ce4844\" >".$jumlah_error." data tidak bisa ditambahkan/diperbaharui </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