<?php
include "pin/header.php";
include "pin/sidenav.php";



?>

<!-- ============================================================== -->
<!-- Start Page Content here -->
<!-- ============================================================== -->

<div class="content-page">
    <div class="content">
        <div class="container-fluid">

            <div class="row mt-5">
                <div class="col-12">
                    <div class="card">
                        <div class="card-body">
                            <h4 class="header-title mt-0 mb-4">Attendance File Upload</h4>
                            <form id="form_submit" enctype="multipart/form-data">
                                <div class="row">

                                    <!-- 
                                    <div class="col-md-6 order-md-2">
                                        <h4 class="text-success">Successfully Attendance Imported Successfully !</h4>
                                    </div> -->

                                    <div class="col-md-6 order-md-1">
                                        <div class="form-group">
                                            <label for="importAttendance">Upload File<span class="text-danger">*</span></label>
                                            <input name="importAttendance" id="importAttendance" type="file" class="form-control" required />
                                        </div>
                                        <p class="text-danger" style="font-size:0.8rem">Upload only .xlsx, .xls File.<br> <strong>Please maintain excel First row as column names like:-</strong><br> `employee_id`, `attendance_status`, `punch_in`, `punch_out`, `which_month`.<strong><br> Order of columns not compulsory.</strong></p>
                                    </div>

                                </div>

                                <div class="text-right mt-3">
                                    <button type="submit" name="importAttendanceSubmit" class="btn btn-danger px-4">
                                        <span>Import<i class="uil uil-arrow-right ml-1 mt-2"></i></span>
                                        <span class="spinner-border" role="status" style="width:1rem; height:1rem; display:none;"></span>
                                    </button>
                                </div>
                            </form>
                        </div> <!-- end card-body -->
                    </div>
                </div> <!-- end col-->
            </div>
            <!-- end row -->

        </div>
    </div> <!-- content -->




</div>

<!-- ============================================================== -->
<!-- End Page content -->
<!-- ============================================================== -->



<?php
include "pin/footer.php";
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script>
    $(document).ready(function() {
        $(".custom-select-picker").select2();

        $(".custom-responsive-datatable").parent().css("overflow", "auto");
    });


    // read data from file when click on importAttendanceSubmit this button <p class="text-danger" style="font-size:0.8rem">Upload only .xlsx, .xls File.<br> <strong>Please maintain excel First row as column names like:-</strong><br> `employee_id`, `attendance_status`, `punch_in`, `punch_out`, `which_month`.<strong><br> Order of columns not compulsory.</strong></p>
    let form = document.getElementById("form_submit");
    form.addEventListener("submit", function(event) {
        event.preventDefault(); // Prevent the default form submission

        // show spinner
        $('button[type="submit"]').prop('disabled', true);
        $('button[type="submit"] .spinner-border').show();
        $('button[type="submit"] span:first-child').hide();

        let fileInput = document.getElementById("importAttendance");
        let file = fileInput.files[0];

        if (!file) {
            alert("Please select a file first!");
            return;
        }

        let reader = new FileReader();
        reader.onload = function(e) {
            let data = new Uint8Array(e.target.result);
            let workbook = XLSX.read(data, {
                type: "array",
                cellDates: true
            });

            // Take first sheet
            let sheetName = workbook.SheetNames[0];
            let worksheet = workbook.Sheets[sheetName];

            // Convert sheet to JSON with raw = false (so formatting is applied)
            let jsonData = XLSX.utils.sheet_to_json(worksheet, {
                defval: "",
                raw: false
            });

            console.log("Excel Data:", jsonData);

            // Example: loop through and print employee_id
            // jsonData.forEach(row => {
            //     console.log("Employee:", row.employee_id, "Status:", row.attendance_status);
            // });


            let chunkSize = 1000; // send 1000 rows per request
            let index = 0;

            function sendChunk() {
                if (index >= jsonData.length) {
                    $('button[type="submit"]').prop('disabled', false);
                    $('button[type="submit"] .spinner-border').hide();
                    $('button[type="submit"] span:first-child').show();
                    alert("All data uploaded successfully!");
                    return;
                }

                let chunk = jsonData.slice(index, index + chunkSize);

                // Send via AJAX
                $.ajax({
                    url: "fun/importAttend",
                    type: "POST",
                    data: {
                        importAttendanceChunk: 1,
                        data: JSON.stringify(chunk)
                    },
                    success: function(res) {
                        console.log(res);
                        console.log("Uploaded rows:", index, "-", index + chunk.length);
                        index += chunkSize;
                        sendChunk(); // recursive call until done
                    },
                    error: function() {
                        alert("Error uploading data. Try again.");
                    }
                });
            }

            sendChunk(); // start uploading
        };
        reader.readAsArrayBuffer(file);
    });
</script>