<?php
session_start();
include "../../inc/config.php";
$json_response = array();
if ($_POST['total_data']>0) {
		$jumlah = array();
		$url_rest = get_service_url('rest');
		$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();
		$data_deleted = array();
		$nim_data = array();
		$id_akm = array();
		$final_update = array();
		$final_up = 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();
		$check_akm_exist_concat = array();
		$check_akm_exist_concat_del = array();
		$restore_data = array();
		$data_loop_check = array();
		$data_loop_check_deleted = array();
		$array_exist_akm = array();
		$data_id_akm_deleted = array();
		$id_restore_akm = 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 16");

		foreach ($datas as $dt_id) {
			$nim_concat[convert_ascii($dt_id->nim).$dt_id->id_sms] = "('".$dt_id->nim."','".convert_ascii($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[] = $dt_id;
			$data_loop_check[] = $dt_id;
			$data_loop_check_deleted[] = $dt_id;
		}

 		$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 = "(trim(nim),id_prodi) in ($nim_concat_where)";
			$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));

/*		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_loop_check as $dt) {
				if (in_array(convert_ascii($dt->nim).$dt->id_sms, array_keys($nim_data))) {
					$check_akm_exist_concat[] = "('".$nim_data[convert_ascii($dt->nim).$dt->id_sms]."','".$dt->semester."')";

				}
			}

/*			if (!empty($check_akm_exist_concat)) {
				$akm_concat_where = implode(",", $check_akm_exist_concat);
				$data_req_akm = [
					'act' => 'GetAktivitasKuliahMahasiswa',
				    'token' => $token,
				    'filter' => "(id_registrasi_mahasiswa,id_semester) in ($akm_concat_where)",
				    'order' => "",
				    'limit' => "",
				    'offset' => ""

				];
				$check_akm_exist = json_decode($db->run($data_req_akm,$url_rest));
				if (!empty($check_akm_exist->data)) {
					foreach ($check_akm_exist->data as $akm) {
						$array_exist_akm[convert_ascii($akm->nim).$akm->id_prodi] = $akm->id_registrasi_mahasiswa;
					}
				}
			}*/

function updateNativeArray($data)
{
    $datas = [
 		  "id_smt" => $data->semester,
		  "id_stat_mhs" => $data->status_kuliah,
		  "ips" => $data->ips,
		  "sks_smt" => $data->sks_smt,
		  "ipk" => $data->ipk,
		  "sks_total" => $data->sks_total,
		  "biaya_smt" => $data->biaya_smt,
		 // "nim" => $data->nim
    ];
    return $datas;
}
$config_feeder = $db->fetch_single_row('config_user','id',1);
function updateNative($data,$param) {
    global $config_feeder;
    global $token;
    $return_data = array();
    $url = $config_feeder->url.':'.$config_feeder->port.'/ws/kuliahmhs/edit?id_reg_pd='.$param['id_reg_pd'].'&id_smt='.$param['id_smt'];
  
    $insert_reg = service_native($data,$url,'PUT');
/*    dump($data);
    dump($insert_reg);*/
    if (property_exists($insert_reg, 'message')) {
      if ($insert_reg->code==200) {
        $return_data = array(
            'error' => '',
            'id_registrasi_mahasiswa' => $insert_reg->data->id_reg_pd
        );
      } else {
        $return_data = array(
            'error' => $insert_reg->message,
            'id_registrasi_mahasiswa' => ''
        );
      }

    } else {
        $return_data = array(
            'error' => 'Gagal di import, pastikan data sesuai template',
            'id_registrasi_mahasiswa' => ''
        );
    }

/*    if ($insert_reg->code==200) {
        $return_data = array(
            'error' => '',
            'id_registrasi_mahasiswa' => $insert_reg->data->id_reg_pd
        );
    } else {
        $return_data = array(
            'error' => $insert_reg->message,
            'id_registrasi_mahasiswa' => ''
        );
    }*/
    return $return_data;
}
 
function addNative($data) {
    global $config_feeder;
    global $token;
    $return_data = array();
    $url = $config_feeder->url.':'.$config_feeder->port.'/ws/kuliahmhs/add';
  
    $insert_reg = service_native($data,$url,'POST');
/*    dump($data);
    dump($insert_reg);*/
    if (property_exists($insert_reg, 'message')) {
      if ($insert_reg->code==200) {
        $return_data = array(
            'error' => '',
            'id_registrasi_mahasiswa' => $insert_reg->data->id_reg_pd
        );
      } else {
        $return_data = array(
            'error' => $insert_reg->message,
            'id_registrasi_mahasiswa' => ''
        );
      }

    } else {
        $return_data = array(
            'error' => 'Gagal di import, pastikan data sesuai template',
            'id_registrasi_mahasiswa' => ''
        );
    }

/*    if ($insert_reg->code==200) {
        $return_data = array(
            'error' => '',
            'id_registrasi_mahasiswa' => $insert_reg->data->id_reg_pd
        );
    } else {
        $return_data = array(
            'error' => $insert_reg->message,
            'id_registrasi_mahasiswa' => ''
        );
    }*/
    return $return_data;
}
		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 ($value->biaya_smt=="") {
				$biaya = '0';
			} else {
				$biaya = $value->biaya_smt;
			}

			if ($_POST['method']=='up') {
				$array_key = array(
								'id_semester' => $value->semester, 
								'id_registrasi_mahasiswa' => $nim_data[$nim.$value->id_sms]
							);
							$array_data = array(
									'id_status_mahasiswa' => $value->status_kuliah,
									'ips' => $value->ips,
									'ipk' => $value->ipk,
									'sks_semester' => $value->sks_smt,
									'total_sks' => $value->sks_total,
									'biaya_kuliah_smt' => $biaya,
									'id_pembiayaan' => $value->id_pembiayaan
							);
							  $data_dic_update = [
							      'act' => 'UpdatePerkuliahanMahasiswa',
							      'key' => $array_key,
							        'token' => $token,
							        'record' => $array_data,

							    ];
								$temp_recs = service_request($data_dic_update);
/*					dump($data_dic_update);
					dump($temp_recs);*/
								$value_data = addslashes($temp_recs->error_desc);
								if ($value_data!='') {
									$error_update_data[] = array(
										'keterangan' => $value_data,
										'status_error' => 2
									);
									$data_id_error[] = $value->id_akm;
								} else {
									$update_data[] = array(
										'keterangan' => '',
										'status_error' => 1
									);
									$data_id_sukses[] = $value->id_akm;
								}
			} else {
				$temp_data = array(
									'id_registrasi_mahasiswa' => $nim_data[$nim.$value->id_sms],
									'id_semester' => $value->semester,
									'id_status_mahasiswa' => $value->status_kuliah,
									'ips' => $value->ips,
									'ipk' => $value->ipk,
									'sks_semester' => $value->sks_smt,
									'total_sks' => $value->sks_total,
									'biaya_kuliah_smt' => $biaya,
									'id_pembiayaan' => $value->id_pembiayaan
									);
								  $data_dic = [
								      'act' => 'InsertPerkuliahanMahasiswa',
								        'token' => $token,
								        'record' => $temp_data,
								    ];
							   // exit();
								$temp_recs = service_request($data_dic);
								$value_data = addslashes($temp_recs->error_desc);
								if ($value_data!='') {
									$error_update_data[] = array(
										'keterangan' => $value_data,
										'status_error' => 2
									);
									$data_id_error[] = $value->id_akm;
								} else {
									$array_key = array(
										'id_semester' => $value->semester, 
										'id_registrasi_mahasiswa' => $nim_data[$nim.$value->id_sms]
									);
									$array_data = array(
											'id_status_mahasiswa' => $value->status_kuliah,
											'ips' => $value->ips,
											'ipk' => $value->ipk,
											'sks_semester' => $value->sks_smt,
											'total_sks' => $value->sks_total,
											'biaya_kuliah_smt' => $biaya,
											'id_pembiayaan' => $value->id_pembiayaan
									);
									  $data_dic_update = [
									      'act' => 'UpdatePerkuliahanMahasiswa',
									      'key' => $array_key,
									        'token' => $token,
									        'record' => $array_data,

									    ];
									$temp_recs = service_request($data_dic_update);
									$update_data[] = array(
										'keterangan' => '',
										'status_error' => 1
									);
									$data_id_sukses[] = $value->id_akm;
								}
			}

						/*if (in_array($nim.$value->id_sms, array_keys($array_exist_akm))) {
							
						} else {
							

						}*/
		} else {
			$error_update_data[] = array(
				'keterangan' => "Mahasiswa ini tidak ada di feeder",
				'status_error' => 2
			);
			$data_id_error[] = $value->id_akm;
		}

			$all_id[] = $value->id_akm;
	}
		//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);
?>