<?php
session_start();
include "../../inc/config.php";
$json_response = array();
$jumlah = array();
$config_feeder = $db->fetch_single_row('config_user','id',1);
$id_sp = $config_feeder->id_sp;
$user_id = $config_feeder->id_user;

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 = "";
        $error_nipd = "";
        $msg = "";
        $error_restore= "";
        $id_reg_pd = "";
        $final_update=array();
        $final_up=array();
        $data_ids=array();
        $data_nipd=array();
        $all_id=array();
        $data_loop = array();
        $data_loop_check = array();
        $nim_data = array();
        $error_data = "";
		$error_update_data = array();
		$data_id_error = array();
		$update_data = array();
		$data_id_sukses = array();
		$check_prestasi_exist_concat = array();
		$array_exist_prestasi = array();

		$kode_prodi = $_POST['jurusan'];

		if ($kode_prodi=="all") {
			$jurusan = "";
			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 *,prestasi_mahasiswa.id from prestasi_mahasiswa inner join jurusan on prestasi_mahasiswa.kode_jurusan=jurusan.kode_jurusan where prestasi_mahasiswa.id is not null $jurusan and status_error!=1 $query_not_in limit 11");

			foreach ($datas as $dt_id) {
				//$nim_concat[convert_ascii($dt_id->nipd).$dt_id->id_sms] = "('".$dt_id->nipd."','".$dt_id->id_sms."')";
				$nim_like[$dt_id->nipd] = "nim like '%$dt_id->nipd%'";
				$sms_and[$dt_id->id_sms] = "('".$dt_id->id_sms."')";
				$data_loop[] = $dt_id;
				$data_loop_check[] = $dt_id;
				
			}


			//$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,
						'id_pd' => $nim_mhs->id_mahasiswa
					);
				}
			}

			foreach ($data_loop_check as $dt) {
				if (in_array(convert_ascii($dt->nipd).$dt->id_sms, array_keys($nim_data))) {
					$check_prestasi_exist_concat[] = "('".$nim_data[convert_ascii($dt->nipd).$dt->id_sms]['id_pd']."','".$dt->id_jns_prestasi."','".$dt->id_tkt_prestasi."','".$dt->thn_prestasi."')";

				}
			}

			if (!empty($check_prestasi_exist_concat)) {
				$prestasi_concat_where = implode(",", $check_prestasi_exist_concat);
				$data_req_prestasi = [
					'act' => 'GetListPrestasiMahasiswa',
				    'token' => $token,
				    'filter' => "(id_mahasiswa,id_jenis_prestasi,id_tingkat_prestasi,tahun_prestasi) in ($prestasi_concat_where)",
				    'order' => "",
				    'limit' => "",
				    'offset' => ""

				];
				$check_prestasi_exist = json_decode($db->run($data_req_prestasi,$url_rest));


				if (!empty($check_prestasi_exist->data)) {
					foreach ($check_prestasi_exist->data as $pres) {
						$penyelenggara = str_replace("'", '"', $pres->penyelenggara);
						$array_exist_prestasi[$pres->id_mahasiswa.$pres->id_jenis_prestasi.$pres->id_tingkat_prestasi.$pres->tahun_prestasi.$penyelenggara] = $pres->id_prestasi;
					}
				}
			}


		foreach ($data_loop as $value) {
		$nim = convert_ascii($value->nipd);


			//check if mhs exist
			if (in_array($nim.$value->id_sms, array_keys($nim_data))) {
				$id_pd = $nim_data[$nim.$value->id_sms]['id_pd'];
				$penyelenggara = str_replace("'", '"', $value->penyelenggara);


			if ($_POST['method']=='up') {
					$array_key = array(
						'id_prestasi' => $value->id_prestasi
					);
					$array_update_prestasi_mhs = array(
			             'id_jenis_prestasi' => $value->id_jns_prestasi,
						 'id_tingkat_prestasi' => $value->id_tkt_prestasi,
						 'id_mahasiswa' => $id_pd,
						 'nama_prestasi' => str_replace("'", '"', $value->nm_prestasi),
						 'tahun_prestasi' => $value->thn_prestasi,
						 'penyelenggara' => $penyelenggara,
						 'peringkat' => $value->peringkat
		            );
					$param_update = array(
						'act' => 'UpdatePrestasiMahasiswa',
						'key' => $array_key,
						'token' => $token,
						'record' => $array_update_prestasi_mhs
					);

					$update_prestasi_mhs = service_request($param_update);
					/*dump($param_update);
					dump($update_prestasi_mhs);*/
					$value_data = addslashes($update_prestasi_mhs->error_desc);
					if ($value_data!='') {
						$error_update_data[] = array(
							'keterangan' => $value_data,
							'status_error' => 2
						);
						$data_id_error[] =  $value->id;
					} else {
						$update_data[] = array(
							'keterangan' => '',
							'status_error' => 1
						);
						$data_id_sukses[] =  $value->id;
					}
			} else {
				if (in_array($id_pd.$value->id_jns_prestasi.$value->id_tkt_prestasi.$value->thn_prestasi.$penyelenggara, array_keys($array_exist_prestasi))) {
					$error_update_data[] = array(
						'keterangan' => "Prestasi ini sudah ada di feeder",
						'status_error' => 2
					);
					$data_id_error[] = $value->id;
				} else {
					if (strlen($value->nm_prestasi)>160) {
						$error_update_data[] = array(
							'keterangan' => 'Nama prestasi tidak boleh lebih dari 160 karakter',
							'status_error' => 2
						);
						$data_id_error[] =  $value->id;
					} else {
						$temp_data = array(
						 'id_jenis_prestasi' => $value->id_jns_prestasi,
						 'id_tingkat_prestasi' => $value->id_tkt_prestasi,
						 'id_mahasiswa' => $id_pd,
						 'nama_prestasi' => str_replace("'", '"', $value->nm_prestasi),
						 'tahun_prestasi' => $value->thn_prestasi,
						 'penyelenggara' => $penyelenggara,
						 'peringkat' => $value->peringkat,
						 //'id_aktivitas' => '3903dd12-9143-4af0-934f-cb4ae6cf88b4'
						);
						  $data_dic = [
						      'act' => 'InsertPrestasiMahasiswa',
						        'token' => $token,
						        'record' => $temp_data,
						    ];

						   // exit();
						$temp_recs = json_decode($db->run($data_dic,$url_rest));
/*dump($data_dic);
						dump($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[] =  $value->id;
								} else {
									$update_data[] = array(
										'keterangan' => '',
										'status_error' => 1
									);
									$data_id_sukses[] = $value->id;
									$db->update('prestasi_mahasiswa',array('id_prestasi' => $temp_recs->data->id_prestasi),'id',$value->id);
								}

					}
				}
			}
				
			} else {
					$error_update_data[] = array(
						'keterangan' =>"Error, mahasiswa dengan nipd $nim tidak ada di feeder",
						'status_error' => 2
					);
					$data_id_error[] = $value->id;
			}

		$all_id[] = $value->id;

	}



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

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

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

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

		$db->fetch_custom("update prestasi_mahasiswa set unik_id=0 where  unik_id=".$_POST['random_number']);
		
		$msg =  "<div class=\"alert alert-warning \" role=\"alert\">
		<font color=\"#3c763d\">".$jumlah_sukses." data Prestasi 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</span><p>";
	$jumlah['last_notif'] = $msg;
}

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