<?php
session_start();
include "../../inc/config.php";
$json_response = array();
$jumlah = array();
if ($_POST['total_data']>0) {
    $url_rest = get_service_url('rest');
    $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();
    $data_trf = array();
    $error_update_data = array();
  
    $all_errors = array();
    $all_error = array();
    $query_not_in = "";
    $error_nim = "";
    $msg = "";
    $id_reg_pd = "";
    $id_mk = "";
    $error_ada="";
    $sks_mk = "";

    $query_jurusan = '';
     $data_nim = array();
    $data_ids = array();
	$error_code ="";
    $nim_concat = array();
    $mk_data = array();
    $mk_data_all = array();
    $nilai_exist = array();
    $data_id_error_exist = array();
    $error_update_data_exist = array();
    $nim_data = array();

	  # MENDAPATKAN TOKEN
	  $token = $db->get_token();
		$query_not_in = "and unik_id not in(".$_POST['random_number'].")"; ;

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

		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']."'";
      		}
		}


		$data_nim_query = $db->fetch_custom("select *,nilai_transfer.id as id_krs from nilai_transfer inner join jurusan on nilai_transfer.kode_jurusan=jurusan.kode_jurusan where nilai_transfer.id is not null $query_jurusan $sem and status_error!=1 $query_not_in limit 11");
		function is_uuid($string) {
		  return preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i', $string) === 1;
		}
		$kode_pt = array();
		$check_akt_exist = array();
		foreach ($data_nim_query as $dt_id) {
			$nim_concat[convert_ascii($dt_id->nim).$dt_id->id_sms] = "('".$dt_id->nim."','".$dt_id->id_sms."')";
			$nim_like[$dt_id->nim] = "nim like '%$dt_id->nim%'";
			$sms_and[$dt_id->id_sms] = "('".$dt_id->id_sms."')";
			$for_filter_mk[] = "('".$dt_id->id_sms."'".",'".trim($dt_id->kode_mk)."')";
			$for_filter_mk_all[] = "'".trim($dt_id->kode_mk)."'";
			$data[] = $dt_id;
			$kode_pt[] = "'".trim($dt_id->kode_pt)."'";
			if ($dt_id->id_aktivitas!="" && is_uuid($dt_id->id_aktivitas)==false) {
				$check_akt_exist[] = "('".convert_ascii($dt_id->semester)."','".$dt_id->id_sms."','".convert_ascii($dt_id->id_aktivitas)."')";
			}
			

		}

		$nim_concat_where = implode(",", $nim_concat);
		$implode_nim_like = implode(" or ",$nim_like);
		$implode_prodi = implode(",",$sms_and);
        //$filter_mhs = "(regexp_replace(trim(nim), '[^[:alnum:]\s.]+', ''), id_prodi) in ($nim_concat_where)";
       //$filter_mhs = "(nim,id_prodi) in ($nim_concat_where)";
	   // $filter_mhs,
		$data_req_mhs = [
			'act' => 'GetListMahasiswa',
		    'token' => $token,
		    'filter' => "id_registrasi_mahasiswa is not null and ($implode_nim_like) and id_prodi in($implode_prodi)",
		    'order' => "",
		    'limit' => "",
		    'offset' => ""
		];
		
		//dump($data_req_mhs);
		

		$check_nim_exist = json_decode($db->run($data_req_mhs,$url_rest));
		//dump($check_nim_exist);
		foreach ($check_nim_exist->data as $nim_mhs) {
			$nim_data[convert_ascii($nim_mhs->nim).$nim_mhs->id_prodi] = $nim_mhs->id_registrasi_mahasiswa;
		}

		$mk_concat_where = array_unique($for_filter_mk);
		$implode_filter_mk = implode(",", $mk_concat_where);
		$filter_mk = "(id_prodi,trim(kode_mata_kuliah)) IN ($implode_filter_mk)";

		//searching matkul 
		$data_req_mk = [
			'act' => 'GetListMataKuliah',
		    'token' => $token,
		    'filter' =>  $filter_mk,
		    'order' => "",
		    'limit' => "",
		    'offset' => ""

		];

		$check_mk_exist = json_decode($db->run($data_req_mk,$url_rest));
		if (!empty($check_mk_exist->data)) {
			foreach ($check_mk_exist->data as $mk_id) {
				$mk_data[$mk_id->id_prodi."#".$mk_id->kode_mata_kuliah] = array(
					'id_matkul' => $mk_id->id_matkul,
					'sks_diakui' => $mk_id->sks_mata_kuliah
				);;
			}
		}

		$mk_concat_where_all = array_unique($for_filter_mk_all);
		$implode_filter_mk_all = implode(",", $mk_concat_where_all);
		$filter_mk_all = "(trim(kode_mata_kuliah)) IN ($implode_filter_mk_all)";

		//searching matkul 
		$data_req_mk_all = [
			'act' => 'GetListMataKuliah',
		    'token' => $token,
		    'filter' =>  $filter_mk_all,
		    'order' => "",
		    'limit' => "",
		    'offset' => ""

		];

		$check_mk_exist_all = json_decode($db->run($data_req_mk_all,$url_rest));
		if (!empty($check_mk_exist_all->data)) {
			foreach ($check_mk_exist_all->data as $mk_id_all) {
				$mk_data_all[$mk_id_all->kode_mata_kuliah] = array(
					'id_matkul' => $mk_id_all->id_matkul,
					'sks_diakui' => $mk_id_all->sks_mata_kuliah
				);
			}
		}

		$id_pt_array = array();
		$kode_pt = array_filter($kode_pt);
	    if (!empty($kode_pt)) {
	        //check if id_mhs used
	        $concat_where = implode(",", $kode_pt);
	            $data_req_pt = [
	                'act' => 'GetAllPT',
	                'token' => $token,
	                'filter' => "(kode_perguruan_tinggi) in ($concat_where)",
	                'order' => "",
	                'limit' => "",
	                'offset' => ""

	            ];
	        $check_exist = json_decode($db->run($data_req_pt,$url_rest));
	        if ($check_exist) {
	            foreach ($check_exist->data as $id_pt) {
	                $id_pt_array[convert_ascii($id_pt->kode_perguruan_tinggi)] = array(
	                    'id_sp' => $id_pt->id_perguruan_tinggi,
	                    'nm_lemb' => $id_pt->nama_perguruan_tinggi
	                );
	            }
	        }
	    }

	    $data_akt = array();
		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[$akt_data->id_semester.$akt_data->id_prodi.$akt_data->keterangan] = $akt_data->id_aktivitas;
				}
			}
		}




	    
		foreach ($data as $value) {
		$nim = convert_ascii($value->nim);
		$kode_mk = trim($value->kode_mk);
		$id_sms = $value->id_sms;

		//check if mhs exist
			if (in_array($nim.$id_sms, array_keys($nim_data))) {
					$id_reg_pd = $nim_data[$nim.$id_sms];
				 	if (in_array($value->id_sms."#".$value->kode_mk,array_keys($mk_data))) {
				 		$id_mk = $mk_data[$value->id_sms."#".$value->kode_mk]['id_matkul'];
				 		$sks_mk = $mk_data[$value->id_sms."#".$value->kode_mk]['sks_diakui'];
				 	} elseif (in_array($value->kode_mk,array_keys($mk_data_all))) {
				 		$id_mk = $mk_data_all[$value->kode_mk]['id_matkul'];
				 		$sks_mk = $mk_data_all[$value->kode_mk]['sks_diakui'];
				 	}

				 	if ($id_mk!="") {
				 		//check for exist
				 		$filter_exist[] = "('".$id_reg_pd."','".$id_mk."','".trim($value->kode_mk_asal)."','".$value->semester."')";

				 		$temp_data[$id_reg_pd."#".$id_mk."#".trim($value->kode_mk_asal)."#".$value->semester] = array(
							'id_reg_pd' => $nim_data[$nim.$id_sms],
							'id_semester' => $value->semester,
							'id_mk' => $id_mk,
							'kode_mk_asal' => $value->kode_mk_asal,
							'nm_mk_asal' => $value->nm_mk_asal,
							'id_sms' => $id_sms,
							'id_aktivitas' => $value->id_aktivitas,
							'sks_asal' => $value->sks_asal,
							'sks_diakui' => floatval($sks_mk),
							'nilai_huruf_asal' => $value->nilai_huruf_asal,
							'nilai_huruf_diakui' => $value->nilai_huruf_diakui,
							'nilai_angka_diakui' => $value->nilai_angka_diakui,
							'id_akm' => $value->id_krs,
							'id_aktivitas' => $value->id_aktivitas
						);
				        if (in_array(convert_ascii($value->kode_pt), array_keys($id_pt_array))) {
				            $temp_data[$id_reg_pd."#".$id_mk."#".trim($value->kode_mk_asal)."#".$value->semester]["id_perguruan_tinggi"] = $id_pt_array[convert_ascii($value->kode_pt)]['id_sp'];
				        }
				 	} else {
						$error_update_data[] = array(
							'keterangan' => "Kode Matakuliah tidak ditemukan di feeder",
							'status_error' => 2
						);
						$data_id_error[] = $value->id_krs;
				 	}

			} else {
				$error_update_data[] = array(
					'keterangan' => "Nim Mahasiswa ini tidak ditemukan di feeder",
					'status_error' => 2
				);
				$data_id_error[] = $value->id_krs;
			}

		$id_mk = "";
		$all_id[] = $value->id_krs;

		}


		if (!empty($filter_exist)) {
			$implode_check = implode(",", $filter_exist);
			$filter_check = "(id_registrasi_mahasiswa,id_matkul,trim(kode_mata_kuliah_asal)) IN ($implode_check)";
			//searching matkul 
			$data_req_nilai = [
				'act' => 'GetNilaiTransferPendidikanMahasiswa',
			    'token' => $token,
			    'filter' =>  $filter_check,
			    'order' => "",
			    'limit' => "",
			    'offset' => ""

			];

			$check_nilai_exist = json_decode($db->run($data_req_nilai,$url_rest));
			if (!empty($check_nilai_exist->data)) {
				foreach ($check_nilai_exist->data as $nilai_trf) {
					$nilai_exist[$nilai_trf->id_registrasi_mahasiswa."#".$nilai_trf->id_matkul."#".trim($nilai_trf->kode_mata_kuliah_asal)."#".$nilai_trf->id_semester] = $nilai_trf->id_transfer;
				}
			}

			if ($_POST['method']=='up') {
				foreach ($temp_data as $key => $data_input) {
						if (in_array($key, array_keys($nilai_exist))) {
							$array_key_update[] = array(
								'id_transfer' => $nilai_exist[$data_input['id_reg_pd']."#".$data_input['id_mk']."#".trim($data_input['kode_mk_asal'])]
							);
							$data_trf_array = array(
									'id_semester' => $data_input['id_semester'],
									'id_registrasi_mahasiswa' => $data_input['id_reg_pd'],
									'id_matkul' => $data_input['id_mk'],
									'kode_mata_kuliah_asal' =>$data_input['kode_mk_asal'],
									'nama_mata_kuliah_asal' => $data_input['nm_mk_asal'],
									'sks_mata_kuliah_asal' => $data_input['sks_asal'],
									'sks_mata_kuliah_diakui' => $data_input['sks_diakui'],
									'nilai_huruf_asal' => $data_input['nilai_huruf_asal'],
									'nilai_huruf_diakui' => $data_input['nilai_huruf_diakui'],
									'nilai_angka_diakui' => $data_input['nilai_angka_diakui']
								);
							if (in_array('id_perguruan_tinggi', array_keys($data_input))) {
							$data_trf_array['id_perguruan_tinggi'] = $data_input['id_perguruan_tinggi'];
							}
							if (in_array(convert_ascii($data_input['id_semester']).$data_input['id_sms'].convert_ascii($data_input['id_aktivitas']), array_keys($data_akt))) {
								$data_trf_array['id_akt_mhs'] = $data_akt[convert_ascii($data_input['id_semester']).$data_input['id_sms'].convert_ascii($data_input['id_aktivitas'])];
							} elseif (is_uuid($data_input['id_aktivitas'])) {
								$data_trf_array['id_akt_mhs'] = $data_input['id_aktivitas'];
							}
							$data_trf[] = $data_trf_array;
							$data_ids[] = $data_input['id_akm'];
						} else {
							$error_update_data_exist[] = array(
								'keterangan' => 'Nilai Transfer dengan Kode MK Asal dan Mk diakui ini Tidak ditemukan di Neo Feeder, silakan lakukan insert',
								'status_error' => 2
							);
							$data_id_error_exist[] = $data_input['id_akm'];
						}
					}
				
			} else {
					foreach ($temp_data as $key => $data_input) {
					
						if (!in_array($key, array_keys($nilai_exist))) {
							$data_trf_array = array(
									'id_semester' => $data_input['id_semester'],
									'id_registrasi_mahasiswa' => $data_input['id_reg_pd'],
									'id_matkul' => $data_input['id_mk'],
									'kode_mata_kuliah_asal' =>$data_input['kode_mk_asal'],
									'nama_mata_kuliah_asal' => $data_input['nm_mk_asal'],
									'sks_mata_kuliah_asal' => $data_input['sks_asal'],
									'sks_mata_kuliah_diakui' => $data_input['sks_diakui'],
									'nilai_huruf_asal' => $data_input['nilai_huruf_asal'],
									'nilai_huruf_diakui' => $data_input['nilai_huruf_diakui'],
									'nilai_angka_diakui' => $data_input['nilai_angka_diakui']
								);
							if (in_array('id_perguruan_tinggi', array_keys($data_input))) {
							$data_trf_array['id_perguruan_tinggi'] = $data_input['id_perguruan_tinggi'];
							}
							if (in_array(convert_ascii($data_input['id_semester']).$data_input['id_sms'].convert_ascii($data_input['id_aktivitas']), array_keys($data_akt))) {
								$data_trf_array['id_akt_mhs'] = $data_akt[convert_ascii($data_input['id_semester']).$data_input['id_sms'].convert_ascii($data_input['id_aktivitas'])];
							} elseif (is_uuid($data_input['id_aktivitas'])) {
								$data_trf_array['id_akt_mhs'] = $data_input['id_aktivitas'];
							}

							
							
							$data_trf[] = $data_trf_array;
							$data_ids[] = $data_input['id_akm'];
						} else {
							$error_update_data_exist[] = array(
								'keterangan' => 'Nilai Transfer Sudah Ada di Feeder',
								'status_error' => 2
							);
							$data_id_error_exist[] = $data_input['id_akm'];
						}

					}
			}

		}





		if (!empty($data_trf)) {
				foreach ($data_trf as $key => $trf) {

					if ($_POST['method']=='up') {
						$array_key = $array_key_update[$key];
						$data_dic = [
							      'act' => 'UpdateNilaiTransferPendidikanMahasiswa',
							      'key' => $array_key,
							      'token' => $token,
							      'record' => $trf,

							    ];
					} else {
						$data_dic = [
						      'act' => 'InsertNilaiTransferPendidikanMahasiswa',
						        'token' => $token,
						        'record' => $trf,
						    ];

						    	
					}

					$temp_recs = json_decode($db->run($data_dic,$url_rest));
					
					$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 exist
		if (!empty($error_update_data_exist)) {
			updateMulti('nilai_transfer',$error_update_data_exist,'id',$data_id_error_exist);
		}


		//update error
		if (!empty($error_update_data)) {
			updateMulti('nilai_transfer',$error_update_data,'id',$data_id_error);
		}
		$error_update_data = array();
		$data_id_error = array();
		//update sukses
		if (!empty($update_data)) {
			updateMulti('nilai_transfer',$update_data,'id',$data_id_sukses);
		}
		$update_data = array();
		$data_id_sukses = array();
		
		$implode_id = implode(",", $all_id);

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

		$sukses_count = $jml_error_sukses->jml_sukses;
		$error_count = $jml_error_sukses->jml_error;
		
		$db->fetch_custom("update nilai_transfer set unik_id=0 where  unik_id=".$_POST['random_number']);

		$jumlah_sukses = $sukses_count;
		$jumlah_error = $error_count;

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