<?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('-2 Days'));

?>

<!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>OD Leave Request</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<?php	include ('header.php');	?>
	
	<script>
        var apiKey = 'a967cab3-ce6f-11eb-8089-0200cd936042';
        function sendOTP() {
            var mobile = document.getElementById('mobile').value;
            var otp = Math.floor(100000 + Math.random() * 900000);
            var url = 'https://2factor.in/API/V1/' + apiKey + '/SMS/' + mobile + '/' + otp;
            $.ajax({
                url: url,
                type: 'GET',
                success: function (response) {
                    if (response.Status === 'Success') {
                        alert('OTP sent successfully.');
                        document.getElementById('otp').value = otp;
                    } else {
                        alert('Failed to send OTP.');
                    }
                },
                error: function () {
                    alert('Failed to send OTP.');
                }
            });
        }

        function submitForm() {
            var enteredOtp = document.getElementById('enteredOtp').value;
            var storedOtp = document.getElementById('otp').value;
            if (enteredOtp === storedOtp) {
                alert('Required valid OTP');
                document.getElementById('myForm').submit();
            } else {
                alert('Invalid OTP.');
            }
        }
    </script>
	
	<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['ODsubmit']))
		if ($_SERVER['REQUEST_METHOD'] === 'POST')
		{
		$apiEndpoint = 'https://maps.googleapis.com/maps/api/geocode/json';
		
		$apiKey = 'AIzaSyB-FZbEtDvYXFk3M7ALNt11S4kfMO1XVPo';
		
		$latitude = $_POST['lat'];
		$longitude = $_POST['longt'];
		
		$requestUrl = $apiEndpoint . '?latlng=' . $latitude . ',' . $longitude;
		
		if (!empty($apiKey)) {
			$requestUrl .= '&key=' . $apiKey;
		}
		
		$response = file_get_contents($requestUrl);
		
		$data = json_decode($response);
		
		$LocationAddress = $data->results[0]->formatted_address;
		echo $LocationAddress;

			$DateFrom = $_POST['DateFrom'];
			$query=mysqli_query($conn,"select * from emp_leave where empid='".@$user_id1."' AND DateFrom = '$DateFrom' ORDER BY id ASC ");
			$dataEL=mysqli_fetch_array($query);
				$LeaveCategory=($_POST['LeaveCategory']);
				$LeaveType  = ($_POST['LQTY']."-".$_POST['LeaveCategory']);
				//echo "<pre>"; print_r($_POST); exit;
				$query=mysqli_query($conn,"insert into emp_leave (empid, Employee_Full_Name, Department, Team_Name, LeaveCategory, ProspectID, ProspectFor, lat, longt, LocationAddress, LeaveType, LQTY, DateFrom, Remarks, ClientName, mobile, otp, enteredOtp, Functional_Reporting, Reporting_Head_Code, Team_Head_Code, Status)
				values ('".$_POST['empid']."', '".$_POST['Employee_Full_Name']."', '".$_POST['Department']."', '".$_POST['Team_Name']."', '".$_POST['LeaveCategory']."', '".$_POST['ProspectID']."', '".$_POST['ProspectFor']."', '".$_POST['lat']."', '".$_POST['longt']."', '$LocationAddress', '$LeaveType',  '".$_POST['LQTY']."', '".$_POST['DateFrom']."', '".$_POST['Remarks']."', '".$_POST['ClientName']."', '".$_POST['mobile']."', '".$_POST['otp']."', '".$_POST['enteredOtp']."', '".$_POST['Functional_Reporting']."', '".$_POST['Reporting_Head_Code']."', '".$_POST['Team_Head_Code']."', '".$_POST['Status']."' )");
				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 mysqli_error($conn);
					echo "<div class='col-md-12 text-center btn btn-danger'><strong>Error!</strong>Sorry something went wrong!</div>";	}
		}
		
		?>

				<div class="row">
					<div class="wallet-footer"><h6 class="text-center">Apply OD</h6></div>
					
					<div class="d-none d-lg-block">
						<div class="col-md-12 col-sm-12 alert alert-danger"><h5><b>Apply OD</b> have been enabled Only on Mobile Device</h5></div>
					</div>
					<form class="form-horizontal d-lg-none" method="POST" action="" id="myForm">
						<div class="row">
							<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='OD'>
							
							<?php
							$datelast = date('Y-m-d', strtotime('-2 Days'));
							$doj = $fetch1['Date_of_Joining'];
							if ($datelast >= $doj)
							{
								$datemin = date('Y-m-d', strtotime('-2 Days'));
							}
							else {
								$datemin = $fetch1['Date_of_Joining'];
							}
							?>
							
							<?php
							if ($fetch1['Role'] == 'Sales')
							{
							echo '<div class="row text-center">
										<div class="col">
											<a href="leave-request-od.php"><div class="icon-wrapper"><i class="fas fa-cog"></i></div>
												<strong class="pstrong">Developer visit / Project Training / Event</strong>
											</a>
										</div>
										<div class="col">
											<a href="leave-request-od-cm.php"><div class="icon-wrapper bg-success text-white"><i class="fas fa-handshake"></i></div>
												<strong class="pstrong">Client Meeting</strong>
											</a>
										</div>
								</div>';
							}
							?>
							
							
							<div class="col">
								<label>Day Type <span class="red">*</span></label>
								<select name="LQTY" class="form-control" required>
									<option value="0.5">Half Day</option>
									<option value="1">Full Day</option>
								</select>
							</div>

							<div class="col"><label>Date For <span class="red">*</span></label>
								<input class="form-control" type="date" name="DateFrom" min="<?php echo $datemin; ?>"  max="<?php echo $date; ?>" required / >
							</div>
						</div>
						
						  <div class="row">
							<div class="col">
								<label><input type='radio' name='entry' onClick='getMyLocation();' id='submit' value='Mark OD' required> Mark OD *</h6></label>
								<br><b class='text-danger'>Allow / Enable Device Location Services</b>
								<br>
								<input class="form-control" type="hidden" name="lat" id="lat" onkeydown="return false;" >
								<input class="form-control" type="text" name="longt" id="longt" onkeydown="return false;" style="pointer-events: none;" placeholder="No Manual Entry" required>
							</div>
						  </div>

<?php
	if ($fetch1['Role'] == 'Sales')
		{
		echo '<div class="row">
				<div class="col-md-12 col-sm-12">
					<input type="hidden" name="ProspectFor" class="form-control" value="Client Meeting" required>
					<input type="text" name="ClientName" class="form-control" placeholder="Enter Client Name" required>
				</div>
				<div class="col">
					<input class="form-control" id="mobile" name="mobile" type="text" maxlength="10" required oninput="this.value = this.value.replace(/[^0-9.]/g, "").replace(/(\..*?)\..*/g, "$1");" placeholder="10 Digits Mobile No">
				</div>
				<div class="col">
					<input type="hidden" id="otp" name="otp" required>
					<input type="text" id="enteredOtp" name="enteredOtp" placeholder="Enter OTP" style="display:none;" maxlength="6" class="numericOnly form-control" value="" placeholder="Enter OTP" required > 
				</div>
					<div style="color:red; font-size:15px; text-align: left !important;" class="mobileError"></div>
					<div style="color:red; font-size:15px; text-align: left !important;" class="enteredOtpErr"></div>
					
					<button type="submit" id="HideBtnOTP" onclick="sendOTP()" style="display:none;" class="btn btn-info">Send OTP</button>
					<span id="message"></span>
				
			</div>';
		}
?>
							
						<div class="row">	
							<div class="col-md-12 col-sm-12">
								<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 class="col-md-12 col-sm-12 mt5 text-center">
								<input class="form-control" type="hidden" name="Status" value="Pending">
								<button type="submit" id="HidesubmitForm" onclick="submitForm()" class="btn btn-success">Save OD</button>
								
								<p class="footer-title text-danger">Must Approve within 48 Hrs.</p>
							</div>
						</div>
					</form>
				</div>
            </div>
        </div>


 


	<?php	include ('include/copyright.php');	?>
	</div>
	
	<?php	include ('footer.php');	?>


<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>

<script>

$("#mobile").keyup(function(){
	$(".otpError").html("");
	var mobile= $("#mobile").val();
	var mobileLen= mobile.length;
	var SITEURL = window.location.origin;  
	
	if(mobileLen>10){
	  $(".mobileError").html("Only 10 Digits Mobile No. is allow.");
	  $("#enteredOtp").hide();
	  $("#HidesubmitForm").hide();
	}else if(mobileLen<10){
	  $(".mobileError").html("Only 10 Digits Mobile No. is allow.");
	  $("#enteredOtp").hide();
	  $("#HidesubmitForm").hide();
    }else{
	  $(".mobileError").html("");
	  $("#enteredOtp").show();
	  $("#HideBtnOTP").show();
	}	
});

$("#enteredOtp").keyup(function(){
	$(".otpError").html("");
	var enteredOtp= $("#enteredOtp").val();
	var enteredOtplen= enteredOtp.length;
	var SITEURL = window.location.origin;  
	
	if(enteredOtplen>6){
	  $(".enteredOtpErr").html("Only 6 Digits OTP is allow.");
	  $("#HideBtnOTP").hide();
	  $("#HidesubmitForm").hide();
    }else if(enteredOtplen<6){
	  $(".enteredOtpErr").html("Only 6 Digits OTP is allow.");
	  $("#HideBtnOTP").hide();
	  $("#HidesubmitForm").hide();
    }else{
	  $(".enteredOtpErr").html("");
	  $("#HideBtnOTP").hide();
	  $("#HidesubmitForm").show();
	}
});

/* $('#otp, #enteredOtp').on('keyup', function () {
  if ($('#otp').val() != $('#enteredOtp').val()) {
    $('#message').html('OTP Not Matching').css('color', 'red');
  } else 
    $('#message').html('Matching').css('color', 'Green');
}); */
</script>