<?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_count_in = 0;

        $error_msg = array();

        $filter_mk_where = array();
        $check_akt_exist = array();
        $update_data = array();
        $update_data_status = array();

        $update_data_er =array();
        $update_data_er_status =array();
        $error_mk = "";
        $array_id_anggota = array();
        $array_exist_konversi = array();
        $array_id_mk = array();
        $array_id_mk_cross = array();
        $data_id_sukses = array();
        $data_id_error= array();

        $all_errors = array();
        $all_error = array();
        $query_not_in = "";
        $id_mk = "";
        $error_mk = "";

        $msg = "";
        $array_konversi = array();
        $filter_mk_where_cross = array();
        $array_id_mk_cross = array();
        
        $query_jenis = '';
        $query_jurusan = '';
        $all_id = array();
        $id_konversi = array();

        $sem = "";
        $data_ids = array();

        $data_akt = array();
        $aktivitas_id = array();
        $data_id_aktivitas = array();
        $nim_data = array();
        $check_konversi_exist = array();

        $jurusan = "";
        $query_matkul = "";

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

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

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

		$data = $db->fetch_custom("select *,nilai_kampus_merdeka.id as id_krs from nilai_kampus_merdeka inner join jurusan on nilai_kampus_merdeka.kode_jurusan=jurusan.kode_jurusan where status_error!=1 $sem $jurusan $query_matkul  $query_not_in limit 11");


		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;
}


		foreach ($data as $dt_id) {
			$data_loop[] = $dt_id;
			if (is_uuid($dt_id->id_aktivitas)) {
				$data_id_aktivitas[] = $dt_id->id_aktivitas;
				$aktivitas_id[$dt_id->id_aktivitas] = convert_ascii($dt_id->semester).convert_ascii($dt_id->id_sms).convert_ascii($dt_id->id_aktivitas);
				$data_akt[convert_ascii($dt_id->semester).convert_ascii($dt_id->id_sms).convert_ascii($dt_id->id_aktivitas)] = $dt_id->id_aktivitas;
			} else {
				$check_akt_exist[] = "('".convert_ascii($dt_id->semester)."','".$dt_id->id_sms."','".convert_ascii($dt_id->id_aktivitas)."')";
			}
			$filter_mk_where[$dt_id->id_sms.convert_ascii($dt_id->kode_mk)] = "('".$dt_id->id_sms."','".convert_ascii($dt_id->kode_mk)."')";
			$filter_mk_where_cross[convert_ascii($dt_id->kode_mk)] = "('".convert_ascii($dt_id->kode_mk)."')";
		}

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

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



			if (!empty($data_id_aktivitas)) {

			$implode_id_anggota = sprintf("'%s'", implode("','", $data_id_aktivitas ) ); 
			$data_req_akt_anggota = [
				'act' => 'GetListAnggotaAktivitasMahasiswa',
			    'token' => $token,
			    'filter' => "(id_aktivitas) IN ($implode_id_anggota)",
			    'order' => "",
			    'limit' => "",
			    'offset' => ""

			];
			
			$check_akt_exist_anggota = json_decode($db->run($data_req_akt_anggota,$url_rest));
			
				if (!empty($check_akt_exist_anggota->data)) {
					foreach ($check_akt_exist_anggota->data as $akt) {
						
						$array_id_anggota[convert_ascii($akt->nim).$aktivitas_id[$akt->id_aktivitas]] = array(
								'id_aktivitas' => $akt->id_aktivitas,
								'id_anggota' => $akt->id_anggota,
							    'id_registrasi_mahasiswa' => $akt->id_registrasi_mahasiswa,
						   		'nim' => $akt->nim,
						   		'nama_mahasiswa' => $akt->nama_mahasiswa,
						   		'jenis_peran' => $akt->jenis_peran,
						   		'nama_jenis_peran' => $akt->nama_jenis_peran,
						   		'raw_id' => $aktivitas_id[$akt->id_aktivitas]
						);
					}
				}
			}

			//dump($array_id_anggota);
//echo "<pre>";
			//print_r($array_id_anggota);

		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));

			if (!empty($check_matkul_exist->data)) {
				foreach ($check_matkul_exist->data as $dts) {
					$array_id_mk[$dts->id_prodi.convert_ascii($dts->kode_mata_kuliah)] = array(
						'id_mk' => $dts->id_matkul,
						'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($filter_mk_where_cross)) {
			$implode_id_mk = implode(",", $filter_mk_where_cross);
			$filter_mk = "(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));
			if (!empty($check_matkul_exist->data)) {
				foreach ($check_matkul_exist->data as $dts) {
					$array_id_mk_cross[convert_ascii($dts->kode_mata_kuliah)] = array(
						'id_mk' => $dts->id_matkul,
						'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
					); 
				}				
			}
		}

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

		foreach ($data_loop as $dt) {
		$id_sms = $dt->id_sms;
		$nim = convert_ascii($dt->nim);

		if (in_array(convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas), array_keys($data_akt))) {
			//echo "good1";
			if (in_array($nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas), array_keys($array_id_anggota))) {
				//echo "good2";
				if (in_array($dt->id_sms.convert_ascii($dt->kode_mk), array_keys($array_id_mk))) {
					$sks = $dt->sks;
					if ($dt->sks=="") {
						$sks = $array_id_mk[$dt->id_sms.convert_ascii($dt->kode_mk)]['sks_mk'];
					}
					$array_konversi[$array_id_mk[$dt->id_sms.convert_ascii($dt->kode_mk)]['id_mk'].$array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_anggota'].$array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_aktivitas']] = array(
					  'id_matkul' => $array_id_mk[$dt->id_sms.convert_ascii($dt->kode_mk)]['id_mk'],
					  'id_anggota' => $array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_anggota'],
		              'id_aktivitas' =>$array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_aktivitas'],
		              'sks_mata_kuliah' => $sks,
		              'id_semester' => $dt->semester,
		              'nilai_angka' => $dt->nilai_angka,
		              'nilai_indeks' => $dt->nilai_indeks,
		              'nilai_huruf' => $dt->nilai_huruf
		            );

					$check_konversi_exist[$array_id_mk[$dt->id_sms.convert_ascii($dt->kode_mk)]['id_mk'].$array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_anggota'].$array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_aktivitas']] = "('".$array_id_mk[$dt->id_sms.convert_ascii($dt->kode_mk)]['id_mk']."','". $array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_anggota']."','".$array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_aktivitas']."')";

					$data_ids[$array_id_mk[$dt->id_sms.convert_ascii($dt->kode_mk)]['id_mk'].$array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_anggota'].$array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_aktivitas']] = $dt->id_krs;
				} else {
					if (in_array(convert_ascii($dt->kode_mk), array_keys($array_id_mk_cross))) {
						$sks = $dt->sks;
						if ($dt->sks=="") {
							$sks = $array_id_mk_cross[convert_ascii($dt->kode_mk)]['sks_mk'];
						}
						$array_konversi[$array_id_mk_cross[convert_ascii($dt->kode_mk)]['id_mk'].$array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_anggota'].$array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_aktivitas']] = array(
						  'id_matkul' => $array_id_mk_cross[convert_ascii($dt->kode_mk)]['id_mk'],
						  'id_anggota' => $array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_anggota'],
			              'id_aktivitas' =>$array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_aktivitas'],
			              'sks_mata_kuliah' => $sks,
			              'id_semester' => $dt->semester,
			              'nilai_angka' => $dt->nilai_angka,
			              'nilai_indeks' => $dt->nilai_indeks,
			              'nilai_huruf' => $dt->nilai_huruf
			            );

						$check_konversi_exist[$array_id_mk_cross[convert_ascii($dt->kode_mk)]['id_mk'].$array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_anggota'].$array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_aktivitas']] = "('".$array_id_mk_cross[convert_ascii($dt->kode_mk)]['id_mk']."','". $array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_anggota']."','".$array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_aktivitas']."')";

						$data_ids[$array_id_mk_cross[convert_ascii($dt->kode_mk)]['id_mk'].$array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_anggota'].$array_id_anggota[$nim.convert_ascii($dt->semester).$dt->id_sms.convert_ascii($dt->id_aktivitas)]['id_aktivitas']] = $dt->id_krs;
					} else {
						$error_update_data[] = array(
							'keterangan' => "Kode MK $dt->kode_mk tidak ditemukan di Feeder",
							'status_error' => 2
						);
						$data_id_error[] = $dt->id_krs;
					}

				}

			} else {
				$error_update_data[] = array(
					'keterangan' => "Error Mahasiswa dengan NIM $dt->nim Tidak Ditemukan di Aktivitas",
					'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('nilai_kampus_merdeka',$error_update_data,'id',$data_id_error);
		}
		$error_update_data = array();
		$data_id_error = array();

		//echo "<pre>";
		//print_r($check_konversi_exist);

		//echo "<pre>";
if (!empty($array_konversi)) {

	$limit = count($array_konversi);

/*	print_r($limit);
	print_r($array_konversi);*/

	//check if exist
			$implode_id_konversi = implode(",", $check_konversi_exist);
			$data_req_akt_konversi = [
				'act' => 'GetListKonversiKampusMerdeka',
			    'token' => $token,
			    'filter' => "(id_matkul,id_anggota,id_aktivitas) IN ($implode_id_konversi)",
			    'order' => "",
			    'limit' => "",
			    'offset' => ""

			];
			
			$check_exist_konversi = json_decode($db->run($data_req_akt_konversi,$url_rest));
			
				if (!empty($check_exist_konversi->data)) {
					foreach ($check_exist_konversi->data as $akt) {
						$array_exist_konversi[] = convert_ascii($akt->id_matkul).convert_ascii($akt->id_anggota).convert_ascii($akt->id_aktivitas);
						$id_konversi[convert_ascii($akt->id_matkul).convert_ascii($akt->id_anggota).convert_ascii($akt->id_aktivitas)] = $akt->id_konversi_aktivitas;
					}
				}
//($array_exist_konversi);
				//echo "<pre>";
			if ($_POST['method']=='up') {
				foreach ($array_konversi as $key => $konversi) {
					if (in_array($key, $array_exist_konversi)) {
						$key_id['id_konversi_aktivitas'] = $id_konversi[$konversi['id_matkul'].$konversi['id_anggota'].$konversi['id_aktivitas']];
						$data_dic = [
					      'act' => 'UpdateKonversiKampusMerdeka',
					        'token' => $token,
					        'key' => $key_id,
					        'record' => $konversi,
					    ];

					   
						$temp_recs = json_decode($db->run($data_dic,$url_rest));
						//print_r($data_dic);
						//print_r($temp_recs);
								$value_data = addslashes($temp_recs->error_desc);
								$data_key = $data_ids[$konversi['id_matkul'].$konversi['id_anggota'].$konversi['id_aktivitas']];

								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_update_data[] = array(
							'keterangan' => "Error, Nilai Konversi Belum ada, silakan pilih Method Insert",
							'status_error' => 2
						);
						$data_id_error[] = $data_ids[$konversi['id_matkul'].$konversi['id_anggota'].$konversi['id_aktivitas']];
					}

				}
			} else {
				foreach ($array_konversi as $key => $konversi) {
					// Convert all values (including nested) to string
					array_walk_recursive($konversi, function (&$value) {
					    $value = (string)$value;
					});
					if (!in_array($key, $array_exist_konversi)) {
						  $data_dic = [
						      'act' => 'InsertKonversiKampusMerdeka',
						        'token' => $token,
						        'record' => $konversi,
						    ];

						   // exit();
							$temp_recs = json_decode($db->run($data_dic,$url_rest));
									$value_data = addslashes($temp_recs->error_desc);
									$data_key = $data_ids[$konversi['id_matkul'].$konversi['id_anggota'].$konversi['id_aktivitas']];

									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_update_data[] = array(
							'keterangan' => "Error, Nilai Konversi Sudah Ada",
							'status_error' => 2
						);
						$data_id_error[] = $data_ids[$konversi['id_matkul'].$konversi['id_anggota'].$konversi['id_aktivitas']];
					}
				}

			}

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

			    print_r($data_id_error);
*/
				
		}

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

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

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

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

		$db->fetch_custom("update nilai_kampus_merdeka set unik_id=0 where  unik_id=".$_POST['random_number']);
		
		$msg =  "<div class=\"alert alert-warning \" role=\"alert\">
		<font color=\"#3c763d\">".$jumlah_sukses." data Konversi Nilai 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