<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>

<style>
	.bootstrap-timepicker-widget table td input {
    width: 100%; /* Adjust the width as needed */
}
</style>

<?php
	$uid = "";
	if(isset($_POST['uid'])){
		if(!empty($_POST['uid'])){
			$uid = $_POST['uid'];
		}
	}
?>

<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 - Update</h2>
            </div>
        </div>
    </div>
</div>

<div class="page-body">
	<section class="content">
		<div class="container-fluid">
			<div class="card card-outline card-info">
				<form role="form" id="frmChange">
					<div class="card-body">
						<div class="row">
							<div class="col-md-3"></div>
							<div class="col-md-6">
                                <div class="form-group row">
                                    <label for="txtDatePicker" class="col-md-4 col-form-label text-right">Date: </label>
                                    <div class="col-md-8">
                                        <div class="input-group">
                                            <div class="input-group-prepend">
                                                <span class="input-group-text" style="width: 40px;">
                                                    <i class="far fa-calendar-alt"></i>
                                                </span>
                                            </div>
                                            <input type="text" class="form-control" id="txtDatePicker" value="2020-02-04" aria-label="Date Picker" placeholder="Select a date">
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group row mt-3">
                                    <label class="col-md-4 col-form-label" style="text-align: right;">Name:</label>
                                    <div class="col-md-6">
                                        <select class="form-select" id="cboStaff"></select>
                                    </div>
                                </div>
								<input type="hidden" id="attId">
								<div class="form-group row mt-3">
                                    <label class="col-md-4 col-form-label" style="text-align: right;">Duty In:</label>
                                    <div class="col-md-6">
                                        <input type="time" class="form-control" id="txtDutyIn">
                                    </div>
                                </div>
                                
                                <div class="form-group row mt-3">
                                    <label class="col-md-4 col-form-label" style="text-align: right;">Duty Out:</label>
                                    <div class="col-md-6">
                                        <input type="time" class="form-control" id="txtDutyOut">
                                    </div>
                                </div>

                                <div class="form-group row mt-3">
                                    <label class="col-md-4 col-form-label" style="text-align: right;">Second Duty In:</label>
                                    <div class="col-md-6">
                                        <input type="time" class="form-control" id="txtSecondDutyIn">
                                    </div>
                                </div>
                                
                                <div class="form-group row mt-3">
                                    <label class="col-md-4 col-form-label" style="text-align: right;">Second Duty Out:</label>
                                    <div class="col-md-6">
                                        <input type="time" class="form-control" id="txtSecondDutyOut">
                                    </div>
                                </div>

								<div class="form-group row mt-3">
									<label class="col-md-4 col-form-label"></label>
									<div class="col-md-6">
										<button id="btnSubmit" class="btn btn-outline-success col-md-5" type="button" value="Create" style="float: right;" onclick="validateAndSave()">Update</button>
									</div>
									<div class="col-md-2"></div>
								</div>
							</div>
							<div class="col-md-3"></div>
						</div>
					</div>
				</form>
			</div>
		</div>
	</section>
</div>
<?php include '../footer.php'; ?>
<script>	
    var staff_id = '<?php echo $_SESSION["staff_id"]; ?>';

    var today = new Date().toISOString().split('T')[0];
    var d = new Date();
	var n = d.getTime();
	var customDate = d.toISOString().split('T')[0]; // Format as yyyy-mm-dd

	$(function(){
        $("body").addClass("sidebar-collapse");
        $('#txtDatePicker').datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: 'yy-mm-dd',
			showButtonPanel: true,
            showAnim: 'clip',
            autoclose: true
        }).val(customDate);
        getAllStaff();
	});



    function getAllStaff(){
		$("#cboStaff").find("option").remove();
		$.ajax({
			url: APP_URL + "api/staff/get_all_rows.php"
		}).done(function(data) {
			$("#cboStaff").append("<option value = ''>Select a name</option>");
			$.each(data.records, function(i, v) {
					$("#cboStaff").append("<option value='" + v.id + "'>" + v.name + "</option>");
			});
		});
	}

    function fetchAttendanceData() {
        var date = $("#txtDatePicker").val();
        var staff_id = $("#cboStaff").val();
        
        $.ajax({
            url: APP_URL + "api/attendance/get_one_attendance.php",
            type: "POST",
            data: JSON.stringify({ date: date, staff_id: staff_id }),
            success: function(data) {
                $("#attId").val(data.id);

                // Convert 12-hour time format to 24-hour format
                function convertTo24HourFormat(time12) {
                    if (!time12) return "";
                    
                    const [time, period] = time12.split(' ');
                    let [hours, minutes] = time.split(':');
                    hours = parseInt(hours, 10);

                    if (period === 'PM' && hours !== 12) {
                        hours += 12;
                    } else if (period === 'AM' && hours === 12) {
                        hours = 0;
                    }

                    return `${hours.toString().padStart(2, '0')}:${minutes}`;
                }

                // Set values in time inputs
                $("#txtDutyIn").val(convertTo24HourFormat(data.duty_in_time));
                $("#txtDutyOut").val(convertTo24HourFormat(data.duty_out_time));
                $("#txtSecondDutyIn").val(convertTo24HourFormat(data.second_duty_in_time));
                $("#txtSecondDutyOut").val(convertTo24HourFormat(data.second_duty_out_time));
            }
        });
    }

    $("#txtDatePicker").change(fetchAttendanceData);
$("#cboStaff").change(fetchAttendanceData);

function convertTo24Hour(time12) {
    if (!time12) return "";
    
    const [time, period] = time12.split(' ');
    let [hours, minutes] = time.split(':');
    hours = parseInt(hours, 10);

    if (period === 'PM' && hours !== 12) {
        hours += 12;
    } else if (period === 'AM' && hours === 12) {
        hours = 0;
    }

    return `${hours.toString().padStart(2, '0')}:${minutes}`;
}

function validateAndSave() {
    var id = $("#attId").val();
    var date = $("#txtDatePicker").val();
    var staff_id = $("#cboStaff").val();
    var duty_in_time = convertTo24Hour($("#txtDutyIn").val());
    var duty_out_time = convertTo24Hour($("#txtDutyOut").val());
    var second_duty_in_time = convertTo24Hour($("#txtSecondDutyIn").val());
    var second_duty_out_time = convertTo24Hour($("#txtSecondDutyOut").val());

    if (staff_id.trim() === "") {
        bootbox.alert("Select a name.");
        return;
    }
    if (date.trim() === "") {
        bootbox.alert("Select a date.");
        return;
    }

    $.ajax({
        type: "POST",
        url: APP_URL + "api/attendance/create.php",
        data: JSON.stringify({ id: id, date: date, staff_id: staff_id, duty_in_time: duty_in_time, duty_out_time: duty_out_time, second_duty_in_time: second_duty_in_time, second_duty_out_time: second_duty_out_time }),
        contentType: "application/json", 
        success: function(data) {    
            if (data.message === "created") {
                $("#cboStaff").val("");
                $("#txtDutyIn").val("");
                $("#txtDutyOut").val("");
                $("#txtSecondDutyIn").val("");
                $("#txtSecondDutyOut").val("");
                bootbox.alert("Successfully Created.");
            } else if (data.message === "updated") {
                $("#cboStaff").val("");
                $("#txtDutyIn").val("");
                $("#txtDutyOut").val("");
                $("#txtSecondDutyIn").val("");
                $("#txtSecondDutyOut").val("");
                bootbox.alert("Successfully Updated.");
            } else if (data.message === "duplicate") {
                bootbox.alert("Duplicate entry.");
            }
        },
        error: function(xhr, status, error) {
            bootbox.alert("An error occurred while saving the data. Please try again.");
            console.error("Error:", status, error);
        }
    });
}


</script>