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

		$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();
		$id_kls_reg_pd_error = 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 = "";
		$id_krs = "";
		$all_id = array();
		$data_for_id_kelas = array();

    	if ($_POST['sem']!='all') {
      		$sem = "and krs.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(krs.kode_jurusan_kelas)='".trim($_POST['jurusan'])."'";
		} else {
			if ($_SESSION['level']!=1) {
				$jurusan = "and trim(krs.kode_jurusan_kelas)='".$_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 krs.*,jurusan.id_sms as id_sms_kelas,krs.id as id_krs,
		(select id_sms from jurusan where jurusan.kode_jurusan=krs.kode_jurusan) as id_sms_mhs from krs inner join jurusan on krs.kode_jurusan_kelas=jurusan.kode_jurusan
		 where krs.id is not null $sem $jurusan $status_data $query_matkul $query_kelas $query_not_in limit 69");

			foreach ($data_for_id_kelas as $dt_id) {
				//$nim_concat[convert_ascii($dt_id->nim)] = "('".$dt_id->nim."')";
				//$nim_sms_concat[convert_ascii($dt_id->nim)] = "('".$dt_id->nim."','".$dt_id->id_sms_mhs."')";
				$nim_like[$dt_id->nim] = "nim like '%$dt_id->nim%'";
				$sms_and[$dt_id->id_sms_mhs] = "('".$dt_id->id_sms_mhs."')";
				$id_kelas_where[$dt_id->id_sms_kelas.trim($dt_id->kode_mk).trim($dt_id->nama_kelas).$dt_id->semester] = "('".$dt_id->id_sms_kelas."','".trim($dt_id->kode_mk)."','".trim($dt_id->nama_kelas)."','".trim($dt_id->semester)."')";
				$data_loop_kelas[] = $dt_id;
			}

			$implode_id_kelas = implode(",", $id_kelas_where);
			$kelas_filter = "(id_prodi,trim(kode_mata_kuliah),trim(nama_kelas_kuliah),id_semester) IN ($implode_id_kelas)";

			$data_req_kelas = [
				'act' => 'GetDetailKelasKuliah',
			    'token' => $token,
			    'filter' => $kelas_filter,
			    'order' => "",
			    'limit' => "",
			    'offset' => ""

			];
			$check_kelas_exist = json_decode($db->run($data_req_kelas,$url_rest));
/*			dump($data_req_kelas);
			dump($check_kelas_exist);*/
			if (!empty($check_kelas_exist->data)) {
				foreach ($check_kelas_exist->data as $dt_id_kelas) {
				$id_kelas_feeder[$dt_id_kelas->id_prodi.convert_ascii($dt_id_kelas->kode_mata_kuliah).convert_ascii($dt_id_kelas->nama_kelas_kuliah).convert_ascii($dt_id_kelas->id_semester)] = $dt_id_kelas->id_kelas_kuliah;
				}
			}

/*			$nim_concat_where = implode(",", $nim_concat);
			$filter_mhs = "trim(nim) in ($nim_concat_where)";*/
/*		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)";
		}*/
		//$nim_concat_where = implode(",", $nim_sms_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));
		if (!empty($check_nim_exist->data)) {
			foreach ($check_nim_exist->data as $nim_mhs) {
				$nim_data[convert_ascii($nim_mhs->nim).'n'] = $nim_mhs->id_registrasi_mahasiswa;
			}
		}

		foreach ($data_loop_kelas as $value) {

			$nim = convert_ascii($value->nim).'n';
			$kode_mk = convert_ascii($value->kode_mk);
			$kelas = convert_ascii($value->nama_kelas);
			$semester = $value->semester;
			$id_sms = convert_ascii($value->id_sms_kelas);

			//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];
							$data_krs = array(
								'id_kelas_kuliah' => $id_kls,
								'id_registrasi_mahasiswa' => $id_reg_pd,
								//'asal_data' => 9
								);
							  $data_dic_krs = [
							      'act' => 'InsertPesertaKelasKuliah',
							        'token' => $token,
							        'record' => $data_krs,
							    ];

							$temp_recs_krs = json_decode($db->run($data_dic_krs,$url_rest));
							$value_data = addslashes($temp_recs_krs->error_desc);
							if ($value_data!='') {
									$error_update_data[] = array(
										'keterangan' => $value_data,
										'status_error' => 2
									);
									$data_id_error[] = $value->id_krs;
							} else {
								$update_data[] = array(
									'keterangan' => '',
									'status_error' => 1
								);
								$data_id_sukses[] = $value->id_krs;
							}

					} else {
						$error_update_data[] = array(
							'keterangan' => "Pastikan Kelas Sudah Dibuat",
							'status_error' => 2
						);
						$data_id_error[] = $value->id_krs;
					}

			} else {
				$error_update_data[] = array(
					'keterangan' => "Nim Mahasiswa ini tidak ditemukan di feeder",
					'status_error' => 2
				);
				$data_id_error[] = $value->id_krs;
			}

					
			$all_id[] = $value->id_krs;

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

		}

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

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

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

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

		$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 KRS 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