<?php
$message = (isset($_SESSION['message'])) ? $_SESSION['message'] :"";
$action = (isset($_REQUEST['action'])) ? $_REQUEST['action'] : "insert";

$collapse_booke_timesheet_area = "collapse";

$where 	= " WHERE 1=1 ";


$query_string = "";

$button_value 	= "Add";
$table_name		= "timesheet";

$next_page_condition 	= "";

if($_REQUEST['hide_top']){
	$next_page_condition.="&hide_top=1";
}
if($_REQUEST['hide_left']){
	$next_page_condition.="&hide_left=1";
}
/* if($_SESSION['is_consultant']){
	if(count($criscrm->getJobIdsByConsultantId($_SESSION['admin_user_id'])) > 0){
		$job_id_string = implode(",",$criscrm->getJobIdsByConsultantId($_SESSION['admin_user_id']));
		$where 	.= " AND job_id IN('$job_id_string') ";
		//$next_page_condition.="&job_id_search=".$_REQUEST['job_id_search'];
	}
} */

if(isset($_REQUEST['source'])){
	$source = $_REQUEST['source'];
	$next_page_condition.="&source=$source";
}
if($_REQUEST['job_id_search']){
	$job_id = $_REQUEST['job_id_search'];
}

$paging ="";
if($_REQUEST['start']){
	$paging .="&start=".$_REQUEST['start'];
	//$next_page_condition.="&start=$start";
}
$query_string =  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
################################################## START EDIT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){
	$collapse_booke_timesheet_area = "";
	$query_string =  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
	
	$action 	= "update";
	$button_value 	= "Update";
	$page_name		= "Edit Timesheet";	
		
    $id = $_REQUEST['id'];
    $sql= "SELECT * FROM $table_name WHERE id = $id";
    $result_edit = mysqli_query($conn,$sql);
    $row_edit = mysqli_fetch_array($result_edit);

    $id= $row_edit['id'];
    $job_id= $row_edit['job_id'];
	$project_id= $row_edit['project_id'];
	$timesheet_option= $row_edit['timesheet_option'];
    $admin_id= explode(",",$row_edit['admin_id']);
	$timesheet_text= $row_edit['timesheet_text'];
	$timesheet_date= $row_edit['timesheet_date'];
	$timesheet_time= $row_edit['timesheet_time'];
	$from_time= $row_edit['from_time'];
	$to_time= $row_edit['to_time'];
}
################################################# END EDIT #######################################################

################################################## START update ################################################## 
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'update'){    
	utility::addslashesOnAllInput(array("query_string","admin_id"));
	$id= $_REQUEST['id'];
    $job_id= $_REQUEST['job_id'];
	$project_id	= (isset($_REQUEST['project_id']) && $_REQUEST['project_id'] != '') ? $_REQUEST['project_id'] : '0';
	$timesheet_option= $_REQUEST['timesheet_option'];
    $admin_id= implode(",",$_REQUEST['admin_id']);
    $timesheet_text= $_REQUEST['timesheet_text'];
	$timesheet_date	 = utility::setFormatedDate($_REQUEST['timesheet_date']);
	$timesheet_time= $gsi->getTimesheetTimeInRound($_REQUEST['timesheet_time']);
	$from_time= $_REQUEST['from_time'];
	$to_time= $_REQUEST['to_time'];

    $sql= "UPDATE timesheet SET job_id = '$job_id',project_id = '$project_id',timesheet_option = '$timesheet_option',admin_id = '$admin_id',timesheet_text = '$timesheet_text',timesheet_date = '$timesheet_date',timesheet_time = '$timesheet_time',from_time = '$from_time',to_time = '$to_time',updated_by = '".$_SESSION['user_id']."' WHERE id = $id";
    mysqli_query($conn,$sql);
	
	$query_string = (isset($_REQUEST['query_string']) && !empty($_REQUEST['query_string'])) ? $_REQUEST['query_string'] : "";
  	$query_string = str_ireplace(array("page=add","action=edit"), array("page=list",""), $query_string);
	$query_string = "&".$query_string;
	$tmp = ucfirst(str_replace("_"," ", $table_name));
	
	$_SESSION['message']	= ucfirst("timesheet updated sucessfully");
	$redirect = "index?page=view_timesheet_for_admin$query_string";
	header("Location: $redirect");
	exit();
	
}
################################################# END update ################################################# 

################################################## START INSERT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert'){	    
	utility::addslashesOnAllInput(array("query_string","admin_id"));
    $job_id = $_REQUEST['job_id'];
	$project_id	= (isset($_REQUEST['project_id']) && $_REQUEST['project_id'] != '') ? $_REQUEST['project_id'] : '0';
	$timesheet_option= $_REQUEST['timesheet_option'];	
    $source =  $gsi->getEnqQuoteJobStatusById($_REQUEST['job_id']);	
    $admin_id = implode(",",$_REQUEST['admin_id']);
	$timesheet_text = $_REQUEST['timesheet_text'];
	$entry_for_month = $gsi->getEntryForMonthByJobId($job_id);
	$timesheet_date	 = utility::setFormatedDate($_REQUEST['timesheet_date']);
	$timesheet_time = $gsi->getTimesheetTimeInRound($_REQUEST['timesheet_time']);
	$from_time = $_REQUEST['from_time'];
	$to_time = $_REQUEST['to_time'];
	$created_on = date("Y-m-d");
		
	if(isset($_REQUEST['search_job_id']) && $_REQUEST['search_job_id'] !=""){
		$job_id_search_string = "&job_id_search=".$_REQUEST['search_job_id']."";
	}
	
    $sql= "INSERT INTO $table_name (job_id,project_id,timesheet_option,source,admin_id,timesheet_text,entry_for_month,timesheet_date,timesheet_time,from_time,to_time,updated_by,created_on) VALUES('$job_id','$project_id','$timesheet_option','$source','$admin_id','$timesheet_text','$entry_for_month','$timesheet_date','$timesheet_time','$from_time','$to_time','".$_SESSION['user_id']."','$created_on')";
    mysqli_query($conn,$sql);
	
	$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['message']	= ucfirst("timesheet added sucessfully");
	$redirect = "index?page=view_timesheet_for_admin$job_id_search_string$query_string";
	header("Location: $redirect");
	exit();
}
################################################# END INSERT #################################################
if($_REQUEST['admin_id_search']){
	$admin_id_search = $_REQUEST['admin_id_search'];
	$where 	.= " AND admin_id ='$admin_id_search' ";
	$next_page_condition.="&admin_id_search=".$_REQUEST['admin_id_search'];
}
if($_REQUEST['timesheet_option_search']){
	$timesheet_option_search = $_REQUEST['timesheet_option_search'];
	$where 	.= " AND timesheet_option ='$timesheet_option_search' ";
	$where_for_admin .= " AND timesheet_option ='$timesheet_option_search' ";
	$next_page_condition.="&timesheet_option_search=".$_REQUEST['timesheet_option_search'];
}
if($_REQUEST['job_id_search']){
	$job_id_search = $_REQUEST['job_id_search'];
	$where 	.= " AND job_id ='$job_id_search' ";
	$next_page_condition.="&job_id_search=".$_REQUEST['job_id_search'];
}
if($_REQUEST['project_id_search']){
	$project_id_search = $_REQUEST['project_id_search'];
	$where 	.= " AND project_id ='$project_id_search' ";
	$next_page_condition.="&project_id_search=".$_REQUEST['project_id_search'];
}
$from_timesheet_date = isset($_REQUEST['from_timesheet_date']) ? utility::setFormatedDate($_REQUEST['from_timesheet_date']) : "";
$to_timesheet_date = isset($_REQUEST['to_timesheet_date']) ? utility::setFormatedDate($_REQUEST['to_timesheet_date']) : "";
if($from_timesheet_date && $to_timesheet_date){
	$where .= " AND timesheet_date BETWEEN '$from_timesheet_date 00:00:00' and '$to_timesheet_date 23:59:59' ";
	$where_for_admin .= " AND timesheet_date BETWEEN '$from_timesheet_date 00:00:00' and '$to_timesheet_date 23:59:59' ";
    $next_page_condition.="&from_timesheet_date=".$_REQUEST['from_timesheet_date']."&to_timesheet_date=".$_REQUEST['to_timesheet_date']."";
}else if($from_timesheet_date){
	$where.= " AND timesheet_date >= '$from_timesheet_date' ";
	$where_for_admin .= " AND timesheet_date >= '$from_timesheet_date' ";
	$next_page_condition.="&from_timesheet_date=".$_REQUEST['from_timesheet_date'];
}else if($to_timesheet_date){
	$where.= " AND timesheet_date <= '$to_timesheet_date' ";
	$where_for_admin .= " AND timesheet_date <= '$to_timesheet_date' ";
	$next_page_condition.="&to_timesheet_date=".$_REQUEST['to_timesheet_date'];
}
###########################################  PAGING WITH PER PAGE  #####################################
$file_name		= "index"; // this is file name which is used during paging  , included at the bottom of the page
$paging_table_name	= $table_name;
$paging_query		= $where;
$join_query_for_paging = "SELECT * FROM $table_name  $where ";
$page_header = "Timesheet Management ";
include("paging/paging_query.inc.php");
$query = "SELECT * FROM $table_name $where ORDER BY id DESC LIMIT $eu, $limit ";
/*if(!$_REQUEST['job_id_search']){ 
	include("paging/paging_query.inc.php");
	############################################ END PAGING WITH PER PAGE  #######################################
	$query = "SELECT * FROM $table_name $where ORDER BY timesheet_date ASC LIMIT $eu, $limit ";
}else{
	$query = "SELECT * FROM $table_name $where ORDER BY timesheet_date ASC ";
}*/
$sql=mysqli_query($conn,$query);
$result=mysqli_num_rows($sql);

$total_no_of_timesheets = mysqli_num_rows(mysqli_query($conn,$join_query_for_paging));
#################################   DELETE    #########################################
// when we click on delete this area of php timesheet will execute
if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete'){
	$id	= $_REQUEST['id'];
	mysqli_query($conn,"DELETE FROM $table_name WHERE id = $id ");
	
	$_SESSION['message']	= ucfirst("Timesheet deleted sucessfully");
	$redirect = "index?page=view_timesheet_for_admin";
	header("Location: $redirect");
	exit();
}
#################################  END DELETE    #########################################
#################################  Export CSV    #########################################
if(isset($_REQUEST['action']) && $_REQUEST['action']=='export_timesheet_details'){
  include("export_timesheet_details_to_csv.inc.php");
}
###########################################  End Export  #####################################
?>
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-12">
                <h1 class="m-0"><? echo str_replace(array("_"),array(" "),$page_header); ?></h1>
            </div>
        </div>
        <!-- /.row -->
    </div>
    <!-- /.container-fluid -->
</div>
<!----------------------- Message ------------------------------->
	<? if(isset($_SESSION['message'])){ ?>
	<section class="content-header">
	  <div class="alert alert-info alert-dismissable" style="margin-bottom:0px;">
		<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
		<? echo $_SESSION['message'];
			unset($_SESSION['message']);
		?>
	  </div>
	</section>
	<? } ?>
<!----------------------- End Message ------------------------------->
	<section class="content">
		<div class="container-fluid">
		<div class="row">
			<div class="col-lg-12">
				<div class="card">

				<div class="card-body">
				<div class="" style="padding:0px 10px;">
					<?php include_once('add_timesheet_for_admin.inc.php');?>
				</div>
				Total No. of timesheets <?=$total_no_of_timesheets;?><br>
				<div id="total_timesheet_time_div"></div>
				<? if(isset($_REQUEST['admin_id_search']) && !(isset($_REQUEST['job_id_search']) && $_REQUEST['job_id_search'] !="")){ ?>
				<b>Total Time <? echo $gsi->getTotalTimeByAdminId($_REQUEST['admin_id_search'],$lead,$where_for_admin)?></b>
				<? } ?>
				<div style="float:right;margin-bottom:4px;" class="hide_search_div">Export Timesheet Details &nbsp;&nbsp;<a href="index?page=view_timesheet_for_admin&action=export_timesheet_details<?=$next_page_condition;?>"><i class="fa fa-download" style="font-size:20px;"></i></a></div>
									
				<form action="?page=view_timesheet_for_admin&name=<?=$name?>" method="post" name="form1" id="form1">
				<? if($result>0){
				?>
					<!-- Start  records header -->
				<table id="example1" class="table table-bordered table-striped">
					<thead>
						<tr>
							<th>Org. Name</th>
							<!--<th>Pro. Name</th>-->
							<th class="no-sort" style="width:30%;">Description</th>
							<th class="no-sort">T. Option</th>
							<th class="no-sort" style="width:100px;">Consultant</th>
							<th class="no-sort">Date</th>
							<th class="no-sort">Time</th>
							<th class="no-sort">From Time</th>
							<th class="no-sort">To Time</th>
							<th class="no-sort">Units</th>
							<? /*if($_REQUEST['job_id_search']){ ?>
							<th class="no-sort">Hours Work</th>
							<th>Hours Remaining (Total <? echo utility::getTableFieldById("job","total_hours","id",$_REQUEST['job_id_search'])?>)</th>
							<? }*/ ?>
							<th class="hide_search_div no-sort">Edit</th>						
							<th class="hide_search_div no-sort">Delete</th>
						</tr>
					</thead>
					<tbody>
					<!-- End records header -->
					<?
					$total_timesheet_time = 0;
					$total_hours = utility::getTableFieldById("job","total_hours","id",$_REQUEST['job_id_search']);
					while($row = mysqli_fetch_array($sql)){						
						$units = $gsi->getUnitByTime($row['timesheet_time']);
					?>
					<!-- Start data -->
					<tr>
						<td><?php echo utility::getTableFieldById('job','first_name','id',$row['job_id']); ?></td>
						<!--<td><?php //echo utility::getTableFieldById('job_project_mapping','project_title','id',$row['project_id']); ?></td>-->
						<td><?php echo '<span title="'.ucfirst($row['timesheet_text']).'">'.utility::ellipsis(ucfirst($row['timesheet_text']),65).'</span>'; ?></td>
						<td><?php echo Keycode::getkeycodeById($row['timesheet_option']); ?></td>
						<td><?php echo Admin::getAdminsById($row['admin_id']); ?></td>
						<td nowrap><?php echo utility::getFormatedDateReturn($row['timesheet_date']); ?></td>
						<td><?php echo $row['timesheet_time']; ?></td>
						<td><?php echo $row['from_time']; ?></td>
						<td><?php echo $row['to_time']; ?></td>
						<td><?php echo $units; ?></td>
						<? /*if($_REQUEST['job_id_search']){ ?>
						<td>
							<? echo $criscrm->getTotalTimeInDecimal($row['timesheet_time']);?>
						</td>
						<td>
							<?
								$time_in_decimal = $criscrm->getTotalTimeInDecimal($row['timesheet_time']);
								$remaining_time = $total_hours - $time_in_decimal;
								echo $remaining_time;
							?>
						</td>
						<? }*/ ?>
						<!--<td class="hide_search_div"><a href="index?page=view_timesheet_for_admin&action=edit&id=<?=$row['id'].$next_page_condition.$paging;?>"> <img src="../images/edit.gif" border="0" /> </a></td>-->
						<td class="hide_search_div"><a href="" class="edit_timesheet" data-toggle="modal" data-target="#myModal" alt="<?=$row['id'].$next_page_condition.$paging;?>"> <i class="fa fa-fw fa-edit"></i> </a></td>
						<td class="hide_search_div"><a
							href="index?page=view_timesheet_for_admin&action=delete&id=<?=$row['id'].$next_page_condition.$paging; ?>"
							onclick=" javascript:return confirm('Are you sure! You want to delete');"><img
							src="../images/del.gif" border="0" /> </a></td>
					</tr>
					<!-- End data -->
					<? 
						$total_timesheet_time = $total_timesheet_time + $time_in_decimal;
						$total_hours = $remaining_time;
						}
					?>
					
					<?}else{?>
					<tr>
						<td colspan="10">No timesheet found...</td>
					</tr>
					<?php }?>
					</tbody>
					
				</table>
					<!-- Paging starts here  -->
					<? 
					if(!$_REQUEST['job_id_search']){ 
						$next_page_condition .="&page=view_timesheet_for_admin";
						include("paging/paging_row.inc.php");
					}
					?>
						
					<!-- Paging ends starts here  -->
						
					<!--</table>-->
					</form>
					Total No. of timesheets <?=$total_no_of_timesheets;?><br>
					<? /*if($_REQUEST['job_id_search']){ ?>
					<b>Total Time <? echo $total_timesheet_time;?> hours</b>
					<? }*/ ?>
					</div>
				</div>
			</div>
		</div>
		</div>
	</section>
<style>
@media print
{
	.hide_search_div{
		display:none;
	}
}
</style>	
<? if($_REQUEST['job_id_search']){ ?>
<script type="text/javascript">
$(document).ready(function() {
	/*$('#example1').DataTable({
		  "paging": false,
		  "lengthChange": false,
		  "searching": false,
		  "ordering": true,
		  "info": false,
		  "autoWidth": false,
		   "columnDefs": [ {
			  "targets": 'no-sort',
			  "orderable": false,
		} ],
	"order": [[ 8, "asc" ]]
    });*/
	<? /*if($_REQUEST['job_id_search']){ ?>
		$('#total_timesheet_time_div').html("<b>Total Time <? echo $total_timesheet_time;?> hours</b>");
	<? }*/ ?>
});	
</script>
<? } ?>
<script type="text/javascript">
$(document).ready(function() {
	//$("#timesheet_time").focus(function(){
	<? if($_POST['action']!='edit'){ ?>
	$("#from_time,#to_time").change(function(){
		var from_time = $("#from_time").val();
		var to_time = $("#to_time").val();		
		if(!((from_time == "00:00" || from_time == "00:00:00") && (to_time == "00:00" || to_time == "00:00:00"))){
			var form_data   = {'from_time':from_time,'to_time':to_time};       
			$.ajax({
				async: false,
				type: "POST",
				url: site_url+"/modules/timesheet_management/index.php?page=ajax_actions&action=calculate_time",
				data: form_data,
				success: function(result){  
					var resultObj = jQuery.parseJSON(result); 
					$('#timesheet_time').val(resultObj.calculate_time);
				}
			});
		}
	});
	<?}?>
	$(".edit_timesheet").click(function(){
		$("#myModalLabel").text("Timesheets");
		var hide_top_left = "&hide_top=1&hide_left=1";
		//var job_id = "<?=$row['id'];?>";	
		var timesheet_id = $(this).attr("alt");
		var view_timesheet_for_admin = "&view_timesheet_for_admin=show_contact_list";		
		$(".modal_iframe").attr("src","<?=$config->frontEndURL?>/admin/timesheet_management/index?page=view&action=edit&id="+timesheet_id+view_timesheet_for_admin+hide_top_left);
	});
});	
</script>
