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


// check permission
if ( !permissionCheck($row_user, 'staff-list-view') && !permissionCheck($row_user, 'foreign-only') ){
	echo '<script>alert("Sorry You Don\'t Have The Permission.")</script>';

	header('Location: index.php') ;
	exit ;
}

// 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']) ;

// mode type | all list | new | edit
switch($page_mode){
	
	// all type list
	case 'all' :
	default :
		
		// query type
		$search_query = '' ;
		$staff_id     = escapeString($_GET['staff_id']) ;
		$ty_type      = escapeString($_GET['ty_type']) ;
		$st_type      = escapeString($_GET['st_type']) ;
		$sort_by      = escapeString($_GET['sort_by']) ;
		$sort_by 	  = ( $sort_by != '' ? $sort_by : 'created_at' ) ;
	    $sort_by_type = escapeString($_GET['sort_by_type']) ;
		$sort_by_type = ( $sort_by_type != '' ? $sort_by_type : 'desc' ) ;
		$export       = escapeString($_GET['export']) ;

		// form submit
		if ( $_POST['hide'] == '1' ){
			$leave_annual_id = escapeString($_POST['leave_annual_id']) ;
			$leave_annual    = escapeString($_POST['leave_annual']) ;
			$leave_sick_id   = escapeString($_POST['leave_sick_id']) ;
			$leave_sick      = escapeString($_POST['leave_sick']) ;
			if ( $leave_annual_id > 0 && $leave_annual != '' ){
				$mysqli->query("UPDATE staff_leave_year SET leave_days = '".$leave_annual."' WHERE leave_year_id = '".$leave_annual_id."'") ;
			}
			if ( $leave_sick_id > 0 && $leave_sick != '' ){
				$mysqli->query("UPDATE staff_leave_year SET leave_days = '".$leave_sick."' WHERE leave_year_id = '".$leave_sick_id."'") ;
			}
		}
		
		// search query
		if ($search != ''){
			$search_query .= " AND (leave_reason LIKE '%".$search."%')" ;
		}
		if ($ty_type != ''){
			$search_query .= " AND leave_type = '".$ty_type."'" ;
		}
		if ($st_type != ''){
			$search_query .= " AND leave_status = '".$st_type."'" ;
		}
		
		// active menu bar
		$active_main_menu = 'hr' ;
		$active_sub_menu  = 'hr-leave' ;
		
		// 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.'&staff_id='.$staff_id.'&ty_type='.$ty_type.'&st_type='.$st_type.'&sort_by='.$sort_by.'&sort_by_type='.$sort_by_type ;
		
		// page query
		$mysqli_query = "SELECT a.leave_id as leave_id, a.leave_type, a.leave_from, a.leave_to, a.leave_day, a.leave_file, a.leave_reason, a.leave_status, a.created_at, a.updated_at, b.staff_name, b.staff_idno FROM staff_leave a
						 LEFT JOIN staff b ON ( a.staff_id = b.staff_id )
						 WHERE a.staff_id = '".$staff_id."' AND a.deleted_at IS NULL " . $search_query ;

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

			include 'PhpExcel/PHPExcel.php' ;

			$page_filename = 'StaffLeave-'.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, 'Excel2007' ) ;

		    // default parameter
		    $count       = 1 ;
		    $char        = 'A' ;
		    $count_row   = 1 ;

		    $array_title = array( 'No.', 'Request By', 'Type', 'From ~ To', 'Reason', 'Status', 'Created Date', 'Updated Date' ) ;

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

			$row_q = $mysqli->query($mysqli_query." ORDER BY a.created_at DESC") ;
			if ( $row_q->num_rows > 0 ){
				while ( $row = $row_q->fetch_assoc() ){
					$newChar = $char ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, $count_row ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, dataFilter($row['staff_name']).' ( '.dataFilter($row['staff_idno']).' )' ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, ucwords($row['leave_type']) ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, dataFilter($row['leave_from']).' ~ '.dataFilter($row['leave_to']).' ('.dataFilter($row['leave_day']).')' ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, dataFilter($row['leave_reason']) ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, dataFilter($row['leave_status']) ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, resetDateFormat($row['created_at']) ) ;
	                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( ($newChar++).$count, resetDateFormat($row['updated_at']) ) ;

	                $count++ ;
	                $count_row++ ;
				}
			}

			// Submission from
		    header( 'Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) ; 
		    header( 'Content-Disposition: attachment;filename="'.$page_filename.'.xls"' ) ;
		    header( 'Cache-Control: max-age=0' ) ;
		    // save to pc
		    $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' ;

		setStaffLeaveYear( $staff_id ) ;
		?>
		<!-- Header Ends -->
		<div class="warper container-fluid">   

			<div class="page-header">
				<h1><?= $lang['Staff Leave']?> <small><?= $lang['list']?></small></h1>
				<a href="?<?= $search_url ?>&export=yes" target="_blank" style="float: right; margin-top: -30px;"><?= $lang['export_as']?> Excel</a>
			</div>

			<?php
			$get_year = $mysqli->query("SELECT leave_year_id, leave_type, leave_days FROM staff_leave_year
										WHERE staff_id = '".$staff_id."' AND leave_year = '".date('Y', time())."'") ;
			if ( $get_year->num_rows > 0 ){
				$annual_id = '' ;
				$annual    = '' ;
				$sick_id   = '' ;
				$sick      = '' ;
				while ( $row_year = $get_year->fetch_assoc() ){
					if ( $row_year['leave_type'] == 'annual' ){
						$annual_id = $row_year['leave_year_id'] ;
						$annual    = $row_year['leave_days'] ;
					}
					if ( $row_year['leave_type'] == 'sick' ){
						$sick_id   = $row_year['leave_year_id'] ;
						$sick      = $row_year['leave_days'] ;
					}
				}
				?>
				<form method="post" class="form-horizontal">
					<div class="panel panel-default">
		                <div class="panel-heading"></div>
		                <div class="panel-body">
		                	<div class="form-group">
	                    		<div class="col-sm-2 control-label">Annual</div>
						        <div class="col-sm-9">
						            <input class="form-control temporarynotcontrol group_1" name="leave_annual" id="leave_annual" type="text" value="<?= $annual ?>" placeholder="Annual" />
						        </div>
						    </div>
						    <div class="form-group">
	                    		<div class="col-sm-2 control-label">Sick</div>
						        <div class="col-sm-9">
						            <input class="form-control temporarynotcontrol group_1" name="leave_sick" id="leave_sick" type="text" value="<?= $sick ?>" placeholder="Sick" />
						        </div>
						    </div>
						    <div class="form-group">
	                            <div class="col-sm-2 control-label"></div>
	                            <div class="col-sm-9">
	                                <button type="submit" class="btn btn-purple" style="float:right">Submit</button>
	                                <input type="hidden" name="hide" value="1" />
	                                <input type="hidden" name="leave_annual_id" value="<?= $annual_id ?>" />
	                                <input type="hidden" name="leave_sick_id" value="<?= $sick_id ?>" />
	                            </div>
	                        </div>
		                </div>
		            </div>
		        </form>
				<?php
			}
			?>

            <div class="panel panel-default">
                <div class="panel-heading"></div>
                <div class="panel-body">
					<table cellpadding="0" cellspacing="0" border="0" class="responsive table table-striped table-bordered" id="basic-datatable">
						<thead>
							<tr>
								<th><?= $lang['Request By']?></th>
								<th class="custom_dropdownbox">
									<div class="custom_dropdown_title"><?= $lang['type']?> </div>
									<div class="dropdown custom_dropdown custom_dropdown_lf" id="custom_dropdown_lf">
										<a href="#" class="dropdown-toggle custom_dropdown_toggle" data-toggle="dropdown"><b class="caret"></b></a>
									    <ul class="dropdown-menu">
									    	<li <?= ($ty_type == '' ? 'class="active"' : '') ?> ><a href="?<?= $search_url ?>&ty_type="><?= $lang['All']?></a></li>
									    	<li <?= ($ty_type == 'unpaid' ? 'class="active"' : '') ?> ><a href="?<?= $search_url ?>&ty_type=unpaid"><?= $lang['Unpaid']?></a></li>
									    	<li <?= ($ty_type == 'annual' ? 'class="active"' : '') ?> ><a href="?<?= $search_url ?>&ty_type=annual"><?= $lang['Annual']?></a></li>
									    	<li <?= ($ty_type == 'sick' ? 'class="active"' : '') ?> ><a href="?<?= $search_url ?>&ty_type=sick"><?= $lang['Sick']?></a></li>
									    </ul>
									</div>
								</th>
								<th><?= $lang['From To']?></th>
								<th><?= $lang['File']?></th>
								<th><?= $lang['Reason']?></th>
								<th class="custom_dropdownbox">
									<div class="custom_dropdown_title"><?= $lang['status']?> </div>
									<div class="dropdown custom_dropdown custom_dropdown_lf" id="custom_dropdown_lf">
										<a href="#" class="dropdown-toggle custom_dropdown_toggle" data-toggle="dropdown"><b class="caret"></b></a>
									    <ul class="dropdown-menu">
									    	<li <?= ($st_type == '' ? 'class="active"' : '') ?> ><a href="?<?= $search_url ?>&st_type="><?= $lang['All']?></a></li>
									    	<li <?= ($st_type == 'pending' ? 'class="active"' : '') ?> ><a href="?<?= $search_url ?>&st_type=pending"><?= $lang['Pending']?></a></li>
									    	<li <?= ($st_type == 'confirmed' ? 'class="active"' : '') ?> ><a href="?<?= $search_url ?>&st_type=confirmed"><?= $lang['Confirmed']?></a></li>
									    	<li <?= ($st_type == 'rejected' ? 'class="active"' : '') ?> ><a href="?<?= $search_url ?>&st_type=rejected"><?= $lang['Rejected']?></a></li>
									    </ul>
									</div>
								</th>
								<th><?= $lang['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)){

									if ( $row_page['leave_status'] == 'pending' ){
										$button =  '<button class="btn btn-xs bg-yellow margin" type="button"><b>'.$lang['PENDING'].'</b></button>' ;
									}elseif ( $row_page['leave_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>' ;
									}

									echo '
									 <tr class="odd gradeX">
										<td>'.dataFilter($row_page['staff_name']).'<br />( '.dataFilter($row_page['staff_idno']).' )</td>
										<td class="align_center">'.ucwords($row_page['leave_type']).'</td>
										<td class="align_center">'.dataFilter($row_page['leave_from']).' ~ '.dataFilter($row_page['leave_to']).' ('.dataFilter($row_page['leave_day']).')</td>
										<td>' ;
											if ( $row_page['leave_file'] != '' ){
												echo '
												<a href="'.PATH.'/uploads/Leave/'.dataFilter($row_page['leave_file']).'" class="fancybox">
													<img src="'.PATH.'/uploads/Leave/'.dataFilter($row_page['leave_file']).'" style="width:50px" />
												</a>' ;
											}
										echo '
										</td>
										<td>'.dataFilter($row_page['leave_reason']).'</td>
										<td class="align_center">'.$button.'</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>
								</tr>' ;
							}
							?>
						</tbody>
					</table>
					<?= $page_pagination['page_pagination'] ?>
                </div>
            </div>

		</div>
		<?php
	break ;
}
// footer
include 'requires/page_footer.php' ;
?>