<?php
date_default_timezone_set('Asia/Kolkata');
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[empid]'");
$dataFR=mysqli_fetch_array($queryFR);

$queryFR=mysqli_query($conn,"select * from emp_leave where Functional_Reporting='$fetch1[empid]'");
$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 emp_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">
				<?php	include ('include/wallet-balance.php');	?>
				<?php
				if(isset($_POST['submit']))
				{
					$powid=($_POST['powid']);
					$LeaveCategory=($_POST['LeaveCategory']);
					$LeaveType  = ($_POST['LQTY']."-".$_POST['LeaveCategory']);
					$queryPOW=mysqli_query($conn,"select * from emp_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']);

					if ($LeaveCategory == 'COFF') {
						$TStatus='Taken';
						$query = mysqli_query($conn,"update emp_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);
					}
				}
				?>
    <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
        // Adjusted SQL query to ensure Admin_Approval_Date is in the correct format and matches 'Y-m-d'
        $sql = "SELECT * FROM emp_pow WHERE empid='" . @$user_id1 . "' AND Status='POW' AND Admin_Approval_Date >= DATE_ADD(CURDATE(), INTERVAL -65 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(); setLQTY();" onClick="getMyLocation();" required class="form-control powid">
                <option value="">-Select-</option>
                <?php
                if ($result->num_rows > 0) {
                    while ($row = $result->fetch_assoc()) {
                        // Format Admin_Approval_Date to 'Y-m-d'
                        $formattedCreatedAt = date('Y-m-d', strtotime($row["Admin_Approval_Date"]));
                        echo "<option value='" . $row["powid"] . "' data-Admin_Approval_Date='" . $formattedCreatedAt . "' data-lqty='" . $row["LQTY"] . "'>(" . $row["OfficeDate"] . ")" . $row["LQTY"] . "</option>";
                    }
                } else {
                    echo "<option value=''>No COFF Available</option>";
                }
                ?>
            </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="hidden" name="Admin_Approval_Date" id="Admin_Approval_Date" value="<?php echo date('Y-m-d', strtotime($dataPOW['Admin_Approval_Date'])); ?>" /> <!-- Corrected Admin_Approval_Date format -->
        </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 ($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>';
            }
            ?>
        </div>
    </div>
</form>

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

    // Function to set LQTY value based on selected powid
    function setLQTY() {
        const selectedOption = document.getElementById('powid');
        const selectedOptionValue = selectedOption.options[selectedOption.selectedIndex].value;
        const selectedOptionLQTY = selectedOption.options[selectedOption.selectedIndex].getAttribute('data-lqty');
        
        if (selectedOptionValue) {
            document.getElementById('LQTY').value = selectedOptionLQTY; // Set LQTY hidden field value
        }
    }

    function generateCalendar() {
        const selectedOption = document.getElementById('powid');
        const selectedOptionText = selectedOption.options[selectedOption.selectedIndex].text;
        const createdAt = selectedOption.options[selectedOption.selectedIndex].getAttribute('data-Admin_Approval_Date');

        if (!createdAt) {
            console.error('No Admin_Approval_Date date found');
            return;
        }

        const selectedDate = new Date(createdAt);
        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() + 44);

        for (let week = 0; week < 7; 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>



				</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];
				document.getElementById("Admin_Approval_Date").value = myObj[2];
			}
		};
		xmlhttp.open("GET", "leave-request-coff-search-emp-pow.php?powid=" + selectedp, true);
		xmlhttp.send();
	});
});
</script>
 
<script>
	function getMyLocation(){
		if(navigator.geolocation){
			navigator.geolocation.getCurrentPosition(showPosition);
		}
		navigator.geolocation.getCurrentPosition(showPosition);
		function showPosition(position){
			document.getElementById("lat").value = position.coords.latitude;
			document.getElementById("longt").value = position.coords.longitude;
		}
	}
</script>
</html>
