<?php
session_start();


include "../../inc/config.php";



$json_response = array();
$jumlah = array();
if ($_POST['total_data']>0) {
		//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;
		}

		$sem = "";
		$query_matkul = "";
		$query_kelas  = "";
		$jurusan = "";
		$status_data  = "";
		$query_not_in = "";
		$nim_concat = array();
		$nim_sms_concat = array();
		$data_loop_kelas = 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();
		$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 = "";
		$all_id = array();
		$all_krs_nilai = array();
		$id_kls_reg_pd_error = array();
		$data_krs_nilai = array();

		$data_update_nilai = array();
		$data_id_update_nilai = array();
		$data_update_nilai_temp = array();
		$data_nilai_temp_restore = array();

		$data_nilai_temp_restore_final = array();
		$data_id_final = array();


    	if ($_POST['sem']!='all') {
      		$sem = "and nilai.semester='".$_POST['sem']."'";
    	}

		if ($_POST['matkul']!='all') {
			$query_matkul = "and kode_mk='".$_POST['matkul']."'";
		}
		if ($_POST['kelas']!='all') {
			$query_kelas  = "and nama_kelas='".$_POST['kelas']."'";
		}
		
		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']."'";
			}
		}

		  if ($_POST['status_data']!='all') {
		    $status_data  = "and status_error='".$_POST['status_data']."'";
		  } else {
		    $status_data  = "and status_error!=1";
		  }

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

		$data_for_id_kelas = $db->fetch_custom("select *,nilai.id as id_krs from nilai inner join jurusan on nilai.kode_jurusan=jurusan.kode_jurusan where nilai.id is not null $sem $jurusan $status_data $query_matkul $query_kelas $query_not_in limit 19");


		
		foreach ($data_for_id_kelas as $dt_id) {
			//$id_kelas_array[] = $dt_id->id_krs;
			$nim_concat[convert_ascii($dt_id->nim)] = "('".$dt_id->nim."')";
			$nim_sms_concat[convert_ascii($dt_id->nim)] = "('".$dt_id->id_sms."','".$dt_id->nim."')";
			$data_loop_kelas[] = $dt_id;
			$id_kelas_where[$dt_id->id_sms.trim($dt_id->kode_mk).trim($dt_id->nama_kelas).$dt_id->semester] = "('".$dt_id->id_sms."','".trim($dt_id->kode_mk)."','".trim($dt_id->nama_kelas)."','".trim($dt_id->semester)."')";
		}




		$implode_id_kelas = implode(",", $id_kelas_where);
		$kelas_filter = "(p.id_sms,trim(kode_mk),trim(nm_kls),p.id_smt) IN ($implode_id_kelas)";
		$get_id_kelas = $proxy->GetRecordset($token,'kelas_kuliah',$kelas_filter,"","","");
		if (!empty($get_id_kelas['result'])) {
			foreach ($get_id_kelas['result'] as $dt_id_kelas) {
				$id_kelas_feeder[$dt_id_kelas['id_sms'].trim($dt_id_kelas['kode_mk']).trim($dt_id_kelas['nm_kls']).trim($dt_id_kelas['id_smt'])] = $dt_id_kelas['id_kls'];
			}
		}


		if ($_POST['metode_prodi']=='1') {
			$nim_concat_where = implode(",", $nim_sms_concat);
			$filter_mhs = "(id_prodi,trim(nim)) in ($nim_concat_where)";
		} else {
			$nim_concat_where = implode(",", $nim_concat);
			$filter_mhs = "trim(nim) in ($nim_concat_where)";
		}

		$data_req_mhs = [
			'act' => 'GetListMahasiswa',
		    'token' => $token,
		    'filter' => $filter_mhs,
		    '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_registrasi_mahasiswa;
			}
		}

	
		foreach ($data_loop_kelas as $value) {

			$nim = trim($value->nim);
			$kode_mk = trim($value->kode_mk);
			$kelas = trim($value->nama_kelas);
			$semester = $value->semester;
			$id_sms = trim($value->id_sms);

			//check if mhs exist
				if (in_array($nim, array_keys($nim_data))) {
					$id_reg_pd = $nim_data[$nim];

						if (in_array($id_sms.$kode_mk.$kelas.$semester, array_keys($id_kelas_feeder))) {
							$id_kls = $id_kelas_feeder[$id_sms.$kode_mk.$kelas.$semester];
							//echo $id_kls.'='.$id_reg_pd;
							$id_kls_reg_pd[$value->id_krs] = "('".$id_kls."'".",'".$id_reg_pd."')";
							$data_nim[$id_kls."#".$id_reg_pd] = $value->id_krs; 
						} else {
							$error_code = "Pastikan Kelas Sudah Dibuat";
						}

				} else {
					$error_code = "Nim Mahasiswa ini tidak ditemukan di feeder";
				}






			if ($error_code=="") {

					$temp_key = array(
						'id_kls' => $id_kls,
						'id_reg_pd' => $id_reg_pd
					);
			
					$temp_data = array(
						'nilai_angka' => $value->nilai_angka,
						'nilai_huruf' => $value->nilai_huruf,
						'nilai_indeks' => $value->nilai_indek
					);
					$all_krs_nilai[$value->id_krs] = array_merge($temp_key,$temp_data);
					$data_update_nilai_temp[$id_kls."#".$id_reg_pd] = array(
						'id_kls' => $id_kls,
						'id_reg_pd' => $id_reg_pd,
						'nilai_angka' => $value->nilai_angka,
						'nilai_huruf' => $value->nilai_huruf,
						'nilai_indeks' => $value->nilai_indek
					);
					
					if ($_POST['metode']=='in_krs') {
						$data_krs_nilai[] = array_merge($temp_key,$temp_data);
					} else {
						$data_krs[] = array('key'=>$temp_key,'data'=>$temp_data);
					}

					//sukses id
					$data_ids[] = $value->id_krs;

			} else {
					$error_update_data[] = array(
						'keterangan' => $error_code,
						'status_error' => 2
					);
					$data_id_error[] = $value->id_krs;
			}
					
			$all_id[] = $value->id_krs;

			$id_kls = "";
			$id_reg_pd = "";
			$error_code = "";

		}


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

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


		if (!empty($data_krs_nilai)) {

			$result = $proxy->InsertRecordset($token, 'nilai',json_encode($data_krs_nilai));
			
		
				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;
						$id_kls_reg_pd_error[$data_key] = $id_kls_reg_pd[$data_key];
						$data_update_nilai[] = array(
							'key'=> array(
								'id_kls' => $all_krs_nilai[$data_key]['id_kls'],
								'id_reg_pd' => $all_krs_nilai[$data_key]['id_reg_pd'],
							),
							'data'=> array(
								'nilai_angka' => $all_krs_nilai[$data_key]['nilai_angka'],
								'nilai_huruf' => $all_krs_nilai[$data_key]['nilai_huruf'],
								'nilai_indeks' => $all_krs_nilai[$data_key]['nilai_indeks']
							)
						);

						$data_id_update_nilai[] = $data_key;
					} else {
						$update_data[] = array(
							'keterangan' => '',
							'status_error' => 1
						);
						$data_id_sukses[] = $data_key;
					}

				}

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

		//update nilai if exist krs
		

		if (!empty($data_update_nilai)) {

			$result = $proxy->UpdateRecordset($token, 'nilai',json_encode($data_update_nilai));
				foreach ($result['result'] as $key => $value) {

					$value_data = addslashes($value['error_desc']);
					$data_key = $data_id_update_nilai[$key];

					if ($value_data!='') {
						$error_update_data[] = array(
							'keterangan' => $value_data,
							'status_error' => 2
						);
						$data_id_error[] = $data_key;
						$id_kls_reg_pd_error_new[] = $id_kls_reg_pd_error[$data_key];
					} else {
						$update_data[] = array(
							'keterangan' => '',
							'status_error' => 1
						);
						$data_id_sukses[] = $data_key;
					}

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

		if (!empty($id_kls_reg_pd_error_new)) {
			$implode_kls_reg = implode(",", $id_kls_reg_pd_error_new);
			$cek_krs = "(p.id_kls,p.id_reg_pd) IN ($implode_kls_reg)";
			$cek_deleted = $proxy->GetDeletedRecordset($token,'nilai',$cek_krs,"","","");
			if (!empty($cek_deleted['result'])) {
				foreach ($cek_deleted['result'] as $deleted) {
					$temp_data_up = array(
						'id_kls' =>  $deleted['id_kls'],
						'id_reg_pd' => $deleted['id_reg_pd']
					);
					$data_krs_update[] = $temp_data_up;
					$data_ids_up[] = $data_nim[$deleted['id_kls']."#".convert_ascii($deleted['id_reg_pd'])];
					$data_nilai_temp_restore[$data_nim[$deleted['id_kls']."#".convert_ascii($deleted['id_reg_pd'])]] = $data_update_nilai_temp[$deleted['id_kls']."#".convert_ascii($deleted['id_reg_pd'])];
				}
			}
		}


		if (!empty($data_krs_update)) {

			$result = $proxy->RestoreRecordset($token, 'nilai',json_encode($data_krs_update));


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

					$value_data = $value['error_desc'];
					$data_key = $data_ids_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;
						$data_nilai_temp_restore_final[] = array(
							'key'=> array(
								'id_kls' => $data_nilai_temp_restore[$data_key]['id_kls'],
								'id_reg_pd' => $data_nilai_temp_restore[$data_key]['id_reg_pd'],
							),
							'data'=> array(
								'nilai_angka' => $data_nilai_temp_restore[$data_key]['nilai_angka'],
								'nilai_huruf' => $data_nilai_temp_restore[$data_key]['nilai_huruf'],
								'nilai_indeks' => $data_nilai_temp_restore[$data_key]['nilai_indeks']
							)
						);
						$data_id_final[] = $data_key;

					}

				}

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


		if (!empty($data_nilai_temp_restore_final)) {

			$result = $proxy->UpdateRecordset($token, 'nilai',json_encode($data_nilai_temp_restore_final));
			
		
				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('nilai',$error_update_data,'id',$data_id_error);
			}
			$error_update_data = array();
			$data_id_error = array();
			//update sukses
			if (!empty($update_data)) {
				updateMulti('nilai',$update_data,'id',$data_id_sukses);
			}
			$update_data = array();
			$data_id_sukses = array();
		}

		if (!empty($data_krs)) {

			//echo "<pre>";
			//print_r($data_krs);
			

		/*	foreach ($data_krs as $key => $dt_krs) {
	            $record['nilai_angka'] = $dt_krs['data']['nilai_angka'];
	            $record['nilai_indeks' ] = $dt_krs['data']['nilai_indeks'];
	            $record['nilai_huruf' ] = $dt_krs['data']['nilai_huruf'];

				$key_input['id_registrasi_mahasiswa'] = $dt_krs['key']['id_reg_pd'];
				$key_input['id_kelas_kuliah'] = $dt_krs['key']['id_kls'];
				  $data_dic = [
				      'act' => 'UpdateNilaiPerkuliahanKelas',
				      'key' => $key_input,
				        'token' => $token,
				        'record' => $record,

				    ];
			$temp_recs = json_decode($db->run($data_dic,$url_rest));
			$data_key = $data_ids[$key];
			$value_data = addslashes($temp_recs->error_desc);

			if ($temp_recs->error_desc!='') {
				$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;
			}
			//print_r($temp_recs);

			}*/

			//exit();

			$result = $proxy->UpdateRecordset($token, 'nilai',json_encode($data_krs));
			
		
				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('nilai',$error_update_data,'id',$data_id_error);
			}
			$error_update_data = array();
			$data_id_error = array();
			//update sukses
			if (!empty($update_data)) {
				updateMulti('nilai',$update_data,'id',$data_id_sukses);
			}
			$update_data = array();
			$data_id_sukses = array();
				
		}



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

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

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

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