<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>
<style> 
	video{
		width: 300px;
		height: auto;
	}
	.custom-button{
		width: 140px;
		height: 45px;
		text-align: center;
	}
	.mb-10{
		margin-bottom: 10px;
	}
	@media only screen and (min-width: 768px) {
	  .mb-responsive {
	  	text-align: right;
	  }
	}
</style>

<div class="page-header d-print-none">
    <div class="container-xl">
        <div class="row g-2 align-items-center">
            <div class="col d-flex justify-content-between">
                <h2 class="page-title">Attendance - Entry</h2>
            </div>
        </div>
    </div>
</div>


	<div class="wrapper">
		<div class="content-wrapper"> 
			<section class="content" style="margin-top: 5px;">
				<div class="container-fluid">
					<?php if($_SESSION['userrole']!="X"){ ?>
					<form id="frmDutyInOut">
						<div class="row">
							<div class="col-md-6 offset-md-2 offset-1">
								<form role="form" id="frmDutyInOut">
									<center>
										<div class="row mb-10 CameraPanel">
											<div class="col-md-12 imgContainer">
												<video id="video" autoplay playsinline poster="" style="width: 250px;"></video>
												<img src="" id="img" style="width: 300px; display: none;">
											</div>
										</div>
										<div class="row mb-10 CameraPanel">
											<div class="col-md-12">
												<button type="button" class="btn btn-primary custom-button " id="button" style="display:none;">Open Camera</button>
			
												<button type="button" class="btn btn-success custom-button" id="btnDutyIn" style="display:none;" onclick="validateAndSave(this);">Duty In</button>
				
												<button type="button" class="btn btn-danger custom-button" id="btnDutyOut" style="display:none;" onclick="validateAndSave(this);">Duty Out</button>

												<button type="button" class="btn btn-success custom-button" id="btnSecondDutyIn" style="display:none;width:150px;" onclick="validateAndSave2(this);">Second Duty In</button>
				
												<button type="button" class="btn btn-danger custom-button" id="btnSecondDutyOut" style="display:none;width:150px;" onclick="validateAndSave2(this);">Second Duty Out</button>
			
											</div>
										</div>
										<div class="row mb-3 mt-3">
											<label class="col-form-label col-5 text-end">Duty In:</label>
											<div class="col-4">
												<input type="text" class="form-control" id="txtDutyInTime" readonly style="font-weight: bold;">
											</div>
										</div>
										<div class="row mb-3">
											<label class="col-form-label col-5 text-end">Duty Out:</label>
											<div class="col-4">
												<input type="text" class="form-control" id="txtDutyOutTime" readonly style="font-weight: bold;">
											</div>
										</div>
										<div class="row mb-3">
											<label class="col-form-label col-5 text-end">Second Duty In:</label>
											<div class="col-4">
												<input type="text" class="form-control" id="txtSecondDutyInTime" readonly style="font-weight: bold;">
											</div>
										</div>
										<div class="row mb-3">
											<label class="col-form-label col-5 text-end">Second Duty Out:</label>
											<div class="col-4">
												<input type="text" class="form-control" id="txtSecondDutyOutTime" readonly style="font-weight: bold;">
											</div>
										</div>

									</center>
								</form>
							</div>
						</div>
					</form>
					<?php } ?>
				</div>
			</section>
		</div>
	</div>

<?php include '../footer.php'; ?>
<script>

	$(function(){
		document.getElementById('video').setAttribute('poster', APP_URL + "/attendance/dummy_face.png");
		$("body").addClass("sidebar-collapse");
		getAttendanceInOut();
	});

    $("#button").click(function(){
			openCamera();
		});

        function openCamera() {
		const video = document.getElementById('video');

		navigator.mediaDevices.getUserMedia({ video: true })
			.then(stream => {
				video.srcObject = stream;
				video.play();
			})
			.catch(err => {
				console.error("Error accessing the camera: ", err);
				alert("Unable to access the camera. Please ensure the camera is connected and the browser has permission.");
			});
	}
    
	// $("#txtActualSalary").on("input", function(){
	// 	var actual_salary = (($("#txtActualSalary").val()!="")?parseInt($("#txtActualSalary").val().replace(/,/g, '')):0);
	// 	var duty_min_per_month = parseInt($("#txtDutyMinPerMonth").val().replace(/,/g, ''));
	// 	var earn_min = parseInt($("#txtEarnMin").val().replace(/,/g, ''));
	// 	var pay = Math.round(((actual_salary/duty_min_per_month) * earn_min)/1000)*1000;
	// 	$("#txtPay").val(pay.toLocaleString());
	// });

	// function getSummary(){
	// 	$.ajax({
	// 		url: APP_URL + "api/payroll/get_summary.php"
	// 	}).done(function(data){	
	// 		$("#txtMonth").text(data.current_month);
	// 		$("#txtWorkingDays").val(data.working_days);
	// 		$("#txtHolidays").val(data.holidays);
	// 		$("#txtDutyMinPerMonth").val(data.duty_min_per_month);
	// 		$("#txtAttMin").val(data.att_min);
	// 		$("#txtMonthlyBenefitMin").val(data.monthly_benefit_min);
	// 		$("#txtOTMin").val(data.ot_min);
	// 		$("#txtEarnMin").val(data.earn_min);
	// 		$("#txtDeductMin").val(data.deduct_min);
	// 		$("#txtExtraMin").val(data.extra_min);
	// 	});
	// }


	function getAttendanceInOut() {
    $.ajax({
        url: APP_URL + "api/attendance/get_in_out.php",
        method: "POST",
        dataType: "json"
    }).done(function(data) {
        var DUTY_IN = data.duty_in_time;
        var DUTY_OUT = data.duty_out_time;
        var SECOND_DUTY_IN = data.second_duty_in_time;
        var SECOND_DUTY_OUT = data.second_duty_out_time;

        $("#txtDutyInTime").val(DUTY_IN);
        $("#txtDutyOutTime").val(DUTY_OUT);
        $("#txtSecondDutyInTime").val(SECOND_DUTY_IN);
        $("#txtSecondDutyOutTime").val(SECOND_DUTY_OUT);

        if(DUTY_IN == ""){
            $("#btnDutyOut").css("display", "none");
            $("#button").css("display", "");
            $("#btnDutyIn").css("display", "");
        }
        if(DUTY_IN != "" && DUTY_OUT == ""){
            $("#btnDutyIn").css("display", "none");
            $("#button").css("display", "");
            $("#btnDutyOut").css("display", "");
            $("#DutyInPanel").css("display", "");
        }
        if(DUTY_IN != "" && DUTY_OUT != "" && SECOND_DUTY_IN == "" ){
            $("#btnDutyIn").css("display", "none");
            $("#btnDutyOut").css("display", "none");
			$("#button").css("display", "");
            $("#DutyInPanel").css("display", "");
            $("#DutyOutPanel").css("display", "");

			$("#btnSecondDutyOut").css("display", "none");
			$("#button").css("display", "");
			$("#btnSecondDutyIn").css("display", "");
        }

		if(DUTY_IN != "" && DUTY_OUT != "" && SECOND_DUTY_IN != ""){
			$("#DutyInPanel").css("display", "");
            $("#DutyOutPanel").css("display", "");
			$("#SecondDutyInPanel").css("display", "");

			$("#btnSecondDutyIn").css("display", "none");
			$("#button").css("display", "");
			$("#btnSecondDutyOut").css("display", "");
        }

		if(DUTY_IN != "" && DUTY_OUT != "" && SECOND_DUTY_IN != "" && SECOND_DUTY_OUT != ""){
			$("#DutyInPanel").css("display", "");
            $("#DutyOutPanel").css("display", "");
			$("#SecondDutyInPanel").css("display", "");
			$("#SecondDutyOutPanel").css("display", "");

			$(".custom-button").css("display", "none");
        }


    }).fail(function() {
        console.error("Failed to retrieve attendance data.");
    });
}


	function validateAndSave(obj){ 
		var photo = $("#img").attr("src");	

		if(photo==""){
			showAlert("Please take a selfie.","warning");
		}else{
			$("#" + $(obj).attr("id")).attr("disabled", true);
			$.ajax({
				url: APP_URL + "api/attendance/" + (($(obj).text()=="Duty In")?"create_duty_in.php":"create_duty_out.php"),
				type: "POST",
				data: JSON.stringify({ photo: photo })
			}).done(function(data){	
				$("#" + $(obj).attr("id")).attr("disabled", false);
				if(data.message=="created"){		
					showAlert("Duty In Success.","success");
					document.location = APP_URL + '/attendance/attendance.php';
				}else if(data.message=="updated"){
					showAlert("Duty Out Success.","success");
					document.location = APP_URL + '/attendance/attendance.php';
				}else if(data.message=="session expire"){
					showAlert("Session Expire! Please refresh the browser and login again.","warning");
				}else{
					showAlert("Error on server side.");
				}
			});
		}   
	}

	function validateAndSave2(obj){ 
		var photo = $("#img").attr("src");	

		if(photo==""){
			showAlert("Please take a selfie.");
		}else{
			$("#" + $(obj).attr("id")).attr("disabled", true);
			$.ajax({
				url: APP_URL + "api/attendance/" + (($(obj).text()=="Second Duty In")?"update_second_duty_in.php":"update_second_duty_out.php"),
				type: "POST",
				data: JSON.stringify({ photo: photo })
			}).done(function(data){	
				$("#" + $(obj).attr("id")).attr("disabled", false);
				if(data.message=="updated"){		
					showAlert("Second Duty In Success.","success");
					document.location = APP_URL + '/attendance/attendance.php';
				}else if(data.message=="updated"){
					showAlert("Second Duty Out Success.","success");
					document.location = APP_URL + '/attendance/attendance.php';
				}else if(data.message=="session expire"){
					showAlert("Session Expire! Please refresh the browser and login again.","warning");
				}else{
					showAlert("Error on server side.");
				}
			});
		}   
	}

	function isNumber(evt) { 
		evt = (evt) ? evt : window.event;
		var charCode = (evt.which) ? evt.which : evt.keyCode;
		if ( (charCode > 31 && charCode < 48) || charCode > 57) {
			return false;
		}
		return true;
	}

	function btozero(obj){
		if($(obj).val() == "") $(obj).val(0);
	}	
	
	function AddComma(obj) {
        var amount = $(obj).val().replace(/,/g, '');
		$(obj).val(parseInt(amount).toLocaleString());
    }

	function showAlert(message, type) {
		Swal.fire({
			title: type == 'success' ? 'Success' : 'Oops!',
			text: message,
			icon: type
		});
	}
</script>