<?php
session_start();
include "../../inc/config.php";
$config_feeder = $db->fetch_single_row('config_user','id',1);
$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;
		}
        $sukses_count = 0;
    
        $error_count = 0;
        $error_count_in = 0;

        $error_msg = array();
    
        $array_id_pt = array();
        $array_sms_asal = array();
        $array_sks_diakui = array();
        $error_pt_asal = "";
        $error_nim = "";
        $error_prodi_asal = "";

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

        $data_id_sukses = array();
        $data_id_error= array();
    
        $all_errors = array();
        $all_error = array();
        $query_not_in = "";
        $jurusan = "";

        $msg = "";

        $sem = "";
        $data_ids = array();
        $data_nim = array();
        $array_history = array();
        $all_id = array();
        $data_ids = array();
        $data_loop = array();
        $nim_data = array();
        $error_data = "";
		$error_update_data = array();
		$data_id_error = array();
		$update_data = array();
		$data_id_sukses = array();
		$asal_prodi = array();
		$kode_pt_asal = array();
		$data_prodi_asal = array();
		$error_data="";
		$data_lokal_jurusan = array();

		$data_id_npsn = array();

    	if ($_POST['sem']!='all') {
      		$sem = "and mulai_smt='".$_POST['sem']."'";
    	}
    	
		$id_sp = get_config_user()->id_sp;

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

		}

		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']."'";
			}
		}

		$query_not_in = "and unik_id not in(".$_POST['random_number'].")";
            $new_jurusan = $db->fetch_custom("select id_sms,nama_jurusan,kode_jurusan from jurusan");
            foreach ($new_jurusan as $dt) {
                $data_lokal_jurusan[$dt->kode_jurusan] = $dt->id_sms;
            }
		$datas = $db->fetch_custom("select history_pendidikan.*,id_sms,new_kode_jurusan from history_pendidikan inner join jurusan on history_pendidikan.kode_jurusan=jurusan.kode_jurusan where history_pendidikan.id is not null $sem $jurusan and status_error!=1 and jenis_method='".$_POST['jenis_method']."' $query_not_in limit 11");

    $check_array_kode_pt = array();
    $check_array_prodi_asal = array();
			foreach ($datas as $dt_id) {
				//$nim_concat[convert_ascii($dt_id->nipd).$dt_id->id_sms] = "('".$dt_id->nipd."','".$dt_id->id_sms."')";
                $nim_like[$dt_id->nipd] = "nim like '%$dt_id->nipd%'";
                $sms_and[$dt_id->id_sms] = "('".$dt_id->id_sms."')";
				$data_loop[] = $dt_id;
		        if ($dt_id->kode_pt_asal!='') {
		            $check_array_kode_pt[convert_ascii($dt_id->kode_pt_asal)] = "('".convert_ascii($dt_id->kode_pt_asal)."')";
		        }
		        if ($dt_id->kode_pt_asal!='' && $dt_id->kode_prodi_asal!='') {
		            $check_array_prodi_asal[convert_ascii($dt_id->kode_pt_asal).convert_ascii($dt_id->kode_prodi_asal)] = "('".convert_ascii($dt_id->kode_pt_asal)."','".$dt_id->kode_prodi_asal."')";
		        }
			}

			//$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));
			if (!empty($check_nim_exist->data)) {
				foreach ($check_nim_exist->data as $nim_mhs) {
					$nim_data[convert_ascii($nim_mhs->nim).$nim_mhs->id_prodi] = array(
						'id_reg_pd' => $nim_mhs->id_registrasi_mahasiswa,
						'id_pd' => $nim_mhs->id_mahasiswa
					);
				}
			}

function check_id_valid($table_name,$id_name) {
    global $db;
    $jenis = $db->fetch_custom_single("SELECT group_concat($id_name) as id FROM $table_name");
    return explode(",",$jenis->id); 
}
function validasiMhs($biodata)
{
    global $id_pt_array;
    global $id_prodi_array;
/*    echo $biodata->kode_pt_asal.$biodata->kode_prodi_asal;
    dump($id_prodi_array);*/
    //jenis daftar
    $jenis_daftar = check_id_valid('jenis_pendaftaran','id_jns_daftar');
    $jalur_masuk = check_id_valid('jalur_masuk','id');
    $jenis_pembiayaan = array(1,2,3);
    $error_validasi = "";
    if (strlen($biodata->mulai_smt)!=5) {
        $error_validasi = "Mulai Semester Pastikan Sesuai Template";
    } elseif (!validateDate($biodata->tgl_masuk_sp)) {
        $error_validasi = "Tanggal Pendaftaran pastikan Sesuai Template";
    } elseif (!in_array($biodata->id_jns_daftar, $jenis_daftar)) {
       $error_validasi = "Id Jenis Pendaftaran Salah, Pastikan Sesuai Template";
    } elseif (!in_array($biodata->id_jalur_masuk, $jalur_masuk)) {
       $error_validasi = "Id Jalur Pendaftaran Salah, Pastikan Sesuai Template";
    } elseif (!in_array($biodata->id_pembiayaan, $jenis_pembiayaan)) {
       $error_validasi = "ID Jenis Pembiayaan Salah, Pastikan Sesuai Template";
    }  elseif ($biodata->biaya_masuk_kuliah=="") {
       $error_validasi = "Biaya Masuk Kuliah Wajib diisi";
    }/* elseif ($biodata->id_jns_daftar!='1') {
        if ($biodata->kode_pt_asal=="") {
            $error_validasi = "Selain Peserta didik baru, Kode PT Asal Tidak Boleh Kosong";
        } elseif ($biodata->kode_prodi_asal=="") {
            $error_validasi ='Selain Peserta didik baru, Kode Prodi Asal Tidak Boleh Kosong';
        } elseif (!in_array(convert_ascii($biodata->kode_pt_asal), array_keys($id_pt_array))) {
            $error_validasi = 'Kode PT tidak ditemukan di Feeder';
        } elseif (!in_array(convert_ascii($biodata->kode_pt_asal).convert_ascii($biodata->kode_prodi_asal), array_keys($id_prodi_array))) {
            $error_validasi = 'Kode Prodi Asal tidak ditemukan di Feeder';
        }
    }*/

    return $error_validasi;
}

    $id_pt_array = array();
    if (!empty($check_array_kode_pt)) {
        //check if id_mhs used
        $concat_where = implode(",", $check_array_kode_pt);
            $data_req_mhs = [
                'act' => 'GetAllPT',
                'token' => $token,
                'filter' => "(kode_perguruan_tinggi) in ($concat_where)",
                'order' => "",
                'limit' => "",
                'offset' => ""

            ];
        $check_exist = json_decode($db->run($data_req_mhs,$url_rest));
        if ($check_exist) {
            foreach ($check_exist->data as $id_pt) {
                $id_pt_array[convert_ascii($id_pt->kode_perguruan_tinggi)] = array(
                    'id_sp' => $id_pt->id_perguruan_tinggi,
                    'nm_lemb' => $id_pt->nama_perguruan_tinggi
                );
            }
        }
    }
    $id_prodi_array = array();
    if (!empty($check_array_prodi_asal) and !empty($id_pt_array)) { 
        $concat_where = implode(",", $check_array_prodi_asal);
            $data_req_prodi = [
                'act' => 'GetAllProdi',
                'token' => $token,
                'filter' => "(kode_perguruan_tinggi,kode_program_studi) in ($concat_where)",
                'order' => "",
                'limit' => "",
                'offset' => ""
            ];

        
        $check_exist = json_decode($db->run($data_req_prodi,$url_rest));
        if ($check_exist) {
            foreach ($check_exist->data as $id_pt_prodi) {
                $id_prodi_array[convert_ascii($id_pt_prodi->kode_perguruan_tinggi).convert_ascii($id_pt_prodi->kode_program_studi)] = array(
                    'id_sms' => $id_pt_prodi->id_prodi,
                    'nm_lemb' => $id_pt_prodi->nama_program_studi
                );
            }
        }
    }

function insertRegPdArray($biodata,$additional_data)
{
    global $id_sp;
    global $id_pt_array;
    global $id_prodi_array;
    $biodatas = [
        "id_mahasiswa" => $additional_data['id_mahasiswa'],
        "id_jenis_daftar" => $biodata->id_jns_daftar,
        "id_jalur_daftar" => $biodata->id_jalur_masuk,
        "id_periode_masuk" => $biodata->mulai_smt,
        "tanggal_daftar" => $biodata->tgl_masuk_sp,
        "id_perguruan_tinggi" => $id_sp,
        "id_bidang_minat" => null,
        "id_jenis_keluar" => 1,
        "id_pembiayaan" => $biodata->id_pembiayaan,
        "biaya_masuk"  => $biodata->biaya_masuk_kuliah,
        "id_bidang_minat"  => $biodata->id_bidang_minat
        
    ];
    if ($biodata->jenis_method=='0') {
        $biodatas["id_prodi"] = $additional_data['id_sms_baru'];
    } elseif ($biodata->jenis_method=='3') {
    	$biodatas["id_prodi"] = $additional_data['id_sms_baru'];
    }  else {
        $biodatas["id_prodi"] = $biodata->id_sms; 
    }

    if ($biodata->jenis_method=='1') {
    	$biodatas['nim'] = $biodata->nipd;
    } elseif ($biodata->jenis_method=='3') {
    	$biodatas['nim'] = $biodata->nipd;
    } else {
    	$biodatas['nim'] = $biodata->new_nipd;
    }

    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["id_perguruan_tinggi_asal"] = $id_pt_array[convert_ascii($biodata->kode_pt_asal)]['id_sp'];
        }
        if (in_array(convert_ascii($biodata->kode_pt_asal).convert_ascii($biodata->kode_prodi_asal), array_keys($id_prodi_array))) {
           $biodatas["id_prodi_asal"] = $id_prodi_array[convert_ascii($biodata->kode_pt_asal).convert_ascii($biodata->kode_prodi_asal)]['id_sms'];
        }
    }
    return $biodatas;
}

function updateHistory($datas,$id_reg_pd) {
	$param = array(
		'act' => 'UpdateRiwayatPendidikanMahasiswa',
		'token' => get_token(),
		'key' => array('id_registrasi_mahasiswa' => $id_reg_pd),
		'record' => $datas
	);
	$update = service_request($param);
	return $update;
}

function insertHistory($datas) {
	$param = array(
		'act' => 'InsertRiwayatPendidikanMahasiswa',
		'token' => get_token(),
		'record' => $datas
	);
	$update = service_request($param);
	return $update;
}


function objectToCommaSeparatedString($obj) {
    $parts = [];
    foreach ($obj as $key => $value) {
        $parts[] = "$key: $value";
    }
    return implode(', ', $parts);
}
function responseCheck($data) {
	$return_array = array();
	$return_array['data'] = array();
	$return_array['is_error'] = 1;
	if (is_object($data)) {
		if (property_exists($data, 'error_desc')) {
			$value_data = addslashes($data->error_desc);
			if ($value_data!='') {
				$return_array['data'] = array(
					'keterangan' => $value_data,
					'status_error' => 2
				);
			} else {
				$return_array['is_error'] = 0;
				$return_array['data'] = array(
					'keterangan' => '',
					'status_error' => 1
				);
			}
		} else {
			$return_array['data'] = array(
				'keterangan' => objectToCommaSeparatedString($data),
				'status_error' => 2
			);
		}
	} else {
		$return_array['data'] = array(
			'keterangan' => print_r($data, true),
			'status_error' => 2
		);
	}
	//dump($return_array);

	return $return_array;
}
	foreach ($data_loop as $value) {
		$npsn = convert_ascii($value->kode_pt_asal);
		$kode_prodi_asal = convert_ascii($value->kode_prodi_asal);
		$nim = convert_ascii($value->nipd);
		$validasi_mhs = validasiMhs($value);

	    if (!in_array($nim.$value->id_sms, array_keys($nim_data))) {

	        $error_update_data[] = [
	            "keterangan" => 'NIM tidak ditemukan di feeder',
	            "status_error" => 2,
	        ];
	        $data_id_error[] = $value->id;
	    } elseif ($validasi_mhs != "") {
            //echo "yes";
	        $error_update_data[] = [
	            "keterangan" => $validasi_mhs,
	            "status_error" => 2,
	        ];
	        $data_id_error[] = $value->id;
	    } else {
	    	if ($_POST['jenis_method']=='1') {
		    	$additional_data = array(
                    'id_reg_pd' => $nim_data[$nim.$value->id_sms]['id_reg_pd'],
		    		'id_mahasiswa' => $nim_data[$nim.$value->id_sms]['id_pd']
		    	);

		    	$array_history = insertRegPdArray($value,$additional_data);
		    

		    	$update_history = updateHistory($array_history,$nim_data[$nim.$value->id_sms]['id_reg_pd']);
                
		    	$check_response = responseCheck($update_history);
		    	
		    	if ($check_response['is_error']==0) {
		    		$update_data[] = $check_response['data'];
		    		$data_id_sukses[] = $value->id;
		    	} else {
		    		$error_update_data[] = $check_response['data'];
		    		$data_id_error[] = $value->id;
		    	}
	    	} elseif ($_POST['jenis_method']=='3') {
	    		$id_sms_baru = $data_lokal_jurusan[convert_ascii($value->new_kode_jurusan)];
                $additional_data = array(
                    'id_mahasiswa' => $nim_data[$nim.$value->id_sms]['id_pd'],
                    'id_sms_baru' => $id_sms_baru
                );

		    	$array_history = insertRegPdArray($value,$additional_data);

		    	$update_history = updateHistory($array_history,$nim_data[$nim.$value->id_sms]['id_reg_pd']);
		    	$check_response = responseCheck($update_history);
		    	
		    	if ($check_response['is_error']==0) {
		    		$update_data[] = $check_response['data'];
		    		$data_id_sukses[] = $value->id;
		    	} else {
			    		$error_update_data[] = $check_response['data'];
			    		$data_id_error[] = $value->id;
		    	}
	    	} else {
                $id_sms_baru = $data_lokal_jurusan[convert_ascii($value->new_kode_jurusan)];
                $additional_data = array(
                    'id_mahasiswa' => $nim_data[$nim.$value->id_sms]['id_pd'],
                    'id_sms_baru' => $id_sms_baru
                );

		    	$array_history = insertRegPdArray($value,$additional_data);


		    	$insert_history = insertHistory($array_history);
		    	$check_response = responseCheck($insert_history);
		    	
		    	if ($check_response['is_error']==0) {
		    		$update_data[] = $check_response['data'];
		    		$data_id_sukses[] = $value->id;
		    	} else {
			    		$error_update_data[] = $check_response['data'];
			    		$data_id_error[] = $value->id;
		    	}
	    	}

	    }
		$all_id[] = $value->id;
	}



    if (!empty($error_update_data)) {
        updateMulti("history_pendidikan", $error_update_data, "id", $data_id_error);
    }
    $error_update_data = array();
    $data_id_error = array();
	if (!empty($update_data)) {
		updateMulti('history_pendidikan',$update_data,'id',$data_id_sukses);
	}
	$update_data = array();
	$data_id_sukses = array();


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

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

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

		$db->fetch_custom("update history_pendidikan set unik_id=0 where  unik_id=".$_POST['random_number']);

	
		$msg =  "<div class=\"alert alert-warning \" role=\"alert\">
		<font color=\"#3c763d\">".$jumlah_sukses." data History 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 =  "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