<?php include '../header.php'; ?> 
<?php include '../sidemenu.php'; ?> 
<style>
.table-responsive {
    overflow: visible !important;
}

.dropdown {
    position: relative !important;
}

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

<div class="page-body">
    <div class="container-xl">
        <div class="row row-cards">
            <div class="col-12">
						<div class="row">
							<div class="col-3 mb-3 row">
                                <label class="col-4 col-form-label text-end">Date From</label>
                                <div class="col">
                                    <input type="text" class="flatpickr flatpickr-input active form-control" id="dateFrom" required>
                                </div>
                            </div>
							<div class="col-3 mb-3 row">
                                <label class="col-4 col-form-label text-end">Date To</label>
                                <div class="col">
                                    <input type="text" class="flatpickr flatpickr-input active form-control" id="dateTo" required>
                                </div>
                            </div>
                            <div class="col-3 mb-3 row">
                                <label for="cboStaff" class="col-4 col-form-label text-end">Name</label>
                                <div class="col">
                                    <select class="form-select" id="cboStaff" name="cboStaff" placeholder="Select account head">
                                    </select>
                                </div>
                            </div>
						</div>
                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="myTable" class="table card-table table-vcenter text-nowrap datatable" >
                                <thead>
                                    <tr>
                 
										<th style="text-align: left;">Date</th>
                                        <th style="text-align: left;">Name</th>
                                        <th>Duty<span class="searchable">🔍</span></th>
                                        <th style="text-align: left;">Duty In</th>
                                        <th style="text-align: left;">Duty In Photo</th>
                                        <th style="text-align: left;">Duty Out</th>
                                        <th style="text-align: left;">Duty Out Photo</th>
                                        <th style="text-align: left;">Second Duty In</th>
                                        <th style="text-align: left;">Second Duty In Photo</th>
                                        <th style="text-align: left;">Second Duty Out</th>
                                        <th style="text-align: left;">Second Duty Out Photo</th>
                                        <th style="text-align: left;">Duty Minute</th>
                                        <th style="text-align: left;">Att Minute</th>
                                        <th style="text-align: left;">Extra/Short Minute</th>
                                    </tr>
                                </thead>
                                <tfoot>
                                    <tr>
                                        <th colspan="11" style="text-align: right;">Total:</th>
                                        <th id="footer_sum_duty_minute"></th>
                                        <th id="footer_sum_att_minute"></th>
                                        <th id="footer_sum_extra_short_minute"></th>
                                    </tr>
                                </tfoot>
                                <tbody>

                                </tbody>
                            </table>
                        </div>
                        <!-- <div class="d-flex justify-content-end text-bold">Total Amount: <span id="totalAmount">0.00</span></div> -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div id="photoModal" class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-body text-center">
        <img id="largePhoto" src="" alt="Large Photo" class="img-fluid">
      </div>
    </div>
  </div>
</div>


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

<script>
var today = new Date(); // Get today's date as a Date object
const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1); // First day of the current month

$(function() {
    getStaff();
    flatpickr("#dateFrom", {
        dateFormat: "Y-m-d", 
        defaultDate: startOfMonth,  
        maxDate: today,      
    });
    flatpickr("#dateTo", {
        dateFormat: "Y-m-d", 
        defaultDate: today,  
        maxDate: today,      
    });
});


$("#dateFrom, #dateTo, #cboStaff").change(function() {
    if($("#cboStaff").val()!="-"){
        getAll();
    }
});

// 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 = '-' disabled selected>Select a name</option>");
//         $.each(data.records, function(i, v) {	
//             $("#cboStaff").append("<option value = '" + v.id + "'>" + v.name + "</option>");						
//         });
//     });
// } i want to show staff that is match $_SESSION['staff_id'] only
function getStaff() {
    const staffId = "<?php echo $_SESSION['staff_id']; ?>"; // Current staff ID from session
    const userId = "<?php echo $_SESSION['userrole_id']; ?>"; // Current user ID from session

    $.ajax({
        url: APP_URL + "api/staff/get_all_rows.php",
        type: "POST",
        data: JSON.stringify({ account_type: "" }),
        contentType: "application/json"
    }).done(function (data) {
        $("#cboStaff").find("option").remove(); // Clear existing options
        $("#cboStaff").append("<option value = '-' disabled selected>Select a name</option>"); // Add default option

        // Check if the user is admin (userid == 1)
        if (userId == 1) {
            // Admin sees all staff
            $.each(data.records, function (i, v) {
                $("#cboStaff").append("<option value='" + v.id + "'>" + v.name + "</option>");
            });
        } else {
            // Filter to only show the matching staff ID
            $.each(data.records, function (i, v) {
                if (v.id == staffId) {
                    $("#cboStaff").append("<option value='" + v.id + "'>" + v.name + "</option>");
                }
            });
        }
    });
}


function getAll() {
    var df = $("#dateFrom").val();
    var dt = $("#dateTo").val();
    var staff_id = $("#cboStaff").val();

    $('#myTable').DataTable().destroy();
    let table = $('#myTable').DataTable({
        ajax: {
            url: APP_URL + "api/attendance/search.php",
            method: "GET",
            dataType: "json",
            data: {
                df: df,
                dt: dt,
                staff_id: staff_id
            },
            dataSrc: function(json) {
                return json.records;
            }
        },
        columns: [
            { data: 0 },
            { data: 1 },
            { data: 2 },
            { data: 3 , visible: false },
            { 
                data: 4,
                render: function(data, type, row) {
                    const additionalData = row[3];
                    return `
                        <img src="${data}" alt="" 
                            style="width:25px; height:25px; cursor:pointer;" 
                            onclick="showPhoto('${data}')">
                        <span>${additionalData}</span>
                    `;
                }
            },
            { data: 5 , visible: false },
            { 
                data: 6,
                render: function(data, type, row) {
                    const additionalData = row[5];
                    return `
                        <img src="${data}" alt="" 
                            style="width:25px; height:25px; cursor:pointer;" 
                            onclick="showPhoto('${data}')">
                        <span>${additionalData}</span>
                    `;
                }
            },
            { data: 7 , visible: false },
            { 
                data: 8,
                render: function(data, type, row) {
                    const additionalData = row[7];
                    return `
                        <img src="${data}" alt="" 
                            style="width:25px; height:25px; cursor:pointer;" 
                            onclick="showPhoto('${data}')">
                        <span>${additionalData}</span>
                    `;
                }
            },
            { data: 9 , visible: false },
            { 
                data: 10,
                render: function(data, type, row) {
                    const additionalData = row[9];
                    return `
                        <img src="${data}" alt="" 
                            style="width:25px; height:25px; cursor:pointer;" 
                            onclick="showPhoto('${data}')">
                        <span>${additionalData}</span>
                    `;
                }
            },
            { data: 11 },
            { 
                data: 12,
                render: function(data, type, row) {
                    var color;
                    if (row[12] < row[11]) {
                        color = 'red';
                    } else if (row[12] > row[11]) {
                        color = 'green';
                    } else {
                        color = 'black';
                    }
                    return `<span style="color: ${color};">${data}</span>`;
                }
            },
            { data: 13 },
        ],
        columnDefs: [
            {
                targets: [1, 2, 4],
                createdCell: function (td, cellData, rowData, row, col) {
                    $(td).css('text-align', 'left');
                }
            },
            {
                targets: [2, 3, 6],
                searchable: true
            },
            {
                targets: [0, 1, 4, 5, 7, 8, 9, 10, 11, 12, 13], 
                searchable: false
            }
        ],
        paging: true,
        scrollX: true,
        language: {
            emptyTable: "No records found",
            info: "Showing _START_ to _END_ of _TOTAL_ entries",
            lengthMenu: "Show _MENU_ entries",
            search: "Search:",
            zeroRecords: "No records found"
        },
        lengthMenu: [[50, 100, -1], [50, 100, "All"]],
        order: [[0, 'asc']],
        footerCallback: function (row, data, start, end, display) {
            var api = this.api();

            var sum11 = api.column(11, { page: 'current' }).data().reduce(function (a, b) {
                return parseFloat(a) + parseFloat(b);
            }, 0);

            var sum12 = api.column(12, { page: 'current' }).data().reduce(function (a, b) {
                return parseFloat(a) + parseFloat(b);
            }, 0);

            var sum13 = api.column(13, { page: 'current' }).data().reduce(function (a, b) {
                return parseFloat(a) + parseFloat(b);
            }, 0);

            $('#footer_sum_duty_minute').html(sum11);
            $('#footer_sum_att_minute').html(sum12);
            $('#footer_sum_extra_short_minute').html(sum13);

            var color = sum12 < sum11 ? 'red' : (sum12 > sum11 ? 'green' : 'black');

            $(this.api().column(12).footer()).html(`<span style="color: ${color};">${sum12}</span>`);
        }

    });
}



function showPhoto(photoUrl) {
    document.getElementById('largePhoto').src = photoUrl;
    $('#photoModal').modal('show');
}

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