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

		$jurusan = "";
		$status_data  = "";
		$query_not_in = "";
		$nim_concat = array();
		$data_loop = array();
		$id_kelas_where = array();
		$id_kelas_feeder = array();
		$nim_data = array();
		$id_kls_reg_pd = array();
		$error_code = "";
		$data_krs = array();
		$data_ids = array();
		$error_update_data = array();
		$data_id_error = array();
		$data_nim = array();
		$id_kls_reg_pd_error = array();
		$update_data = array();
		$data_id_sukses = array();
		$data_krs_update = array();
		$data_ids_up = array();
		$jumlah_sukses = 0;
		$jumlah_error = 0;
		$all_errors = array();
		$msg = "";
		$id_krs = "";
		$all_id = array();
		$mhs_update = array();

		
		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_niks = $db->fetch_custom("select *,update_nik.id as id_krs from update_nik inner join jurusan on update_nik.kode_jurusan=jurusan.kode_jurusan where status_error!='1' $jurusan $query_not_in limit 35");

			foreach ($data_niks 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;
			}


			$nim_concat_where = implode(",", $nim_concat);
			$implode_nim_like = implode(" or ",$nim_like);
			$implode_prodi = implode(",",$sms_and);
			$data_req_mhs = [
				'act' => 'GetListMahasiswa',
			    'token' => $token,
			    //'filter' => "(trim(nim),id_prodi) in ($nim_concat_where)",
		    	'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,
						'id_pd' => $nim_mhs->id_mahasiswa,
						'nama_mahasiswa' => $nim_mhs->nama_mahasiswa
						);
				}
			}

		foreach ($data_loop as $value) {

			$nim = convert_ascii($value->nim);
			$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];
				$data_nik = array(
					/*'nik' => $value->nik,
					'no_hp' => $value->nik,
					'email' => $value->email,
					'jln' => $value->alamat,*/
				);
				foreach ($_POST['kolom_updated'] as $updt) {
					$data_nik['id_mahasiswa'] = $nim_data[$nim.$id_sms]['id_pd'];
					//$data_nik['nama_mahasiswa'] = $nim_data[$nim.$id_sms]['nama_mahasiswa'];
					$data_nik[$updt] = $value->{$updt};
					if (in_array('id_wil', array_keys($data_nik))) {
						$data_nik['id_wilayah'] = $value->id_wil;
						unset($data_nik['id_wil']);
					}
					if (in_array('no_hp', array_keys($data_nik))) {
						$data_nik['handphone'] = $value->no_hp;
						unset($data_nik['no_hp']);
					}
					if (in_array('jln', array_keys($data_nik))) {
						$data_nik['jalan'] = $value->jln;
						unset($data_nik['jln']);
					}
				}
				
					$mhs_update[] = $data_nik;
					//$mhs_update = array_merge($mhs_update,$data_nik);

					$data_ids[] = $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;
			}

					
			$all_id[] = $value->id_krs;		

		}


		if (!empty($error_update_data)) {
			updateMulti('update_nik',$error_update_data,'id',$data_id_error);
		}

		$error_update_data = array();
		$data_id_error = array();


if (!empty($mhs_update)) {

	//dump($mhs_update);

		foreach ($mhs_update as $key => $update_mhs) {
			//dump($update_mhs);
			$key_id['id_mahasiswa'] = $update_mhs['id_mahasiswa'];
			unset($update_mhs['id_mahasiswa']);
		$data_dic = [
	      'act' => 'UpdateBiodataMahasiswa',
	        'token' => $token,
	        'key' => $key_id,
	        'record' => $update_mhs,
	    ];

			$temp_recs = json_decode($db->run($data_dic,$url_rest));
/*			dump($data_dic);
			dump($temp_recs);*/
			$data_key = $data_ids[$key];
				$value_data = addslashes($temp_recs->error_desc);
				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->UpdateRecordset($token, 'mahasiswa',json_encode($mhs_update));
		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('update_nik',$error_update_data,'id',$data_id_error);
		}
		$error_update_data = array();
		$data_id_error = array();
		//update sukses
		if (!empty($update_data)) {
			updateMulti('update_nik',$update_data,'id',$data_id_sukses);
		}
		$update_data = array();
		$data_id_sukses = array();




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

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

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

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

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

			$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\">".$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