<?php
include 'connect/cms-config.php' ;
include 'requires/function.php' ;
include 'requires/session.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']) ;

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

// check permission
if ( !permissionCheck($row_user, 'advance') ){
	header('Location: index.php') ;
	exit ;
}

// get all country
$country     = [] ;
$get_country = $mysqli->query("SELECT * FROM master_country
							  WHERE deleted_at IS NULL") ;
if ( $get_country->num_rows > 0 ){
	while ( $row_country = $get_country->fetch_assoc() ){
		$country[$row_country['country_id']] = $row_country['country_desc'] ;
	}
}

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

	// edit advance
	case 'new' :
	case 'edit' :

		// check query exsits
		$submit_type = 'new' ;
		$mysqli_page = $mysqli->query("SELECT * FROM staff_advance
									   WHERE advance_id = '".$page."' AND deleted_at IS NULL LIMIT 1");
		if ($mysqli_page->num_rows > 0){
			// keep query value in array
			$row_page    = $mysqli_page->fetch_array(MYSQLI_ASSOC) ;
			$submit_type = 'edit' ;
		}

		// update database
		if ( !($row_page['advance_id']>0) && isset($type) && ( $type == 'new' || $type == 'edit' ) && $_POST['hide'] == 1 ){

			$error_message  = '<div class="result_error">Please enter all required field.</div>' ;

			$staff_id  		= escapeString($_POST['staff_id']) ;
			$advance_paidby = escapeString($_POST['advance_paidby']) ;
			$advance_amount = escapeString($_POST['advance_amount']) ;
			$advance_reason = escapeString($_POST['advance_reason']) ;

			if ( ( ( $submit_type == 'new' && $staff_id != '' ) || $submit_type == 'edit' ) && $advance_paidby != '' && $advance_amount != '' ){

				$advance_reason = ( $advance_reason != '' ? $advance_reason : 'ADVANCE' ) ;

				$error_message = '<div class="result_error">No setting found.</div>' ;

				$day = date('j', strtotime(TODAYDATE)) ;

		        // check query exsits
		        $setting_query = $mysqli->query("SELECT post_id, post_title as advance_from, post_link as advance_to, post_content as advance_remark FROM system_post
		                                         WHERE post_type = 'page-advance' AND post_categories = 'page-advance' AND post_trash = '0' LIMIT 1") ;
		        $setting     = [] ;
		        if ( $setting_query->num_rows > 0 ){
		            $setting = $setting_query->fetch_assoc() ;
		        }

		        $boolean_advance = false ;
		        if ( $setting['advance_from'] != '' ){
		            if ( $setting['advance_from'] <= $day && $setting['advance_to'] >= $day ){
		                $boolean_advance = true ;
		            }
		        }else{
		            $boolean_advance = true ;
		        }

		        if ( $setting['advance_remark'] != '' ){
		        	$error_message = '<div class="result_error">'.$setting['advance_remark'].'</div>' ;
		        }

		        if ( $boolean_advance ){

		            $error      = 0 ;
		            $mysqli->autocommit( false ) ;

		            try {

		                $amount = is_numeric($advance_amount) ? number_format($advance_amount, 2, '.', '') : 0 ;

		                // insert into advance
		                $mysqli->query("INSERT INTO staff_advance
		                                (staff_id, advance_paidby, advance_amount, advance_reason, advance_status, created_at, updated_at) VALUES
		                                ('".$staff_id."', '".$advance_paidby."', '".$advance_amount."', '".$advance_reason."', 'pending', '".TODAYDATE."', '".TODAYDATE."')") ;
		                $page = $mysqli->insert_id ;

						pushToUserCron( 'staff_advance', $page, $staff_id, 'Apply Advance', 'Your advance was submitted.' ) ;

		            }catch( Exception $e ){
		                $error_message = '<div class="result_error">'.$e.'</div>' ;
		                $error++;
		            }

		            if( $error == 0 ) {

		                // commit query
		                $mysqli->commit() ; 
		                $error_message = '<div class="result_success">'.$lang['Advance was submitted'].'</div>' ;

		            }else{
		                $mysqli->rollback() ;
		            }

		        }

			}
		
			// refresh page
			header("Location:hr-advance.php?page_mode=".$page_mode."&page=".$page) ;
			$_SESSION['system_result'] = $error_message ;
			exit ;
		}elseif($row_page['advance_id']>0 && $_POST['hide'] == 1 && $type == 'edit'){
			
			$advance_paidby = escapeString($_POST['advance_paidby']);
			$advance_amount = escapeString($_POST['advance_amount']);
			$advance_reason = escapeString($_POST['advance_reason']);
			$error      = 0 ;
		    $mysqli->autocommit( false ) ;

		    try {
		    	$q = "UPDATE `staff_advance` SET
		    	advance_paidby = '".$advance_paidby."',
		    	advance_amount = '".$advance_amount."',
		    	advance_reason = '".$advance_reason."'
		    	WHERE advance_id = '".$page."' ";
		    	$mysqli->query($q);
		    	if($mysqli->error == ''){

		    	}else{
		    		$error_message = '<div class="result_error">Failed Update</div>' ;
		    		$error++;
		    	}
	    	}catch( Exception $e ){
                $error_message = '<div class="result_error">'.$e.'</div>' ;
                $error++;
            }

            if( $error == 0 ) {
                // commit query
                $mysqli->commit() ; 
                $error_message = '<div class="result_success">Update success</div>' ;
            }else{
                $mysqli->rollback() ;
            }
            header("Location:hr-advance.php?page_mode=".$page_mode."&page=".$page) ;
			$_SESSION['system_result'] = $error_message ;
			exit;
		}

		// active menu bar
		$active_main_menu = 'hr' ;
		$active_sub_menu  = 'hr-advance' ;

		if ( ( $page_mode == 'new' && !permissionCheck($row_user, 'advance-new') ) ||
			 ( $page_mode == 'edit' && !permissionCheck($row_user, 'advance-update') ) ){
			header('Location: hr-advance.php') ;
			exit ;
		}

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

		// get all requires 
		// get all staff
		$staff_list   = [] ;
		$mysqli_staff = $mysqli->query("SELECT staff_id, staff_name, staff_idno FROM staff
										WHERE deleted_at IS NULL ".$user_branch_permission_sql) ;
		if ( $mysqli_staff->num_rows > 0 ){
			while ( $row_staff = $mysqli_staff->fetch_assoc() ){
				$staff_list[$row_staff['staff_id']] = dataFilter($row_staff['staff_name']) . ' ( ' . dataFilter($row_staff['staff_idno']) . ' )' ;
			}
		}

		?>

		<div class="warper container-fluid">   	
		<div class='container' style="background-color: white; border-radius: 10px;">
			<div class="page-header" style="margin: 30px 0px 0px 0px;padding: 0px;"><h1><?= $lang['advance'] ?> <small><?= $lang[$page_mode] ?></small></h1></div>
			<?php
            if ($_SESSION['system_result'] != ''){
            	echo $_SESSION['system_result'] ;
                unset($_SESSION['system_result']) ;
            }
            ?>
            <div class="panel panel-default">
                <div class="panel-heading"></div>
                <div class="panel-body">
                    <form method="post" class="form-horizontal" id="quotationForm" enctype="multipart/form-data" action="hr-advance.php?page_mode=edit&page=<?= $page ?>&type=edit" novalidate="novalidate">
                    	 <?php if ( $submit_type == 'new' ){ ?>
						<div class="form-group">
                            <div class="col-sm-2 control-label"><?= $lang['Staff'] ?></div>
                            <div class="col-sm-9">
                            	<select name="staff_id" id="selectuser" class="chosen-select form-control tab_index ui-dropdown-select ui-search-input select2-basic-single" required>
                            		<option value=""><?= $lang['select'] ?></option>
									<?php
									if ( count($staff_list) > 0 ){
										foreach ( $staff_list as $k => $v ){
											echo '<option value="'.$k.'" '.( $k == $row_page['staff_id'] ? 'selected' : '').'>'.$v.'</option>' ;
										}
									}
									?>
								</select>
                            </div>
                        </div>
                         <?php } ?>
                        <div class="form-group">
                            <div class="col-sm-2 control-label"><?= $lang['Paid By'] ?></div>
                            <div class="col-sm-9">
                            	<select name="advance_paidby" class="form-control tab_index" required>
                            		<option value=""><?= $lang['select'] ?></option>
                            		<option value="cash" <?= $row_page['advance_paidby'] == 'cash' ? 'selected' : '' ?> ><?= $lang['Cash'] ?></option>
                            		<option value="debit" <?= $row_page['advance_paidby'] == 'debit' ? 'selected' : '' ?> ><?= $lang['Debit Bank'] ?></option>
                            	</select>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-2 control-label"><?= $lang['amount'] ?></div>
                            <div class="col-sm-9">
                            	<input type="text" name="advance_amount" value="<?= $row_page['advance_amount'] ?>" class="form-control tab_index" required />
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-2 control-label"><?= $lang['Reason'] ?></div>
                            <div class="col-sm-9">
                            	<input type="text" name="advance_reason" value="<?= ( $row_page['advance_reason'] != '' ? $row_page['advance_reason'] : 'Advance' ) ?>" class="form-control tab_index" />
                            </div>
                        </div>

                        <?php if ( $submit_type == 'edit' ){ ?>
                        	<!--
	                        <div class="form-group">
	                            <div class="col-sm-2 control-label">Status</div>
	                            <div class="col-sm-9">
	                            	<select name="advance_status" class="chosen-select form-control tab_index ui-dropdown-select ui-search-input select2-basic-single" id="advance_fullhalf" required>
	                            		<option value="pending" <?= ( $row_page['advance_status'] == 'pending' ? 'selected' : '' ) ?> >Pending</option>
	                            		<option value="confirmed" <?= ( $row_page['advance_status'] == 'confirmed' ? 'selected' : '' ) ?> >Confirmed</option>
	                            		<option value="rejected" <?= ( $row_page['advance_status'] == 'rejected' ? 'selected' : '' ) ?> >Rejected</option>
									</select>
	                            </div>
	                        </div>
	                    	-->
                        <?php } ?>

                        <?php if ( $submit_type == 'new' || $submit_type == 'edit' ){ ?>
                        <div class="form-group">
                            <div class="col-sm-2 control-label"></div>
                            <div class="col-sm-9">
                                <button type="submit" class="btn" style="color:white;background-color: #5e5bd0;float:right; margin-top: 5px;width: 100px;"><?= $lang['submit']?></button>
                                <input type="hidden" name="hide" value="1">
                                <input type="hidden" name="page_status" value="<?= $submit_type ?>">
                            </div>
                        </div> 
                        <?php } ?>

                    </form>
                </div>
            </div>
        </div>
		</div>

		<?php
	break ;

	//print
	case 'print' :
		// active menu bar
		$active_main_menu = 'hr' ;
		$active_sub_menu  = 'hr-advance' ;

		$company_name = COMPANY ;

		include 'hr-advance-print.php';

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

	break ;

	// all type list
	case 'all' :
	default :

		$search		           = escapeString($_GET['search']) ;
		$search_name           = escapeString($_GET['search_name']) ;
		$search_idno           = escapeString($_GET['search_idno']) ;
		$search		           = escapeString($_GET['search']) ;
		$search_paidby         = escapeString($_GET['search_paidby']) ;
		$search_status_type    = escapeString($_GET['search_status_type']) ;
		$search_payment_status = escapeString($_GET['search_payment_status']) ;
		$search_date_from 	   = escapeString($_GET['search_date_from']) ;
		$search_date_to   	   = escapeString($_GET['search_date_to']) ;
		$sort_by               = escapeString($_GET['sort_by']) ;
		$sort_by 	           = ( $sort_by != '' ? $sort_by : 'staff_idno' ) ;
	    $sort_by_type          = escapeString($_GET['sort_by_type']) ;
		$sort_by_type          = ( $sort_by_type != '' ? $sort_by_type : 'asc' ) ;
		$export                = escapeString($_GET['export']) ;
		
		// query type
		$search_query = '' ;
		
		// search query
		if ($search != ''){
			$search_query .= " AND (advance_reason LIKE '%".$search."%')" ;
		}

		if( $search_name != ''){
			$search_query .= " AND staff_name LIKE '%".$search_name."%'" ;
		}
		if( $search_idno != ''){
			$search_query .= " AND staff_idno LIKE '%".$search_idno."%'" ;
		}
		if ( $search_paidby != '' ){
			$search_query .= " AND advance_paidby = '".$search_paidby."'" ;
		}
		if( $search_status_type != ''){
			$search_query .= " AND advance_status LIKE '%".$search_status_type."%'" ;
		}
		if( $search_payment_status != ''){
			$search_query .= " AND advance_payment_status LIKE '%".$search_payment_status."%'" ;
		}
		if ( $search_date_from != '' ){
			if ( $search_date_to != '' ){
				$search_query .= " AND a.created_at BETWEEN '".$search_date_from." 00:00:00' AND '".$search_date_to." 23:59:59'" ;
			}else{
				$search_query .= " AND a.created_at LIKE '".$search_date_from."%'" ;
			}
		}

		// active menu bar
		$active_main_menu = 'hr' ;
		$active_sub_menu  = 'hr-advance' ;
		
		// form submit
		if ( $_POST['hide'] == '1' && $_POST['hide_status'] == 'action' ){

			$result = 'failed-action' ;
			$page_action = $_POST['page_action'] ;

			if ( count( $_POST['multiple_print'] ) > 0 ){

				$new_print_id = [] ;
				foreach ( $_POST['multiple_print'] as $key => $value ){
					$new_print_id[] = $key ;
				}
				$print_id = implode(',', $new_print_id) ;
				$_SESSION['open_in_new'] = $print_id ;

			}else{

				// trash item
				if ( $page_action != '' ){
					switch ( $page_action ){
						case 'confirmed' :
						case 'rejected' :
						case 'trash' :

							$result = 'failed-check' ;

							$multiple    	 = $_POST['multiple_trash'] ;
							$staff_list 	 = [] ;
							$update_list     = [] ;
							if ( arrayCheck($multiple) ){
								foreach ( $multiple as $key => $value ){
									$update_list[] = $key ;
									$staff_list[]  = $value ;
								}

								if ( $page_action == 'trash' ){
									if ( $mysqli->query("UPDATE staff_advance SET
														 deleted_at             = '".TODAYDATE."',
														 advance_updated_author = '".$_SESSION['system_id']."'
														 WHERE advance_id IN (".implode(',', $update_list).") AND advance_payment_status = 'no'") ){
										$result = 'success-update' ;
									}
								}else{
									if ( $mysqli->query("UPDATE staff_advance SET
														 advance_status = '".$page_action."',
														 advance_updated_author = '".$_SESSION['system_id']."'
														 WHERE advance_id IN (".implode(',', $update_list).") AND advance_status = 'pending' AND advance_payment_status = 'no'") ){
										$result = 'success-update' ;
									}
								}

							}

						break ;
					}
				}

				// update payment status
				$update_payment_status = $_POST['update_payment_status'];

				if( $update_payment_status != '' ){
					
					$multiple    	 = $_POST['multiple_trash'] ;
					if ( arrayCheck($multiple) ){
						foreach ( $multiple as $key => $value ){

							$result = 'success-update' ;
							$mysqli->query("UPDATE staff_advance SET 
											advance_payment_status = '".$update_payment_status."',
											advance_payment_date = '".TODAYDATE."',
											advance_updated_author = '".$_SESSION['system_id']."' 
											WHERE advance_id IN (".$key.") ") ;

							pushToUserCron( 'staff_advance', $key, $value, 'Advance '.ucwords($page_action), 'Your advance has been '.$page_action.'.' ) ;
						}
					}
				}

				$_SESSION['system_result'] = $result ;
			}
		}
		
		// 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 = 'search='.$search.'&search_paidby='.$search_paidby.'&search_status_type='.$search_status_type.'&search_payment_status='.$search_payment_status.'&search_date_from='.$search_date_from.'&search_date_to='.$search_date_to.'&sort_by='.$sort_by.'&sort_by_type='.$sort_by_type ;

		// page query
		$mysqli_query = "SELECT a.advance_id, a.advance_paidby, a.advance_amount, a.advance_reason, a.advance_status, a.advance_payment_status, a.advance_payment_date, a.created_at, a.updated_at, b.staff_id, b.staff_name, b.staff_idno, b.staff_accountno, b.staff_icno, b.staff_passportno, b.country_id FROM staff_advance a
						 LEFT JOIN staff b ON ( a.staff_id = b.staff_id )
						 WHERE a.deleted_at IS NULL " . $search_query.$user_branch_permission_sql_b ;

		// export excel
		if ( $export == 'yes' ){

			include 'PhpExcel/PHPExcel.php' ;

			$page_filename = 'Advance-'.date( 'Ymd', time() ) ;
		    $objPHPExcel   = new PHPExcel() ;
		    $objPHPExcel->getProperties()
		                ->setCreator(COMPANY)
		                ->setTitle(COMPANY)
		                ->setSubject(COMPANY)
		                ->setDescription(COMPANY)
		                ->setKeywords(COMPANY)
		                ->setCategory(COMPANY) ;

		    $objPHPExcel->getActiveSheet()->setTitle( $page_filename ) ;
		    $objPHPExcel->setActiveSheetIndex(0);
		    $objWriter   = PHPExcel_IOFactory::createWriter( $objPHPExcel, 'Excel5' ) ;
		    $border_Style = array(
	            'borders' => array(
	                'allborders' => array(
	                    'style' => PHPExcel_Style_Border::BORDER_THIN
	                )
	            )
        	);

		    // default parameter
		    $count       = 1 ;
		    $from_count  = $count;
		    $char        = 'A' ;
		    $count_staff = 1 ;
		    $total_amt   = 0 ;

		    $array_title = array( 'Emp. No', 'Name', 'Country', 'IC', 'Passport', 'Bank Account No.', 'Paid By', 'Amount RM', 'Reason', 'Status', 'Payment Status', 'Created Date', 'Updated Date' ) ;

		    $newChar     = $char ;
		    foreach( $array_title as $k => $v ){
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( $newChar.$count, $v ) ;
                $newChar++ ;
		    }
		    $count++ ;

			$staff_advance = $mysqli->query( $mysqli_query." ORDER BY a.created_at DESC" ) ;
			if ( $staff_advance->num_rows > 0 ){
				while ( $staff_adv = $staff_advance->fetch_assoc() ){

					$staff_idno = ucwords($staff_adv['staff_idno']) ;

					switch ( $staff_adv['advance_paidby'] ){
						case 'cash' : 
							$paidby = 'Cash' ;
						break ;
						case 'debit' : 
							$paidby = 'Debit Bank' ;
						break ;
						default : 
							$paidby = '' ;
					}

					switch ( $staff_adv['advance_payment_status'] ){
						case 'no' : 
							$payment_status = 'Pending' ;
						break ;
						case 'yes' : 
							$payment_status = 'Done ('.$staff_adv['advance_payment_date'].')' ;
						break ;
						default : 
							$payment_status = '' ;
					}
					
					$newChar = $char ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, $staff_idno ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, $staff_adv['staff_name'] ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, $country[$staff_adv['country_id']] ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, $staff_adv['staff_icno'] ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, $staff_adv['staff_passportno'] ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, "'".$staff_adv['staff_accountno'] ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, $paidby ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, $staff_adv['advance_amount'] ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, $staff_adv['advance_reason'] ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, ucwords( $staff_adv['advance_status'] ) ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, $payment_status ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, $staff_adv['created_at'] ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, $staff_adv['updated_at'] ) ;

	                $count++ ;
	                $count_staff++ ;

	                $total_amt += $staff_adv['advance_amount'] ;
				}

				$newChar = $char ;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, '' ) ;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, '' ) ;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, '' ) ;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, '' ) ;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, '' ) ;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, '' ) ;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, 'Total :' ) ;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, $total_amt ) ;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, '' ) ;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, '' ) ;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, '' ) ;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, '' ) ;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, '' ) ;
                $count++ ;

			}
			$to_count = $count-1;

			$objPHPExcel->getActiveSheet()->getStyle('A') ->getAlignment()->setWrapText(true); 
			$objPHPExcel->getActiveSheet()->getStyle('A'.$count.':A'.$to_count)->getAlignment()->applyFromArray(
	            array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER)
	        );
	        $objPHPExcel->getActiveSheet()->getStyle('Q'.$count.':Q'.$to_count)->getAlignment()->applyFromArray(
	            array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER)
	        );

	        $objPHPExcel->getActiveSheet()->getStyle('A1:M'.$to_count)->applyFromArray($border_Style) ;
			$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth("5"); 
			$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth("28"); 
			$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth("7"); 
			$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth("5");
			$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth("5"); 
			$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth("28"); 
			$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth("7"); 

		    header( 'Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' ) ; 
		    header( 'Content-Disposition: attachment;filename="'.$page_filename.'.xls"' ) ;
		    header( 'Cache-Control: max-age=0' ) ;
		    // save to pc
		    ob_clean();
		    $objWriter->save('php://output') ;
		    header( "Refresh: 0" ) ;
			exit ;
		}

		$mysqli_page = $mysqli->query($mysqli_query." ORDER BY a.created_at DESC LIMIT $start_from, " . LIMIT) ;

		// load pagination
		$page_pagination = nextPrevious($product_page, LIMIT, $search_url, $mysqli_query) ;
		
		// start header here
		include 'requires/page_header.php' ;
		include 'requires/page_top.php' ;

		if ( $_SESSION['open_in_new'] != '' ){
			echo '<script type="text/javascript">window.open("hr-advance.php?page_mode=print&page='.$print_id.'&type=print");</script>' ;			
			unset( $_SESSION['open_in_new'] ) ;
		}
		
		?> 
		<!-- Header Ends -->

		<div class="warper container-fluid">   
		<div class='container' style="background-color: white; border-radius: 10px;">
            <div class="page-header" style="margin: 30px 0px 0px 0px;padding: 0px;">
                <div class="row">
                    <div class="pull-left col"> 
						<h1><?= $lang['advance']?> <small><?= $lang['list']?></small></h1>
					</div>
					<div class="pull-right col">
					<?php if ( permissionCheck($row_user, 'advance-new') ){ ?>
						<a href="hr-advance.php?page_mode=new" class="btn" style="color:white;margin:5px;background-color: #5e5bd0;margin-top: 5px;" target="_blank"><?= $lang['add_new']?></a>
					<?php } ?>
						<a href="?<?= $search_url ?>&export=yes" class="btn" style="color:white;margin:5px;background-color: #5e5bd0;margin-top: 5px;" target="_blank"><?= $lang['export_as'] ?> Excel</a>
					</div>
				</div>
				<?php
				if ($_SESSION['system_result'] != ''){
					switch($_SESSION['system_result']){
						case 'failed-action' : 
							echo '<div class="result_error" style="margin-top: 5px;">'.$lang['Sorry invalid action type'].'</div>' ;	
						break ;
						case 'failed-check' : 
							echo '<div class="result_error" style="margin-top: 5px;">'.$lang['Sorry please select at least one'].'</div>' ;	
						break ;
						case 'success-update' :
							echo '<div class="result_success" style="margin-top: 5px;">'.$lang['Thank you status updated sucessfully'].'</div>' ;	
						break ;
					}
					unset($_SESSION['system_result']) ;
				}
				?>
			</div>
			<div class="panel panel-default" id="basic-table-title">
		        <div class="panel-heading">search</div>
		        <div class="panel-body">
		            <form method="get" class="form-horizontal">
		                <div class="form-group">
		                    <label class="col-sm-2 control-label"><?= $lang['Name'] ?></label>
		                    <div class="col-sm-9">
		                        <input type="text" name="search_name" value="<?= $search_name ?>" class="form-control" />
		                    </div>
		                </div>
		                <div class="form-group">
		                    <label class="col-sm-2 control-label"><?= $lang['ID No'] ?></label>
		                    <div class="col-sm-9">
		                        <input type="text" name="search_idno" value="<?= $search_idno ?>" class="form-control" />
		                    </div>
		                </div>
		                <div class="form-group">
                            <label class="col-sm-2 control-label"><?= $lang['Paid By'] ?></label>
                            <div class="col-sm-9">
                                <select name="search_paidby" class="form-control">
                                    <option value=""><?= $lang['All'] ?></option>
                                    <option value="cash" <?= $search_paidby == 'cash' ? 'selected' : '' ?> ><?= $lang['Cash'] ?></option>
                                    <option value="debit" <?= $search_paidby == 'debit' ? 'selected' : '' ?> ><?= $lang['Debit Bank'] ?></option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="col-sm-2 control-label"><?= $lang['status'] ?></label>
                            <div class="col-sm-9">
                                <select name="search_status_type" class="form-control">
                                    <option value=""><?= $lang['All'] ?></option>
                                    <option value="pending" <?= $search_status_type == 'pending' ? 'selected' : '' ?> ><?= $lang['Pending'] ?></option>
                                    <option value="confirmed" <?= $search_status_type == 'confirmed' ? 'selected' : '' ?> ><?= $lang['Confirmed'] ?></option>
                                    <option value="rejected" <?= $search_status_type == 'rejected' ? 'selected' : '' ?> ><?= $lang['Rejected'] ?></option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-2 control-label"><?= $lang['Payment Status'] ?></label>
                            <div class="col-sm-9">
                                <select name="search_payment_status" class="form-control">
                                    <option value=""><?= $lang['All'] ?></option>
                                    <option value="no" <?= $search_payment_status == 'no' ? 'selected' : '' ?> ><?= $lang['Pending'] ?></option>
                                    <option value="yes" <?= $search_payment_status == 'yes' ? 'selected' : '' ?> ><?= $lang['Done'] ?></option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
		                    <label class="col-sm-2 control-label"><?= $lang['Date From']?></label>
		                    <div class="col-sm-9">
		                        <input type="text" name="search_date_from" value="<?= $search_date_from ?>" class="form-control tab_index datepicker" />
		                    </div>
		                </div>
		                <div class="form-group">
		                    <label class="col-sm-2 control-label"><?= $lang['Date To']?></label>
		                    <div class="col-sm-9">
		                        <input type="text" name="search_date_to" value="<?= $search_date_to ?>" class="form-control tab_index datepicker" />
		                    </div>
		                </div>

		                <div class="form-group">
		                    <div class="col-sm-11">
		                        <input type="hidden" name="page_mode" value="<?= $page_mode ?>" />
		                        <input type="hidden" name="search" value="<?= $search ?>" />
		                        <input type="hidden" name="sort_by" value="<?= $sort_by ?>" />
		                        <input type="hidden" name="sort_by_type" value="<?= $sort_by_type ?>" />
		                        <button type="submit" class="btn" style="color:white;float:right;background-color: #5e5bd0;margin-top: 5px;width: 100px;"><?= $lang['submit'] ?></button>
		                    </div>
		                </div>
		            </form>
		        </div>
		    </div>

            <form method="post">
                
                <?php if ( permissionCheck($row_user, 'advance-update') ){ ?>
                <div class="panel panel-default">
                    <div class="panel-body">

                    	<div class="clearfix" style="margin-bottom:10px;">
	                        <select name="page_action" class="form-control selectpicker">
	                            <option value=""><?= $lang['select']?></option>
	                            <option value="confirmed"><?= $lang['Confirmed']?></option>
	                            <option value="rejected"><?= $lang['Rejected']?></option>
	                            <option value="trash"><?= $lang['trash']?></option>
	                        </select>
	                    </div>

                    	<div class="clearfix" style="margin-bottom:10px;">
	                        <select name="update_payment_status" class="form-control selectpicker">
	                            <option value=""><?= $lang['select']?></option>
	                            <option value="yes"><?= $lang['Done']?></option>
	                            <option value="no"><?= $lang['Pending']?></option>
	                        </select>
	                    </div>

                        <input type="hidden" name="hide" value="1" />
                        <input type="hidden" name="hide_status" value="action" />
                        <input type="submit" class="btn" style="color: white;background-color: #5e5bd0;width: 100px;" value="<?= $lang['submit']?>" />
                    </div>
                </div>
                <?php } ?>

                <div class="panel panel-default">
                    <div class="panel-heading"></div>
                    <div class="panel-body">
						<table cellpadding="0" cellspacing="0" border="0" class="listing-table responsive table table-striped table-bordered" id="basic-datatable">
							<thead>
								<tr>
									<th width="50">Update Status</th>
									<th><?= $lang['Action']?></th>
									<th><?= $lang['Request By']?></th>
									<th><?= $lang['Reason']?></th>
									<th><?= $lang['Paid By']?></th>
									<th><?= $lang['Amount RM']?></th>
									<th><?= $lang['status']?></th>
									<th><?= $lang['Payment Status']?></th>
									<th><?= $lang['created_date']?></th>
									<th><?= $lang['Last Updated']?></th>
								</tr>
							</thead>
							<tbody>
								<?php
								if ($mysqli_page->num_rows > 0){
									while ($row_page = $mysqli_page->fetch_array(MYSQLI_ASSOC)){

										$staff_idno = ucwords($row_page['staff_idno']) ;

					                    // advance status
										if ( $row_page['advance_paidby'] == 'cash' ){
											$button_paidby =  '<b>'.$lang['Cash'].'</b>' ;
										}elseif ( $row_page['advance_paidby'] == 'debit' ){
											$button_paidby = '<b>'.$lang['Debit Bank'].'</b>' ;
										}

					                    // advance status
										if ( $row_page['advance_status'] == 'pending' ){
											$button =  '<button class="btn btn-xs bg-yellow margin" type="button"><b>'.$lang['PENDING'].'</b></button>' ;
										}elseif ( $row_page['advance_status'] == 'confirmed' ){
											$button = '<button class="btn btn-xs bg-green margin" type="button"><b>'.$lang['CONFIRMED'].'</b></button>' ;
										}else{
											$button = '<button class="btn btn-xs bg-red margin" type="button"><b>'.$lang['REJECTED'].'</b></button>' ;
										}

										// payment status
										if ( $row_page['advance_payment_status'] == 'yes' ){
											$button_p = '<button class="btn btn-xs bg-green margin" type="button"><b>'.$lang['DONE'].' <br />( '.date('m / Y', strtotime($row_page['advance_payment_date'])).' )</b></button>' ;
										}else{
											$button_p =  '<button class="btn btn-xs bg-yellow margin" type="button"><b>'.$lang['PENDING'].'</b></button>' ;
										}

										echo '
										 <tr class="odd gradeX">
											<td>' ;
												if ( $row_page['advance_payment_status'] == 'no' ){
													echo '
													<div class="checkbox multiple_trash">
														<input type="checkbox" name="multiple_trash['.$row_page['advance_id'].']" class="trash_button" value="'.$row_page['staff_id'].'">
														<label for="checkbox1"></label>
													</div>' ;
												}
											echo '
											</td>
											<td style="text-align:center;">
										 		<a title="Edit" href="hr-advance.php?page_mode=edit&page='.$row_page['advance_id'].'&type=edit"><i class="fa fa-edit"></i></a>
										 		<span class="split">|</span>
										 		<a title="Edit" href="hr-advance.php?page_mode=print&page='.$row_page['advance_id'].'&type=print" target="_blank"><i class="fa fa-print"></i></a>
											</td>
											<td>'.dataFilter($row_page['staff_name']).'<br />( '.$staff_idno.' )</td>
											<td>'.dataFilter($row_page['advance_reason']).'</td>
											<td class="align_center">'.$button_paidby.'</td>
											<td class="align_center">'.dataFilter($row_page['advance_amount']).'</td>
											<td class="align_center">'.$button.'</td>
											<td class="align_center">'.$button_p.'</td>
											<td class="align_center">'.resetDateFormat($row_page['created_at']).'</td>
											<td class="align_center">'.resetDateFormat($row_page['updated_at']).'</td>
										</tr>';
									}
								}else{
									echo '
									<tr class="odd gradeX">
										<td class="border_none">'.$lang['no_data'].'</td>
										<td class="border_none"></td>
										<td class="border_none"></td>
										<td class="border_none"></td>
										<td class="border_none"></td>
										<td class="border_none"></td>
										<td class="border_none"></td>
										<td class="border_none"></td>
										<td class="border_none"></td>
										<td class="border_none"></td>
									</tr>' ;
								}
								?>
							</tbody>
						</table>
						<?= $page_pagination['page_pagination'] ?>
                    </div>
                </div>
			</form>
		</div>
		</div>
		<?php
	break ;
}
// footer
include 'requires/page_footer.php' ;
?>