<?php
session_start();


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


$json_response = 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();
		$token = get_token();

		$error_kelas = "";

			$sukses_count = 0;
	
		$error_count = 0;
		$error_count_in = 0;

		$error_msg = array();
		$data_mat_key = array();
				$error_mk = "";
	
		$update_data = array();
		$update_data_status = array();
		$update_data_er =array();
		$update_data_er_status =array();


		//matkur
		$update_data_matkur = array();
		$update_data_status_matkur = array();
		$update_data_er_matkur =array();
		$update_data_er_status_matkur =array();


		$data_id_sukses = array();
		$data_id_error= array();

		$data_id_sukses_matkur = array();
		$data_id_sukses_matkur = array();
		$data_id_error_matkur= array();
	
		$all_errors = array();
		$all_error = array();
		$query_not_in = "";
		$id_mk = "";
		$error_mk = "";

		$msg = "";


		$total_error=0;
		$sukses_count=0;
		$error_msg=0;


		$query_not_in = "";
		$sukses_count = 0;
	
		$error_count = 0;
		$error_count_in = 0;
		$sukses_count_kur = 0;

		$error_msg = array();

		$kur_id = "";
		$id_kur = "";
		$id_kurikulum = "";
		$data_id_parsial = array();
		$error_msg_kur = array();
		$error_msg_matkur = array();

		$data_mk = array();
		$data_id_mk = array();
		$error_count_kur = 0;
		$error_count_mat_kur = 0;
		$sukses_count_mat_kur = 0;

		$data_mat_kur_parsial = array();
		$data_mat_kur_parsial_second = array();
		$data_mat_kur = array();
		$data_mat_kur_parsial_third = array();
		$data_mat = array();
		$msg = "";
		$check_matkul = array();
		$data_mat_kur_restore = array();
		$data_mat_kur_restore_update = array();
		$data_id_restore = array();
		$check_mat_kur = array();
		$data_mat_kur_check = array();
		$data_loop = array();
		$data_deleted = array();

		$all_id = array();

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

		$data_ids = array();


	if ($_POST['offset']==0) {
			$value = $db->fetch_custom_single("select kurikulum.*,jurusan.kode_jurusan,id_sms,id_jenj_didik from kurikulum 
inner join jurusan on kurikulum.kode_jurusan=jurusan.kode_jurusan 
where jurusan.kode_jurusan='".$_POST['jurusan']."' and kurikulum.id='".$_POST['id_kur']."'");

					$id_sms = $value->id_sms;
					$id_jenj_didik = $value->id_jenj_didik;
					$nama_kurikulum = $value->nama_kur;
					$jml_sks_wajib = $value->jml_sks_wajib;
					$jml_sks_pilihan = $value->jml_sks_pilihan;
					$mulai_berlaku = $value->mulai_berlaku;
		
			$filter_check = "id_sms='".$id_sms."' and id_jenj_didik='".$id_jenj_didik."' and id_smt='".$mulai_berlaku."' and soft_delete='0'";
			$temp_check = $proxy->GetRecord($token,'kurikulum',$filter_check);

			if ($temp_check['result']) {
			$id_kur = $temp_check['result']['id_kurikulum_sp'];
			$error_msg_kur[] = "<b>Error Kurikulum ini Sudah Ada di Feeder</b>";
			$db->update('kurikulum',array('status_error' => 2, 'keterangan'=>"Kurikulum sudah ada di Feeder"),'id',$value->id);
				++$error_count_kur;
			} else {
					//var_dump($temp_kls['result']);
			$temp_data = array(
				'nm_kurikulum_sp' => $nama_kurikulum,
				'jml_sks_wajib' => $jml_sks_wajib,
				'jml_sks_pilihan' => $jml_sks_pilihan,
				'jml_sks_lulus' => $jml_sks_wajib+$jml_sks_pilihan,
				'id_smt' => $mulai_berlaku,
				'id_jenj_didik' => $id_jenj_didik,
				'id_sms' => $id_sms,
				);

			$insert_kur = $proxy->InsertRecord($token, "kurikulum", json_encode($temp_data));

			if ($insert_kur['result']['error_desc']==NULL) {
				$id_kur = $insert_kur['result']['id_kurikulum_sp'];
				$db->update('kurikulum',array('status_error'=>1,'keterangan'=>''),'id',$value->id);
				++$sukses_count_kur;
			} else {
				$error_msg_kur[] = "<b>Error ".$insert_kur['result']['error_desc'];
				$db->update('kurikulum',array('status_error' => 2, 'keterangan'=>"Error ".$insert_kur['result']['error_desc']),'id',$value->id);
				++$error_count_kur;
			}
			
		}
		$id_kurikulum = $id_kur;

	} else {
		$id_kurikulum = $_POST['kur_id'];
	}


		if (!empty($_POST['all_id'])) {
			$trim_data_id = rtrim($_POST['all_id'], ',');
			$query_not_in = "and mat_kurikulum.id not in(".$trim_data_id.")";

		}


		$data = $db->fetch_custom("select kurikulum.*,mat_kurikulum.*,mat_kurikulum.id as id_mat, jurusan.kode_jurusan,id_sms,id_jenj_didik from kurikulum 
inner join jurusan on kurikulum.kode_jurusan=jurusan.kode_jurusan 
inner join mat_kurikulum on kurikulum.id=mat_kurikulum.id_kurikulum where jurusan.kode_jurusan='".$_POST['jurusan']."' and kurikulum.id='".$_POST['id_kur']."' and mat_kurikulum.status_error!=1 $query_not_in limit 7");



foreach ($data as $dt_id) {
	$check_matkul[] = "('".$dt_id->id_sms."','".$dt_id->id_jenj_didik."','".convert_ascii($dt_id->kode_mk)."')";
	$data_loop[] = $dt_id;
}


			$implode_mat = implode(",", $check_matkul);
			$filter_mat = "(p.id_sms,p.id_jenj_didik,trim(p.kode_mk)) IN ($implode_mat)";
			$get_mat = $proxy->GetRecordset($token,'mata_kuliah',$filter_mat,"","","");
			if (!empty($get_mat['result'])) {
				foreach ($get_mat['result'] as $dt_mat_data) {
					$data_mat[$dt_mat_data['id_sms'].$dt_mat_data['id_jenj_didik'].convert_ascii($dt_mat_data['kode_mk'])] = array(
						'id_mk' => $dt_mat_data['id_mk'],
						'sks_mk' => $dt_mat_data['sks_mk']
					);
					$check_mat_kur[$dt_mat_data['id_mk']] = $dt_mat_data['id_mk'];
				}
			}


			if (!empty($check_mat_kur)) {
				$implode_mat = "'" . implode ( "','", $check_mat_kur ) . "'";
				$filter_mat = "(p.id_mk) IN ($implode_mat)";
				$get_mat = $proxy->GetRecordset($token,'mata_kuliah_kurikulum',$filter_mat,"","","");
				if (!empty($get_mat['result'])) {
					foreach ($get_mat['result'] as $dt_mat_data) {
						$data_mat_kur_check[$dt_mat_data['id_kurikulum_sp'].$dt_mat_data['id_mk']] = $dt_mat_data['id_kurikulum_sp'];
					}
				}

				$get_deleted = $proxy->GetDeletedRecordset($token,'mata_kuliah_kurikulum',$filter_mat,"","","");
				if (!empty($get_deleted['result'])) {
					foreach ($get_deleted['result'] as $dt_mat_del) {
						$data_deleted[$dt_mat_del['id_kurikulum_sp'].$dt_mat_del['id_mk']] = array(
							'id_kur' => $dt_mat_del['id_kurikulum_sp'],
							'id_mk' => $dt_mat_del['id_mk']
						);
					}
				}

			}
			//check deleted matkur
			


		$counter=0;
		foreach ($data_loop as $dt) {

			$jmlsks_mk=$dt->sks_tm+$dt->sks_prak+$dt->sks_prak_lap+$dt->sks_sim;
			$wajib = $dt->jns_mk;
				//check if wajib 
				if ($dt->jns_mk=='A' or $dt->jns_mk=='W') {
					$wajib_mat = 1;
				} else {
					$wajib_mat = 0;
				}


		/*if ($jmlsks_mk>9) {
			++$error_count;
			$db->update('mat_kurikulum',array('status_error' => 2, 'keterangan'=>"Error Jumlah SKS > 9"),'id',$dt->id_mat);
			$error_msg[] = "Jumlah SKS > 9";
		} else*/
		if ($jmlsks_mk<1) {
			++$error_count;
			$db->update('mat_kurikulum',array('status_error' => 2, 'keterangan'=>"Error Total Jumlah SKS tidak boleh 0"),'id',$dt->id_mat);
			$error_msg[] = "Total Jumlah SKS tidak boleh 0";
		} else {

			if (in_array($dt->id_sms.$dt->id_jenj_didik.convert_ascii($dt->kode_mk), array_keys($data_mat))) {
				$id_mk = $data_mat[$dt->id_sms.$dt->id_jenj_didik.convert_ascii($dt->kode_mk)]['id_mk'];
				$jmlsks_mk= $data_mat[$dt->id_sms.$dt->id_jenj_didik.convert_ascii($dt->kode_mk)]['sks_mk'];
				++$error_count;
				$error_msg[] = "Matakuliah $dt->kode_mk $dt->nama_mk sudah ada di Feeder";
				$db->update('mat_kurikulum',array('status_error' => 2, 'keterangan'=>"Matakuliah ini sudah ada di Feeder"),'id',$dt->id_mat);

				if (!in_array($id_kurikulum.$id_mk, array_keys($data_mat_kur_check))) {

					//check deleted recordset matkur
					if (in_array($id_kurikulum.$id_mk, array_keys($data_deleted))) {
					$data_mat_kur_restore[] = array(
						'id_kurikulum_sp' => $id_kurikulum,
						'id_mk' => $id_mk
						);
					$data_mat_kur_restore_update[] = array(
						'smt' => $dt->semester,
						'sks_mk' => $jmlsks_mk,
						'sks_tm' =>$dt->sks_tm,
					    'sks_prak' =>  $dt->sks_prak,
				   		'sks_prak_lap' =>$dt->sks_prak_lap,
						'sks_sim' => $dt->sks_sim,
						'a_wajib' => $wajib_mat
						);
					$data_id_restore[] = $dt->id_mat;
				} else {
					//insert to matkul kurikulum
					$data_mat_kur_parsial[] = array(
						'id_kurikulum_sp' => $id_kurikulum,
						'id_mk' => $id_mk,
						'smt' => $dt->semester,
						'sks_mk' => $jmlsks_mk,
						'sks_tm' =>$dt->sks_tm,
					    'sks_prak' =>  $dt->sks_prak,
				   		'sks_prak_lap' =>$dt->sks_prak_lap,
						'sks_sim' => $dt->sks_sim,
						'a_wajib' => $wajib_mat
						);
					$data_id_parsial[] = $dt->id_mat;

				}
					
				} else {
					$error_count_mat_kur++;
					$db->update('mat_kurikulum',array('status_error' => 2, 'keterangan'=>"Matakuliah ini sudah ada di kurikulum"),'id',$dt->id_mat);
					$error_msg_matkur[] = "$dt->kode_mk $dt->nama_mk Matakuliah ini sudah ada di kurikulum";
				}


				} else {
						
					$data = array(
					'id_sms' => $dt->id_sms,
					'id_jenj_didik' => $dt->id_jenj_didik,
			        'kode_mk' => $dt->kode_mk,
			        'nm_mk' => $dt->nama_mk,
			        'jns_mk' => $wajib,
			        'sks_mk' => $jmlsks_mk,
			        'sks_tm' => $dt->sks_tm,
			        'sks_prak' => $dt->sks_prak,
			        'sks_prak_lap' => $dt->sks_prak_lap,
			        'sks_sim' => $dt->sks_sim,
				    'tgl_mulai_efektif' => $dt->tgl_mulai_efektif,
					'tgl_akhir_efektif' => $dt->tgl_akhir_efektif,
			        );

					//mat kur for second access
	        		$data_mat_kur_parsial_second[] = array(
					'id_kurikulum_sp' => $id_kurikulum,
					'smt' => $dt->semester,
					'sks_mk' => $jmlsks_mk,
					'sks_tm' =>$dt->sks_tm,
				    'sks_prak' =>  $dt->sks_prak,
			   		'sks_prak_lap' =>$dt->sks_prak_lap,
					'sks_sim' => $dt->sks_sim,
					'a_wajib' => $wajib_mat
					);

			        $data_mk[] = $data;
			        $data_id_mk[] = $dt->kode_mk.' '.$dt->nama_mk;
					$data_ids[] = $dt->id_mat;
			        //print_r($data);
			}

		}
		$all_id[] = $dt->id_mat;
	}


		if (!empty($data_mk)) {

			$result = $proxy->InsertRecordset($token, 'mata_kuliah',json_encode($data_mk));
			
			
				foreach ($result['result'] as $key => $value) {

					$value_data = $value['error_desc'];
					$data_key = $data_ids[$key];
					$data_label = $data_id_mk[$key];
					$acces_second_matkur = $data_mat_kur_parsial_second[$key];

					if ($value_data!='') {
						$error_msg[] = $data_label." ".$value_data;
						$error_update_data[] = array(
							'keterangan' => $value_data,
							'status_error' => 2
						);
						$data_id_error[] = $data_key;
						$error_count++;
					} else {
						//insert to matkul kurikulum
						$data_mat_kur_parsial_third[] = array(

							'id_kurikulum_sp' => $data_mat_kur_parsial_second[$key]['id_kurikulum_sp'],
							'smt' => $data_mat_kur_parsial_second[$key]['smt'],
							'id_mk' => $value['id_mk'],
							'sks_mk' => $data_mat_kur_parsial_second[$key]['sks_mk'],
							'sks_tm' =>$data_mat_kur_parsial_second[$key]['sks_tm'],
						    'sks_prak' =>  $data_mat_kur_parsial_second[$key]['sks_prak'],
					   		'sks_prak_lap' =>$data_mat_kur_parsial_second[$key]['sks_prak_lap'],
							'sks_sim' => $data_mat_kur_parsial_second[$key]['sks_sim'],
							'a_wajib' => $data_mat_kur_parsial_second[$key]['a_wajib']
						);
						$data_mat_key[] = $data_key;
						$sukses_count++;
						$update_data[] = array(
							'keterangan' => '',
							'status_error' => 1
						);
						$data_id_sukses[] = $data_key;
					}

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


if (!empty($data_mat_kur_restore)) {
	$result = $proxy->RestoreRecordset($token, 'mata_kuliah_kurikulum',json_encode($data_mat_kur_restore));

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

					$value_data = $value['error_desc'];
					$data_key = $data_id_restore[$key];


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

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

//echo "<pre>";
	if (!empty($data_mat_kur_parsial)) {
/*
					print_r($data_mat_kur_parsial);
			
			print_r($data_id_parsial);*/

			$result = $proxy->InsertRecordset($token, 'mata_kuliah_kurikulum',json_encode($data_mat_kur_parsial));
			//print_r($result);
			foreach ($result['result'] as $key => $value) {
				if ($key<count($data_id_parsial)) {
								//foreach ($data_mat_kur_parsial as $dt_mat) {
						$data_key = $data_id_parsial[$key];
						//$result = $proxy->InsertRecord($token, 'mata_kuliah_kurikulum',json_encode($dt_mat));
							$value_data = $value['error_desc'];
							$data_key = $data_id_parsial[$key];

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

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

		}



	if (!empty($data_mat_kur_parsial_third)) {

		$result = $proxy->InsertRecordset($token, 'mata_kuliah_kurikulum',json_encode($data_mat_kur_parsial_third));
			//print_r($result);
			foreach ($result['result'] as $key => $value) {
					if ($key<count($data_mat_key)) {
						$data_key = $data_mat_key[$key];
						if ($value_data!='') {
							$error_msg_matkur[] = $value_data;
							$error_update_data[] = array(
								'keterangan' => $value_data,
								'status_error' => 2
							);
							$data_id_error[] = $data_key;
							$error_count_mat_kur++;
						} else {
								$update_data[] = array(
									'keterangan' => '',
									'status_error' => 1
								);
								$data_id_sukses[] = $data_key;
							$sukses_count_mat_kur++;
						}
					}
				
		}

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


	$total_error = $error_count+$error_count_in;

	//$jumlah['not_in'] = $query_not_in;
	$jumlah['all_id'] = $all_id;
	$jumlah['kur_id'] = $id_kurikulum;
	$jumlah['jumlah_error_kur'] = $error_count_kur;
	$jumlah['jumlah_sukses_kur'] = $sukses_count_kur;
	$jumlah['jumlah_error'] = $error_count;
	$jumlah['jumlah_sukses'] = $sukses_count;
	$jumlah['jumlah_error_matkur'] = $error_count_mat_kur;
	$jumlah['jumlah_sukses_matkur'] = $sukses_count_mat_kur;
	$jumlah['error_msg_kur'] = $error_msg_kur;
	$jumlah['error_msg'] = $error_msg;
	$jumlah['error_msg_matkur'] = $error_msg_matkur;

	if (isset($_POST['id_data'])) {

		$jumlah_sukses_kur = $_POST['jumlah_sukses_kur']+$sukses_count_kur;
		$jumlah_error_kur = $_POST['jumlah_error_kur']+$error_count_kur;


		$jumlah_sukses = $_POST['jumlah_sukses']+$sukses_count;
		$jumlah_error = $_POST['jumlah_error']+$error_count;

		$jumlah_sukses_matkur = $_POST['jumlah_sukses_matkur']+$sukses_count_mat_kur;
		$jumlah_error_matkur = $_POST['jumlah_error_matkur']+$error_count_mat_kur;


	$msg =  "<div class=\"alert alert-warning\" role=\"alert\">
			<font color=\"#3c763d\">".$jumlah_sukses_kur." data Kurikulum baru berhasil ditambah</font><br />
			<font color=\"#ce4844\" >".$jumlah_error_kur." data tidak bisa ditambahkan </font>";
			if (!$jumlah_error_kur==0) {
			$msg .= "<a data-toggle=\"collapse\" href=\"#collapseExample\" aria-expanded=\"false\" aria-controls=\"collapseExample\">Detail error</a>";
			//pesan error 

			if (!empty($_POST['error_msg_kur'])) {
				$trim_error = rtrim($_POST['error_msg_kur'], ',');
			
				$all_error = explode(",", $trim_error);
			}
			

			$all_errors = array_merge($all_error,$error_msg_kur);
			
			}
			//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>";

	$msg .=  "<div class=\"alert alert-warning\" role=\"alert\">
			<font color=\"#3c763d\">".$jumlah_sukses." data Matakuliah baru berhasil ditambah</font><br />
			<font color=\"#ce4844\" >".$jumlah_error." data tidak bisa ditambahkan </font>";
	if (!$jumlah_error==0) {
			$msg .= "<a data-toggle=\"collapse\" href=\"#collapseExamples\" aria-expanded=\"false\" aria-controls=\"collapseExample\">Detail error</a>";
			//pesan error 

			if (!empty($_POST['error_msg'])) {
				$trim_error = rtrim($_POST['error_msg'], ',');
			
				$all_error = explode(",", $trim_error);
			}
			

			$all_errors = array_merge($all_error,$error_msg);
			
		}
		//echo "<br />Total: ".$i." baris data";
		$msg .= "<div class=\"collapse\" id=\"collapseExamples\">";
				$i=1;
				foreach ($all_errors as $pesan) {
						$msg .= "<div class=\"bs-callout bs-callout-danger\">".$i.". ".$pesan."</div><br />";
					$i++;
					}
		$msg .= "</div>
		</div>";

	$msg .=  "<div class=\"alert alert-warning\" role=\"alert\">
			<font color=\"#3c763d\">".$jumlah_sukses_matkur." data Matakuliah baru berhasil ditambah Ke Kurikulum</font><br />
			<font color=\"#ce4844\" >".$jumlah_error_matkur." data tidak bisa ditambahkan </font>";
	if (!$jumlah_error_matkur==0) {
			$msg .= "<a data-toggle=\"collapse\" href=\"#collapseExampled\" aria-expanded=\"false\" aria-controls=\"collapseExample\">Detail error</a>";
			//pesan error 

			if (!empty($_POST['error_msg_matkur'])) {
				$trim_error = rtrim($_POST['error_msg_matkur'], ',');
			
				$all_error = explode(",", $trim_error);
			}
			

			$all_errors = array_merge($all_error,$error_msg_matkur);
			
		}
			//echo "<br />Total: ".$i." baris data";
			$msg .= "<div class=\"collapse\" id=\"collapseExampled\">";
					$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 =  "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