<?php

if(!$db){
	include("$DOCUMENT_ROOT/s/config.php");
	include("$DOCUMENT_ROOT/classes/bootstrap.php");
}
if($act!='jsonws'){
	$b = new bootstrap;
	$debug=0;
	$b->basicheader();
}

$nip = $login_nip;

$max_bidang_sama = 2;	// maksimal posisi yang bisa diapply di bidang yang sama
$max_total_lamaran = 2;	// maksimal total lowongan

$mpp_id = $f->getLastMppUsed();

if ($act=="jsonws") {
	if ($wsdata=="apply") {
		//echo "test";
		// disini logic untuk pengecekan bidang yang dilamar, apakah sudah pernah melamar bidang yang sama?
		/*if (empty($_POST['nip'])) {
			$wsresult = array('status' => false, 'message' => 'missing nip');
		} else*/
		if (empty($_POST['req_id'])) {
			$wsresult = array('status' => false, 'message' => 'missing req_id');
		} else {
			$cek_nip = base64_decode($_POST['nip']);
			$cek_req_id = $_POST['req_id'];
			
			$sql_cek_lowongan_apply = "SELECT 
									  'a'
									FROM 
									  REC_PELAMAR_INTERNAL AS rpi
									WHERE 
									  rpi.NIP = '$cek_nip'
									  AND rpi.STATUS IN ('0','1','2','4')";
			$result_cek_lowongan_apply = $db->Execute($sql_cek_lowongan_apply);
			$num_cek_lowongan_apply = $result_cek_lowongan_apply->RecordCount();
			if ($num_cek_lowongan_apply>=$max_total_lamaran) {
				$bisa_apply = false;
				$failed_message = "Anda tidak bisa melamar lowongan ini karena telah melamar ".$num_cek_lowongan_apply." posisi";
			} else {
				// cek jumlah
				if ($num_cek_lowongan_apply==0) {
					// munculin semua
					$prioritas_terdaftar = 0;
				} else {
					// munculin yang udah terdaftar
					$sql_cek_prioritas = "SELECT 
									  PRIORITAS
									FROM 
									  REC_PELAMAR_INTERNAL AS rpi
									WHERE 
									  rpi.NIP = '$cek_nip'
									  AND rpi.STATUS IN ('0','1','2','4')";
					$result_cek_prioritas = $db->Execute($sql_cek_prioritas);
					while($val = $result_cek_prioritas->FetchRow()){
						$prioritas_terdaftar = $val['PRIORITAS'];
					}
				}
				
				//$bisa_apply = true;
				$sql_cek_bidang_apply = "SELECT 
										  'a'
										FROM 
										  REC_PELAMAR_INTERNAL AS rpi INNER JOIN
										  REC_PTK AS rp ON rpi.REQ_ID = rp.PTK_ID INNER JOIN
										  REC_PTK AS rp_cek ON LEFT(rp.KD_UNIT_ORG,3) = LEFT(rp_cek.KD_UNIT_ORG,3)
										WHERE 
										  rpi.NIP = '$cek_nip'
										  AND rpi.STATUS IN ('0','1','2','4')
										  AND rp_cek.PTK_ID = '$cek_req_id'";
				$result_cek_bidang_apply = $db->Execute($sql_cek_bidang_apply);
				$num_cek_bidang_apply = $result_cek_bidang_apply->RecordCount();
				$bisa_apply = null;
				$failed_message = null;
				if ($num_cek_bidang_apply>=$max_bidang_sama) {
					$bisa_apply = false;
					$failed_message = "Anda tidak bisa melamar lowongan ini karena telah melamar ".$num_cek_bidang_apply." posisi di bidang yang sama";
				} else {
					$bisa_apply = true;
				}
			}
			
			$wsresult = array('status' => true, 'apply' => $bisa_apply, 'message' => $failed_message, 'prioritas_terdaftar' => $prioritas_terdaftar);
		}
	} elseif ($wsdata=="jodetail") {
		if (empty($_POST['id_formasi'])) {
			$wsresult = array('status' => false, 'message' => 'missing ID formasi');
		} else {
			$cek_id_formasi = $_POST['id_formasi'];
			$cek_id_room = $_POST['id_room'];
			
			$dampak = "";
			
			$sql = "select b.req_id,a.ptk_id,b.keterangan,c.satker,c.bidang,e.path_urjab,
					c.formasi as posisi_jabatan,b.tanggal_publish,b.tanggal_selesai,b.jam_selesai, c.JNS_JABATAN, a.JUMLAH, c.NM_KANTOR,
					c.dampak,
					CASE 
						WHEN c.JNS_JABATAN = 'struktural' THEN
							CASE
								WHEN LEFT(TRIM(c.dampak), 5) = '[FTO]' THEN 1 
								ELSE 0 
							END
						ELSE
							0
					END	AS fto
					from rec_ptk a
					left join rec_permintaan_advertising b ON a.id_formasi=b.id_formasi
					inner join rec_rencana_pemenuhan_peg c on a.id_formasi=c.id_formasi
					inner join rec_kunci_lowongan_jabatan d on c.kd_gol=d.kd_gol and c.mpp_id=d.mpp_id
					left join spg_indesk_urjab_satker e on c.kd_satker=e.kd_satker
					where b.ram_id='RAM-000020' and b.rac_id='RAC-000001' and a.id_formasi='$cek_id_formasi'
					order by a.id_formasi desc ";
			//$f->pre($sql);
			$result=$f->get_last_record($sql);
			if (!$result) {
				$wsresult = array('status' => false, 'message' => 'Gagal memuat data');
			} else {
				// begin: cek apakah ada fto atau enggak
				//$sql_cek_fto = "SELECT * FROM dbo.REC_MPP_TARGET WHERE MPP_ID = '$mpp_id' AND LEFT(TRIM(ALASAN), 5) = '[FTO]'";
				$sql_cek_fto = "SELECT * FROM dbo.REC_RENCANA_PEMENUHAN_PEG WHERE MPP_ID = '$mpp_id' AND LEFT(TRIM(dampak), 5) = '[FTO]'";
				$result_cek_fto = $db->Execute($sql_cek_fto);
				if (!$result_cek_fto) {
					print $db->ErrorMsg();
				}
				$num_cek_fto = $result_cek_fto->RecordCount();
				$ada_fto = false;
				if ($num_cek_fto>0) {
					$ada_fto = true;
				}
				// end: cek apakah ada fto atau enggak
				
				foreach($result as $key=>$val){
					$$key=trim($val);
				}
				$thn_kurangdua=date('Y',strtotime($tanggal_buat))-2;
				$thn_kurangsatu=date('Y',strtotime($tanggal_buat))-1;
				$thn_sekarang=date('Y',strtotime($tanggal_buat));
				if($sanksi==0){
					$ket_sanksi="Tidak sedang kena sanksi";
				}
				else{
					$ket_sanksi="Sedang kena sanksi";
				}
				$sql_cek = "SELECT * FROM rec_pelamar_internal WHERE NIP = '$login_nip' AND STATUS IN ('0','1','2','4') AND ID_FORMASI = '$cek_id_formasi'";
				if (!empty($cek_id_room)) {
					$sql_cek .= " and ID_ROOM = ".$cek_id_room;
				}
				$result_cek = $db->Execute($sql_cek);
				if(!$result_cek)print $db->ErrorMsg();
				$num_cek = $result_cek->RecordCount();
				if ($num_cek>0) {
					$bisabatal = true;
				} else {
					$bisabatal = false;
				}
				$nm_file_urjab = str_replace("i/urjab_satker/", "", $path_urjab);
				
				$nm_room = "";
				if (!empty($cek_id_room)) {
					$sql_room = "SELECT NM_ROOM, DAMPAK FROM REC_ROOM_FORMASI_FUNCTIONAL WHERE ID = '$cek_id_room' AND ID_FORMASI = '$cek_id_formasi'";
					$result_room = $f->get_last_record($sql_room);
					if (!empty($result_room['nm_room'])) {
						$nm_room = " ".$result_room['nm_room'];
						if (!empty($result_room['dampak'])) {
							$dampak = $result_room['dampak'];
						}
					}
				}
				
				$regulerfto = "";
				if ($ada_fto) {
					//if ($fto=='1') {
					//	$regulerfto = "<br>[ FTO ]";
					//} else {
					//	$regulerfto = "<br>[ REGULER ]";
					//}
					if (!empty($dampak)) {
						$regulerfto = "<br>".$dampak;
					}
				}
				$tmp_arr = array(
								'keterangan' => nl2br($keterangan),
								'kantor' => $nm_kantor,
								'bidang' => $bidang,
								'satker' => $satker,
								'posisi_jabatan' => $posisi_jabatan.$nm_room,
								'tanggal_selesai' => $f->convert_date_id($tanggal_selesai),
								'jam_selesai' => $jam_selesai,
								'req_id' => $req_id,
								'tmp_tanggal_publish' => $tanggal_publish,
								'tmp_tanggal_selesai' => $tanggal_selesai,
								'batal' => $bisabatal,
								'path_urjab' => $path_urjab,
								'nm_file_urjab' => $nm_file_urjab,
								'jns_jabatan' => $jns_jabatan,
								'jumlah' => $jumlah,
								'regulerfto' => $regulerfto
							);
				$wsresult = array('status' => true, 'data' => $tmp_arr);
			}
		}
	} elseif ($wsdata=="doapply") {
		if (empty($_POST['nip'])) {
			$wsresult = array('status' => false, 'message' => 'missing nip');
		} elseif (empty($_POST['req_id'])) {
			$wsresult = array('status' => false, 'message' => 'missing req_id');
		} elseif (empty($_POST['id_formasi'])) {
			$wsresult = array('status' => false, 'message' => 'missing id_formasi');
		} else {
			$cek_nip = base64_decode($_POST['nip']);
			$cek_req_id = $_POST['req_id'];
			$cek_id_formasi = $_POST['id_formasi'];
			$cek_id_room = $_POST['id_room'];
			$cek_prioritas = $_POST['prioritas'];
			
			$sql_cek_formasi = "SELECT * FROM dbo.REC_PELAMAR_INTERNAL WHERE NIP = '$cek_nip' AND ID_FORMASI = " . $cek_id_formasi;
			if (!empty($cek_id_room)) {
				$sql_cek_formasi .= " and ID_ROOM = ".$cek_id_room;
			}
			$result_cek_formasi = $db->Execute($sql_cek_formasi);
			if (!$result_cek_formasi) print $db->ErrorMsg();
			$jml_cek_formasi = $result_cek_formasi->RecordCount();
			if ($jml_cek_formasi==0) {
			
				$key_id=$f->generate_nomorkolom("rec_pelamar_internal","rpi_id","RPI");
				//$detail_pegawai=$f->detailPegawai($login_nip);
				$detail_pegawai=$f->detailPegawai($cek_nip);
				$nm_peg = $detail_pegawai['nm_peg'];
				$nm_peg = str_replace("'", "''", $nm_peg);
				
				$status_pelamar = 0;	// kalau mau ganti status, disini aja, jangan di query
				if (!empty($cek_id_room)) {
					$value_id_room = $cek_id_room;
				} else {
					$value_id_room = "NULL";
				}
				$sql="INSERT INTO dbo.REC_PELAMAR_INTERNAL
				(RPI_ID,NIP,NM_PEG,REQ_ID,TANGGAL_APPLY,STATUS,PENGANGKATAN,JUMLAH_PINDAH_LOWONGAN,BIDANG,DEPUTI_KOMISIONER,DEPARTEMEN,DIREKTORAT,SATKER,FORMASI,JABATAN,UNIT_ORGANISASI,KD_GOL,NM_GOL,USIA,MASA_DINAS_LVL_JABATAN,MASA_DINAS_JABATAN,MASA_DINAS_OJK,NILAI_KINERJA_1,NILAI_KINERJA_2,NILAI_KINERJA_3,NILAI_KINERJA_TOTAL,TGL_LAHIR,TEMPAT_LAHIR_PEG,NM_PEND_UMUM,KD_SATKER,KD_JABATAN_STR,ID_FORMASI,CMP_ID,KD_KANTOR,KD_UNIT_ORG,PRIORITAS, ID_ROOM)
				SELECT TOP 1
					'$key_id','$cek_nip','$nm_peg','$cek_req_id',getdate(),'$status_pelamar','0',0,
					d.nm_unit_org bidang,
					e.nm_unit_org deputi_komisioner,
					f.nm_unit_org departemen,
					g.nm_unit_org direktorat,
					c.nama_satker_organisasi,
					j.posisi,
					b.nm_jabatan,
					c.nm_unit_org,
					b.kd_gol,
					b.nm_gol,
					(DATEDIFF(DAY, b.TGL_LAHIR_PEG, GETDATE()) / 365) usia,
					CAST((DATEDIFF(DAY, b.tmt_gol, GETDATE()) / 365) AS VARCHAR(3)) + ' Thn '
					+ CAST(((DATEDIFF(MONTH, b.tmt_gol, GETDATE())) - ((DATEDIFF(DAY, b.tmt_gol, GETDATE()) / 365) * 12)) AS VARCHAR(3))
					+ ' Bln' AS masa_dinas_lvl_jabatan,
					CAST((DATEDIFF(DAY, b.tmt_jabatan, GETDATE()) / 365) AS VARCHAR(3)) + ' Thn '
					+ CAST(((DATEDIFF(MONTH, b.tmt_jabatan, GETDATE())) - ((DATEDIFF(DAY, b.tmt_jabatan, GETDATE()) / 365) * 12)) AS VARCHAR(3))
					+ ' Bln' AS masa_dinas_jabatan,
					CAST((DATEDIFF(DAY, b.tgl_masuk, GETDATE()) / 365) AS VARCHAR(3)) + ' Thn '
					+ CAST(((DATEDIFF(MONTH, b.tgl_masuk, GETDATE())) - ((DATEDIFF(DAY, b.tgl_masuk, GETDATE()) / 365) * 12)) AS VARCHAR(3))
					+ ' Bln' AS masa_dinas_ojk,
					nk.nk1,
					nk.nk2,
					nk.nk3,
					nk.nktotal,
					b.tgl_lahir_peg,
					b.tempat_lahir_peg,
					b.nm_pend_umum,
					c.kode_satker_organisasi,
					b.kd_jabatan_str,
					$cek_id_formasi,
					b.cmp_id,
					b.kd_kantor,
					b.kd_unit_org,
					$cek_prioritas,
					$value_id_room
				FROM
					spg_data_current b
					LEFT JOIN
					spg_08_unit_organisasi c ON
						b.kd_unit_org = c.kd_unit_org
					LEFT JOIN
					spg_08_unit_organisasi d ON
						c.kd_unit_es1 = d.kd_unit_org
					LEFT JOIN
					spg_08_unit_organisasi e ON
						c.kd_unit_es2 = e.kd_unit_org
					LEFT JOIN
					spg_08_unit_organisasi f ON
						c.kd_unit_es3 = f.kd_unit_org
					LEFT JOIN
					spg_08_unit_organisasi g ON
						c.kd_unit_es4 = g.kd_unit_org
					LEFT JOIN
					spg_08_jabatan_unit j ON
						b.kd_jabatan_str = j.kd_jabatan
						AND b.kd_unit_org = j.kd_unit_org
					OUTER APPLY
					(
						SELECT
							nip,
							SUM(CASE x.no
								WHEN 1 THEN x.nilai
								ELSE 0
							END) AS nk1,
							SUM(CASE x.no
								WHEN 2 THEN x.nilai
								ELSE 0
							END) AS nk2,
							SUM(CASE x.no
								WHEN 3 THEN x.nilai
								ELSE 0
							END) AS nk3,
							AVG(x.nilai) AS nktotal
						FROM
							(
								SELECT TOP 3
									ROW_NUMBER() OVER (ORDER BY pfm_id DESC) AS no,
									DATEPART(year,tanggal_selesai) as tahun, 
									id,
									nilai,
									nip
								FROM 
									PFM_RIWAYAT_KINERJA 
								WHERE 
									nip=b.nip 
							) AS x
						GROUP BY
							nip
					) AS nk
				WHERE
					b.NIP = '$cek_nip'
					
				SELECT SCOPE_IDENTITY() AS id_pelamar;";

				if($debug) $f->pre($sql);
				$result=$db->Execute($sql);

				//if(!$result)print $db->ErrorMsg();
				if(!$result) {
					$wsresult = array('status' => false, 'caption' => 'Gagal', 'message' => 'Gagal mengirim lamaran');
				} else {
					$wsresult = array('status' => true, 'caption' => 'Berhasil', 'message' => 'Lamaran Anda berhasil disimpan');

					while($result->nextRecordSet() and $result->fieldCount()<1){	// lanjut ke next record set, sampai nemu hasil
					}

					while ( $row = $result->FetchRow () ) {
						$id_pelamar = $row['id_pelamar'];
					}
					
					if (empty($id_pelamar)) {
						$f->insert_log("GAGAL INSERT AKTIFITAS PELAMAR. ID_PELAMAR: gagal digenerate, ID_FORMASI:$cek_id_formasi","$sql","$login_nip");
					} else {
						$sql_aktifitas = "INSERT INTO dbo.REC_PELAMAR_AKTIFITAS
													   (ID_PELAMAR
													   ,ID_FORMASI
													   ,STS_PELAMAR
													   ,KET_STS_PELAMAR
													   ,TGL_BUAT_AKTIFITAS
													   ,NIP_BUAT_AKTIFITAS
													   ,MPP_ID
													   ,PRIORITAS
													   ,ID_ROOM)
											SELECT
												$id_pelamar,
												$cek_id_formasi,
												KD_STATUS_PELAMAR,
												STATUS_PELAMAR,
												GETDATE(),
												'$nip',
												(SELECT MPP_ID FROM REC_PTK WHERE ID_FORMASI = $cek_id_formasi),
												$cek_prioritas,
												$value_id_room
											FROM
												dbo.REC_STATUS_PELAMAR
											WHERE
												KD_STATUS_PELAMAR = $status_pelamar";
						$res_sql_aktifitas = $db->Execute($sql_aktifitas);
						$f->insert_log("INSERT AKTIFITAS PELAMAR. ID_PELAMAR:$id_pelamar, ID_FORMASI:$cek_id_formasi","$sql_aktifitas","$login_nip");
					}
				}
			}
        }
	} elseif ($wsdata=="listpelamar") {
		if (!empty($_POST['page'])) {
			if (is_numeric($_POST['page'])) {
				$hal = $_POST['page'];
			} else {
				$hal = 1;
			}
		} else {
			$hal = 1;
		}
		$perhalaman = 10;	// jumlah item yg di tampilkan perhalaman
		$offset = $perhalaman * ($hal - 1) + 1;
		$rowstart = $offset;
		$rowend = $offset + $perhalaman;
		
		if (empty($_POST['req_id'])) {
			$wsresult = array('status' => false, 'message' => 'missing req_id');
		} elseif (empty($_POST['tanggal_publish'])) {
			$wsresult = array('status' => false, 'message' => 'missing tanggal_publish');
		} elseif (empty($_POST['tanggal_selesai'])) {
			$wsresult = array('status' => false, 'message' => 'missing tanggal_selesai');
		} else {
			$cek_req_id = $_POST['req_id'];
			$cek_tanggal_publish = $_POST['tanggal_publish'];
			$cek_tanggal_selesai = $_POST['tanggal_selesai'];
			$cek_id_room = $_POST['id_room'];
			
			$sql_totalrow = "SELECT COUNT(*) AS jmlrow FROM rec_pelamar_internal a inner join rec_permintaan_advertising g on a.req_id=g.req_id 
			where a.req_id='$cek_req_id' and g.tanggal_publish='$cek_tanggal_publish' and g.tanggal_selesai='$cek_tanggal_selesai'";
			if (!empty($cek_id_room)) {
				$sql_totalrow .= " and a.ID_ROOM = ".$cek_id_room;
			}
			$result_totalrow = $f->get_last_record($sql_totalrow);
			
			if ($result_totalrow['jmlrow']%$perhalaman>0) {
				$jumlahhalaman = (($result_totalrow['jmlrow']-($result_totalrow['jmlrow'] % $perhalaman)) / $perhalaman +1);
			} else {
				$jumlahhalaman = (($result_totalrow['jmlrow']-($result_totalrow['jmlrow'] % $perhalaman)) / $perhalaman);
			}
			
			/*$sql = "select a.nip, a.nm_peg, b.nm_jns_kelamin_peg, b.nm_pend_umum, b.nm_kantor, d.nm_unit_org as satker, e.nm_unit_org as depkom, f.nm_unit_org as bidang
					from rec_pelamar_internal a
					inner join spg_data_current b on a.nip=b.nip
					left join spg_08_unit_organisasi c on b.kd_unit_org=c.kd_unit_org
					left JOIN SPG_08_UNIT_ORGANISASI d on c.KD_UNIT_ES3=d.KD_UNIT_ORG
					left JOIN SPG_08_UNIT_ORGANISASI e on c.KD_UNIT_ES2=e.KD_UNIT_ORG
					left JOIN SPG_08_UNIT_ORGANISASI f on c.KD_UNIT_ES1=f.KD_UNIT_ORG
					left join rec_permintaan_advertising g on a.req_id=g.req_id
					where a.req_id='$cek_req_id' and g.tanggal_publish='$cek_tanggal_publish' and g.tanggal_selesai='$cek_tanggal_selesai' ORDER BY	a.no";*/
			$sql = "SELECT a.*
			FROM
				(
					select 
					ROW_NUMBER() OVER (ORDER BY a.nm_peg) AS no,
					a.nip, a.nm_peg, b.nm_jns_kelamin_peg, b.nm_pend_umum, b.nm_kantor, CASE WHEN COALESCE(d.nm_unit_org, '') <> '' THEN d.nm_unit_org ELSE c.nama_satker_organisasi END AS satker, e.nm_unit_org as depkom, f.nm_unit_org as bidang
					from rec_pelamar_internal a
					inner join spg_data_current b on a.nip=b.nip
					left join spg_08_unit_organisasi c on b.kd_unit_org=c.kd_unit_org
					left JOIN SPG_08_UNIT_ORGANISASI d on c.KD_UNIT_ES3=d.KD_UNIT_ORG
					left JOIN SPG_08_UNIT_ORGANISASI e on c.KD_UNIT_ES2=e.KD_UNIT_ORG
					left JOIN SPG_08_UNIT_ORGANISASI f on c.KD_UNIT_ES1=f.KD_UNIT_ORG
					inner join rec_permintaan_advertising g on a.req_id=g.req_id
					where a.req_id='$cek_req_id' and g.tanggal_publish='$cek_tanggal_publish' and g.tanggal_selesai='$cek_tanggal_selesai'";
			if (!empty($cek_id_room)) {
				$sql .= " and a.ID_ROOM = ".$cek_id_room;
			}
			$sql .= "
				) AS a
			WHERE
				a.no >= $rowstart
				AND a.no < $rowend
			ORDER BY
				a.no";
			$result=$db->Execute($sql);
			
			$tmp_data = array();
			$td = 0;
			while($row=$result->FetchRow()){
				$tmp_data[$td] = $row;
				$td++;
			}
			//print_r($tmp_data);
			
			$wsresult = array('status' => true, 'total_rows' => $result_totalrow['jmlrow'], 'total_pagess' => $jumlahhalaman, 'rows_per_page' => $perhalaman, 'page' => $hal, 'data' => $tmp_data);
			
		}
	} elseif ($wsdata=="dodelete") {
		if (empty($_POST['nip'])) {
			$wsresult = array('status' => false, 'message' => 'missing nip');
		} elseif (empty($_POST['req_id'])) {
			$wsresult = array('status' => false, 'message' => 'missing REQ_ID');
		} elseif (empty($_POST['id_formasi'])) {
			$wsresult = array('status' => false, 'message' => 'missing id_formasi');
		} else {
			$del_nip = base64_decode($_POST['nip']);
			$del_req_id = $_POST['req_id'];
			$del_id_formasi = $_POST['id_formasi'];
			$del_id_room = $_POST['id_room'];
			if (!empty($del_id_room)) {
				$value_id_room = $del_id_room;
			} else {
				$value_id_room = "NULL";
			}

			$sql_get_id = "SELECT ID AS id_pelamar FROM REC_PELAMAR_INTERNAL WHERE ID_FORMASI = $del_id_formasi AND REQ_ID = '$del_req_id' AND NIP = '$del_nip'";
			if (!empty($del_id_room)) {
				$sql_get_id .= " and ID_ROOM = ".$del_id_room;
			}
			$id_pelamar = $db->getOne($sql_get_id);
			
			$sql_get_prioritas = "SELECT PRIORITAS FROM REC_PELAMAR_INTERNAL WHERE ID_FORMASI = $del_id_formasi AND REQ_ID = '$del_req_id' AND NIP = '$del_nip'";
			if (!empty($del_id_room)) {
				$sql_get_prioritas .= " and ID_ROOM = ".$del_id_room;
			}
			$prioritas = $db->getOne($sql_get_prioritas);
			
			$sql_history = "INSERT INTO dbo.REC_PELAMAR_INTERNAL_HISTORY (RPI_ID, NIP, NM_PEG, REQ_ID, TANGGAL_APPLY, STATUS, TANGGAL_SELEKSI, NAMA_SELEKSI, TANGGAL_ANGKAT, NAMA_ANGKAT, PEGAWAI, CMP_ID, KD_KANTOR, KD_UNIT_ORG, KD_JABATAN, KD_PANGKAT, KD_SKALA_GAJI, NO_SK, TGL_SK, TGL_MULAI_BERLAKU, TGL_PUBLISH, KSO_KASUSNOMOR, TGL_PINDAH_LOWONGAN, NAMA_PINDAH_LOWONGAN, TOTAL_SKOR, STATUS_PUBLISH, TGL_LIHAT_PUBLISH, PENGANGKATAN, TGL_PINDAH_SELAMBATNYA, STATUS_SEBELUM_BATAL, JUMLAH_PINDAH_LOWONGAN, BIDANG, DEPUTI_KOMISIONER, DEPARTEMEN, DIREKTORAT, SATKER, FORMASI, JABATAN, UNIT_ORGANISASI, KD_GOL, NM_GOL, USIA, MASA_DINAS_LVL_JABATAN, MASA_DINAS_JABATAN, MASA_DINAS_OJK, NILAI_KINERJA_1, NILAI_KINERJA_2, NILAI_KINERJA_3, NILAI_KINERJA_TOTAL, TGL_LAHIR, TEMPAT_LAHIR_PEG, NM_PEND_UMUM, KD_SATKER, KD_JABATAN_STR, ID_FORMASI, ID_PELAMAR, TANGGAL_BATAL, STATUS_BATAL, PRIORITAS, ID_ROOM)	SELECT RPI_ID, NIP, NM_PEG, REQ_ID, TANGGAL_APPLY, STATUS, TANGGAL_SELEKSI, NAMA_SELEKSI, TANGGAL_ANGKAT, NAMA_ANGKAT, PEGAWAI, CMP_ID, KD_KANTOR, KD_UNIT_ORG, KD_JABATAN, KD_PANGKAT, KD_SKALA_GAJI, NO_SK, TGL_SK, TGL_MULAI_BERLAKU, TGL_PUBLISH, KSO_KASUSNOMOR, TGL_PINDAH_LOWONGAN, NAMA_PINDAH_LOWONGAN, TOTAL_SKOR, STATUS_PUBLISH, TGL_LIHAT_PUBLISH, PENGANGKATAN, TGL_PINDAH_SELAMBATNYA, STATUS_SEBELUM_BATAL, JUMLAH_PINDAH_LOWONGAN, BIDANG, DEPUTI_KOMISIONER, DEPARTEMEN, DIREKTORAT, SATKER, FORMASI, JABATAN, UNIT_ORGANISASI, KD_GOL, NM_GOL, USIA, MASA_DINAS_LVL_JABATAN, MASA_DINAS_JABATAN, MASA_DINAS_OJK, NILAI_KINERJA_1, NILAI_KINERJA_2, NILAI_KINERJA_3, NILAI_KINERJA_TOTAL, TGL_LAHIR, TEMPAT_LAHIR_PEG, NM_PEND_UMUM, KD_SATKER, KD_JABATAN_STR, ID_FORMASI, ID, GETDATE(), 1, PRIORITAS, ID_ROOM FROM dbo.REC_PELAMAR_INTERNAL WHERE REQ_ID = '$del_req_id' AND NIP = '$del_nip' AND STATUS IN ('0','1','2','4') AND ID_FORMASI = $del_id_formasi";
			if (!empty($del_id_room)) {
				$sql_history .= " AND ID_ROOM = ".$del_id_room;
			}
			//echo $sql_history;
			$result_history = $db->Execute($sql_history);
			//print_r($result_history);
			if(!$result_history) {
				$wsresult = array('status' => false, 'caption' => 'Gagal', 'message' => 'Gagal membatalkan lamaran');
			} else {
				$sql_delete = "DELETE FROM rec_pelamar_internal WHERE REQ_ID = '$del_req_id' AND NIP = '$del_nip' AND STATUS IN ('0','1','2','4')";
				if (!empty($del_id_room)) {
					$sql_delete .= " and ID_ROOM = ".$del_id_room;
				}
				//echo $sql_delete;
				$result_delete = $db->Execute($sql_delete);
				//print_r($result_delete);
				if(!$result_delete) {
					$wsresult = array('status' => false, 'caption' => 'Gagal', 'message' => 'Gagal membatalkan lamaran');
				} else {
					$sql_aktifitas = "INSERT INTO dbo.REC_PELAMAR_AKTIFITAS
												   (ID_PELAMAR
												   ,ID_FORMASI
												   ,STS_PELAMAR
												   ,KET_STS_PELAMAR
												   ,TGL_BUAT_AKTIFITAS
												   ,NIP_BUAT_AKTIFITAS
												   ,MPP_ID
												   ,PRIORITAS
												   ,ID_ROOM)
										SELECT
											$id_pelamar,
											$del_id_formasi,
											KD_STATUS_PELAMAR,
											STATUS_PELAMAR,
											GETDATE(),
											'$nip',
											(SELECT MPP_ID FROM REC_PTK WHERE ID_FORMASI = $del_id_formasi),
											$prioritas,
											$value_id_room
										FROM
											dbo.REC_STATUS_PELAMAR
										WHERE
											KD_STATUS_PELAMAR = 9";	// 9: Batal/Pindah Lowongan
					$res_sql_aktifitas = $db->Execute($sql_aktifitas);
				
					$wsresult = array('status' => true, 'caption' => 'Berhasil', 'message' => 'Lamaran Anda berhasil dibatalkan');
				
					$f->insert_log("DELETE APPLY LOWONGAN INTERNAL. REQ_ID:$del_req_id, NIP:$del_nip","$sql_delete","$login_nip");
				}
			}
		}
	}
	header('Content-Type: application/json');
	echo json_encode($wsresult);
} elseif ($act=="detail") {
        $sql = "select b.req_id,a.ptk_id,b.keterangan,e.nm_unit_org as satker,f.nm_unit_org as depkom,c.nm_kantor as kantor,m.masa_dinas_minimal,m.sisa_dinas,m.tanggal_dinas, g.nm_unit_org as bidang,n.NM_PEND_UMUM,
                isnull(n.KD_PEND_UMUM,0) as kd_pend_umum, j.posisi as posisi_jabatan,a.kd_jabatan,b.tanggal_publish,b.tanggal_selesai,b.jam_selesai,m.kd_gol,a.mpp_id,m.tanggal_buat,h.NM_GOLONGAN,
                m.nilai_kinerja as nilai1, m.nilai_kinerja_1 as nilai2, m.nilai_kinerja_2 as nilai3
                from rec_ptk a
                left join rec_permintaan_advertising b ON a.ptk_id=b.req_id
                left join SPG_08_KANTOR c on a.kd_kantor=c.kd_kantor
                left join spg_08_unit_organisasi d on a.kd_unit_org=d.kd_unit_org
                left JOIN SPG_08_UNIT_ORGANISASI e on d.KD_UNIT_ES3=e.KD_UNIT_ORG
                left JOIN SPG_08_UNIT_ORGANISASI f on d.KD_UNIT_ES2=f.KD_UNIT_ORG
                left JOIN SPG_08_UNIT_ORGANISASI g on d.KD_UNIT_ES1=g.KD_UNIT_ORG
                left join SPG_08_JABATAN_UNIT j on (a.KD_JABATAN=j.KD_JABATAN and a.KD_UNIT_ORG=j.KD_UNIT_ORG)
                left join SPG_08_JABATAN_STR k on a.kd_jabatan=k.KD_JABATAN_STR
                left join SPG_JABATAN_PANGKAT l on a.kd_jabatan=l.KD_JABATAN_STR
                left join REC_PERSYARATAN m on (m.KD_GOL=l.KD_GOL and m.periode=a.mpp_id)
                left join spg_golongan h on m.kd_gol=h.kd_gol
                left join spg_eselon i on h.KD_ESELON=i.KD_ESELON
                left join SPG_JNS_PEND_UMUM n on m.PENDIDIKAN = n.KD_PEND_UMUM
                where b.ram_id='RAM-000020' and b.rac_id='RAC-000001' and b.req_id='$req_id'
                order by a.ptk_id desc ";
        //$f->pre($sql);
        $result=$f->get_last_record($sql);
        foreach($result as $key=>$val){
            $$key=trim($val);
        }
        $thn_kurangdua=date('Y',strtotime($tanggal_buat))-2;
        $thn_kurangsatu=date('Y',strtotime($tanggal_buat))-1;
        $thn_sekarang=date('Y',strtotime($tanggal_buat));
        if($sanksi==0){
            $ket_sanksi="Tidak sedang kena sanksi";
        }
        else{
            $ket_sanksi="Sedang kena sanksi";
        }
        echo"
        <div id='loading'></div>

        <table class='table no-border'>
            <tr>
                <td colspan=\"2\"><span style=\"color: #C20D0D\"><B><I>Perubahan Jabatan yang dilamar hanya dapat dilakukan 1x</B></td></span>
            </tr>
            <tr>
                <td width=\"140px\"><B><I>Keterangan </B>: <P>".nl2br($keterangan)."</td>
                <td></td>
            </tr>
            <tr>
                <td><B>Kantor</B></td>
                <td>$kantor</td>
            </tr>
            <tr>
                <td><B>Bidang</B></td>
                <td>$bidang</td>
            </tr>

            <tr>
                <td><B>Satuan Kerja</B></td>
                <td>$satker</td>
            </tr>
            <tr>
                <td><B>Formasi</B></td>
                <td>$posisi_jabatan</td>
            </tr>
            <tr>
                <td><B>Batas Akhir</B></td>
                <td>".$f->convert_date_id($tanggal_selesai)." Pukul $jam_selesai WIB</td>
            </tr>
            <tr>
                <td valign=top colspan=\"2\"><B>Pelamar:</B><br>
			";
			$sql = "select a.nip, a.nm_peg, b.nm_jns_kelamin_peg, b.nm_pend_umum, b.nm_kantor, d.nm_unit_org as satker, e.nm_unit_org as depkom, f.nm_unit_org as bidang
					from rec_pelamar_internal a
					inner join spg_data_current b on a.nip=b.nip
					left join spg_08_unit_organisasi c on b.kd_unit_org=c.kd_unit_org
					left JOIN SPG_08_UNIT_ORGANISASI d on c.KD_UNIT_ES3=d.KD_UNIT_ORG
					left JOIN SPG_08_UNIT_ORGANISASI e on c.KD_UNIT_ES2=e.KD_UNIT_ORG
					left JOIN SPG_08_UNIT_ORGANISASI f on c.KD_UNIT_ES1=f.KD_UNIT_ORG
					left join rec_permintaan_advertising g on a.req_id=g.req_id
					where a.req_id='$req_id' and g.tanggal_publish='$tanggal_publish' and g.tanggal_selesai='$tanggal_selesai'";
			#$f->pre($sql);
			echo"
			<table style=\"border-spacing: 1px; border-collapse: separate;\">
				<tr style=\"background-color: #e1e1e1;\">
					<th style=\"padding: 4px;\">No.</th>
					<th style=\"padding: 4px;\">NIP</th>
					<th style=\"padding: 4px;\">Nama Pegawai</th>
					<th style=\"padding: 4px;\">Jenis Kelamin</th>
					<th style=\"padding: 4px;\">Pendidikan Terakhir</th>
					<th style=\"padding: 4px;\">Kantor</th>
					<th style=\"padding: 4px;\">Satuan Kerja</th>
				</tr>";
			$result=$db->Execute($sql);
			$i=0;
			while($row=$result->FetchRow()){
			foreach($row as $key=>$val){
				$key=strtolower($key);
				$$key=$val;
			}
			if($satker==''){
					$satuan_kerja="$bidang >> $depkom";
				}
				if($depkom==''){
					$satuan_kerja="$bidang";
				}
				else{
					$satuan_kerja="$bidang >> $depkom >> $satker";
				}
			$i++;
			echo"
				<tr>
					<td style=\"padding: 4px;\">$i</td>
					<td style=\"padding: 4px;\">$nip</td>
					<td style=\"padding: 4px;\">$nm_peg</td>
					<td style=\"padding: 4px;\">$nm_jns_kelamin_peg</td>
					<td style=\"padding: 4px;\">$nm_pend_umum</td>
					<td style=\"padding: 4px;\">$nm_kantor</td>
					<td style=\"padding: 4px;\">$satuan_kerja</td>

				</tr>";
			}
			echo"</table>";
			echo "
                </td>
            </tr>";

            /*<tr>
                <td colspan=2 align=center><br><b>Apakah Anda Yakin Apply Lowongan ini ?</b>
				
				<input value=\"test Apply\" class=\"button\" type=\"button\" data-toggle=\"modal\" data-target=\"#msgModal\" >
				
				<a href=\"javascript:void(0);\" data-href=\"getContent.php?id=1\" class=\"openPopup\">test Apply</a>
				<input value=\"test Apply 2\" class=\"button\" type=\"button\" onlick=\"submit_modal()\" >
				</td>
            </tr>";*/
            if($_GET['apply']=='1'){
                /*echo "
                    <tr>
                    <form method=\"post\" action=\"lowongan_internal_v2.php?act=do_apply\">
                    <input type=hidden name=req_id id=req_id value='$req_id'>
                        <td><input type=\"submit\" name=\"submit\" class=\"btn2\" style=\"width:130px;\" value=\"Apply\"/></td>
                    </form>
                    </tr>";*/
				echo "
                    <tr>
					<input value=\"Apply\" style=\"width:130px;\" class=\"btn2\" type=\"button\" data-toggle=\"modal\" data-target=\"#msgModal\" ></td>
                    </tr>";

            }
		
		
        echo "</table>";
		
		$sql_cek = "SELECT * FROM rec_pelamar_internal WHERE NIP = '$login_nip' AND STATUS IN ('0','1','2','4') AND REQ_ID = '$req_id'";
		$result_cek = $db->Execute($sql_cek);
        if(!$result_cek)print $db->ErrorMsg();
        $num_cek = $result_cek->RecordCount();


		if ($num_cek>0) {
			echo "<form onsubmit=\"return confirm('Yakin akan membatalkan lamaran ini?');\" method=\"post\" action=\"lowongan_internal_v3_detail.php?act=do_cancel\">";
			echo "<input value=\"Batal Lamar\" style=\"width:130px;\" class=\"btn2\" type=\"submit\" >";
		} else {
			echo "<form onsubmit=\"return confirm('Yakin akan melamar lowongan ini?');\" method=\"post\" action=\"lowongan_internal_v3_detail.php?act=do_apply\">";
			//echo "<div class=\"box-detail\"><a href=\"lowongan_internal_v3_detail.php?act=detail&req_id=$req_id\" class=\"btn btn-primary btn-sm\">Apply</a></div>";
			echo "<input value=\"Apply\" style=\"width:130px;\" class=\"btn2\" type=\"submit\" >";
		}
		echo "&nbsp;&nbsp;<input type=button value='&larr;Kembali' onclick=\"history.back(-1);\" id='tombol_kembali'>";
		echo "<input type=hidden name=req_id id=req_id value='$req_id'>";
		echo "<input type=hidden name=es1 id=req_id value='".$es1."'>";
		echo "</form><br><br>";
/*		
		$bisa_apply = true;
         echo "<div id=\"msgModal\" class=\"modal fade bs-example-modal-sm\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"msgModalLabel\" aria-hidden=\"true\">
                    <div class=\"modal-dialog modal-sm\">
                        <div class=\"modal-content\">
                            <div class=\"modal-header\">
                                <button type=\"button\" class=\"close\" data-dismiss=\"modal\"><span aria-hidden=\"true\">&times;</span><span class=\"sr-only\">Close</span></button>
                                <h5 class=\"modal-title\" id=\"msgModalLabel\">";
		if ($bisa_apply) {
			echo "Konfirmasi";
		} else {
			echo "";
		}
		echo "</h5>
                            </div>
                            <div class=\"modal-body\" style=\"height:auto\">
								<p style=\"font-size: 12px;margin: 10px 8px 10px;line-height: 20px;\">";
		if ($bisa_apply) {
			echo "Apakah Anda yakin akan melamar lowongan ini?";
		} else {
			echo "Anda tidak bisa melamar lowongan ini karena telah melamar di bidang yang sama";
		}
								echo "</p>
                            </div>
                            <div class=\"modal-footer\">
                                <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>";
		if ($bisa_apply) {
			echo "<form method=\"post\" action=\"lowongan_internal_v3_detail.php?act=do_apply\">
                    <input type=hidden name=req_id id=req_id value='$req_id'>
                        <td><input type=\"submit\" name=\"submit\" class=\"btn2\" style=\"width:130px;\" value=\"Apply\"/></td>
                    </form>";
		}
                            echo "</div>
                        </div>
                    </div>
                </div>";*/
}elseif($act=="do_apply"){
        if(isset($_POST)){
            $key_id=$f->generate_nomorkolom("rec_pelamar_internal","rpi_id","RPI");
            $detail_pegawai=$f->detailPegawai($login_nip);
            $nm_peg=$detail_pegawai['nm_peg'];
            $sql="insert into rec_pelamar_internal (rpi_id,nip,nm_peg,req_id,tanggal_apply,status,pengangkatan,jumlah_pindah_lowongan) values ('$key_id','$login_nip','$nm_peg','$req_id',getdate(),'2','0',0)";
            if($debug) $f->pre($sql);
            $result=$db->Execute($sql);
            if(!$result)print $db->ErrorMsg();

            $f->insert_log("INSERT APPLY LOWONGAN INTERNAL. REQ_ID:$req_id, NIP:$nip","$sql","$login_nip");
            //$f->result_message("Lamaran Anda berhasil di simpan<P><a href=../../home.php>&larr; Kembali</a>");
			echo "<script type=\"text/javascript\">
			alert('Lamaran Anda berhasil di simpan');
			window.location = 'lowongan_internal_v3_detail.php?es1=".$_POST['es1']."';
			</script>
			";
        }

} else {

//$menu=array(basename($PHP_SELF)=>"Lowongan Yang Dilamar");
//echo $template->tab_top_relative($title,$menu);




	echo "<style>
	.list-container {
	  display: grid;
	  /*width: 466px;*/
	  /*height: 100%;*/
	  grid-template-columns: 1fr;
	  grid-template-rows: auto auto 1fr;
	}
	.list-container > div {
	  /*border: 1px dashed #888;*/
	  padding: 4px;
	  margin: 4px;
	}

	.box-jo {
		-webkit-box-shadow: 4px 4px 11px -6px rgba(0,0,0,0.5); 
		box-shadow: 4px 4px 11px -6px rgba(0,0,0,0.5);
		background: #EAEAEA;
		/*height: 61px;*/
		padding: 6px;
		position: relative;
		overflow: auto;
	}
	.box-jo:hover {
		-webkit-box-shadow: 5px 5px 14px -2px rgba(0,0,0,0.9); 
		box-shadow: 5px 5px 14px -2px rgba(0,0,0,0.9);
		background: #EFEFEF;
	}
	body#tinymce {
	background: #FFFFFF
	}

	.box-no {
		float: left;
		width: 25px;
	}
	.box-jml {
		position: absolute;
		text-align: left;
		bottom: 0;
		left: 25px;
		padding: 6px;
	}
	.box-detail {
		position: absolute;
		text-align: right;
		bottom: 0;
		right: 0;
		padding: 10px;
	}
	
	.overriderow > tbody > tr > td, .overriderow > tr > td {
		border-top: 1px solid #f7f7f7;
	}
	
	.clear {
	  clear: both;
	}

	.tabel1 {
	  border-collapse: collapse;
	  /*width: 30em;*/
	  border: 1px solid #666;
	  font-size: 11px;
	  font-family: 'Tahoma';
	  line-height:normal;
	}

	.tabel1 caption {
	  font-size: 1.2em;
	  /*font-weight: bold;
	  margin: 1em 0;*/
	}

	.tabel1 col {
	  border-right: 1px solid #ccc;
	}

	.tabel1 col#lastCol {
	  border: none;
	}

	.tabel1 thead {
	  background: #ccc url(images/bar.gif) repeat-x left center;
	  border-top: 1px solid #a5a5a5;
	  border-bottom: 1px solid #a5a5a5;
	}

	.tabel1 tfoot {
	  /*background: #fff;*/
	  background: #F0F0F0;
	  border-top: 1px solid #dcdcdc;
	  border-bottom: 1px solid #a5a5a5;
	}

	.tabel1 th {
	  font-weight: normal;  /*font-weight: bold;*/
	  text-align: center;   /*text-align: left;*/
	}

	.tabel1 #tablePosHead {
	  text-indent: -1000em;
	}

	.tabel1 th, .tabel1 td {
	  padding: 0.1em 0.3em;
	}

	.tabel1 .linktable {
	  color: #005;
	}

	.tabel1 .linktable:hover {
	  color: #fff;
	  /*font-weight: bold;*/
	}

	.tabel1 .odd {
	  background-color:#edf5ff;
	}

	.tabel1 .even {
	  background-color:#fff;
	}

	.tabel1 .read {
	  background-color:#D6D6D6;		/* #E6E6E6 */
	}

	.tabel1 .judul {
	  background-color:#ccc;
	  border-top: 1px solid #a5a5a5;
	  border-bottom: 1px solid #dcdcdc;
	}

	.tabel1 .judul:hover {
	  /*background-color: transparent;	// kalo ga ada warna bekgron */
	  background-color:#ccc;
	  color: inherit;
	}

	.tabel1 tr:hover {
	  background-color:#78A8E9;
	  /*background-color:#3d80df;*/
	  color: #fff;
	}

	.tabel1 thead tr:hover {
	  background-color: transparent;
	  color: inherit;
	}

	.tabel1 tfoot tr:hover {
	  background-color: transparent;
	  color: inherit;
	}
	
	.divTable{
		display: table;
		width: 100%;
		/*margin-left: 20px;*/
	}
	.divTableRow {
		display: table-row;
	}
	.divTableRow:hover {
		background-color: white;
	}
	.divTableHeading {
		background-color: #EEE;
		display: table-header-group;
	}
	.divTableCell, .divTableHead {
		/*border: 1px solid #999999;*/
		display: table-cell;
		/*padding: 3px 10px;*/
		padding: 2px 2px 2px 5px;
	}
	.divTableHeading {
		background-color: #EEE;
		display: table-header-group;
		font-weight: bold;
	}
	.divTableFoot {
		background-color: #EEE;
		display: table-footer-group;
		font-weight: bold;
	}
	.divTableBody {
		display: table-row-group;
	}
	</style>

	<script type=\"text/javascript\">
	
	$(document).ready(function(){
		//var dropdowndepkom = document.getElementById('depkom');
		//dropdowndepkom.selectedIndex = 0;
		
		$('#filter').val('');
		$('#filter').keyup(function() {

			var filter = $(this).val(),
			count = 0;

			$('.list-container .results').each(function() {

				if ($(this).find('.lowjab_desc').text().search(new RegExp(filter, 'i')) < 0) {
					$(this).hide();
				} else {
					$(this).show();
					
					count++;
				}

			});

		});
		
	});
		
		function loadpelamar(lp_req_id, lp_tanggal_publish, lp_tanggal_selesai, id_room = null, hal = 1) {
			$.ajax({
				method: \"POST\",
				dataType: \"json\",
				url: \"lowongan_internal_v3_detail.php?act=jsonws&wsdata=listpelamar\",
				data: { req_id: lp_req_id, tanggal_publish: lp_tanggal_publish, tanggal_selesai: lp_tanggal_selesai, id_room: id_room, page: hal },
				success: function(data) {
					if (data.status) {
						// console.log(data.data);
						$('#list_pelamar tbody').empty();
						if (data.data.length>0) {
							$.each(data.data, function(k, v) {
								if (k % 2 === 0) {
									var oddeven = 'even';
								} else {
									var oddeven = 'odd';
								}
								var baris = '<tr class=\"'+oddeven+'\"><td style=\"padding: 4px;\">'+v.no+'</td><td style=\"padding: 4px;\">'+v.nip+'</td><td style=\"padding: 4px;\">'+v.nm_peg+'</td><td style=\"padding: 4px;\">'+v.nm_jns_kelamin_peg+'</td><td style=\"padding: 4px;\">'+v.nm_pend_umum+'</td><td style=\"padding: 4px;\">'+v.nm_kantor+'</td><td style=\"padding: 4px;\">'+v.satker+'</td></tr>';
								$('#list_pelamar tbody').append(baris);
							});
						} else {
							var baris = '<tr class=\"even\"><td colspan=\"7\" style=\"padding: 4px; text-align: center;\">Tidak ada pelamar</td></tr>';
							$('#list_pelamar tbody').append(baris);
						}
						var jumlahhalaman = 0;
						if (data.total_rows % data.rows_per_page>0) {
							jumlahhalaman = ((data.total_rows - (data.total_rows % data.rows_per_page)) / data.rows_per_page +1);
						} else {
							jumlahhalaman = ((data.total_rows - (data.total_rows % data.rows_per_page)) / data.rows_per_page);
						}
						var awal = 0;
						var akhir = 0;
						if (jumlahhalaman<=5) {
							awal = 1;
							akhir = jumlahhalaman;
						} else {
							if (data.page<=3) {
								awal = 1;
								akhir = 5;
							} else if ((data.page+2)>=jumlahhalaman) {
								awal = jumlahhalaman-4;
								akhir = jumlahhalaman;
							} else {
								awal = data.page-2;
								akhir = data.page+2;
							}
						}
						if (jumlahhalaman>1) {
							var listpaging = '';
							if (data.page>2) {
								listpaging += '<a href=\"javascript:void(0);\" onclick=\"loadpelamar(\''+lp_req_id+'\', \''+lp_tanggal_publish+'\', \''+lp_tanggal_selesai+'\', '+id_room+', \'1\');\" title=\"Halaman pertama\" style=\"color: blue;\">[first]</a>&nbsp;&nbsp;';
							}

							if (data.page>1) {
								var prev_page = parseInt(data.page)-1;
								listpaging += '<a href=\"javascript:void(0);\" onclick=\"loadpelamar(\''+lp_req_id+'\', \''+lp_tanggal_publish+'\', \''+lp_tanggal_selesai+'\', '+id_room+', '+prev_page+');\" title=\"Halaman sebelumnya\" style=\"color: blue;\">[prev]</a>&nbsp;&nbsp;';
							}


							for (i=awal; i<=akhir; i++) {
								if (parseInt(data.page)==i) {
									listpaging += '<b>'+i+'</b>&nbsp;&nbsp;';
								} else {
									listpaging += '<a href=\"javascript:void(0);\" onclick=\"loadpelamar(\''+lp_req_id+'\', \''+lp_tanggal_publish+'\', \''+lp_tanggal_selesai+'\', '+id_room+', \''+i+'\');\" title=\"Halaman '+i+'\" style=\"color: blue;\">'+i+'</a>&nbsp;&nbsp;';
								}
							}

							if (data.page<jumlahhalaman) {
								console.log(data.page);
								var next_link = parseInt(data.page)+1;
								listpaging += '<a href=\"javascript:void(0);\" onclick=\"loadpelamar(\''+lp_req_id+'\', \''+lp_tanggal_publish+'\', \''+lp_tanggal_selesai+'\', '+id_room+', '+next_link+');\" title=\"Halaman berikutnya\" style=\"color: blue;\">[next]</a>&nbsp;&nbsp;';
							}

							if (data.page<(jumlahhalaman-1)) {
								listpaging += '<a href=\"javascript:void(0);\" onclick=\"loadpelamar(\''+lp_req_id+'\', \''+lp_tanggal_publish+'\', \''+lp_tanggal_selesai+'\', '+id_room+', '+jumlahhalaman+');\" title=\"Halaman akhir\" style=\"color: blue;\">[last]</a>&nbsp;&nbsp;';
							}

							$('#paging').html(listpaging);
						}
					} else {
						alert('Gagal memuat daftar pelamar');
					}
				},
				error: function() {
					console.log('error');
					alert('Error');
				}
			});
		}

		function detailLowongan(req_id, id_formasi, id_room){
			//var req_id = $('#req_id').val();
			//alert(req_id);
			$.ajax({
				method: \"POST\",
				dataType: \"json\",
				url: \"lowongan_internal_v3_detail.php?act=jsonws&wsdata=jodetail\",
				data: { req_id: req_id, id_formasi: id_formasi, id_room: id_room },
				success: function(data) {
					if (data.status) {
						// console.log(data.data);
						
						$('#md_kantor').html(data.data.kantor);
						$('#md_bidang').html(data.data.bidang);
						$('#md_satker').html(data.data.satker);
						$('#md_posisi_jabatan').html(data.data.posisi_jabatan);
						$('#md_regulerfto').html(data.data.regulerfto);
						$('#md_tanggal_selesai').html(data.data.tanggal_selesai);
						$('#md_jam_selesai').html(data.data.jam_selesai);
						$('#md_keterangan').html(data.data.keterangan);
						if (data.data.jns_jabatan=='fungsional') {
							$('#kolom_jml_pemenuhan').show();
							$('#md_jml_pemenuhan').text(data.data.jumlah);
						} else {
							$('#kolom_jml_pemenuhan').hide();
							$('#md_jml_pemenuhan').text('');
						}
						$('#md_req_id').val(data.data.req_id);
						$('#md_id_formasi').val(id_formasi);
						$('#md_id_room').val(id_room);
						$('#md_bidang').html(data.data.bidang);
						if (data.data.nm_file_urjab=='') {
							$('#row_urjab').hide();
						} else {
							$('#row_urjab').show();
						}
						$('#md_nm_file_urjab').html(data.data.nm_file_urjab);
						$('#md_path_urjab').attr('href', data.data.path_urjab);
						if (data.data.batal) {
							$('#btn_batal').show();
							$('#btn_apply').hide();
						} else {
							$('#btn_batal').hide();
							$('#btn_apply').show();
						}
						$('#modalDetail').modal('show');
						$('#paging').html('');
						
						var lp_req_id = data.data.req_id;
						var lp_tanggal_publish = data.data.tmp_tanggal_publish;
						var lp_tanggal_selesai = data.data.tmp_tanggal_selesai;
						if (lp_req_id && lp_tanggal_publish && lp_tanggal_selesai) {
							loadpelamar(lp_req_id, lp_tanggal_publish, lp_tanggal_selesai, id_room, '1');
						} else {
							console.log('missing params');
							alert('Gagal memuat daftar pelamar');
						}
					} else {
						console.log(data.message);
						alert('Gagal');
					}
				},
				error: function() {
					console.log('error');
					alert('Error');
				}
			});
		}
		
		// clear
		$(document).on('hidden.bs.modal','#modalDetail', function () {
			$('#md_kantor').html('');
			$('#md_bidang').html('');
			$('#md_satker').html('');
			$('#md_posisi_jabatan').html('');
			$('#md_regulerfto').html('');
			$('#md_tanggal_selesai').html('');
			$('#md_jam_selesai').html('');
			$('#md_keterangan').html('');
			$('#kolom_jml_pemenuhan').hide();
			$('#md_jml_pemenuhan').text('');
			$('#md_req_id').val('');
			$('#md_id_formasi').val('');
			$('#md_id_room').val('');
			$('#md_nm_file_urjab').val('');
			$('#md_path_urjab').val('');
			$('#paging').html('');
		});
		
		function loadbidang(es) {
			//alert(es);
			window.location = 'lowongan_internal_v3_detail.php?es1='+es;
		}
		
		function loaddepkom(es,es2) {
			//alert(es);
			window.location = 'lowongan_internal_v3_detail.php?es1='+es+'&es2='+es2;
		}
		
		
		$(document).on('shown.bs.modal','#modalDetail', function () {
			var modalBodyWidth = $('#modalDetail').find('.modal-body').outerWidth(true) - 20;
			$('#areabody').width(modalBodyWidth);
			// console.log ('modalBodyWidth = ' + modalBodyWidth);

			var setModalBodyWidth = function () {
				var modalBodyWidth = $('#modalDetail').find('.modal-body').outerWidth(true) - 20;
				$('#areabody').width(modalBodyWidth);
				// console.log ('modalBodyWidth = ' + modalBodyWidth);
			};

			$(window).resize(setModalBodyWidth);
		});
		
		function apply(nip){
			var req_id = $('#md_req_id').val();
			var id_formasi = $('#md_id_formasi').val();
			var id_room = $('#md_id_room').val();
			//alert(req_id);
			$.ajax({
				method: \"POST\",
				dataType: \"json\",
				url: \"lowongan_internal_v3_detail.php?act=jsonws&wsdata=apply\",
				data: { req_id: req_id, nip: nip, id_formasi: id_formasi, id_room: id_room },
				success: function(data) {
					if (data.status) {
						if (data.apply) {
							// console.log('bisa apply');
							$('#msgModalTitle').text('Konfirmasi');
							$('#msgModalBody').text('Apakah Anda yakin akan melamar lowongan ini?');
							$('#msgModalpilihan_prioritas').show();
							//if (data.prioritas_terdaftar!=0) {
							//	console.log('prioritas terdaftar: '+data.prioritas_terdaftar);
							//	$('#prioritas').children('option[value=\"+data.prioritas_terdaftar+\"]').css('display','none');
							//}
							if (data.prioritas_terdaftar==1) {
								//$('#prioritas').children('option[value=\"2\"]').
								//$('#prioritas option[value=2]').attr('selected', 'selected');
								$('#prioritas option[value=2]').prop({selected: true});
								$('#prioritas').prop('disabled', true);
							} else if (data.prioritas_terdaftar==2) {
								//$('#prioritas option[value=1]').attr('selected', 'selected');
								$('#prioritas option[value=1]').prop({selected: true});
								$('#prioritas').prop('disabled', true);
							} else {
								//$('#prioritas option[value=1]').attr('selected', 'selected');
								//$('#prioritas').prop('selectedIndex', -1);
								$('#prioritas option[value=1]').removeProp('selected');
								$('#prioritas option[value=2]').removeProp('selected');
								$('#prioritas').prop('disabled', false);
							}
							$('#msgModalprioritas_terdaftar').val(data.prioritas_terdaftar);
							$('#msgModalSubmit').show();
							$('#msgModalBatal').hide();
							$('#msgModalForm :input').prop('disabled', false);
							$('#msgModalreq_id').val(req_id);
							$('#msgModalid_formasi').val(id_formasi);
							$('#msgModalid_room').val(id_room);
							//$('#msgModal').modal('show');
						} else {
							// console.log('tidak bisa apply');
							$('#msgModalTitle').text('Tidak Bisa Apply');
							$('#msgModalBody').text(data.message);
							$('#msgModalpilihan_prioritas').hide();
							$('#msgModalprioritas_terdaftar').val('');
							$('#msgModalSubmit').hide();
							$('#msgModalBatal').hide();
							$('#msgModalForm :input').prop('disabled', true);
							$('#msgModalreq_id').val('');
							$('#msgModalid_formasi').val('');
							$('#msgModalid_room').val('');
							//$('#msgModal').modal('show');
						}
						$('#msgModal').modal('show');
					} else {
						console.log(data.message);
						alert('Gagal');
					}
				},
				error: function() {
					console.log('error');
					alert('Error');
				}
			});
        }
		
		function doapply(nip){
			var req_id = $('#msgModalreq_id').val();
			var id_formasi = $('#msgModalid_formasi').val();
			var id_room = $('#msgModalid_room').val();
			var prioritas = $('#prioritas').children('option:selected').val();
			var prioritas_terdaftar = $('#msgModalprioritas_terdaftar').val();
			if (prioritas_terdaftar==0 && prioritas=='') {
				alert('Silakan pilih prioritas lamaran');
			} else {
				//alert(req_id);
				$('#msgModalSubmit').attr('disabled', true);
				$.ajax({
					method: \"POST\",
					dataType: \"json\",
					url: \"lowongan_internal_v3_detail.php?act=jsonws&wsdata=doapply\",
					data: { req_id: req_id, nip: nip, id_formasi: id_formasi, id_room: id_room, prioritas: prioritas },
					success: function(data) {
						//$('#msgModal').modal('hide');
						//$('#modalDetail').modal('hide');
						//$('#msgModal').modal('toggle');
						if (data.status) {
							$('#msgModalTitle').text(data.caption);
							$('#msgModalBody').text(data.message);
							$('#msgModalpilihan_prioritas').hide();
							$('#msgModalprioritas_terdaftar').val('');
							$('#msgModalSubmit').removeAttr('disabled');
							$('#msgModalSubmit').hide();
							$('#msgModalBatal').hide();
							$('#msgModalForm :input').prop('disabled', true);
							$('#msgModalreq_id').val('');
							$('#msgModalid_formasi').val('');
							$('#msgModalid_room').val('');
							$('#msgModalreload').val('1');
						} else {
							console.log(data.message);
							alert('Gagal');
							$('#msgModalSubmit').removeAttr('disabled');
						}
						//$('#msgModal').modal('show');
						$('#msgModal').modal('handleUpdate');
					},
					error: function() {
						console.log('error');
						alert('Error');
						$('#msgModalSubmit').removeAttr('disabled');
					}
				});
			}
        }
		
		function batal(nip){
			var req_id = $('#md_req_id').val();
			var id_formasi = $('#md_id_formasi').val();
			var id_room = $('#md_id_room').val();
			$('#msgModalTitle').text('Konfirmasi');
			$('#msgModalBody').text('Yakin akan membatalkan lamaran ini?');
			$('#msgModalpilihan_prioritas').hide();
			$('#msgModalprioritas_terdaftar').val('');
			$('#msgModalSubmit').hide();
			$('#msgModalBatal').show();
			$('#msgModalForm :input').prop('disabled', false);
			$('#msgModalreq_id').val(req_id);
			$('#msgModalid_formasi').val(id_formasi);
			$('#msgModalid_room').val(id_room);
			$('#msgModal').modal('show');
        }

		function dobatal(nip){
			var req_id = $('#msgModalreq_id').val();
			var id_formasi = $('#msgModalid_formasi').val();
			var id_room = $('#msgModalid_room').val();
			//alert(req_id);
			$.ajax({
				method: \"POST\",
				dataType: \"json\",
				url: \"lowongan_internal_v3_detail.php?act=jsonws&wsdata=dodelete\",
				data: { req_id: req_id, nip: nip, id_formasi: id_formasi, id_room: id_room },
				success: function(data) {
					if (data.status) {
						$('#msgModalTitle').text(data.caption);
						$('#msgModalBody').text(data.message);
						$('#msgModalpilihan_prioritas').hide();
						$('#msgModalprioritas_terdaftar').val('');
						$('#msgModalSubmit').hide();
						$('#msgModalBatal').hide();
						$('#msgModalForm :input').prop('disabled', true);
						$('#msgModalreq_id').val('');
						$('#msgModalid_formasi').val('');
						$('#msgModalid_room').val('');
						$('#msgModalreload').val('1');
					} else {
						console.log(data.message);
						alert('Gagal');
					}
					$('#msgModal').modal('handleUpdate');
				},
				error: function() {
					console.log('error');
					alert('Error');
				}
			});
        }
		
		$(document).on('hidden.bs.modal','#msgModal', function () {
			var needreload = $('#msgModalreload').val();
			if (needreload=='1') {
				var queryString = window.location.search;
				window.location = 'lowongan_internal_v3_detail.php'+queryString;
			}
			$('#modalDetail').modal('hide');
		});
		
	</script>
	";
/*
    $debug=0;
    $menu = array (
        basename ( $PHP_SELF ) => "Lowongan Internal"
    );
    $standar_button_off = "0";
    $navigation_off = "0";
    $title_off = "1";
    $cfg_reff_table = "";
    $title = "Lowongan Internal";

    $cfg_title = "Lowongan Internal";
    $cfg_subtitle = "Lowongan Internal";
    $primary_key = "";
    $attr_key1 = "";
    $prefix_primary_key = "";
    $_primary_key = $f->primary_key ( $primary_key );
    if (! $start)$start = '0';
    if (! $order)$order = '';
    if (! $sort)$sort = 'asc';
    if (! $page)$page = '0';
    if (! $num)$num = '10';
    $start = ($page - 1) * $num;
    if ($start < 0)$start = '0';
    echo $template->tab_top_relative ( $title, $menu );
*/
echo "<br><table width=98% border=0 cellpadding=0 cellspacing=0 border=0 bgcolor=white ALIGN=CENTER style=\"border-collapse: collapse;
border-spacing: 0;max-width: 100%;font-family: verdana,Arial,tahoma,sans-serif;
font-size: 12px; line-height: 150%;
border: 0px;\">
	<tr align=left>
		<td style=\"border-bottom: 1px solid #CCCCCC;\">
			<table  height=21 cellpadding=0 cellspacing=0 border=0 width=100% style=\"border-collapse: collapse;border-spacing: 0;max-width: 100%;font-family: verdana,Arial,tahoma,sans-serif;font-size: 11px;border: 0px;\">
			<tr>
						<td style=\"color: #000000;width: 2px;background: #DFEFCA;border-top: 1px solid #c0c0c0;border-bottom: 1px solid #c0c0c0;border-left: 1px solid #c0c0c0;text-align: left;\"><img src=/images/s.gif width=3></td>
						<td style=\"padding-left: 4px;padding-right: 4px;color: #000000;font-weight: bold;background: #DFEFCA;border-top: 1px solid#c0c0c0;border-bottom: 1px solid #c0c0c0;text-align: center;\"><a href=lowongan_internal_v3_detail.php style=\"color: #000000;
font-weight: bold;\">Lowongan&nbsp;Internal</a></td>
						<td style=\"color: #000000;width: 2px;background: #DFEFCA;border-top: 1px solid #c0c0c0;border-bottom: 1px solid #c0c0c0;border-right: 1px solid #c0c0c0;text-align: center;\"><img src=/images/s.gif width=3></td>
						<td style=\"border-bottom:1px solid #c0c0c0;\" width=2><img src=/images/s.gif width=2></td>
						
			<td width=60% style=\"border-bottom:1px solid #c0c0c0;\"><img src=/images/s.gif width=2></td>
			
			</tr>
			</table>
		</td>
	</tr>
	<tr>
		<td style=\"border-left:1px solid #c0c0c0;border-bottom:1px solid #c0c0c0;border-right:1px solid #c0c0c0;padding:10 10 10 10;\" valign=top>";


	$sqllistbidang = "select
	b.kd_bidang,
	b.bidang, COUNT(*) AS jumlah
	from spg_pegawai_eligible a
	left join (
		select b.req_id,a.ptk_id,c.satker,e.NM_UNIT_ORG as depkom,c.nm_kantor as kantor, d.KD_UNIT_ES1 as kd_bidang,
        m.masa_dinas_minimal,m.sisa_dinas,m.tanggal_dinas, c.bidang, n.NM_PEND_UMUM,
        isnull(n.KD_PEND_UMUM,0) as kd_pend_umum, c.FORMASI as posisi_jabatan,a.kd_jabatan,b.tanggal_publish,
        b.tanggal_selesai,b.jam_selesai,m.kd_gol,a.mpp_id,m.tanggal_buat,a.NM_GOLONGAN,
        DATEADD(day, 0, DATEDIFF(day, 0, b.tanggal_selesai)) + DATEADD(day, 0 - DATEDIFF(day, 0, b.jam_selesai), b.jam_selesai) as closing_date
		from rec_ptk a
		left join rec_permintaan_advertising b ON a.ptk_id=b.req_id
		left join REC_RENCANA_PEMENUHAN_PEG c on a.ID_FORMASI=c.ID_FORMASI
		left join SPG_08_UNIT_ORGANISASI d on a.KD_UNIT_ORG=d.KD_UNIT_ORG
		left join SPG_08_UNIT_ORGANISASI e on d.KD_UNIT_ES2=e.KD_UNIT_ORG
		left join REC_PERSYARATAN m on (m.KD_GOL=a.KD_GOL and m.periode=a.mpp_id)
		left join SPG_JNS_PEND_UMUM n on m.PENDIDIKAN = n.KD_PEND_UMUM
		where b.ram_id='RAM-000020' and b.rac_id='RAC-000001'
	) b ON a.periode_pemenuhan = b.mpp_id and a.level_jabatan_pemenuhan = b.nm_golongan
	where 
	a.nip='$login_nip' 
	and b.closing_date >= getdate()
	and a.eligible_combine = 'ELIGIBLE' 
	and b.mpp_id = '$mpp_id'
	GROUP BY b.kd_bidang, b.bidang
	ORDER BY b.kd_bidang";

	$result_lb=$db->Execute($sqllistbidang);
	if (!$result_lb) print $db->ErrorMsg();
	echo "<table class='table no-border' style=\"border-collapse: collapse;text-align: left;align: center;width: 98%;font: normal 11px/100% Verdana, Arial, Helvetica, sans-serif;background: #fff;overflow: hidden;margin-top: 20px;margin-bottom: 20px;margin-left: 10px;\">
	<tr style=\"background-color: #FFE;border: 1px solid #FFD5D5;\">
		<td width=\"140px\" style=\"color: #00557F;border: 1px solid #FFD5D5;font-size: 11px;font-weight: normal;padding: 4px 4px;\"><b>Bidang:</b></td>
		<td style=\"color: #00557F;border: 1px solid #FFD5D5;font-size: 11px;font-weight: normal;padding: 4px 4px;\"><select name='bidang' onChange=\"loadbidang(this.value)\" id='bidang' >";
		if (empty($_GET['es1'])) {
			echo "<option value=\"\"></option>";
		}
	while($row_lb=$result_lb->FetchRow()){
		$optselect = "";
		if ($row_lb['kd_bidang']==$_GET['es1']) {
			$optselect = " selected";
		}
		echo "<option value='".$row_lb['kd_bidang']."' ".$optselect.">".$row_lb['bidang']."</option>";
	}
	echo "		</select></td>
	</tr>
	<tr style=\"background-color: #F4F4F4A8;border: 1px solid #FFD5D5;\">
		<td width=\"140px\" style=\"color: #00557F;border: 1px solid #FFD5D5;font-size: 11px;font-weight: normal;padding: 4px 4px;\"><b>Depkom:</b></td>
		<td style=\"color: #00557F;border: 1px solid #FFD5D5;font-size: 11px;font-weight: normal;padding: 4px 4px;\"><select name=\"depkom\" onChange=\"loaddepkom('".$_GET['es1']."',this.value)\" id=\"depkom\" ><option value=\"\"></option>";
	
	$sqllistdepkom = "select
						b.depkom,
						b.kd_depkom,
						COUNT(*) AS jumlah
					from spg_pegawai_eligible a
						left join (
							select b.req_id,a.ptk_id,c.satker,e.NM_UNIT_ORG as depkom,c.nm_kantor as kantor, d.KD_UNIT_ES1 as kd_bidang,
							m.masa_dinas_minimal,m.sisa_dinas,m.tanggal_dinas, c.bidang, n.NM_PEND_UMUM,
							isnull(n.KD_PEND_UMUM,0) as kd_pend_umum, c.FORMASI as posisi_jabatan,a.kd_jabatan,b.tanggal_publish,
							b.tanggal_selesai,b.jam_selesai,m.kd_gol,a.mpp_id,m.tanggal_buat,a.NM_GOLONGAN,
							DATEADD(day, 0, DATEDIFF(day, 0, b.tanggal_selesai)) + DATEADD(day, 0 - DATEDIFF(day, 0, b.jam_selesai), b.jam_selesai) as closing_date,
						   d.KD_UNIT_ES2 AS kd_depkom
							from rec_ptk a
							left join rec_permintaan_advertising b ON a.ptk_id=b.req_id
							left join REC_RENCANA_PEMENUHAN_PEG c on a.ID_FORMASI=c.ID_FORMASI
							left join SPG_08_UNIT_ORGANISASI d on a.KD_UNIT_ORG=d.KD_UNIT_ORG
							left join SPG_08_UNIT_ORGANISASI e on d.KD_UNIT_ES2=e.KD_UNIT_ORG
							left join REC_PERSYARATAN m on (m.KD_GOL=a.KD_GOL and m.periode=a.mpp_id)
							left join SPG_JNS_PEND_UMUM n on m.PENDIDIKAN = n.KD_PEND_UMUM
							where b.ram_id='RAM-000020' and b.rac_id='RAC-000001'
						) b ON a.periode_pemenuhan = b.mpp_id and a.level_jabatan_pemenuhan = b.nm_golongan
					where 
						a.nip='$login_nip' 
						and b.closing_date >= getdate()
						and a.eligible_combine = 'ELIGIBLE' 
						and b.mpp_id = '$mpp_id'
						and b.kd_bidang = '".$_GET['es1']."'
					GROUP BY b.depkom,
						b.kd_depkom
					ORDER BY b.kd_depkom";
	$result_ld=$db->Execute($sqllistdepkom);
	if (!$result_ld) print $db->ErrorMsg();
	while($row_ld=$result_ld->FetchRow()){
		$optdselect = "";
		if ($row_ld['kd_depkom']==$_GET['es2']) {
			$optdselect = " selected";
		}
		echo "<option value='".$row_ld['kd_depkom']."' ".$optdselect.">".$row_ld['depkom']."</option>";
	}
	echo "	</select></td>
	</tr>
	<tr style=\"background-color: #FFE;border: 1px solid #FFD5D5;\">
		<td width=\"140px\" style=\"color: #00557F;border: 1px solid #FFD5D5;font-size: 11px;font-weight: normal;padding: 4px 4px;\"><b>Cari:</b></td>
		<td style=\"color: #00557F;border: 1px solid #FFD5D5;font-size: 11px;font-weight: normal;padding: 4px 4px;\"><input id=\"filter\" type=\"text\"></td>
	</tr>
	</table>";

	$sql = "
		select
		b.req_id,b.ptk_id,b.kd_satker,b.satker,b.depkom,b.kantor, b.masa_dinas_minimal,b.sisa_dinas,b.tanggal_dinas, b.bidang,b.NM_PEND_UMUM,
		b.KD_PEND_UMUM,b.posisi_jabatan,b.kd_jabatan,b.tanggal_publish,b.tanggal_selesai,b.jam_selesai, b.mpp_id,
		a.tmt_pensiun, (cast((datediff(day,getdate(),a.tmt_pensiun)/365) as int)) as sisa ,b.tanggal_buat,
		b.nilai1, b.nilai2, b.nilai3, b.closing_date,coalesce(jml.jml_pelamar, 0) as jml_pelamar, b.id_formasi, b.JNS_JABATAN, b.JUMLAH AS jml_kebutuhan, 
		room.detail_room, b.kd_depkom
		from spg_pegawai_eligible a
		left join (
			select a.id_formasi,b.req_id,a.ptk_id,c.kd_satker,c.satker,e.NM_UNIT_ORG as depkom,c.nm_kantor as kantor, d.KD_UNIT_ES1,
			m.masa_dinas_minimal,m.sisa_dinas,m.tanggal_dinas, c.bidang, n.NM_PEND_UMUM,
			isnull(n.KD_PEND_UMUM,0) as kd_pend_umum, c.FORMASI as posisi_jabatan,a.kd_jabatan,b.tanggal_publish,
			b.tanggal_selesai,b.jam_selesai,m.kd_gol,a.mpp_id,m.tanggal_buat,a.NM_GOLONGAN, c.JNS_JABATAN, a.JUMLAH, 
			DATEADD(day, 0, DATEDIFF(day, 0, b.tanggal_selesai)) + DATEADD(day, 0 - DATEDIFF(day, 0, b.jam_selesai), b.jam_selesai) as closing_date,
			m.nilai_kinerja as nilai1, m.nilai_kinerja_1 as nilai2, m.nilai_kinerja_2 as nilai3, d.KD_UNIT_ES2 AS kd_depkom
			from rec_ptk a
			left join rec_permintaan_advertising b ON a.ptk_id=b.req_id
			left join REC_RENCANA_PEMENUHAN_PEG c on a.ID_FORMASI=c.ID_FORMASI
			left join SPG_08_UNIT_ORGANISASI d on a.KD_UNIT_ORG=d.KD_UNIT_ORG
			left join SPG_08_UNIT_ORGANISASI e on d.KD_UNIT_ES2=e.KD_UNIT_ORG
			left join REC_PERSYARATAN m on (m.KD_GOL=a.KD_GOL and m.periode=a.mpp_id)
			left join SPG_JNS_PEND_UMUM n on m.PENDIDIKAN = n.KD_PEND_UMUM
			where b.ram_id='RAM-000020' and b.rac_id='RAC-000001'
		) b ON a.periode_pemenuhan = b.mpp_id and a.level_jabatan_pemenuhan = b.nm_golongan
		OUTER APPLY
		(
			SELECT
				REQ_ID,
				COUNT(*) AS jml_pelamar
			FROM
				rec_pelamar_internal
			WHERE
				REQ_ID = b.req_id
			GROUP BY
				REQ_ID
		) AS jml
		OUTER APPLY
		(
			SELECT STUFF((SELECT ',' + CAST(rff.ID AS varchar(4)) + ':' + rff.NM_ROOM + ':' +  CAST(COALESCE(pelamar_room.jml_pelamar,0) AS varchar(4))
			FROM 
				REC_ROOM_FORMASI_FUNCTIONAL AS rff 
				LEFT JOIN 
				(
					SELECT
						rpi.ID_FORMASI,
						rpi.ID_ROOM,
						COUNT(*) AS jml_pelamar
					FROM 
						REC_PELAMAR_INTERNAL AS rpi 
					GROUP BY
						rpi.ID_FORMASI,
						rpi.ID_ROOM
				) AS pelamar_room ON rff.ID_FORMASI = pelamar_room.ID_FORMASI AND rff.ID = pelamar_room.ID_ROOM
			WHERE rff.ID_FORMASI = b.id_formasi
			FOR XML PATH('')) ,1,1,'') AS detail_room
		) AS room
		where 
		a.nip='$login_nip' 
		and b.closing_date >= getdate() 
		and b.KD_UNIT_ES1 = '$es1'
		and (b.kd_depkom = '$es2' OR '$es2' = '')
		and b.mpp_id = '$mpp_id'
		order by b.kd_satker asc, b.kd_gol desc, b.closing_date asc";
	$result=$db->Execute($sql);
	if (!$result) print $db->ErrorMsg();
	$i=0;
	$num=$result->RecordCount();
	if ($num>0) {
		echo "<div class=\"list-container\">";
	}
	while($row=$result->FetchRow()){
		$i++;
		foreach($row as $key => $val){
			$key=strtolower($key);
			$$key=trim($val);
		}

		$sql_check="select nip,req_id from rec_pelamar_internal where req_id='$req_id' and status not in('5','3') and nip='$login_nip'";
		$sql_block="select * from REC_PELAMAR_INTERNAL a
					LEFT JOIN REC_PTK b on a.REQ_ID=b.PTK_ID
					LEFT JOIN SPG_JABATAN_PANGKAT c on b.KD_JABATAN=c.KD_JABATAN_STR
					LEFT JOIN SPG_GOLONGAN d on c.KD_GOL=d.KD_GOL
					LEFT JOIN REC_RENCANA_SELEKSI e on d.NM_GOLONGAN like e.grup
					left join REC_RENCANA_SELEKSI_DETIL f on e.RVS_ID=f.RVS_ID
					where a.nip='$login_nip' and f.TANGGAL_SELESAI >= '$curr_date' and a.status in('0','1','2','4')
					order by f.TANGGAL_SELESAI desc";
		#$f->pre($sql_block);
		#$f->pre($sql_check);
		#$f->pre($tanggal_publish);
		$tgl_selesai=$f->convert_date_id($tanggal_selesai);


		#$tgl_publish=$f->convert_date($tanggal_publish,1);
		#$tgl_selesai=to_date('$tanggal_selesai','yyyy-mm-dd');
		#echo"$tgl_selesai";

		$tanggal_selesai=substr($tanggal_selesai,0,10);
		$tanggal_publish=substr($tanggal_publish,0,10);

		$c_date=$f->convert_date_id($curr_date);
		if($f->check_exist_value($sql_check)){
			$apply_url="<i>Sudah Apply</i>";
		}elseif($f->check_exist_value($sql_block)){
			$apply_url="";
		}
		else{
			$apply_url="<input value=Apply class=button type=button data-toggle=\"modal\" data-target=\"#myModal\" onClick=detailLowongan('$req_id'); >";
		}

		$syarat_url="<a href='' data-toggle=\"modal\" data-target=\"#myModal1\">Syarat </a>";
		$pelamar_url="<input value=\"Pelamar Lain\" class=button type=button data-toggle=\"modal\" data-target=\"#myModal1\" onClick=pelamarLain('$req_id','$tanggal_publish','$tanggal_selesai'); >";
		if($satker==''){
			$satuan_kerja=$depkom;
		}
		if($depkom==''){
			$satuan_kerja=$bidang;
		}
		else{
			$satuan_kerja=$satker;
		}

	/*                echo "

				<div class=\"list-group-item\" >
					<span class=\"pull-right\"><B><em>$i</em></B></span>
					<h6><i class=\"fa  fa fa-user fa-fw\"></i><B>$satuan_kerja - $kantor </B></h6>
					Formasi : $posisi_jabatan
					<p><I>Close Date : $tgl_selesai Pukul $jam_selesai WIB</I> </p>
					<!--<a href=\"#\" onClick=\"parent.addTab('Lowongan Lain', '/lowongan_internal_v2.php?act=detail)\"><span style=\"color: #337ab7\">Detail &raquo</span></a>-->
					$pelamar_url
					$apply_url
				</div>";*/

		 echo "<div class=\"results depkom".substr($kd_depkom,0,6)."\">
				<div class=\"box-jo\">
					<div class=\"box-no\"><b>".$i.".</b></div>
					<div class=\"lowjab_desc\" style=\"float: left;\">
					<b>$satuan_kerja - $kantor</b><br>
					Formasi : $posisi_jabatan";
		if (($jns_jabatan=='fungsional') and (!empty($detail_room))) {
			echo "<br>".PHP_EOL;
			echo "<div class=\"divTable\" style=\"width: 100%;\" ><div class=\"divTableBody\">";

			$rooms = explode(",", $detail_room);
			foreach($rooms as $key=>$val){
				if (!empty($val)) {
					$room = explode(":", $val);
					if (empty($room[0])) {
						$room_value = "null";
					} else {
						$room_value = $room[0];
					}
					echo "<div class=\"divTableRow\" style=\"cursor: default;\">
							<div class=\"divTableCell\" style=\"width: 10px;\">&bull;</div>
							<div class=\"divTableCell\">".$posisi_jabatan." ".$room[1]."</div>
							<div class=\"divTableCell\" style=\"width: 150px;\">Jumlah pelamar: ".$room[2]."</div>
							<div class=\"divTableCell\" style=\"text-align: right; width: 80px;\"><a href=\"javascript:void(0);\" class=\"btn btn-primary btn-sm\" onClick=\"detailLowongan('$req_id','$id_formasi',".$room_value.");\" style=\"padding: 2px 10px;\">Detail</a></div>
						</div>";
				}
			}
			echo "</div></div></div>";
			//print_r($rooms);
		} else {
		
			echo "<br><br>Jumlah pelamar: $jml_pelamar";
			echo "			</div>
					<!-- div class=\"box-jml\">Jumlah pelamar: $jml_pelamar</div -->
					<div class=\"box-detail\"><a href=\"javascript:void(0);\" class=\"btn btn-primary btn-sm\" onClick=\"detailLowongan('$req_id','$id_formasi',null);\" style=\"padding: 3px 10px;\">Detail</a></div>
					<!-- <div class=\"box-detail\"><a href=\"lowongan_internal_v3_detail.php?act=detail&req_id=$req_id&es1=".$_GET['es1']."\" class=\"btn btn-primary btn-sm\">Detail</a></div> -->";
		}
			echo "	</div>
			</div>";
	}
	
	if ($num>0) {
		echo "</div>";
	}
	echo "<br><br>";

echo "<script>function calcBoxSize() { 
var boks = document.getElementsByClassName('box-jo');
var lebar = boks[0].offsetWidth;

var boks2 = document.getElementsByClassName('divTable');
var lebar2 = boks2[0].offsetWidth;

var selisih = lebar - lebar2;

var lebar_desc = lebar - 38;
console.log(lebar_desc+'px');

    var elements = document.getElementsByClassName('lowjab_desc');
    for (var i = 0; i < elements.length; i++) {
        elements[i].style.width=(lebar_desc+'px');
    }
}

window.onresize = calcBoxSize;

document.addEventListener('DOMContentLoaded', function() {
	calcBoxSize();
	setTimeout(function(){
		calcBoxSize();
	}, 1000);
}, false);
</script>";

	echo "  <div id=\"modalDetail\" class=\"modal fade bs-example-modal-lg\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\" aria-hidden=\"true\">
				<div class=\"modal-dialog modal-lg\">
					<div class=\"modal-content\">
						<div class=\"modal-header\">
							<button type=\"button\" class=\"close\" data-dismiss=\"modal\"><span aria-hidden=\"true\">&times;</span><span class=\"sr-only\">Close</span></button>
							<h4 class=\"modal-title\" id=\"myModalLabel\">Detail Lowongan</h4>
						</div>
						<div class=\"modal-body\" style=\"height: auto;\">
							<input type=\"hidden\" name=\"md_req_id\" id=\"md_req_id\" value=''>
							<table class='table no-border overriderow'>
								<!-- <tr>
									<td colspan=\"2\"><span style=\"color: #C20D0D\"><b><i>Perubahan Jabatan yang dilamar hanya dapat dilakukan 1x </i></b></span></td>
								</tr> -->
								<tr>
									<td width=\"110px\"><B>Kantor</B></td>
									<td><span id=\"md_kantor\"></span></td>
								</tr>
								<tr>
									<td><B>Bidang</B></td>
									<td><span id=\"md_bidang\"></span></td>
								</tr>
								<tr>
									<td><B>Satuan Kerja</B></td>
									<td><span id=\"md_satker\"></span></td>
								</tr>
								<tr>
									<td><B>Formasi</B></td>
									<td><span id=\"md_posisi_jabatan\"></span><span id=\"md_regulerfto\"></span></td>
								</tr>
								<tr>
									<td><B>Batas Akhir</B></td>
									<td><span id=\"md_tanggal_selesai\"></span> Pukul <span id=\"md_jam_selesai\"></span> WIB</td>
								</tr>
								<tr>
									<td><b>Keterangan</b></td>
									<td><span id=\"md_keterangan\"></span></td>
								</tr>
								<!-- tr id=\"kolom_jml_pemenuhan\" style=\"display:none;\">
									<td><b>Jumlah Pemenuhan</b></td>
									<td><span id=\"md_jml_pemenuhan\"></span></td>
								</tr -->
								<tr>
									<td valign=top colspan=\"2\"><B>Pelamar:</B><br>";
								echo"
								<div id=\"areabody\" style=\"overflow-x: scroll; width: 582px; padding: 2px;\">
								<table id=\"list_pelamar\" class=\"tabel1\" cellspacing=\"0\" width=\"900px\">
									<colgroup>
										<col id=\"satu\" />
										<col id=\"dua\" />
										<col id=\"tiga\" />
										<col id=\"empat\" />
										<col id=\"lima\" />
										<col id=\"enam\" />
										<col id=\"tujuh\" />
									</colgroup>
									<thead>
									<tr>
										<th scope=\"col\" width=\"21\">No.</th>
										<th scope=\"col\" width=\"45\">NIP</th>
										<th scope=\"col\">Nama Pegawai</th>
										<th scope=\"col\" width=\"75\">Jenis Kelamin</th>
										<th scope=\"col\" width=\"105\">Pendidikan Terakhir</th>
										<th scope=\"col\">Kantor</th>
										<th scope=\"col\">Satuan Kerja</th>
									</tr>
									</thead>";
								echo"<tbody>
									<tr>
										<td style=\"padding: 4px;\">$no</td>
										<td style=\"padding: 4px;\">$nip</td>
										<td style=\"padding: 4px;\">$nm_peg</td>
										<td style=\"padding: 4px;\">$nm_jns_kelamin_peg</td>
										<td style=\"padding: 4px;\">$nm_pend_umum</td>
										<td style=\"padding: 4px;\">$nm_kantor</td>
										<td style=\"padding: 4px;\">$satuan_kerja</td>
									</tr>
									</tbody>";
								echo"</table></div>";
								echo "<div id=\"paging\" style=\"text-align: center;\">halaman</div>";
								echo "</td>
								</tr>
								<tr id=\"row_urjab\">
									<td colspan=2>Unduh Uraian Jabatan: <a style='color:#000;' href='javascript:void(0);' id='md_path_urjab' download><img src='i/icon/pdf.gif'>&nbsp;&nbsp;<span id='md_nm_file_urjab'></span></a></td>
								</tr>";
								echo "</table>";
			echo "		</div>
						<div class=\"modal-footer\">
							<form method=\"post\" action=\"#\">
							<input type=\"hidden\" name=\"req_id\" id=\"md_req_id\" value=\"$req_id\">
							<input type=\"hidden\" name=\"id_formasi\" id=\"md_id_formasi\" value=\"$id_formasi\">
							<input type=\"hidden\" name=\"id_room\" id=\"md_id_room\" value=\"$id_room\">
							<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>
							<!-- <button type=\"button\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#msgModal\" >Apply</button> -->
							<button id=\"btn_apply\" type=\"button\" class=\"btn btn-primary\" onclick=\"apply('".base64_encode($login_nip)."')\" >Apply</button>
							<button id=\"btn_batal\" type=\"button\" class=\"btn btn-primary\" onclick=\"batal('".base64_encode($login_nip)."')\" >Batal</button>
							</form>
						</div>
					</div>
				</div>
			";
			
			echo "<div id=\"msgModal\" class=\"modal fade bs-example-modal-sm\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"msgModalLabel\" aria-hidden=\"true\">
					<div class=\"modal-dialog modal-sm\" style=\"width:340px\">
						<div class=\"modal-content\">
							<div class=\"modal-header\" style=\"height: 46px;\">
								<button type=\"button\" class=\"close\" data-dismiss=\"modal\"><span aria-hidden=\"true\">&times;</span><span class=\"sr-only\">Close</span></button>
								<h5 class=\"modal-title\" id=\"msgModalLabel\"><span id=\"msgModalTitle\"></span></h5>
							</div>
							<div class=\"modal-body\" style=\"height:auto\">
								<p style=\"font-size: 12px;margin: 10px 8px 10px;line-height: 20px;\">
								<span id=\"msgModalBody\"></span>
								<br><br>
								<span id=\"msgModalpilihan_prioritas\" style=\"display:none;\">Prioritas lamaran: <select name=\"prioritas\" id=\"prioritas\">
								<option value=\"\" selected></option>
								<option value=\"1\" visible>Pertama</option>
								<option value=\"2\" visible>Kedua</option>
								</select></span>
								</p>
							</div>
							<div class=\"modal-footer\">
								<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>
								<button type=\"button\" id=\"msgModalSubmit\" style=\"display:none;\" class=\"btn btn-primary\" onclick=\"doapply('".base64_encode($login_nip)."')\" >Apply</button>
								<button type=\"button\" id=\"msgModalBatal\" style=\"display:none;\" class=\"btn btn-primary\" onclick=\"dobatal('".base64_encode($login_nip)."')\" >Ya</button>
								<input type=\"hidden\" name=\"req_id\" id=\"msgModalreq_id\" value=''>
								<input type=\"hidden\" name=\"prioritas_terdaftar\" id=\"msgModalprioritas_terdaftar\" value=''>
								<input type=\"hidden\" name=\"id_formasi\" id=\"msgModalid_formasi\" value=''>
								<input type=\"hidden\" name=\"id_room\" id=\"msgModalid_room\" value=''>
								<input type=\"hidden\" name=\"msgModalreload\" id=\"msgModalreload\" value=''>
								
								<!-- <form id=\"msgModalForm\" method=\"post\" action=\"lowongan_internal_v2.php?act=do_apply\"> -->
								<!-- <button id=\"msgModalSubmit\" style=\"display:none;\" type=\"submit\" name=\"submit\" class=\"btn btn-primary\">Apply</button> -->
								<!-- </form> -->

							</div>
						</div>
					</div>
				</div>";
			
	echo "</body></html>";
}


?>
