<?php
session_start();


include "../../inc/config.php";
 
$json_response = array();

if ($_POST['total_data']>0) {

		$jumlah = array();

		//soap
		$client = new nusoap_client(get_service_url('soap'), true);
		$url_rest = get_service_url('rest');
		$proxy = $client->getProxy();


		$offset = $_POST['offset'];
		$token = $_POST['token'];

		$jumlah['offset'] = $offset;
		$jumlah['token'] = $_POST['token'];

		if ($offset==0) {
			$token = get_token();
		    $jumlah['token'] = $token;
		}


		$sukses_count = 0;
		$error_count = 0;

		$error_msg = array();
		$nim_data = array();
		$id_akm = array();
		$final_update = array();
		$final_update_restore = array();
		$data = array();
		$all_errors = array();
		$nim_concat = array();
		$id_reg_pd_smt  = array();
		$all_id = array();
		$id_reg_pd_smt = array();
		$restore_data = array();

		$error_code = "";

		$sem = "";
		$jurusan = "";

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

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

		$datas = $db->fetch_custom("select *,nilai_akm.id as id_akm from nilai_akm inner join jurusan on nilai_akm.kode_jurusan=jurusan.kode_jurusan where nilai_akm.id is not null $sem $jurusan and status_error!=1 $query_not_in limit 11");

		foreach ($datas as $dt_id) {
			$nim_concat[convert_ascii($dt_id->nim).$dt_id->id_sms] = "('".$dt_id->nim."','".$dt_id->id_sms."')";
			$data[] = $dt_id;
		}

 		$nim_concat_where = implode(",", $nim_concat);

			$data_req_mhs = [
				'act' => 'GetListMahasiswa',
			    'token' => $token,
			    'filter' => "(trim(nim),id_prodi) in ($nim_concat_where)",
			    'order' => "",
			    'limit' => "",
			    'offset' => ""

			];


		$check_nim_exist = json_decode($db->run($data_req_mhs,$url_rest));

		/*echo "<pre>";
		print_r($data_req_mhs);
		print_r($check_nim_exist);
*/
		if ($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;
			}
		}


		foreach ($data as $value) {
			$nim = convert_ascii($value->nim);
		if (in_array($nim.$value->id_sms, array_keys($nim_data))) {
			$data_id_akm[$nim_data[$nim.$value->id_sms]."#".$value->semester] = $value->id_akm;
			if ($_POST['method']=='up') {
						$array_key = array('id_smt' => $value->semester, 'id_reg_pd' => $nim_data[$nim.$value->id_sms]);
						$array_data = array(
									  'ips' => $value->ips,
									  'sks_smt' => $value->sks_smt,
									  'ipk' => $value->ipk,
									  'sks_total' => $value->sks_total,
									  'id_stat_mhs' => $value->status_kuliah,
									  'biaya_smt' => $value->biaya_smt
									);
						$final_update[] = array('key' => $array_key, 'data' => $array_data
							);
					$data_id_up[] = $value->id_akm;
					$data_nim_up[$value->id_akm] = $nim; 
					} else {

					$id_reg_pd_smt[$value->id_akm] = "('".$nim_data[$nim.$value->id_sms]."'".",'".$value->semester."')";

					$temp_data = array(
						'id_smt' => $value->semester,
						  'id_reg_pd' => $nim_data[$nim.$value->id_sms],
						  		'ips' => $value->ips,
						  	'sks_smt' => $value->sks_smt,
						  		'ipk' => $value->ipk,
						  'sks_total' => $value->sks_total,
						 'id_stat_mhs' => $value->status_kuliah,
						 'biaya_smt' => $value->biaya_smt
						);
					$final_up[] = $temp_data;
					$all_akm[$value->id_akm] = $temp_data;
					$data_ids[] =  $value->id_akm;
					$data_nim[$value->id_akm] = $nim; 
					}
		} else {
			$error_code = "Mahasiswa ini tidak ada di feeder";
		}


		if ($error_code!="") {
				$error_update_data[] = array(
					'keterangan' => $error_code,
					'status_error' => 2
				);
				$data_id_error[] = $value->id_akm;
				
		} 

			$all_id[] = $value->id_akm;
			$error_code = "";
			$error_restore = "";
			$id_reg_pd = "";

	}


		if (!empty($final_up)) {
			$result = $proxy->InsertRecordset($token, 'kuliah_mahasiswa',json_encode($final_up));

				if (isset($result['result'])) {
					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;
						}

					}
				}
				 else {
					echo "<pre>";
					print_r($result);
					echo "</pre>";
				}

		

		}

//if method is insert
	if ($_POST['method']!='up') {
		if (!empty($id_reg_pd_smt)) {
			$implode_reg = implode(",", $id_reg_pd_smt);
			$filter_nim = "(p.id_reg_pd,p.id_smt) IN ($implode_reg)";
			$check_delete = $proxy->GetDeletedRecordset($token,'kuliah_mahasiswa',$filter_nim,"","","");
			if (!empty($check_delete['result'])) {
				if ($check_delete['result']) {
						foreach ($check_delete['result'] as $deleted) {
							$restore_data[] = array('id_reg_pd' => $deleted['id_reg_pd'],'id_smt' => $deleted['id_smt']);
							$id_restore_akm[] = $data_id_akm[$deleted['id_reg_pd']."#".$deleted['id_smt']];
						}
					}

			}

		}

	if (!empty($restore_data)) {
		$restore = $proxy->RestoreRecordset($token,'kuliah_mahasiswa',json_encode($restore_data));
		
		foreach ($restore['result'] as $key => $value) {
			$value_data = addslashes($value['error_desc']);
			$data_key = $id_restore_akm[$key];

			if ($value_data!='') {
				$error_update_data[] = array(
					'keterangan' => $value_data,
					'status_error' => 2
				);
				$data_id_error[] = $data_key;
			} else {
				$array_key = array('id_smt' => $value['id_smt'], 'id_reg_pd' => $value['id_reg_pd']);
				$array_data = array(
							  	'ips' => $all_akm[$data_key]['ips'],
							  	'sks_smt' => $all_akm[$data_key]['sks_smt'],
							  	'ipk' => $all_akm[$data_key]['ipk'],
							  	'sks_total' => $all_akm[$data_key]['sks_total'],
							 	'id_stat_mhs' => $all_akm[$data_key]['id_stat_mhs'],
							 	'biaya_smt' => $all_akm[$data_key]['biaya_smt']
							);
				$final_update_restore[] = array('key' => $array_key, 'data' => $array_data);
				$data_id_akm_restore[] = $data_key;
			}

		}
	}

	}


if (!empty($final_update_restore)) {

			$result = $proxy->UpdateRecordset($token, 'kuliah_mahasiswa',json_encode($final_update_restore));

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

					$value_data = addslashes($value['error_desc']);
					$data_key = $data_id_akm_restore[$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($final_update)) {

			$result = $proxy->UpdateRecordset($token, 'kuliah_mahasiswa',json_encode($final_update));

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

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

		$implode_id = implode(",", $all_id);
		$db->fetch_custom("update nilai_akm 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_akm where unik_id=".$_POST['random_number']);

		$sukses_count = $jml_error_sukses->jml_sukses;
		$error_count = $jml_error_sukses->jml_error;

		$jumlah_sukses = $sukses_count;
		$jumlah_error = $error_count;
		$db->fetch_custom("update krs set unik_id=0 where  unik_id=".$_POST['random_number']);
		$msg =  "<div class=\"alert alert-warning \" role=\"alert\">
		<font color=\"#3c763d\">".$jumlah_sukses." data AKM 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\">".$i.". ".$pesan."</div><br />";
					$i++;
					}
		$msg .= "</div>
		</div>";


		$jumlah['last_notif'] = $msg;
	}


} else {
	$msg =  "<span style='color:#f00'>Tidak ada data yang bisa diproses atau data masih ada yang belum valid</span><p>";
	$jumlah['last_notif'] = $msg;
}

array_push($json_response, $jumlah);
echo json_encode($json_response);
?>