<?php
include 'connect/cms-config.php' ;
include 'requires/function.php' ;
include 'extensions/mailer.php' ;

// include the class
include 'requires/class_resize.php' ;

// keep parameter in value
$page 				= escapeString($_GET['page']) ;
$page_mode 			= escapeString($_GET['page_mode']) ;
$type 				= escapeString($_GET['type']) ;
$search 			= escapeString($_GET['search']) ;
$search_category 	= escapeString($_GET['search_category']) ;
$select_worker 		= $_GET['select_worker'] ;
$select_worker 		= ($select_worker == 'Foreign' ? 'Foreign' : 'Local') ;
$sort_type 			= escapeString($_GET['sort_type']) ;
$default_sortby 	= $sortby = escapeString($_GET['sortby']) ;
$show_another_script = true ;
$hide_title 		= false ;

// page header
$letter_head 		= getOwnerCompanyLetterHead($_SESSION['url_get_branch_admin']) ;

// get all requires 
$tier_list          = [] ;
$tier_list_id       = [] ;
$mysqli_tier        = $mysqli->query("SELECT a.tier_id, b.title FROM profile_tier a
                              	      LEFT JOIN profile_tier_translation b ON ( a.tier_id = b.tier_id )
			      				      WHERE a.deleted_at IS NULL AND b.lang = 'en' ORDER BY a.sortable DESC") ;
if ( $mysqli_tier->num_rows > 0 ){
	while ( $row_tier = $mysqli_tier->fetch_assoc() ){
		$tier_list[]  = $row_tier ;
		$tier_list_id[$row_tier['tier_id']] = $row_tier['title'] ;
	}
}

$get_user_tier     	= userTierQuery( $row_user ) ;

// mode type | all list | new | edit
switch($page_mode){

	// new department
	case 'new' :

		// check permission
		if ( !permissionCheck($row_user, 'application-form-view') ){
			echo '<script>alert("Sorry You Don\'t Have The Permission.")</script>';
			header('Location: index.php') ;
			exit ;
		}

		$active_main_menu 	= 'hr' ;
		$active_sub_menu 	= 'hr-employment' ;
		$active_menu 		= 'hr-employment-new' ;

		// start header here
		include 'requires/page_header.php' ;
		include 'requires/page_top.php' ;

		// check select worker
		switch($select_worker){
			case 'Local' :
				include 'HR/hr-local-new.php' ;
			break ;
		}

	break ;

	// edit category
	case 'edit' :

		// check permission
		if ( !permissionCheck($row_user, 'application-list-edit') ){
			echo '<script>alert("Sorry You Don\'t Have The Permission.")</script>';
			header('Location: index.php') ;
			exit ;
		}

		// active page
		$active_main_menu 	= 'hr' ;
		$active_sub_menu 	= 'hr-employment' ;
		$active_menu 		= 'hr-employment' ;

		$boolean_redirect 	= false ;

		$page_status 		= escapeString( $_POST['page_status'] ) ;

		if ( $page_status  == 'new' ){
			$worker_status 	= 'Pending' ;
			$confirmation_date = ($worker_status == 'Confirmation' ? TODAYDATE : '') ;

			$select_employment = $mysqli->query( "SELECT * FROM staff_employment
												  WHERE employment_trash = '0' AND employment_status = 'Pending' AND employment_email = '".escapeString($_POST['personal_email'])."'
												  LIMIT 1" ) ;
			if ( $select_employment->num_rows == 0 ){
				$mysqli->query("INSERT INTO staff_employment (employment_status, employment_confirmation_date, employment_date, employment_modified, employment_trash) VALUES ('".$worker_status."', '".$confirmation_date."', '".TODAYDATE."', '".TODAYDATE."', '0')");
				$page 			= $mysqli->insert_id;
			}else{
				$boolean_redirect = true ;
				$_SESSION['system_result'] = 'failed-exists' ;
				header("Location: hr-employment.php?page_mode=all&select_worker=Local&type=pending") ;
				exit ;
			}
		}

		// check query exsits
		$mysqli_page = $mysqli->query("SELECT * FROM staff_employment
									   WHERE employment_id = '".$page."' AND employment_trash = '0' LIMIT 1") ;
		if ($mysqli_page->num_rows > 0){

			// keep query value in array
			$row_page = $mysqli_page->fetch_array(MYSQLI_ASSOC) ;
			$select_worker = $row_page['employment_type'] ;
			$employment_status = $row_page['employment_status'] ;

			// check select worker
			include 'HR/hr-local-edit.php' ;

		}else{
			$boolean_redirect = true ;
		}

		if ($boolean_redirect){
			print_r('test'.$page);
			exit;
			header("Location: hr-employment.php?page_mode=all") ;
			exit ;
		}

	break ;

	// edit status
	case 'edit_status' :

		// check permission
		if ( !permissionCheck($row_user, 'application-list-edit') ){
			echo '<script>alert("Sorry You Don\'t Have The Permission.")</script>';
			header('Location: index.php') ;
			exit ;
		}

		// active page
		$active_main_menu 	= 'hr' ;
		$active_sub_menu 	= 'hr-employment' ;
		$active_menu 		= 'hr-employment' ;

		$boolean_redirect 	= false ;

		$page_status 		= escapeString( $_POST['page_status'] ) ;

		if ( $page_status  == 'new' ){
			$worker_status  = 'Pending' ;
			$confirmation_date = ($worker_status == 'Confirmation' ? TODAYDATE : '') ;

			$mysqli->query("INSERT INTO staff_employment (employment_status, employment_confirmation_date, employment_date, employment_modified, employment_trash) VALUES ('".$worker_status."', '".$confirmation_date."', '".TODAYDATE."', '".TODAYDATE."', '0')");

			$page 			= $mysqli->insert_id;
		}

		// check query exsits
		$mysqli_page = $mysqli->query("SELECT * FROM staff_employment
									   WHERE employment_id = '".$page."' AND employment_trash = '0' LIMIT 1") ;
		if ( $mysqli_page->num_rows > 0 ){

			// keep query value in array
			$row_page 			= $mysqli_page->fetch_array(MYSQLI_ASSOC) ;
			$select_worker 		= $row_page['employment_type'] ;
			$employment_status 	= $row_page['employment_status'] ;

			// check select worker
			include 'HR/hr-local-edit-status.php' ;
		}else{
			$boolean_redirect = true ;
		}

		if ($boolean_redirect){
			header("Location: hr-employment.php?page_mode=all") ;
			exit ;
		}

	break ;

	// edit status
	case 'edit_interview_det' :

		// check permission
		if ( !permissionCheck($row_user, 'application-list-edit') ){
			echo '<script>alert("Sorry You Don\'t Have The Permission.")</script>';
			header('Location: index.php') ;
			exit ;
		}

		// active page
		$active_main_menu = 'hr' ;
		$active_sub_menu = 'hr-employment' ;
		$active_menu = 'hr-employment' ;
		$boolean_redirect = false ;

		$page_status = $_POST['page_status'] ;
		if ($page_status == 'new'){
			$worker_status = 'Pending' ;
			$confirmation_date = ($worker_status == 'Confirmation' ? TODAYDATE : '') ;
			$mysqli->query("INSERT INTO staff_employment (employment_status, employment_confirmation_date, employment_date, employment_modified, employment_trash) VALUES ('".$worker_status."', '".$confirmation_date."', '".TODAYDATE."', '".TODAYDATE."', '0')");
			$page = $mysqli->insert_id;

		}

		// check query exsits
		$mysqli_page = $mysqli->query("SELECT * FROM staff_employment
									   WHERE employment_id = '".$page."' AND employment_trash = '0' LIMIT 1") ;
		if ($mysqli_page->num_rows > 0){

			// keep query value in array
			$row_page = $mysqli_page->fetch_array(MYSQLI_ASSOC) ;
			$select_worker = $row_page['employment_type'] ;
			$employment_status = $row_page['employment_status'] ;

			// check select worker
			include 'HR/hr-local-edit-interview-det.php' ;

		}else{
			$boolean_redirect = true ;
		}

		if ($boolean_redirect){
			header("Location: hr-employment.php?page_mode=all") ;
			exit ;
		}

	break ;

	// offer update
	case 'offer' :

		// check permission
		if ( !permissionCheck($row_user, 'application-list-update') ){
			echo '<script>alert("Sorry You Don\'t Have The Permission.")</script>';
			header('Location: index.php') ;
			exit ;
		}

		// active page
		$active_main_menu = 'hr' ;
		$active_sub_menu = 'hr-employment' ;
		$active_menu = 'hr-letter-offer' ;

		// check query exsits
		$mysqli_page = $mysqli->query("SELECT * FROM staff_employment
										WHERE employment_id = '".$page."' AND (employment_status = 'Offer' || employment_status = 'Confirmation') AND employment_trash = '0' LIMIT 1") ;


		if ($mysqli_page->num_rows > 0){

			$row_page = $mysqli_page->fetch_array(MYSQLI_ASSOC) ;

			switch($row_page['employment_status']){
				case 'Offer' :
					$active_menu = 'hr-letter-offer' ;
				break ;
				case 'Confirmation' :
					$active_menu = 'hr-letter-confirmation' ;
				break ;
			}

			$status_text = jsonEncodeDecode('decode', $row_page['employment_status_text']) ;
			$offer_status = $status_text['offer_status'] ;

			// update database
			if ($_POST['hide'] == 1){

				$date_to_offer = escapeString($_POST['date_to_offer']) ;
				$starting_date = escapeString($_POST['starting_date']) ;
				$salary = escapeString($_POST['salary']) ;
				$allowance = escapeString($_POST['allowance']) ;
				$comission = escapeString($_POST['comission']) ;
				$return_date = escapeString($_POST['return_date']) ;
				$assign_by = escapeString($_POST['assign_by']) ;

				if ($_POST['sent_offer_letter']!='') {
					$sent_offer_letter = escapeString($_POST['sent_offer_letter']);
					$sent_offer_letter_date = TODAYDATE;
				}else{
					$status_text_temp = jsonEncodeDecode('decode', $row_page['employment_status_text']) ;
					$offer_status_temp = $status_text_temp['offer_status'] ;
					if ($offer_status_temp != '') {
						$sent_offer_letter_date = $offer_status_temp['sent_ol_date'];
						$sent_offer_letter = $offer_status_temp['sent_ol'];
					}else{
						$sent_offer_letter = escapeString($_POST['sent_offer_letter']);
						$sent_offer_letter_date = TODAYDATE;
					}
				}

				if ($date_to_offer != '' && $starting_date != '' && $salary != '' && $return_date != ''){

					$offer_status = array('date_to_offer' => $date_to_offer,
										  'starting_date' => $starting_date,
										  'salary' => $salary,
										  'allowance' => $allowance,
										  'comission' => $comission,
										  'sent_ol' => $sent_offer_letter,
										  'sent_ol_date' => $sent_offer_letter_date,
										  'return_date' => $return_date) ;

					$status_text['offer_status'] = $offer_status ;			  
					$status_text = jsonEncodeDecode('encode', $status_text) ;


					// update database
					if ($mysqli->query("UPDATE staff_employment SET
										employment_status_text = '".$status_text."',
										employment_salary = '".$salary."',
										employment_assign_by = '".$assign_by."'
										WHERE employment_id = '".$page."'")){

						$descrition = $_SESSION['system_name'].'(username) update employment offer letter. ' ;

						if ($sent_offer_letter != '') {
							$descrition .= 'Offer letter is sent ('.TODAYDATE.')';
						}

						$mysqli->query("INSERT INTO system_log_employment (log_table, log_action, log_page_id, log_page_name, log_user_id, log_description, log_record, log_date) VALUES
										('employment', 'update-status', '200', 'AF-".$page."', '".$_SESSION["system_id"]."', '".$descrition."', '".$record."', NOW())");


						if ($_POST['sent_offer_letter']!='') {
							header("Location:?page_mode=sent_email&mail_type=offer_letter&page=".$page);
							exit;
						}

						// refresh page
						header("Location:hr-employment.php?page_mode=offer&page=".$page."&success=1") ;
						exit ;
					}
				}
			}

			// start header here
			include 'requires/page_header.php';
			include 'requires/page_top.php';
			include 'HR/hr-offer-letter-update.php';
		}

		else{
			header("Location: hr-employment.php?page_mode=all&select_worker=Local&type=offer") ;
			exit ;	
		}

	break ;

	// sent email
	case 'sent_email' :

		$mysqli_page = $mysqli->query("SELECT * FROM staff_employment
									   WHERE employment_id = '".$page."' AND employment_trash = '0' LIMIT 1") ;
		if ($mysqli_page->num_rows > 0){	
			$row_page = $mysqli_page->fetch_array(MYSQLI_ASSOC) ;
		}

		$status_text = jsonEncodeDecode('decode', $row_page['employment_status_text']) ;
		$offer_status = $status_text['offer_status'] ;

		include 'HR/hr-local-mail.php';

	break;

	// all category list
	case 'all' :
	default :

		// check permission
		if ( !permissionCheck($row_user, 'application-list-view') ){
			echo '<script>alert("Sorry You Don\'t Have The Permission.")</script>';
			header('Location: index.php') ;
			exit ;
		}

		$search_name = escapeString($_GET['search_name']) ;
		$search_ic = escapeString($_GET['search_ic']) ;
		$search_department = escapeString($_GET['search_department']) ;
		$search_designation = escapeString($_GET['search_designation']) ;
		$search_yexp = escapeString($_GET['search_yexp']) ;
		$search_qualification = escapeString($_GET['search_qualification']) ;
		$search_spoke_en = escapeString($_GET['search_spoke_en']) ;
		$search_spoke_bm = escapeString($_GET['search_spoke_bm']) ;
		$search_spoke_cn = escapeString($_GET['search_spoke_cn']) ;
		$search_mobile = escapeString($_GET['search_mobile']) ;
		$search_mail = escapeString($_GET['search_mail']) ;
		$search_date = ( $_GET['search_date']!= '' ? date('Y-m-d', strtotime($_GET['search_date'])) : '' ) ;

		// query type
		$search_query = '' ;
		if( $search_name != ''){
			$search_query .= " AND employment_name LIKE '%".$search_name."%'" ;
		}
		if( $search_ic != ''){
			$search_query .= " AND employment_nric LIKE '%".$search_ic."%'" ;
		}
		if( $search_department != ''){
			$search_query .= " AND employment_department = '".$search_department."'" ;
		}
		if( $search_designation != ''){
			$search_query .= " AND employment_position = '".$search_designation."'" ;
		}
		if( $search_yexp != ''){
			$search_query .= " AND employment_details LIKE '%\"working_yexp\":\"".$search_yexp."\"%'" ;
		}
		if( $search_qualification != ''){
			$search_query .= " AND employment_details LIKE '%".$search_qualification."%'" ;
		}
		if( $search_spoke_en != ''){
			$search_query .= " AND employment_details LIKE '%".$search_spoke_en."%'" ;
		}
		if( $search_spoke_bm != ''){
			$search_query .= " AND employment_details LIKE '%".$search_spoke_bm."%'" ;
		}
		if( $search_spoke_cn != ''){
			$search_query .= " AND employment_details LIKE '%".$search_spoke_cn."%'" ;
		}
		if( $search_mobile != ''){
			$search_query .= " AND employment_mobile LIKE '%".$search_mobile."%'" ;
		}
		if( $search_mail != ''){
			$search_query .= " AND employment_email LIKE '%".$search_mail."%'" ;
		}
		if ( $search_date != '' ){
		    $search_query .= " AND employment_date like '%".$search_date."%' " ;
		}

		// search query
		if ($search != ''){
			$search_query .= " AND (employment_name LIKE '%".$search."%')" ;
		}

		// active page
		$active_main_menu = 'hr' ;
		$active_menu = 'hr-employment' ;

		// form submit
		if ($_POST['hide'] == '1' && $_POST['hide_status'] == 'action'){
			// trash item
			switch($_POST['page_action']){
				case 'trash':
					$mysqli_query = "UPDATE staff_employment SET
									 employment_trash = '1'
									 WHERE employment_id = " ;
					$trash_page = trashPage('employment', $mysqli, $mysqli_query, $_POST['multiple_trash']) ;
				break;
			}
		}

		// check page selected worker 
		$active_sub_menu = 'hr-employment' ;
	
		// check employment status
		$boolean_offer  = false ;
		$query_order_by = "employment_id DESC" ;
		$boolean_tier   = false ;
		switch($type){
			case 'pending' :
				$active_menu = 'hr-letter-pending' ;
				$employment_status = 'Pending' ;
			break ;
			case 'processing' :
				$active_menu = 'hr-letter-processing' ;
				$employment_status = 'Processing' ;
			break ;
			case 'processing-manager-approved' :
				$active_menu = 'hr-letter-processing-manager-approved' ;
				$employment_status = 'Processing Confirmed' ;
			break ;
			case 'processing-manager-rejected' :
				$active_menu = 'hr-letter-processing-manager-rejected' ;
				$employment_status = 'Processing Rejected' ;
			break ;
			case 'processing-interview-slot' :
				$active_menu = 'hr-letter-processing-interview-slot' ;
				$employment_status = 'Processing Interview Slot' ;
			break ;
			case 'interview' :
				$active_menu = 'hr-letter-interview' ;
				$employment_status = 'Interview' ;
			break ;
			case 'reschedule' :
				$active_menu = 'hr-letter-reschedule' ;
				$employment_status = 'Reschedule' ;
			break ;
			case 'kiv' :
				$active_menu = 'hr-letter-kiv' ;
				$employment_status = 'Keep In View' ;
			break ;
			case 'offer' :
				$active_menu = 'hr-letter-offer' ;
				$employment_status = 'Offer' ;
				$boolean_offer = true ;
			break ;	
			case 'confirmation' :
				$active_menu 		= 'hr-letter-confirmation' ;
				$employment_status 	= 'Confirmation' ;
				$boolean_tier   	= true ;
			break ;	
			case 'terminate' :
				$active_menu 		= 'hr-letter-terminate' ;
				$employment_status 	= 'Terminate' ;
				$boolean_tier   	= true ;
			break ;
			case 'reject' :
				$active_menu 		= 'hr-letter-reject' ;
				$employment_status 	= 'Reject' ;
				$boolean_tier   	= true ;
			break ;
		}

		switch($sort_type){
			case 'dob' :
				$sort_by_dob = ($sortby == 'dob_desc' ? 'dob_asc' : 'dob_desc') ;
				$sortable = ($sort_by_dob == 'dob_asc' ? 'DESC' : 'ASC') ;
				$query_order_by = 'employment_dob ' . $sortable ;
			break ;

		}

		// query for employement status
		if ( $employment_status == 'Processing' ){
			$search_query  .= " AND employment_status IN ( 'Processing', 'Processing Confirmed', 'Processing Rejected', 'Processing Interview Slot' )" ;
		}else{
			$search_query  .= " AND employment_status = '".$employment_status."'" ;
		}

		// query for branch
		$search_query 	   .= " AND employment_branch = '".$_SESSION['url_get_branch_admin']."'" ;

		if ( $boolean_tier ){
			$search_query  .= ( $get_user_tier['check'] ? " AND ( employment_tier = '' || ( employment_tier LIKE '%|" . implode( "|%' OR employment_tier LIKE '%|", $get_user_tier['tiers'] ) . "|%' ) )" : "" ) ;
		}

		// pagination
		if (isset($page) && !empty($page)) { $product_page = $page ; } else { $product_page = 1 ; } // next and prev page (5 thing need to change)
		$start_from 		= ($product_page - 1) * LIMIT ; //end next and prev page

		// set search url
		$search_url 		= 'page_mode=all&select_worker=Local&type=pending&search='.$search.'&search_name='.$search_name.'&search_date='.$search_date.'&search_mobile='.$search_mobile.'&search_mail='.$search_mail ;

		// page query
		$mysqli_query 		= "SELECT * FROM staff_employment
						 	   WHERE employment_trash = '0'".$search_query ;
		$mysqli_page 		= $mysqli->query( $mysqli_query.' ORDER BY '.$query_order_by." LIMIT $start_from, " . LIMIT ) ;

		$page_pagination 	= nextPrevious($product_page, LIMIT, $search_url, $mysqli_query) ;

		// start header here
		include 'requires/page_header.php';
		include 'requires/page_top.php';


		// sort by variable
		$url_sort_by = 'hr-employment.php?page_mode=all&select_worker='.$select_worker.'&type='.$type ;

		// check page selected worker 
		include 'HR/hr-local-list.php';

	break ;
}
?>

<script src="<?= PATH ?>scripts/jquery.datetimepicker.full.min.js"></script><!-- date picker -->
<script>
$(document).ready(function(){

	$('.datetimepicker').datetimepicker({
		timepicker:false,
		format:'d/m/Y',
		formatDate:'Y/m/d',
    	scrollInput : false
	});

	$('.datetimepicker_with_time').datetimepicker({
		format:'d/m/Y H:i',
		formatDate:'Y/m/d',
    	scrollInput : false
	});

	$('.datetimepicker_with_time_employ').datetimepicker({
		format:'Y-m-d H:i',
		formatDate:'Y/m/d',
    	scrollInput : false
	});

	<?=($page_mode=="new" || $page_mode == 'edit' ? 'save_log(true);setInterval(save_log,60000);' : '' )?>

	function save_log($value = false){
		var form = $("#quotationForm");
		if ($value){
			$.ajax({
				type:"POST",
				url:"requires/ajax_log.php",
				data: form.serialize() + "&status=<?=$page_mode?>",
				 success: function(data)
		           {	           		

		           }
			});
		}else{
			$.ajax({
				type:"POST",
				url:"requires/ajax_log.php",
				data: form.serialize() + "&status=<?=$page_mode?>&status1=not-yet",
				 success: function(data)
		           {	           		

		           }
			});
		}
	}
}) ;
</script>

<?php
// footer
include 'requires/page_footer.php' ;
include 'requires/session.php' ;
?>