<?php 
include("includes/FCKeditor/fckeditor.php");
$file_name		= "index?page=view";
$working_hours_query = "SELECT * FROM working_hours ";
$working_hours_sql=mysqli_query($conn,$working_hours_query);
$working_hours_result=mysqli_num_rows($working_hours_sql);
if($working_hours_result>0){
	$form_action	= "update";
}else{
$form_action	= "insert";
}
$button_value 	= "Add";
$table_name 	= "working_hours";
$page_name      = "Shift Management";
$id	 = "";
$vat = "";
$query_string = "";
if(isset($_REQUEST["from"]) && $_REQUEST["from"] !=""){
 $from = $_REQUEST['from'];
}

################################################## START INSERT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert'){	
	utility::addslashesOnAllInput(array("query_string"));
	$created_by					= $_SESSION['user_id'];
	$created_on					= date("Y-m-d H:i:s");	
	$updated_by					= $_SESSION['user_id'];	
	if(count($_REQUEST['day_shifts']) > 0){
		foreach($_REQUEST['day_shifts'] as $key => $day_shifts){
			
			if($day_shifts!=""){
				$shift_name = $_REQUEST['shift_name'][$key];
				$shift_id = $_REQUEST['shift_id'][$key];
				$start_time = $_REQUEST['start_time'][$key];
				$end_time = $_REQUEST['end_time'][$key];
				$pay_rate = $_REQUEST['pay_rate'][$key];
			    $start_timee = strtotime($start_time);
				$end_timee = strtotime($end_time);
				$hourss = (abs($end_timee - $start_timee));
				$hours = floor($hourss / 3600); 
				$minutes = floor(($hourss % 3600)/60);
				$total_hrs = $hours . ':' . $minutes ;
							
				$sql= "shift_name = '".$shift_name."',day_shifts = '".$day_shifts."',shift_id = '".$shift_id."',end_time = '".$end_time."',start_time = '".$start_time."',pay_rate = '".$pay_rate."',hours = '".$total_hrs."',created_on = '".$created_on."', created_by = '".$created_by."', updated_by = '".$updated_by."'";
			
				$sql= "INSERT INTO working_hours SET ".$sql;
				mysqli_query($conn,$sql);
			}
		}
	}
	
	$tmp = ucfirst(str_replace("_"," ", $table_name));
	$_SESSION['info_message'] = "Shift added successfully";
    header("Location: $file_name");
    exit();
}
################################################# END INSERT #################################################

################################################## START EDIT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){	
	$id = $_REQUEST['id'];

	$form_action 	= "update";
	$button_value 	= "Update";
	$page_name      = "Edit Shift Management";
	$query_string 	=  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
	
	
    $sql= "SELECT * FROM $table_name WHERE id = $id";
    $result_edit = mysqli_query($conn,$sql);
    $row_edit = mysqli_fetch_array($result_edit);
	
	$day_shifts	= $row_edit['day_shifts']; 
    $hours	= $row_edit['hours'];
	$pay_rate	= $row_edit['pay_rate'];
	$start_date	= $row_edit['start_date'];
	$start_time	= $row_edit['start_time'];
	$end_time	= $row_edit['end_time'];
	$shift_name	= $row_edit['shift_name'];
}
################################################# END EDIT ################################################# 


################################################## START UPDATE ################################################## 
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'update'){    
	utility::addslashesOnAllInput(array("query_string"));
	 
	$id				= $_REQUEST['id'];	
	$created_by					= $_SESSION['user_id'];
	$created_on					= date("Y-m-d H:i:s");	
	$updated_by					= $_SESSION['user_id'];
	
	if(count($_REQUEST['day_shifts'])>0){	
	foreach($_REQUEST['day_shifts'] as $key => $day_shifts){
		
		$shift_name = $_REQUEST['shift_name'][$key];
		$start_time = $_REQUEST['start_time'][$key];
		$shift_id = $_REQUEST['shift_id'][$key];
		$end_time = $_REQUEST['end_time'][$key];
		$pay_rate = $_REQUEST['pay_rate'][$key];
		$hrs_payrate_mapping_id = $_REQUEST['hrs_payrate_mapping_id'][$key];
		$start_timee = strtotime($start_time);
		$end_timee = strtotime($end_time);
		$hourss = (abs($end_timee - $start_timee));
		$hours = floor($hourss / 3600); 
		$minutes = floor(($hourss % 3600)/60);
		$total_hrs = $hours . ':' . $minutes ;
		
		
		if(mysqli_num_rows(mysqli_query($conn,"SELECT * FROM working_hours WHERE id = '$hrs_payrate_mapping_id' ")) > 0){
			 $sql1= "UPDATE working_hours SET shift_id = '$shift_id',shift_name = '$shift_name',day_shifts = '$day_shifts', start_time = '$start_time', end_time = '$end_time', pay_rate = '$pay_rate', hours = '$total_hrs',updated_by = '$updated_by' WHERE id = '$hrs_payrate_mapping_id' ";
			
			 
		}else{
			 $sql1= "INSERT INTO working_hours (shift_id,shift_name,day_shifts,start_time,end_time,pay_rate,hours,created_by,created_on,updated_by) VALUES('$shift_id','$shift_name','$day_shifts','$start_time','$end_time','$pay_rate','$total_hrs','$created_by','$created_on','$updated_by')";
			
		}
		mysqli_query($conn,$sql1);
	}
	}
	
	
	$query_string = (isset($_REQUEST['query_string']) && !empty($_REQUEST['query_string'])) ? $_REQUEST['query_string'] : "";
  	$query_string = str_ireplace("page=add", "page=view", $query_string);
	$query_string = "&".$query_string;
	$tmp = ucfirst(str_replace("_"," ", $table_name));
	$_SESSION['info_message'] = "Shift updated successfully";
	
	if(isset($from) && $from == "view"){
	   header("Location: index?page=add&hide_top=1&hide_left=1");
       exit();
	}

    header("Location: $file_name$query_string");
    exit();
}
$working_hours_query = "SELECT * FROM working_hours where id = '".$_REQUEST['id']."'";
$working_hours_sql=mysqli_query($conn,$working_hours_query);
$working_hours_result=mysqli_num_rows($working_hours_sql);
################################################# END UPDATE ################################################# 
?>
<style>
em{color:red;font-size: 20px;position: absolute;}
</style>
<div class="col-sm-12 col-lg-12 col-12" id="hrs_payrate_div_to_clone" style="display:none;">
	<div class="row">
		<div class="col-sm-1"> 
				<?php 
				$rr_query = mysqli_query($conn, "SELECT CASE WHEN MAX(shift_id) IS NULL OR MAX(shift_id) = 0 THEN 100 ELSE MAX(shift_id) + 1 END AS new_id FROM working_hours;");
             	$rr_row = mysqli_fetch_assoc($rr_query);
				$shift_id = '';
	            $shift_id =str_pad($rr_row['new_id'], 3, '0', STR_PAD_LEFT);
				
                  
				?>
			 <label class="control-label" for="Shift Id">&nbsp;<em></em></label> 
			 <input type="text" class="form-control" id="shift_id" name="shift_id[]" value="<?php echo  $shift_id ?>" placeholder="Shift Id" autocomplete="off" required readonly> 
             <input type="hidden" id="current_shift_id" value="<?php echo $shift_id; ?>">			 
		</div>
		<div class="col-sm-2"> 
			 <label class="control-label" for="Shift Name">&nbsp;<em></em></label> 
			 <input type="text" class="form-control" id="shift_name" name="shift_name[]" value="" placeholder="Shift Name" autocomplete="off" required>  
		</div>
		<div class="col-sm-2"> 
			 <label class="control-label" for="Day/Shift">&nbsp;<em></em></label> 
             <?= $gsi->getWeekList("day_shifts[]","","100%",false,"form-control part_number part","required"); ?>			 
		</div>
		<div class="col-sm-2"> 
			 <label class="control-label" for="Start Time">&nbsp;<em></em></label>   
			 <?= $gsi->getTimeList("start_time[]","","100%",false,"form-control part_number part","required"); ?>
			
		</div>
		<div class="col-sm-2"> 
			 <label class="control-label" for="End Time">&nbsp;<em></em></label> 
			<?= $gsi->getTimeList("end_time[]","","100%",false,"form-control part_number part",""); ?>
		</div>
		<div class="col-sm-2"> 
			 <label class="control-label" for="Pay Rate">&nbsp;<em></em></label> 
			 <input type="text" class="form-control" id="pay_rate" name="pay_rate[]" value="" placeholder="Pay Rate" autocomplete="off" required>  
		</div>
		<div class="col-sm-1" style="margin-top:35px;"> 
			<div class="custom-trash ">
				<label class="control-label"></label> 
				<span class="fa fa-trash delete_new_hrs_payrate" alt="" style="color: red;"></span>
			</div>
		</div>
	</div>
</div>
<!--<section class="content-header">
	<div class="container-fluid">
		<div class="row mb-2">
			<div class="col-sm-6">
				<h1>
					<?=$page_name;?>
				</h1>
			</div>
			<div class="col-sm-6">
			<?
			$query_string 	=  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
			$query_string = str_ireplace("page=add", "page=view", $query_string);	
			?>
			<button type="button" id="back" name="back" value="back"  style="float:right;margin-right:5px;margin-bottom:8px;" class="btn btn-primary" onclick="window.location.href = 'index?<?=$query_string;?>'">Back</button>
			</div>
		</div>
	</div>
</section>-->
<? if(isset($_SESSION['info_message'])){ ?>
  <div class="alert alert-info alert-primary">
	<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
	<? echo $_SESSION['info_message']; unset($_SESSION['info_message']);?>

	<script type="text/javascript">
	$(document).ready(function(){
		setTimeout(function(){
			window.location.href = 'index?page=view';
			window.parent.jQuery("#myModal .close_button2").click();
		},500);
		
	});
	</script>
  </div>
  <? } ?>
<section class="content">
	<div class="container-fluid">
	<div class="row">
		<div class="col-lg-12">
			<!-- general form elements -->
              <div class="card box-primary">
                <form class="form-horizontal" method="post" name="form1" id="form1" action="index?page=view&action=<? echo $form_action; ?>" onsubmit="return validateForm(this)" enctype="multipart/form-data">
                  <div class="card-body">
					<div class="form-section mt-2">
							<? 
								if($working_hours_result>0){
									$j = 0;
									while($mapp_row = mysqli_fetch_array($working_hours_sql)){
							?>
							<div class="col-sm-12 col-lg-12 col-12 initial_row_for_hrs_payrate" id="new_hrs_payrate<?=$mapp_row['id'];?>" data-personal_count="<?=$mapp_row['id'];?>">
							<div class="row">
							<div class="col-sm-2">
							  <label for="shift_id" class="control-label">Shift Id<em>*</em></label>
							  <div class="">
								<input type="text" id="shift_id" name="shift_id[<?=$j;?>]" class="form-control shift_id" value="<?php echo $mapp_row['shift_id'];?>" placeholder="Day/Shift" required readonly>
							  </div>
							</div>
							<div class="col-sm-2">
							  <label for="Shift Name" class="control-label">Shift Name<em>*</em></label>
							  <div class="">
								<input type="text" id="shift_name" name="shift_name[<?=$j;?>]" class="form-control shift_name" value="<?php echo $mapp_row['shift_name'];?>" placeholder="Pay Rate" required>
							  </div>
							</div>
							<div class="col-sm-2">
							  <label for="day_shifts" class="control-label">Day<em>*</em></label>
							  <div class="">
								<?= $gsi->getWeekList("day_shifts[$j]",$mapp_row['day_shifts'],"100%",false,"form-control select2","required"); ?>
							  </div>
							</div>
							<div class="col-sm-2"> 
								<label class="control-label" for="Start Time">Start Time<em>*</em></label> 
								<div class="">
									<?= $gsi->getTimeList("start_time[$j]",$mapp_row['start_time'],"100%",false,"form-control select2","required"); ?>
								</div>
							</div>
							<div class="col-sm-2"> 
								<label class="control-label" for="End Time">End Time</label>
								<div class="">
									<?= $gsi->getTimeList("end_time[$j]",$mapp_row['end_time'],"100%",false,"form-control select2",""); ?>
								</div>
							</div>
							<div class="col-sm-2">
							  <label for="Exch Rate" class="control-label">Pay Rate<em>*</em></label>
							  <div class="">
								<input type="text" id="pay_rate" name="pay_rate[<?=$j;?>]" class="form-control pay_rate" value="<?php echo $mapp_row['pay_rate'];?>" placeholder="Pay Rate" required>
							  </div>
							</div>
							<div class="col-sm-2" style="margin-top:35px;"> 
								<div class="custom-trash">
									<label class="control-label"></label>
									<input type="hidden" name="hrs_payrate_mapping_id[<?=$j;?>]" value="<?php echo $mapp_row['id'];?>">
									<?php if ($j != 0) { ?>
									<span class="fa fa-trash delete_new_hrs_payrate" style="cursor:pointer; color: red;"  alt="<?php echo $mapp_row['id'];?>"></span>
									<?php } ?>
									<i class="fas fa-sync-alt fa-spin" id="load_new_hrs_payrate_<?=$mapp_row['id'];?>" style="font-size: 20px;display:none;"></i>
									<i class="fa fa-check" id="status_update_personal_done_<?=$mapp_row['id'];?>" style="color:#bad23a;font-size: 20px;display:none;"></i>
								</div>
							</div>
						</div>
					</div>
					<?
					$j++;
					}}else{?>
					<div class="col-sm-12 col-lg-12 col-12 initial_row_for_hrs_payrate" id="new_hrs_payrate0" data-personal_count="0">
						<div class="row">
						    
						    <div class="col-lg-1">
							  <?php $shift_id =100;
								$rr_query = mysqli_query($conn, "SELECT CASE WHEN MAX(shift_id) IS NULL OR MAX(shift_id) = 0 THEN 100 ELSE MAX(shift_id) + 1 END AS new_id FROM working_hours;");
								$rr_row = mysqli_fetch_assoc($rr_query);
								$shift_id =str_pad($rr_row['new_id'], 3, '0', STR_PAD_LEFT);?>
							  <label for="shift_id" class="control-label">Shift Id<em>*</em></label>
							  <div class="">
								<input type="text" id="shift_id" name="shift_id[]" class="form-control shift_id" value="<?php echo $shift_id?>" placeholder="Day/Shift" required readonly>
							  </div>
							</div>
							<div class="col-lg-2">
							  <label for="Shift Name" class="control-label">Shift Name<em>*</em></label>
							  <div class="">
								<input type="text" id="shift_name" name="shift_name[]" class="form-control shift_name" value="" placeholder="Shift Name" required>
							  </div>
							</div>
							<div class="col-lg-2">
							  <label for="day_shifts" class="control-label">Day<em>*</em></label>
							  <div class="">
								<?= $gsi->getWeekList("day_shifts[]","","100%",false,"form-control select2","required"); ?>
							  </div>
							</div>
							<div class="col-lg-2"> 
								<label class="control-label" for="Start Time">Start Time<em>*</em></label> 
								<div class="">
									<?= $gsi->getTimeList("start_time[]","","100%",false,"form-control select2","required"); ?>
								</div>
							</div>
							<div class="col-lg-2"> 
								<label class="control-label" for="End Time">End Time</label>
								<div class="">
									<?= $gsi->getTimeList("end_time[]","","100%",false,"form-control select2",""); ?>
								</div>
							</div>
							<div class="col-lg-2">
							  <label for="Exch Rate" class="control-label">Pay Rate<em>*</em></label>
							  <div class="">
								<input type="text" id="pay_rate" name="pay_rate[]" class="form-control pay_rate" value="" placeholder="Pay Rate" required>
							  </div>
							</div>
						</div>
					</div>
					<?}?>
					<?php if($from == 'view'){
						$hide ='hide';
					}?>
					<div class="form-group col-sm-12 hrs_payrate_div_to_append <?php echo $hide; ?>" >	
						<label class="add_one_more_hrs_payrate" style="margin-left:0%;cursor:pointer;color: #a423a4; "><span class="fa fa-plus"></span>Add More</label>
					</div>
					</div>
                  </div><!-- /.box-body -->
                  <div class="card-footer">
					<input type="hidden" id="id" name="id" value="<?php echo $id;?>">
					<input type="hidden" id="from" name="from" value="<?php echo $from;?>">
					<input type="hidden" id="query_string" name="query_string" value="<?php echo $query_string;?>">
                    <button type="submit" id="submit" name="submit" value="<?php echo $button_value;?>" class="btn btn-primary">Submit
						<i class="fas fa-sync-alt fa-spin" style="display:none;" id="page_load_div"></i>
					</button>
                  </div>
                </form>
              </div><!-- /.box -->
		</div>
	</div>
	</div>
</section>
<script type="text/javascript">
$(function(){
	$('#form1').submit(function(){
		$("#submit").attr("disabled", true);
		$('#page_load_div').show();
	});
	
	$('.add_one_more_hrs_payrate').click(function() { 
    $('#hrs_payrate_div_to_clone').show();
    var div_count = $('.initial_row_for_hrs_payrate').last().attr("data-personal_count");
    div_count++;
    var current_shift_id = parseInt($('#current_shift_id').val());
    var new_shift_id = current_shift_id + 1;
    $('#current_shift_id').val(new_shift_id);
    var cloned_div = $('#hrs_payrate_div_to_clone').clone()
        .addClass("initial_row_for_hrs_payrate")
        .attr("id", "new_hrs_payrate" + div_count)
        .attr("data-personal_count", div_count);
    cloned_div.find('#shift_id').val(new_shift_id.toString().padStart(3, '0')); // Pad the shift ID
    $('.hrs_payrate_div_to_append').before(cloned_div);
    $('#hrs_payrate_div_to_clone').hide();
});

	
	
		$("#form1").on("click", ".delete_new_hrs_payrate",function() {
	    if(confirm('Are you sure you want to delete?')){		
			if($(this).attr("alt") != ""){
				var hrs_payrate_mapping_id = $(this).attr("alt");
				$('#load_new_hrs_payrate_'+hrs_payrate_mapping_id).show();
				var form_data   = {'hrs_payrate_mapping_id':hrs_payrate_mapping_id};      
                //alert(hrs_payrate_mapping_id);				
				$.ajax({
					async: true,
					type: "POST",
					//url: site_url+"/modules/working_hrs_management/index.php?page=ajax_actions&action=delete_hrs_payrate_mapping",
					url: site_url+"/working_hrs_management/index/index?page=ajax_actions&action=delete_hrs_payrate_mapping",
					data: form_data,
					success: function(result){    
						var resultObj = jQuery.parseJSON(result); 
						if(resultObj.status == "success"){
							$('#status_update_personal_done_'+hrs_payrate_mapping_id).show();
							$('#load_new_hrs_payrate_'+hrs_payrate_mapping_id).hide();
							
							setTimeout(function() {
								$('#status_update_personal_done_'+hrs_payrate_mapping_id).hide();
								$('#new_hrs_payrate'+hrs_payrate_mapping_id).remove();
								//location.reload();
							},1000);
						}
					}
				});
			}else{
				$(this).parent().parent().parent().parent().remove();
			}
		}
	});
});
</script>