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

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

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

// keep parameter in value
$page = escapeString($_GET['page']) ;
$page_mode = escapeString($_GET['page_mode']) ;
$type = escapeString($_GET['type']) ;
$search = escapeString($_GET['search']) ;

// active menu bar
$active_main_menu = 'setting' ;
$active_sub_menu = 'setting-hr' ;
$active_menu = 'setting-hr-leave' ;

// mode type | all list | new | edit
switch($page_mode){
	
	// edit leave
	case 'new' :
	case 'edit' :

		// check query exsits
		$submit_type = 'new' ;
		$mysqli_page = $mysqli->query("SELECT * FROM setting_leave
									   WHERE leave_id = '".$page."' 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 ( isset($type) && ( $type == 'new' || $type == 'edit' ) && $_POST['hide'] == 1 ){

			// keep value in variable
			$page_title      = escapeString($_POST['title']) ;
			$page_title      = ($page_title != '' ? $page_title : 'No Title') ;

			if ( $page == '' ){
				$mysqli->query("INSERT INTO setting_leave (created_at) VALUES ('".TODAYDATE."')") ;
				$page = $mysqli->insert_id ;	
			}

			// leave more -> early
            $mores     = [] ;
            $early_key = $_POST['early_key'] ;
            foreach ( $early_key as $key => $value ){
                $mores[] = [
                    'more_from' => $_POST['early_from'][$value],
                    'more_to'   => $_POST['early_to'][$value],
                    'more_days' => $_POST['early_days'][$value]
                ] ;
            }
			
			// update database
			$mysqli->query("UPDATE setting_leave SET
							leave_name  = '".$page_title."',
							leave_code  = '".escapeString($_POST['leave_code'])."',
							leave_rules = '".json_encode($mores)."',
							updated_at  = '".TODAYDATE."'
							WHERE leave_id = '".$page."'") ;
			
			// remove all salary more first
			$mysqli->query("UPDATE setting_leave_more SET
							deleted_at = '".TODAYDATE."' 
							WHERE leave_id = '".$page."'") ;
			
			$key = array("attendance_allowance");
			foreach($key as $v){
				$early_key = $_POST[$v.'_key'] ;
				if(arrayCheck($early_key)){
					foreach ( $early_key as $key => $value ){
						$mysqli->query("INSERT INTO setting_leave_more
										(leave_id, more_type, more_from, more_to, more_amount, created_at, updated_at) VALUES
										('".$page."', '".$v."', '".$_POST[$v.'_from'][$value]."', '".$_POST[$v.'_to'][$value]."', '".$_POST[$v.'_amount'][$value]."', '".TODAYDATE."', '".TODAYDATE."' )") ;
		            }
				}
			}
			
			// refresh page
			header("Location:setting-leave.php?page_mode=edit&page=".$page."&success=1") ;
			$_SESSION['system_result'] = 'success-updated' ;
			exit ;
		}

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

		?>

		<style>
		#map-container,#canvas,#existMap {
		  height: 400px;
		}
		.list_first, .list_second, .list_third, .list_four, .list_five {
		    border: 1px solid #ccc;
		    border-top: 0;
		    padding: 0;
		    width: 20%;
		    text-align: center;
		}
		.list_border {
		    border-top: 1px solid #ccc;
		}
		.bold{
			font-weight: bold;
		}
		/* Map styles. */
		</style>

		<script>
		$(window).load(function(){

			// for early range
			$("#add_early").click(function() {
				earlyRange("new", "", "", "") ;
				return false;
			}) ;
			$(".remove_early").live('click', function(){
				$(this).parents(".early_table_list_tr").remove();
				return false;
			}) ;
			$(".add_table_deduct").click(function() {
				var selector = $(this).data("selector");
				console.log(selector);
				tableRange("new", "", "", "", selector) ;
				return false;
			}) ;
			$(".remove_table").live('click', function(){
				var selector = $(this).data("selector");
				$(this).parents("."+selector+"_tr").remove();
				return false;
			}) ;

			<?php
			$mores = json_decode($row_page['leave_rules'], true) ;
			$mores2       = [] ;
			$get_more    = $mysqli->query("SELECT * FROM setting_leave_more
										   WHERE leave_id = '".$page."' AND deleted_at IS NULL") ;
			if ( $get_more->num_rows > 0 ){
				while ( $value = $get_more->fetch_assoc() ){
					$mores2[] = [
	                    'more_id'     => $value['more_id'],
	                    'more_type'   => $value['more_type'],
	                    'more_from'   => $value['more_from'],
	                    'more_to'     => $value['more_to'],
	                    'more_amount' => $value['more_amount']
	                ] ;
				}
			}


			if ( !empty($mores) ){
				foreach ( $mores as $key => $value ){
						?> earlyRange("edit_<?= $key ?>", "<?= $value['more_from'] ?>", "<?= $value['more_to'] ?>", "<?= $value['more_days'] ?>") ; <?php
				}
			}

			if ( !empty($mores2) ){
				foreach ( $mores2 as $key => $value ){				
					
						?> tableRange("edit_<?= $key ?>", "<?= $value['more_from'] ?>", "<?= $value['more_to'] ?>", "<?= $value['more_amount'] ?>", "<?= $value['more_type'] ?>") ; <?php
					
					
				}
			}
			?>

			function earlyRange(type, from, to, early){
				var thisParent = $(".early_table_list"),
					content = "",
					earlyLength = thisParent.find(".early_table_list_tr").size() + 1 ;

				content += '<tr class="early_table_list_tr">' ;
					content += '<td class="list_first">' ;
						content += '<input type="hidden" name="early_key[]" value="'+(type == 'new' ? 'new_'+earlyLength : type)+'" />' ;
						content += '<input type="text" name="early_from['+(type == 'new' ? 'new_'+earlyLength : type)+']" class="form-control" value="'+from+'" required />' ;
					content += '</td>' ;
					content += '<td class="list_second">' ;
						content += '<input type="text" name="early_to['+(type == 'new' ? 'new_'+earlyLength : type)+']" class="form-control" value="'+to+'" required />' ;
					content += '</td>' ;
					content += '<td class="list_third">' ;
						content += '<input type="text" name="early_days['+(type == 'new' ? 'new_'+earlyLength : type)+']" class="form-control" value="'+early+'" required />' ;
					content += '</td>' ;
					content += '<td class="list_five">' ;
						content += '<a href="#" class="remove_early">x</a>' ;
					content += '</td>' ;
				content += '</tr>' ;

				thisParent.append(content) ;
			}

			// all in one
			function tableRange(type, from, to, late, Selector){
				var thisParent = $("."+Selector+"_list"),
					content = "",
					lateLength = thisParent.find("."+Selector+"_tr").size() + 1 ;

				content += '<tr class="'+Selector+'_tr">' ;
					content += '<td class="list_first">' ;
						content += '<input type="hidden" name="'+Selector+'_key[]" value="'+(type == 'new' ? 'new_'+lateLength : type)+'" />' ;
						content += '<input type="text" name="'+Selector+'_from['+(type == 'new' ? 'new_'+lateLength : type)+']" class="form-control" value="'+from+'" required />' ;
					content += '</td>' ;
					content += '<td class="list_second">' ;
						content += '<input type="text" name="'+Selector+'_to['+(type == 'new' ? 'new_'+lateLength : type)+']" class="form-control" value="'+to+'" required />' ;
					content += '</td>' ;
					content += '<td class="list_third">' ;
						content += '<input type="text" name="'+Selector+'_amount['+(type == 'new' ? 'new_'+lateLength : type)+']" class="form-control" value="'+late+'" required />' ;
					content += '</td>' ;
					content += '<td class="list_five">' ;
						content += '<a href="#" class="remove_table" data-selector="'+Selector+'">x</a>' ;
					content += '</td>' ;
				content += '</tr>' ;

				thisParent.append(content) ;
			}

		}) ;
		</script>

		<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['Leave'] ?> <small><?= $lang[$page_mode] ?></small></h1>
                	</div>
                </div>
			<?php
            if ($_SESSION['system_result'] != ''){
                switch($_SESSION['system_result']){
                    case 'success-updated' :
                        echo '
                        <div class="result_success">
                           '.$lang['thank_you_your_leave_has_been_updated'].'
                        </div>' ;	
                    break ;
                }
                unset($_SESSION['system_result']) ;
            }
            ?>
        	</div>
            <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="setting-leave.php?page_mode=edit&page=<?= $page ?>&type=edit" novalidate="novalidate">
                        <div class="form-group">
                            <div class="col-sm-2 control-label"><?= $lang['Leave Name'] ?></div>
                            <div class="col-sm-9">
                                <input type="text" name="title" class="form-control ui-search-input" value="<?= dataFilter($row_page['leave_name']) ?>" placeholder="<?= $lang['Leave Name'] ?>" >
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-2 control-label"><?= $lang['Code'] ?></div>
                            <div class="col-sm-9">
                                <input type="text" name="leave_code" class="form-control ui-search-input" value="<?= dataFilter($row_page['leave_code']) ?>" placeholder="<?= $lang['Code'] ?>" >
                            </div>
                        </div>

                        <hr />

                        <div class="form-group">
                        	<div class="col-sm-2 control-label"><?= $lang['if_early'] ?></div>
							<div class="col-sm-9">
								
								<table border="0" cellpadding="0" cellspacing="0" width="100%" class="early_table_list">
									<tr class="early_table_list_tr">
										<td colspan="5">
											<a href="#" id="add_early"><?= $lang['add_group'] ?></a>
										</td>
									</tr>
									<tr class="early_table_list_tr">
										<td class="list_first list_border bold"><?= $lang['From (Months)'] ?></td>
										<td class="list_second list_border bold"><?= $lang['To (Months)'] ?></td>
										<td class="list_third list_border bold"><?= $lang['Days'] ?></td>
										<td class="list_five list_border bold">&nbsp;</td>
									</tr>
								</table>

							</div>					
						</div>

						<hr />

                        <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>   
                    </form>
                </div>
            </div>
        </div>
		</div>
		<?php
		
	break ;
	
	// all leave list
	case 'all' :
	default :
		
		// query type
		$search_query = '' ;
		
		// search query
		if ($search != ''){
			$search_query .= " AND (leave_name LIKE '%".$search."%')" ;
		}
		
		// form submit
		if ($_POST['hide'] == '1' && $_POST['hide_status'] == 'action'){
			// trash item
			switch($_POST['page_action']){
				case 'trash':
					$mysqli_query = "UPDATE " . setting_leave . " SET
									deleted_at = '".TODAYDATE."'
									WHERE leave_id = " ;
					$trash_page = trashPage('leave', $mysqli, $mysqli_query, $_POST['multiple_trash']) ;
				break;
			}
		}
		
		// 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 ;
		
		// page query
		$mysqli_query = "SELECT * FROM setting_leave
						 WHERE deleted_at IS NULL " . $search_query ;
		$mysqli_page = $mysqli->query($mysqli_query." ORDER BY leave_id 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' ;
		
		?>
		<!-- 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['Leave'] ?> <small><?= $lang['list'] ?></small></h1>
					</div>
                	<div class="pull-right col">
						<a href="setting-leave.php?page_mode=new" class="btn" style="color:white;background-color: #5e5bd0;" target="_blank"><?= $lang['add_new'] ?></a>
					</div>
				</div>
			</div>

            <form method="post">
                <!-- trash -->
                <div class="panel panel-default">
                    <div class="panel-body">
                        <select name="page_action" class="form-control selectpicker">
                            <option value=""><?= $lang['select'] ?></option>
                            <option value="trash"><?= $lang['move_to_trash'] ?></option>
                        </select>
                        <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>
                <!-- end trash -->
                <div class="panel panel-default">
                    <div class="panel-heading">listing</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><?= $lang['title'] ?></th>
									<th><?= $lang['date'] ?></th>
                                    <th width="50"><?= $lang['trash'] ?></th>
								</tr>
							</thead>
							<tbody>
								<?php
								if ($mysqli_page->num_rows > 0){
									while ($row_page = $mysqli_page->fetch_array(MYSQLI_ASSOC)){

										// default variable
										$id = $row_page['leave_id'] ;
										$title = dataFilter($row_page['leave_name']) ;
		
										echo '
										 <tr class="odd gradeX">
											<td><a href="setting-leave.php?page_mode=edit&page='.$id.'">'.$title.'</a></td>
											<td>'.resetDateFormat($row_page['created_at']).'</td>
											<td>
												<div class="checkbox multiple_trash">
													<input type="checkbox" name="multiple_trash['.$id.']" class="trash_button" value="1">
													<label for="checkbox1"></label>
												</div>
											</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>
									</tr>' ;
								}
								?>
							</tbody>
						</table>
						<?= $page_pagination['page_pagination'] ?>
                    </div>
                </div>
			</form>
		</div>
		</div>
		<?php
	break ;
}
// footer
include 'requires/page_footer.php' ;
?>