<?php
session_start();
include "../../inc/config.php";
$json_response = array();
$jumlah = 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['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 = "";
		$array_aktivitas = array();
		
		$query_jenis = '';
		$query_jurusan = '';
		$all_id = array();

		$data_akt = array();
		$data_nidn_id = array();
		
		$data_nidn = array();
		$data_loop = array();
		$data_nidn_nuptk = array();

		$data_id_pembimbing = array();
		$data_id_penguji = array();
		$nidn = array();

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

		if ($_POST['jenis']!='all') {
			$query_jenis = "and jenis='".trim($_POST['jenis'])."'";
		}

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

		foreach ($data as $dt_id) {
			if (is_uuid($dt_id->nidn_dosen)) {
				$data_nidn_id[$dt_id->nidn_dosen] = $dt_id->nidn_dosen;
			} else {
				$nidn[convert_ascii($dt_id->nidn_dosen)] = "'".convert_ascii($dt_id->nidn_dosen)."'";
			}


			$data_loop[] = $dt_id;
			$id_aks = str_replace("'", "", $dt_id->id_aktivitas);
			$check_akt_exist[] = "('".convert_ascii($dt_id->semester)."','".$dt_id->id_sms."','".convert_ascii($id_aks)."')";
			}

			$akt_concat_where = implode(",", $check_akt_exist);
			$data_req_akt = [
				'act' => 'GetListAktivitasMahasiswa',
			    'token' => $token,
			    'filter' => "(id_semester,id_prodi,TRIM(REPLACE(keterangan, '''', ''))) IN ($akt_concat_where)",
			    'order' => "",
			    'limit' => "",
			    'offset' => ""

			];
			$check_akt_exist = json_decode($db->run($data_req_akt,$url_rest));
			if (!empty($check_akt_exist->data)) {
				foreach ($check_akt_exist->data as $akt_data) {
					$data_akt[$akt_data->id_semester.$akt_data->id_prodi.$akt_data->keterangan] = $akt_data->id_aktivitas;
				}
			}

			if (!empty($nidn)) {
			$implode_nidn = implode(",", $nidn);
			$filter_nidn = "trim(nidn) in ($implode_nidn) or trim(nuptk) in($implode_nidn)";
	          	$data_dic_dosen = [
			      'act' => 'GetListDosen',
			        'token' => $token,
			        'filter' => $filter_nidn,
			        'order' => '',
			        'limit' => '',
			        'offset' => ''
		    	];
				$temp_nidn = json_decode($db->run($data_dic_dosen,$url_rest));

				if (!empty($temp_nidn->data)) {
					foreach ($temp_nidn->data as $nidn_ptk) {
						$data_nidn[$nidn_ptk->nidn] = $nidn_ptk->id_dosen;
						$data_nidn_nuptk[$nidn_ptk->nuptk] = $nidn_ptk->id_dosen;
					}
					
				}
			}



		foreach ($data_loop as $dt) {
		$id_sms = $dt->id_sms;
		$nidn_dosen = convert_ascii($dt->nidn_dosen);
		$id_dosen = '';

if (is_uuid($dt->nidn_dosen)) {
	$id_dosen = $dt->nidn_dosen;
} elseif (in_array($dt->nidn_dosen, array_keys($data_nidn))) {
	 $id_dosen = $data_nidn[$dt->nidn_dosen];
} elseif (in_array($dt->nidn_dosen, array_keys($data_nidn_nuptk))) {
	 $id_dosen = $data_nidn_nuptk[$dt->nidn_dosen];
}


		if (in_array(convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas), array_keys($data_akt))) {
			//check if mhs exist
			if ($id_dosen!='') {
				if ($dt->jenis==1) {
					$array_pembimbing[] = array(
		              'id_aktivitas' => $data_akt[convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)],
		              'id_kategori_kegiatan' => $dt->kategori_kegiatan,
		              'id_dosen' => $id_dosen,
		              'pembimbing_ke' => $dt->urutan,
		            );
		            $data_kls[$dt->id] = $dt->nidn_dosen;
					$data_id_pembimbing[] = $dt->id;
				} else {
					$array_penguji[] = array(
					  'id_aktivitas' => $data_akt[convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)],
		              'id_kategori_kegiatan' => $dt->kategori_kegiatan,
		              'id_dosen' =>  $id_dosen,
		              'penguji_ke' => $dt->urutan,
		            );
		            $data_kls[$dt->id] = $dt->nidn_dosen;
					$data_id_penguji[] = $dt->id;
				}

			} else {
				$error_update_data[] = array(
					'keterangan' => "Error Dosen dengan NIDN/NUPTK/ID $dt->nidn_dosen Tidak Ditemukan di Feeder",
					'status_error' => 2
				);
				$data_id_error[] = $dt->id_krs;
			}


		} else {
				$error_update_data[] = array(
					'keterangan' => "Error ID AKTIVITAS $dt->id_aktivitas Tidak ada Di feeder",
					'status_error' => 2
				);
				$data_id_error[] = $dt->id_krs;
		}
		$all_id[] = $dt->id_krs;
	}
		//update error
		if (!empty($error_update_data)) {
			updateMulti('aktivitas_bimbing_uji',$error_update_data,'id',$data_id_error);
		}
		$error_update_data = array();
		$data_id_error = array();

		if (!empty($array_pembimbing)) {

			foreach ($array_pembimbing as $key => $pembimbing) {
				$data_dic = [
			      'act' => 'InsertBimbingMahasiswa',
			        'token' => $token,
			        'record' => $pembimbing,
			    ];

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

				$value_data = addslashes($temp_recs->error_desc);
				$data_key = $data_id_pembimbing[$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($array_penguji)) {

					foreach ($array_penguji as $key => $penguji) {
						$data_dic = [
					      'act' => 'InsertUjiMahasiswa',
					        'token' => $token,
					        'record' => $penguji,
					    ];

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

						$value_data = addslashes($temp_recs->error_desc);
						$data_key = $data_id_penguji[$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;
						}	

					}


/*			$result = $proxy->InsertRecordset($token, 'uji_mahasiswa',json_encode($array_penguji));

				foreach ($result['result'] as $key => $value) {

					$value_data = addslashes($value['error_desc']);
					$data_key = $data_id_penguji[$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('aktivitas_bimbing_uji',$error_update_data,'id',$data_id_error);
		}
		$error_update_data = array();
		$data_id_error = array();
		//update sukses
		if (!empty($update_data)) {
			updateMulti('aktivitas_bimbing_uji',$update_data,'id',$data_id_sukses);
		}
		$update_data = array();
		$data_id_sukses = array();

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

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

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

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

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