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

		<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">Duty Schedule - Entry</h2>
					</div>
				</div>
			</div>
		</div>
			

		<div class="page-body">
			<div class="container-xl">
				<div class="row row-cards">
					<div class="col-md-4">
						<div class="card card-outline card-primary">
							<form role="form">
								<div class="card-body">
                                    <div class="row">
                                        <div class="col-md-12 mb-3">
                                            <div class="form-group row">
                                            <label class="col-md-4 col-form-label" style="text-align: right;">Year: </label>
                                            <div class="col-md-8">
                                                <select type="text" class="form-select" id="cboYear">
                                                </select>
                                            </div>
                                            </div>
                                        </div>

                                        <div class="col-md-12 mb-3">
                                            <div class="form-group row">
                                            <label class="col-md-4 col-form-label" style="text-align: right;">Month: </label>
                                            <div class="col-md-8">
                                                <select type="text" class="form-select" id="cboMonth">
                                                <option value="">--Select Month--</option>
                                                <option value="01">January</option>
                                                <option value="02">February</option>
                                                <option value="03">March</option>
                                                <option value="04">April</option>
                                                <option value="05">May</option>
                                                <option value="06">June</option>
                                                <option value="07">July</option>
                                                <option value="08">August</option>
                                                <option value="09">September</option>
                                                <option value="10">October</option>
                                                <option value="11">November</option>
                                                <option value="12">December</option>
                                                </select>
                                            </div>
                                            </div>
                                        </div>

                                        <div class="col-md-12 mb-3">
                                            <div class="form-group row">
                                            <label class="col-md-4 col-form-label" style="text-align: right;">Staff Name: </label>
                                                <div class="col-md-8">
                                                    <select class="form-select" id="cboStaff" name="cboStaff" >
                                                        <option value="">--Select Staff Name--</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
								</div>
							</form>
						</div>
					</div>
                    <div class="col-md-8">
                        <div class="card card-outline card-primary">
                            <div class="card-body p-0 table-responsive" style="min-height: 500px;">
                                <div style="max-height: 500px; overflow-y: auto;">
                                    <table class="table table-striped table-bordered" id="myTable" style="font-size: 12px;">
                                        <thead style="position: sticky; top: 0; z-index: 10;">                  
                                            <tr>
                                                <th style="width: 3%; padding: 5px;">#</th>
                                                <th style="padding: 5px;">Date</th>
                                                <th style="padding: 5px;">Duty In</th>
                                                <th style="padding: 5px;">Duty Out</th>
                                                <th style="padding: 5px;">Off Day</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        <div class="d-flex justify-content-end">
                            <button id="saveAll" class="btn btn-outline-success mt-3 text-end">Save All</button>
                        </div>
                    </div>

				</div>
			</div>
		</div>

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


	$(function() {
        const currentDate = new Date();
        const currentYear = currentDate.getFullYear();
        const currentMonth = String(currentDate.getMonth() + 1).padStart(2, '0');

        // Populate year dropdown
        for (let year = currentYear - 1; year <= currentYear + 1; year++) {
        const selected = year == currentYear ? 'selected' : '';
        $('#cboYear').append(`<option value="${year}" ${selected}>${year}</option>`);
        }

        // Preselect current month
        $('#cboMonth').val(currentMonth);

        getStaff();
	});

    function getStaff(){
        $.ajax({
            url: APP_URL + "api/staff/get_all_rows.php",
            type: "POST",
            data: JSON.stringify({account_type: ""})

        }).done(function(data) {	
            $("#cboStaff").find("option").remove();
            $("#cboStaff").append("<option value = '---'></option>");
            $.each(data.records, function(i, v) {	
                $("#cboStaff").append("<option value = '" + v.id + "'>" + v.name + "</option>");						
            });
        });
    }

    $("#cboYear, #cboMonth, #cboStaff").change(function() {
        var cboStaffValue = $("#cboStaff").val();
        if (cboStaffValue !== '---') {
            getAll();
        }else{
            $("#myTable").find("tbody").find("tr").remove();
        }
    });


    function getAll() {
        var year = $("#cboYear").val();
        var month = $("#cboMonth").val();
        var staff_id = $("#cboStaff").val();
        $("#myTable").find("tbody").find("tr").remove();
        $.ajax({
            url: APP_URL + "api/duty_schedule/get_all_rows.php",
            type: "POST",
            data: JSON.stringify({ year: year, month: month, staff_id: staff_id })
        }).done(function(data) {
            console.log(data);
            $.each(data.records, function(i, v) {
                $("#myTable").find("tbody")
                .append($('<tr>')
                    .append("<td style='width: 10px'>" + (i + 1) + "</td>")
                    .append("<td>" + v.date + "</td>")
                    .append(`<td><input type='time' class='form-control form-control-sm duty-in' value='${v.duty_in}'></td>`)
                    .append(`<td><input type='time' class='form-control form-control-sm duty-out' value='${v.duty_out}'></td>`)
                    .append(`<td><input type='checkbox' class='form-check-input off-day' ${v.off_day == "1" ? "checked" : ""}></td>`)
                );
            });
        });
    }

    $("#saveAll").on("click", function () {
        var year = $("#cboYear").val();
        var month = $("#cboMonth").val();
        var staff_id = $("#cboStaff").val();
        let rows = [];

        // Collect data from all rows
        $("#myTable tbody tr").each(function () {
            let row = {
                date: $(this).find("td:nth-child(2)").text(),
                duty_in: $(this).find(".duty-in").val(),
                duty_out: $(this).find(".duty-out").val(),
                off_day: $(this).find(".off-day").is(":checked") ? 1 : 0
            };
            rows.push(row);
        });

        // Send data via AJAX
        $.ajax({
            url: APP_URL + "api/duty_schedule/create.php",
            type: "POST",
            data: JSON.stringify({ year:year,month:month,staff_id:staff_id,schedule: rows }),
            contentType: "application/json",
            success: function (response) {
                showAlert("All rows saved successfully!","success");
                console.log(response);
            },
            error: function (error) {
                console.error("Error saving rows:", error);
            }
        });
    });

	function showAlert(message, type) {
		Swal.fire({
			title: type === 'success' ? 'Success!' : 'Oops!',
			text: message,
			icon: type,
			// confirmButtonText: 'OK',
			timer: 1000, // Auto close after 3000 milliseconds (3 seconds)
			timerProgressBar: true, // Optional: Show a progress bar
			willClose: () => {
				// Optional: Execute code just before the alert closes
				console.log('Alert closed');
			}
		});
	}

</script>
