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

        

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

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

        $data_akt = array();
        $nim_data = array();

        $check_akt_exist = array();

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

		if ($_POST['jenis']!='all') {
			$query_jenis = "and jenis_peran='".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_anggota.*,id_sms,aktivitas_anggota.id as id_krs,

(select id_sms from jurusan where jurusan.kode_jurusan=aktivitas_anggota.kode_jurusan_aktivitas) as id_sms_akt

 from aktivitas_anggota 
 inner join jurusan on aktivitas_anggota.kode_jurusan=jurusan.kode_jurusan where aktivitas_anggota.id is not null $sem $query_jurusan and status_error!=1 $query_jenis $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) {
			//$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."')";
			$data_loop[] = $dt_id;
			$id_aks = str_replace("'", "", $dt_id->id_aktivitas);
			if (is_uuid($dt_id->id_aktivitas)) {
				$data_akt[convert_ascii($dt_id->semester).convert_ascii($dt_id->id_sms).convert_ascii($id_aks)] = $dt_id->id_aktivitas;
			} else {
				$check_akt_exist[] = "('".convert_ascii($dt_id->semester)."','".$dt_id->id_sms_akt."','".convert_ascii($id_aks)."')";
			}
			
		}

		if (!empty($check_akt_exist)) {
			$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 = 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;
				}
			}

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

			];
			$check_nim_exist = json_decode($db->run($data_req_mhs,$url_rest));
			if (!empty($check_nim_exist->data)) {
				foreach ($check_nim_exist->data as $nim_mhs) {
					$nim_data[convert_ascii($nim_mhs->nim).$nim_mhs->id_prodi] = array(
						'id_reg_pd' => $nim_mhs->id_registrasi_mahasiswa,
						'nama_mahasiswa' => $nim_mhs->nama_mahasiswa,
						'nim' => $nim_mhs->nim
					);
				}
			}
		}



		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_akt.convert_ascii($dt->id_aktivitas), array_keys($data_akt))) {
			if (in_array($nim.$id_sms, array_keys($nim_data))) {
				$id_reg_pd =  $nim_data[$nim.$id_sms]['id_reg_pd'];
				$array_aktivitas[] = array(
	              'id_registrasi_mahasiswa' => $id_reg_pd,
	              'id_aktivitas' => $data_akt[convert_ascii($dt->semester).$dt->id_sms_akt.convert_ascii($dt->id_aktivitas)],
/*	              'nm_pd' => $nim_data[$nim.$id_sms]['nama_mahasiswa'],
	              'nipd' => $nim_data[$nim.$id_sms]['nim'],*/
	              'jenis_peran' => $dt->jenis_peran,
	            );

				$data_kls[$dt->id_krs] = $dt->nim;

				$data_ids[] = $dt->id_krs;
			} else {
				$error_update_data[] = array(
					'keterangan' => "Error Mahasiswa dengan NIM $dt->nim Tidak Ditemukan di Feeder",
					'status_error' => 2
				);
				$data_id_error[] = $dt->id_krs;
			}


		} else {
				$error_update_data[] = array(
					'keterangan' => "Error $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_anggota',$error_update_data,'id',$data_id_error);
		}
		$error_update_data = array();
		$data_id_error = array();


		if (!empty($array_aktivitas)) {

			//echo "<pre>";
		foreach ($array_aktivitas as $key => $anggota) {
				$data_dic = [
			      'act' => 'InsertAnggotaAktivitasMahasiswa',
			        'token' => $token,
			        'record' => $anggota,
			    ];

				$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[$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, 'anggota_aktivitas_mahasiswa',json_encode($array_aktivitas));

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

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

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

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