<?php
date_default_timezone_set('Asia/Kolkata'); 
//echo $date = date("Y-m-d", time());
include ('../config.php');
@session_start();
@$user_id1=$_SESSION['user_id1'];
@$idvfied1=$_SESSION['idverified1'];
@$namevfied1=$_SESSION['namevfied1'];
if(!isset($_SESSION['user_id1'])){
	header("Location: index.php");
}

$timeout = 60 * 60 * 24 * 365;
$s_name = session_name();
if(isset( $_COOKIE[ $s_name ] )) {
  setcookie( $s_name, $_COOKIE[ $s_name ], time() + $timeout, '/' );
}

$sel1=mysqli_query($conn,"select * from hr_dump where empid='".@$user_id1."'");
$fetch1=mysqli_fetch_array($sel1);

$queryFR=mysqli_query($conn,"select * from tracker where Functional_Reporting='$fetch1[Employee_Number]'");
$dataFR=mysqli_fetch_array($queryFR);

$queryFR=mysqli_query($conn,"select * from emp_leave where Functional_Reporting='$fetch1[Employee_Number]'");
$dataFR=mysqli_fetch_array($queryFR);

$datemin = date('Y-m-d', strtotime('-10 Days'));
$currYear = date("Y", time());

$datemax = date('Y-m-d', strtotime('+10 Days'));
$currYear = date("Y", time());

$COFFresult=mysqli_query($conn,"select * from pow where empid='".@$user_id1."' AND Status='POW' ORDER BY powid ASC");
$COFFdata=mysqli_fetch_assoc($COFFresult);
?>

<!doctype html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, viewport-fit=cover" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>COFF Leave Request</title>
	<?php	include ('header.php');	?>
	
	<div id="appCapsule">
        <div class="section wallet-card-section pt-1 mb-4">
            <div class="wallet-card">
				<!--<div class="balance">
                    <div class="left">
                        <span class="title"></?php echo $fetch1['Employee_Full_Name']; ?></span>
                        <h4></?php echo $fetch1['Team_Name']; ?></h4>
                        <h6></?php echo $date = date("Y-m-d", time()); ?></h6>
                    </div>
                    <div class="right">
                        <a href="#"><img src="../assets/img/noimage.png" alt="logo" class="logo-profile"></a>
                    </div>
                </div>-->
				
				<?php	include ('include/wallet-balance.php');	?>
<?php
if(isset($_POST['submit']))
{
	$powid=($_POST['powid']);
	$LeaveCategory=($_POST['LeaveCategory']);
	$LeaveType  = ($_POST['LQTY']."-".$_POST['LeaveCategory']);
	
	//echo "<pre>"; print_r($_POST); exit;
	
	$queryPOW=mysqli_query($conn,"select * from pow where powid='$_POST[powid]'");
	$dataPOW=mysqli_fetch_array($queryPOW);
	$DateCoff = $dataPOW['OfficeDate'];

	$stmt = $conn->prepare("INSERT INTO emp_leave (empid, Employee_Full_Name, Department, Team_Name, LeaveCategory, lat, longt, LeaveType, LQTY, DateFrom, DateCoff,  Remarks, Functional_Reporting, Reporting_Head_Code, Team_Head_Code, Status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

	if (!$stmt) {	die("Error preparing statement: " . $conn->error);	}

	$stmt->bind_param("ssssssssssssssss", $_POST['empid'], $_POST['Employee_Full_Name'], $_POST['Department'], $_POST['Team_Name'], $LeaveCategory, $_POST['lat'], $_POST['longt'], $LeaveType, $_POST['LQTY'], $_POST['DateFrom'], $dataPOW['OfficeDate'], $_POST['Remarks'], $_POST['Functional_Reporting'], $_POST['Reporting_Head_Code'], $_POST['Team_Head_Code'], $_POST['Status']);

	/* $query=mysqli_query($conn,"insert into emp_leave (empid, Employee_Full_Name, Department, Team_Name, LeaveCategory, lat, longt, LeaveType, LQTY, DateFrom, DateCoff, Remarks, Functional_Reporting, Reporting_Head_Code, Team_Head_Code, Status)
	values ('".$_POST['empid']."', '".$_POST['Employee_Full_Name']."', '".$_POST['Department']."', '".$_POST['Team_Name']."', '".$_POST['LeaveCategory']."', '".$_POST['lat']."', '".$_POST['longt']."', '$LeaveType',  '".$_POST['LQTY']."', '".$_POST['DateFrom']."', '$DateCoff', '".$_POST['Remarks']."', '".$_POST['Functional_Reporting']."', '".$_POST['Reporting_Head_Code']."', '".$_POST['Team_Head_Code']."', '".$_POST['Status']."' )"); */

	if ($LeaveCategory == 'COFF') {
		$TStatus='Taken';
		$query = mysqli_query($conn,"update pow set Status='$TStatus', Taken_For='".$_POST['DateFrom']."' where powid='$powid'" );
		}
	
	if ($stmt->execute()) {
		echo "<script>window.location.href='leave-view-current.php';</script>";
		exit;
	} else {
		die("Error executing statement: " . $stmt->error);
	}
	
	/* if($query==true) {	echo "<script>window.location.href='leave-view-current.php';</script>"; exit;
		echo "<div class='col-md-12 text-center btn btn-success'>Leave Request Sent! </div>";
		}
	else {
		echo "Error: " . $query . "<br>" . mysqli_error($conn);
		echo "<div class='col-md-12 text-center btn btn-danger'><strong>Error!</strong>Sorry something went wrong!</div>";
		} */
}
?>


    <style>
        #calendarContainer {
            max-width: 300px;
            margin: auto;
        }
        #calendar {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.8em;
        }
        th, td {
            border: 1px solid black;
            text-align: center;
            cursor: pointer;
        }
        .hidden {
            visibility: hidden;
        }
        .selected {
            background-color: #add8e6;
        }
        @media (max-width: 600px) {
            td, th {
                padding: 5px;
            }
            #calendar {
                font-size: 0.6em;
            }
        }
    </style>


 
				<div class="row">
					<div class="wallet-footer"><h6 class="text-center">Apply COFF Leave</h6></div>
					<form class="form-horizontal" name="leavereq" action="" method="post" enctype="multipart/form-data" autocomplete="off">
						<div class="row">
							<p class="text-center">Select COFF Date from List</p>
							<input class="form-control" type="hidden" name="empid" value="<?php echo $fetch1['empid']; ?>" />
							<input class="form-control" type="hidden" name="Employee_Full_Name" value="<?php echo $fetch1['Employee_Full_Name']; ?>" >
							<input class="form-control" type="hidden" name="Department" value="<?php echo $fetch1['Department']; ?>" >
							<input class="form-control" type="hidden" name="Team_Name" value="<?php echo $fetch1['Team_Name']; ?>" >
							<input class="form-control" type="hidden" name="Role" value="<?php echo $fetch1['Role']; ?>" >
							<input class="form-control" type="hidden" name='LeaveCategory' value='COFF'>
							<input class="form-control" type="hidden" name="lat" id="lat" onkeydown="return false;"  placeholder="No Manual Entry">
							<input class="form-control" type="hidden" name="longt" id="longt" onkeydown="return false;" placeholder="No Manual Entry">

							<?php
							$sql = "select * from pow where empid='".@$user_id1."' AND Status='POW' AND OfficeDate >= DATE_ADD( CURDATE(), INTERVAL -30 DAY ) ORDER BY powid ASC";
							$result = $conn->query($sql);
							?>				
							<div class="col-md-3 col-sm-3"><label>COFF Date</label>
								<select id="powid" name="powid" onchange="generateCalendar()" onClick='getMyLocation();' required class="form-control powid">
									<option value=''>-Select-</option>
									<?php	if ($result->num_rows > 0) {
										while($row = $result->fetch_assoc()) {
											//$displayText = $row["powid"] . "(" . $row["OfficeDate"] . ")" . $row["LQTY"];
											echo "<option value='" . $row["powid"] . "'>" . "(" . $row["OfficeDate"] . ")" . $row["LQTY"] . "</option>";
										}
									} else {
										echo "<option value=''>No COFF Available</option>";
									}
									//$conn->close();
									?>
								</select>
								
								
								<input class="form-control" type="hidden" name="DateFrom" id="selectedDate" >
								<div id="calendarContainer">
									<b>Select Date for Leave</b>
									<div id="calendar"></div>
								</div>
								<input class="form-control"  type="hidden" name="Status" id="Status" onkeydown="return false;" required>
								<input class="form-control"  type="hidden" name="LQTY" id="LQTY" onkeydown="return false;" required>
								<!--<input class="form-control" type="date" onClick='getMyLocation();' name="DateFrom" min="<?php echo $date; ?>"  max="<?php echo $datemax; ?>" required>-->
								
							</div>

							<div class="col-md-6 col-sm-6">
								<label>Remarks<span class="red">*</span></label>
								<input class="form-control" type="text" name="Remarks" placeholder="Remarks" maxlength="60" required>
								<input class="form-control" type="hidden" name="Functional_Reporting" value="<?php echo $fetch1['Functional_Reporting']; ?>" >
								<input class="form-control" type="hidden" name="Reporting_Head_Code" value="<?php echo $fetch1['Reporting_Head_Code']; ?>" >
								<input class="form-control" type="hidden" name="Team_Head_Code" value="<?php echo $fetch1['Team_Head_Code']; ?>" >
							</div>
						</div>
						<div class="row">
							<div class="col-md-12 col-sm-12 mt5 text-center">
								<input class="form-control" type="hidden" name="Status" value="Pending">
								<?php 
								//if ($COFFdata['OfficeDate'] == '')
								if ($result->num_rows > 0)
									{	echo '<button type="submit" name="submit" class="btn btn-success">Save</button>';	}
								else 
									{	echo '<a class="btn btn-danger disabled">No Balance</a>';	}
									//echo "No Data";
								?>
							</div>
						</div>
					</form>
				</div>
            </div>
        </div>
	
	<?php	include ('include/copyright.php');	?>
	</div>
	
	<?php	include ('footer.php');	?>



<script>
	$(document).ready(function(){
	$("select.powid").change(function(){
		var selectedp = $(this).children("option:selected").val();
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.onreadystatechange = function()
		{
			if (this.readyState == 4 && this.status == 200)
			{
				var myObj = JSON.parse(this.responseText);
				document.getElementById("Status").value = myObj[0];
				document.getElementById("LQTY").value = myObj[1];
			}
		};
		xmlhttp.open("GET", "leave-request-coff-search.php?powid=" + selectedp, true);
		xmlhttp.send();
	});
});
</script>

<script>
    let selectedDateString = '';
    let chosenDate = null;

    function generateCalendar() {
        // Extract the date from the selected option's text
        const selectedOptionText = document.getElementById('powid').options[document.getElementById('powid').selectedIndex].text;
        const dateMatch = selectedOptionText.match(/\((.*?)\)/);
        if (!dateMatch) {
            console.error('No date found in the selected option');
            return;
        }
        const selectedDate = new Date(dateMatch[1]);
        selectedDateString = selectedDate.toISOString().split('T')[0];
        if (!chosenDate) {
            chosenDate = selectedDate;
        }
        updateSelectedDate(chosenDate.toISOString().split('T')[0]);

        let calendarHtml = '<table><tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr>';

        let firstDayOfWeek = new Date(selectedDate);
        firstDayOfWeek.setDate(selectedDate.getDate() - selectedDate.getDay());

        let lastDayToShow = new Date(selectedDate);
        lastDayToShow.setDate(selectedDate.getDate() + 30);

        for (let week = 0; week < 5; week++) {
            calendarHtml += '<tr>';
            for (let day = 0; day < 7; day++) {
                let currentDate = new Date(firstDayOfWeek);
                currentDate.setDate(firstDayOfWeek.getDate() + week * 7 + day);

                let cellClass = isSameDay(currentDate, chosenDate) ? 'selected' : '';
                let visibilityClass = currentDate >= selectedDate && currentDate <= lastDayToShow ? '' : 'hidden';

                calendarHtml += `<td class="${cellClass} ${visibilityClass}" onclick="selectDate('${currentDate.toISOString().split('T')[0]}')">${formatCalendarDate(currentDate)}</td>`;
            }
            calendarHtml += '</tr>';
        }

        calendarHtml += '</table>';
        document.getElementById('calendar').innerHTML = calendarHtml;
    }

    function formatCalendarDate(date) {
        const options = { day: 'numeric', month: 'short' };
        return date.toLocaleDateString('en-US', options);
    }

    function updateSelectedDate(dateString) {
        document.getElementById('selectedDate').value = `${dateString}`;
    }

    function selectDate(dateString) {
        chosenDate = new Date(dateString);
        updateSelectedDate(dateString);
        generateCalendar(); // Regenerate calendar to update highlighted date
    }

    function isSameDay(date1, date2) {
        return date1.getDate() === date2.getDate() && 
               date1.getMonth() === date2.getMonth() && 
               date1.getFullYear() === date2.getFullYear();
    }
</script>


<script>
	function getMyLocation(){
		if(navigator.geolocation){
			navigator.geolocation.getCurrentPosition(showPosition);
		}
		navigator.geolocation.getCurrentPosition(function(position)
		{
			var coordinates = position.coords;
			document.getElementById('lat').value = coordinates.latitude;
			document.getElementById('longt').value = coordinates.longitude;
		});
	}
</script>

<script type="text/javascript">
    var ab;
    function showPosition(position){
      ab = position.coords.latitude+","+position.coords.longitude;          
    }
    function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
		}
	}
</script>