<?php $__env->startSection('content'); ?>
<style>
    /* Premium Table Table-fixed behavior */
    #attendance-table thead th {
        background: #f1f5f9;
        text-transform: uppercase;
        font-size: 0.7rem;
        font-weight: 700;
        color: #475569;
        padding: 12px 10px;
        border-bottom: 2px solid #cbd5e1;
        white-space: nowrap;
    }

    /* Sticky columns */
    .sticky-col { 
        position: sticky !important; 
        left: 0; 
        background-color: #ffffff !important; 
        z-index: 10; 
    }
    .sticky-col-header { 
        position: sticky !important; 
        left: 0; 
        z-index: 11 !important; 
        background-color: #f1f5f9 !important; 
    }
    .col-sticky-1 { left: 0; min-width: 80px; }
    .col-sticky-2 { left: 80px; min-width: 50px; }
    .col-sticky-3 { left: 130px; min-width: 155px; border-right: 2px solid #e2e8f0 !important; }

    /* Row Status Colors */
    .is-dirty { border-left: 4px solid #fbbf24 !important; }
    .row-saving { background-color: #f8fafc !important; opacity: 0.7; }
    .row-saved { background-color: #f0fdf4 !important; }
    .row-error { border-left: 4px solid #ef4444 !important; }

    /* Action Buttons */
    .action-btn { display: none; padding: 2px 6px; font-size: 11px; }
    .is-dirty .action-btn { display: inline-flex; }

    /* Modern status badges */
    .badge-status { padding: 4px 8px; border-radius: 4px; font-weight: 700; font-size: 10px; text-transform: uppercase; }
    .status-P { background-color: #dcfce7; color: #166534; }
    .status-A { background-color: #fee2e2; color: #991b1b; }
    .status-DF { background-color: #dbeafe; color: #1e40af; }
    .status-H { background-color: #fef3c7; color: #92400e; }

    /* Bulk Action Footer */
    #bulk-action-footer {
        position: fixed; bottom: 0; left: 0; right: 0;
        background: white; border-top: 2px solid #e2e8f0;
        padding: 15px 30px; z-index: 1000;
        box-shadow: 0 -10px 15px -3px rgb(0 0 0 / 0.1);
        display: none;
    }
</style>

<div class="row">
    <div class="col-12">
        <div class="card mb-3 shadow-sm border-0" id="filter-card" style="border-radius: 12px;">
            <div class="card-body p-4">
                <div class="row g-2 align-items-end">
                    <div class="col-md-3">
                        <label class="form-label fw-bold small text-muted">EMPLOYEE</label>
                        <select id="employee_id" class="form-select border-1">
                            <option value="">-- Select Employee --</option>
                            <?php $__currentLoopData = $employee; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $emp): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($emp->id); ?>"><?php echo e($emp->display_text); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label fw-bold small text-muted">FROM DATE</label>
                        <input type="date" id="from_date" class="form-control border-1">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label fw-bold small text-muted">TO DATE</label>
                        <input type="date" id="to_date" class="form-control border-1">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label fw-bold small text-muted">SHIFT</label>
                        <select id="shift_filter" class="form-select border-1">
                            <option value="">All Shifts</option>
                            <?php $__currentLoopData = $shifts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $shift): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($shift->id); ?>"><?php echo e($shift->name); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label fw-bold small text-muted">STATUS</label>
                        <select id="status_filter" class="form-select border-1">
                            <option value="">All Status</option>
                            <option value="P">Present</option>
                            <option value="A">Absent</option>
                            <option value="DF">Day Off</option>
                        </select>
                    </div>
                    <div class="col-md-1">
                        <button id="loadAttendance" class="btn btn-primary w-100 fw-bold py-2 shadow-sm">
                            LOAD
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card shadow-sm border-0" style="border-radius: 12px; overflow: hidden; margin-bottom: 80px;">
    <div class="card-body p-0">
        <div class="attendance-table-wrap">
            <div class="table-responsive" style="max-height: 65vh; min-height: 400px;">
                <table class="table table-hover w-100 mb-0" id="attendance-table">
                    <thead>
                        <tr>
                            <th class="sticky-col-header col-sticky-1">Action</th>
                            <th class="sticky-col-header text-center" style="left: 80px; min-width: 50px;"><input type="checkbox" id="select-all" class="form-check-input"></th>
                            <th class="sticky-col-header col-sticky-3">Attendance Date</th>
                            <th>No</th>
                            <th>Name</th>
                            <th style="min-width:130px;">Shift</th>
                            <th class="text-center" style="min-width:200px;">Status</th>
                            <th class="text-center">Leave</th>
                            <th>In Time</th>
                            <th>Out Time</th>
                            <th>OT</th>
                            <th class="text-center">OT (H)</th>
                            <th class="text-center">SOT (H)</th>
                            <th class="text-center">DOT (H)</th>
                            <th class="text-center">OT (M)</th>
                            <th class="text-center">DOT (M)</th>
                            <th class="text-center">Late</th>
                            <th class="text-center">Short</th>
                            <th class="text-center">Early</th>
                            <th class="text-center">Lunch</th>
                            <th class="text-center">Dinner</th>
                            <th>1st Out</th>
                            <th>2nd In</th>
                            <th>2nd Out</th>
                            <th>3rd In</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
    </div>
</div>


<div id="bulk-action-footer" class="animate__animated animate__slideInUp">
    <div class="container-fluid">
        <div class="row align-items-center">
            <div class="col-md-2">
                <span class="fw-bold text-primary"><i class="ti ti-checkbox me-2"></i><span id="selected-count">0</span> SELECTED</span>
            </div>
            <div class="col-md-3">
                <select id="bulk_shift" class="form-select border-primary">
                    <option value="">-- Change Shift --</option>
                    <?php $__currentLoopData = $shifts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $shift): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($shift->id); ?>" 
                            data-start-time="<?php echo e(substr($shift->work_start_time, 0, 5)); ?>"
                            data-end-time="<?php echo e(substr($shift->work_end_time, 0, 5)); ?>">
                            <?php echo e($shift->name); ?>

                        </option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </select>
            </div>
            <div class="col-md-3">
                <select id="bulk_status" class="form-select border-primary">
                    <option value="">-- Change Status --</option>
                    <option value="P">Present</option>
                    <option value="A">Absent</option>
                    <option value="DF">Day Off</option>
                </select>
            </div>
            <div class="col-md-4 text-end">
                <button class="btn btn-outline-secondary me-2" id="clear-selection">Cancel</button>
                <button class="btn btn-primary px-5 fw-bold" id="bulk-save-btn">
                    <i class="ti ti-device-floppy me-2"></i> BULK SAVE
                </button>
            </div>
        </div>
    </div>
</div>

<?php echo $__env->make('attendance::emp/partials/punch-modal', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script>
var attendanceTable;
var isEditing = false;

$(function () {
    // Initialize Select2 for employee dropdown
    initEmployeeSelect2('#employee_id');

    // CSRF
    $.ajaxSetup({
        headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
    });

    // Initialize Table
    attendanceTable = $('#attendance-table').DataTable({
        processing: true,
        serverSide: true,
        searching: false,
        paging: false,
        ordering: false,
        deferLoading: 0,
        dom: "<'row p-3'<'col-md-6'i><'col-md-6 d-flex justify-content-end'f>>t",
        ajax: {
            url: "<?php echo e(route('attendance.employeewise.index')); ?>",
            type: "GET",
            data: function (d) {
                d.employee_id = $('#employee_id').val();
                d.from_date = $('#from_date').val();
                d.to_date = $('#to_date').val();
                d.shift_id = $('#shift_filter').val();
                d.status = $('#status_filter').val();
            }
        },
        columns: [
            { data: 'action', className: 'sticky-col col-sticky-1' },
            { data: 'checkbox', className: 'sticky-col text-center' },
            { data: 'attendance_date', className: 'sticky-col col-sticky-3 fw-bold' },
            { data: 'employee_no' },
            { data: 'employee_name' },
            { data: 'shift' },
            { data: 'attendance_status', className: 'text-center' },
            { data: 'leave', className: 'text-center' },
            { data: 'in_time' },
            { data: 'out_time' },
            { data: 'remove_ot' },
            { data: 'ot_hrs', className: 'text-center' },
            { data: 'sot_hrs', className: 'text-center', defaultContent: '0' },
            { data: 'dot_hrs', className: 'text-center' },
            { data: 'ot_minutes', className: 'text-center' },
            { data: 'dot_minutes', className: 'text-center' },
            { data: 'late_minutes', className: 'text-center' },
            { data: 'short_leave_minutes', className: 'text-center' },
            { data: 'early_minutes', className: 'text-center' },
            { data: 'lunch', className: 'text-center' },
            { data: 'dinner', className: 'text-center' },
            { data: 'punch_1_out' },
            { data: 'punch_2_in' },
            { data: 'punch_2_out' },
            { data: 'punch_3_in' }
        ],
        drawCallback: function() {
            // All inputs enabled for seamless editing
            $('.row-input, .shift-select, .attendance-status, .punch-edit').prop('disabled', false);
        }
    });

    $('#loadAttendance').on('click', function () {
        if (isEditing) {
            Swal.fire('Warning', 'Please save your changes before reloading.', 'warning');
            return;
        }
        attendanceTable.ajax.reload();
    });

    // DIRTY ROW TRACKING
    $(document).on('change', '.row-input, select.shift-select, select.attendance-status, .punch-edit', function() {
        $(this).closest('tr').addClass('is-dirty');
    });

    // AUTO-SAVE ON ROW CHANGE
    var activeRow = null;
    $(document).on('mousedown focusin', '#attendance-table tbody tr', function() {
        let clickedRow = $(this);
        
        if (activeRow && !activeRow.is(clickedRow)) {
            if (activeRow.hasClass('is-dirty')) {
                saveRowData(activeRow);
            }
        }
        activeRow = clickedRow;
    });

    // AUTO-FILL IN/OUT TIMES BASED ON SHIFT (using data attributes)
    $(document).on('change', '.shift-select', function() {
        let row = $(this).closest('tr');
        let selectedOption = $(this).find('option:selected');
        let dateCell = row.find('td:eq(2)').text().trim(); // Get date from 3rd column
        
        let startTime = selectedOption.data('start-time');
        let endTime = selectedOption.data('end-time');
        
        if (startTime && endTime && dateCell) {
            row.find('.in-time').val(dateCell + 'T' + startTime);
            row.find('.out-time').val(dateCell + 'T' + endTime);
        }
    });

    // AUTO-FILL/CLEAR IN/OUT TIMES BASED ON ATTENDANCE STATUS
    $(document).on('change', '.attendance-status', function() {
        let status = $(this).val();
        let row = $(this).closest('tr');
        let shiftSelect = row.find('.shift-select');
        let selectedOption = shiftSelect.find('option:selected');
        let dateCell = row.find('td:eq(2)').text().trim();

        let startTime = selectedOption.data('start-time');
        let endTime = selectedOption.data('end-time');

        // Handle different status types
        if (status === 'P') {
            // Present - Set both in and out times
            if (startTime && endTime && dateCell) {
                row.find('.in-time').val(dateCell + 'T' + startTime);
                row.find('.out-time').val(dateCell + 'T' + endTime);
            }
        } else if (status === 'HP+HA' || status === 'HP+HDF') {
            // Half Present first - Set only in-time, clear out-time
            if (startTime && dateCell) {
                row.find('.in-time').val(dateCell + 'T' + startTime);
                row.find('.out-time').val('');
            }
        } else if (status === 'HA+HP' || status === 'HDF+HP') {
            // Half Present second - Set only out-time, clear in-time
            if (endTime && dateCell) {
                row.find('.in-time').val('');
                row.find('.out-time').val(dateCell + 'T' + endTime);
            }
        } else {
            // A, DF, HA+HDF, HDF+HA - Clear both times
            row.find('.in-time').val('');
            row.find('.out-time').val('');
        }
    });

    // Save Row Data Function
    function saveRowData(row) {
        if (!row.hasClass('is-dirty')) return;

        let btn = row.find('.save-row');
        let rowId = btn.data('id');
        
        row.removeClass('is-dirty').addClass('row-saving');
        
        let data = {
            id: rowId,
            shift_id: row.find('.shift-select').val(),
            status: row.find('.attendance-status').val(),
            in_time: row.find('.in-time').val(),
            out_time: row.find('.out-time').val(),
            lunch: row.find('.lunch-check').is(':checked') ? 1 : 0,
            dinner: row.find('.dinner-check').is(':checked') ? 1 : 0,
            remove_ot: row.find('.remove-ot').is(':checked') ? 0 : 1,
            punches: []
        };

        row.find('.punch-edit').each(function () {
            data.punches.push({ seq: $(this).data('seq'), datetime: $(this).val() });
        });

        $.post("<?php echo e(route('attendance.updateRow')); ?>", data)
            .done(res => {
                row.removeClass('row-saving').addClass('row-saved');
                setTimeout(() => row.removeClass('row-saved'), 1500);
                updateBulkUI();
                attendanceTable.ajax.reload();
            })
            .fail(err => {
                row.addClass('is-dirty row-error').removeClass('row-saving');
                console.error('Auto-save failed for row ' + rowId);
            });
    }

    // Manual Save Button (still works as explicit save)
    $(document).on('click', '.save-row', function (e) {
        e.stopPropagation();
        saveRowData($(this).closest('tr'));
    });

    // Cancel / Discard Changes
    $(document).on('click', '.cancel-row', function (e) {
        e.stopPropagation();
        let row = $(this).closest('tr');
        if (row.hasClass('is-dirty')) {
            row.removeClass('is-dirty row-error');
            // Flash row to indicate cancellation
            row.addClass('row-saving'); 
            setTimeout(() => {
                row.removeClass('row-saving');
                // Reload the table for this row (simplest way to revert)
                attendanceTable.row(row).invalidate().draw(false);
                Toast.fire({ icon: 'info', title: 'Changes discarded' });
            }, 300);
        }
    });

    // BULK SELECTION LOGIC
    $('#select-all').on('change', function () {
        if (isEditing) return;
        $('.row-check').prop('checked', this.checked);
        updateBulkUI();
    });

    $(document).on('change', '.row-check', updateBulkUI);

    function updateBulkUI() {
        let count = $('.row-check:checked').length;
        $('#selected-count').text(count);
        if (count > 0 && !isEditing) {
            $('#bulk-action-footer').fadeIn().css('display', 'block');
        } else {
            $('#bulk-action-footer').fadeOut();
        }
    }

    $('#clear-selection').on('click', function() {
        $('.row-check, #select-all').prop('checked', false);
        updateBulkUI();
    });

    // AUTO-FILL TIMES FOR BULK SHIFT CHANGE
    $('#bulk_shift').on('change', function() {
        let bulkShiftId = $(this).val();
        if (!bulkShiftId) return;
        
        // Get shift times directly from the bulk dropdown's selected option
        let selectedOption = $(this).find('option:selected');
        let startTime = selectedOption.data('start-time');
        let endTime = selectedOption.data('end-time');
        
        if (startTime && endTime) {
            $('.row-check:checked').each(function() {
                let row = $(this).closest('tr');
                let dateCell = row.find('td:eq(2)').text().trim();
                
                if (dateCell) {
                    row.find('.in-time').val(dateCell + 'T' + startTime);
                    row.find('.out-time').val(dateCell + 'T' + endTime);
                }
            });
        }
    });

    // AUTO-FILL/CLEAR TIMES FOR BULK STATUS CHANGE
    $('#bulk_status').on('change', function() {
        let status = $(this).val();
        if (!status) return;

        $('.row-check:checked').each(function() {
            let row = $(this).closest('tr');
            let shiftSelect = row.find('.shift-select');
            let selectedOption = shiftSelect.find('option:selected');
            let dateCell = row.find('td:eq(2)').text().trim();

            let startTime = selectedOption.data('start-time');
            let endTime = selectedOption.data('end-time');

            // Handle different status types
            if (status === 'P') {
                // Present - Set both in and out times
                if (startTime && endTime && dateCell) {
                    row.find('.in-time').val(dateCell + 'T' + startTime);
                    row.find('.out-time').val(dateCell + 'T' + endTime);
                }
            } else if (status === 'HP+HA' || status === 'HP+HDF') {
                // Half Present first - Set only in-time, clear out-time
                if (startTime && dateCell) {
                    row.find('.in-time').val(dateCell + 'T' + startTime);
                    row.find('.out-time').val('');
                }
            } else if (status === 'HA+HP' || status === 'HDF+HP') {
                // Half Present second - Set only out-time, clear in-time
                if (endTime && dateCell) {
                    row.find('.in-time').val('');
                    row.find('.out-time').val(dateCell + 'T' + endTime);
                }
            } else {
                // A, DF, HA+HDF, HDF+HA - Clear both times
                row.find('.in-time').val('');
                row.find('.out-time').val('');
            }
        });
    });

    // Bulk Save
    $('#bulk-save-btn').on('click', function() {
        let rowsData = [];
        $('.row-check:checked').each(function() {
            let row = $(this).closest('tr');
            let rowId = $(this).data('id');
            
            let rowInfo = {
                id: rowId,
                shift_id: row.find('.shift-select').val(),
                status: row.find('.attendance-status').val(),
                in_time: row.find('.in-time').val(),
                out_time: row.find('.out-time').val(),
                lunch: row.find('.lunch-check').is(':checked') ? 1 : 0,
                dinner: row.find('.dinner-check').is(':checked') ? 1 : 0,
                remove_ot: row.find('.remove-ot').is(':checked') ? 0 : 1,
                punches: []
            };

            row.find('.punch-edit').each(function () {
                rowInfo.punches.push({ seq: $(this).data('seq'), datetime: $(this).val() });
            });

            rowsData.push(rowInfo);
        });

        if (rowsData.length === 0) {
            Swal.fire('Info', 'Please select at least one row.', 'info');
            return;
        }

        $(this).prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span> PROCESSING...');

        $.post("<?php echo e(route('attendance.bulkUpdate')); ?>", { rows: rowsData })
            .done(res => {
                Swal.fire('Success', 'Bulk save completed!', 'success');
                $('#bulk-save-btn').prop('disabled', false).html('<i class="ti ti-device-floppy me-2"></i> BULK SAVE');
                $('.row-check, #select-all').prop('checked', false);
                updateBulkUI();
                attendanceTable.ajax.reload();
            })
            .fail(err => {
                $(this).prop('disabled', false).html('<i class="ti ti-device-floppy me-2"></i> BULK SAVE');
                Swal.fire('Error', 'Bulk save failed!', 'error');
            });
    });

    const Toast = Swal.mixin({
        toast: true, position: 'top-end', showConfirmButton: false, timer: 2000, timerProgressBar: true
    });
});
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /media/madu/E8460E1D460DECDE/projects/laraoffice/app/Modules/HR/Attendance/Providers/../Views/emp/index.blade.php ENDPATH**/ ?>