<?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 15");

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

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

 		//$nim_concat_where = addslashes($nim_concat_where);

			$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_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 insertRegPdNativeArray($biodata,$additional_data)
{
    global $id_sp;
    global $user_id;
    global $id_pt_array;
    global $id_prodi_array;
    $biodatas = [
        "nipd" => $biodata->nipd,
        "jenis_daftar" => array('id_jns_daftar' => $biodata->id_jns_daftar),
        "jalur_masuk" => array('id_jalur_masuk' => $biodata->id_jalur_masuk),
        "pembiayaan" => array('id_pembiayaan' => $biodata->id_pembiayaan),
        "periode_pendaftaran" => $biodata->mulai_smt,
        "tgl_masuk" => $biodata->tgl_masuk_sp,
        "id_perguruan_tinggi" => $id_sp,
        "prodi" => array('id_sms' => $biodata->id_sms),
        "user" => array('id_sp' => $id_sp,'userid' => $user_id),
        "detail" => array('id_pd' => $additional_data['id_mahasiswa']),
        "biaya_masuk_kuliah"  => $biodata->biaya_masuk_kuliah
    ];
    if ($biodata->id_jns_daftar!='1') {
        $biodatas['sks_diakui'] = $biodata->sks_diakui;
        if (in_array(convert_ascii($biodata->kode_pt_asal), array_keys($id_pt_array))) {
            $biodatas["asal_perguruan_tinggi"] = array('id_sp' => $id_pt_array[convert_ascii($biodata->kode_pt_asal)]['id_sp'],'nm_lemb' => $id_pt_array[convert_ascii($biodata->kode_pt_asal)]['nm_lemb']);
        }
        if (in_array(convert_ascii($biodata->kode_pt_asal).convert_ascii($biodata->kode_prodi_asal), array_keys($id_prodi_array))) {
           $biodatas["asal_program_studi"] = array('id_sms' => $id_prodi_array[convert_ascii($biodata->kode_pt_asal).convert_ascii($biodata->kode_prodi_asal)]['id_sms'],'nm_lemb' => $id_prodi_array[convert_ascii($biodata->kode_pt_asal).convert_ascii($biodata->kode_prodi_asal)]['nm_lemb']);
        }
    }
/*    if ($biodata->id_jns_daftar!='1') {
        $array_pindah = array(
            "sks_diakui" => $biodata->sks_diakui,
            "asal_perguruan_tinggi" => array('id_sp' => $id_pt_array[convert_ascii($biodata->kode_pt_asal)]['id_sp'],'nm_lemb' => $id_pt_array[convert_ascii($biodata->kode_pt_asal)]['nm_lemb'])
        );

        if (in_array(convert_ascii($biodata->kode_pt_asal).convert_ascii($biodata->kode_prodi_asal), array_keys($id_prodi_array))) {
            $array_pindah["asal_program_studi"] = array('id_sms' => $id_prodi_array[convert_ascii($biodata->kode_pt_asal).convert_ascii($biodata->kode_prodi_asal)]['id_sms'],'nm_lemb' => $id_prodi_array[convert_ascii($biodata->kode_pt_asal).convert_ascii($biodata->kode_prodi_asal)]['nm_lemb']);
        }
        $biodatas = array_merge($biodatas,$array_pindah);
    }*/
    return $biodatas;
}

function updateNativeArray($data,$additional_data)
{
    $datas = [
 		  "id_smt" => $data->semester,
 		  "id_reg_pd" => $additional_data['id_reg_pd'],
		  "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,
		  "id_pembiayaan" => "1",
		  "id_sms" => $additional_data['id_sms'],
		  "list_mahasiswa" => array(
		  	"id_reg_pd" => $additional_data['id_reg_pd']
		  )
    ];
    return $datas;
}
function responseCheckNative($data) {
   // dump($data);
    $return_array = array();
    $return_array['data'] = array();
    $return_array['is_error'] = 1;
    if (isset($data->message)) {
        if ($data->code=='200') {
            $return_array['is_error'] = 0;
            $return_array['data'] = array(
                'keterangan' => '',
                'status_error' => 1
            );
        } else {
            $return_array['data'] = array(
                'keterangan' => $data->message,
                'status_error' => 2
            );
        }
    } else {
            $return_array['data'] = array(
                'keterangan' => 'Error',
                'status_error' => 2
            );
    }

    

    return $return_array;
}

$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');
/*
    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 $insert_reg;
}
 
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 (in_array($nim.$value->id_sms, array_keys($array_exist_akm))) {
							$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
							);
							$update_data = updateNativeArray($value,array(
								'id_reg_pd' => $nim_data[$nim.$value->id_sms],
								'id_sms' => $value->id_sms
							));
							$update_native = updateNative($update_data,
								array(
									'id_reg_pd' => $nim_data[$nim.$value->id_sms],
									'id_smt' => $value->semester
								)
							);
							
							$check_responses = responseCheckNative($update_native);
		                    if ($check_responses['is_error']==0) {
		                        $success_insert[] = $check_responses['data'];
		                        $success_insert_id[] = $value->id_akm;
		                    } else {
		                        $error_insert[] = $check_responses['data'];
		                        $error_insert_id[] = $value->id_akm;
		                    }
							/*dump($update_data);
							dump($update_native);
							exit();*/
							 /* $data_dic_update = [
							      'act' => 'UpdatePerkuliahanMahasiswa',
							      'key' => $array_key,
							        'token' => $token,
							        'record' => $array_data,

							    ];
								$temp_recs = service_request($data_dic_update);
								$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;
								}

						}
		} 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_insert)) {
        updateMulti("nilai_akm", $error_insert, "id", $error_insert_id);
    }
    $error_insert = [];
    $error_insert_id = [];
    //update sukses
    if (!empty($success_insert)) {
        updateMulti("nilai_akm", $success_insert, "id", $success_insert_id);
    }
    $success_insert = [];
    $success_insert_id = [];

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