@extends('layouts.app')

@section('content')
<style>
    /* ===================== COMPACT ATTENDANCE GRID ===================== */
    .att-filter { background:#f8f9fa; border:1px solid #dee2e6; border-radius:4px; padding:6px 10px; margin-bottom:6px; }
    .att-filter .form-label { font-size:10px; font-weight:700; text-transform:uppercase; color:#6c757d; margin-bottom:1px; }
    .att-filter .form-control,
    .att-filter .form-select { font-size:12px; padding:3px 6px; height:28px; }
    .att-filter .btn { font-size:12px; padding:3px 12px; height:28px; }

    /* Table shell */
    #att-wrap { overflow-x:auto; overflow-y:auto; max-height:calc(100vh - 155px); border:1px solid #ccc; border-radius:4px; }

    #attendance-table {
        border-collapse: collapse;
        font-size: 11px;
        width: 100%;
        table-layout: fixed;
    }

    /* Header */
    #attendance-table thead th {
        position: sticky; top: 0; z-index: 10;
        background: #343a40; color: #fff;
        padding: 3px 3px;
        font-size: 10px; font-weight: 600;
        white-space: nowrap; overflow: hidden;
        border: 1px solid #495057;
        text-align: center;
        line-height: 1.2;
    }

    /* Body cells */
    #attendance-table tbody td {
        padding: 1px 3px;
        border: 1px solid #dee2e6;
        white-space: nowrap;
        overflow: hidden;
        vertical-align: middle;
        line-height: 1.3;
    }

    /* Row colors */
    #attendance-table tbody tr:nth-child(even) { background:#fafafa; }
    #attendance-table tbody tr.row-dayoff   { background:#e8f4fd; }
    #attendance-table tbody tr.row-absent   { background:#fff3f3; }
    #attendance-table tbody tr.row-present  { background:#f0fff4; }
    #attendance-table tbody tr.row-holiday  { background:#fff8e1; }
    #attendance-table tbody tr.is-dirty     { background:#fffbcc !important; border-left:3px solid #f59e0b; }
    #attendance-table tbody tr.row-saved    { background:#d4edda !important; }

    /* Compact inputs */
    #attendance-table input[type="time"],
    #attendance-table input[type="number"] {
        font-size: 11px; padding: 0 2px; height: 20px; width: 100%;
        border: 1px solid #ced4da; border-radius: 2px;
    }
    #attendance-table select {
        font-size: 11px; padding: 0 2px; height: 20px; width: 100%;
        border: 1px solid #ced4da; border-radius: 2px;
    }
    #attendance-table input[type="checkbox"] { width:13px; height:13px; cursor:pointer; }

    /* Save button tiny */
    .btn-save-row {
        font-size:10px; padding:1px 5px; line-height:1.2;
        display:none;
    }
    .is-dirty .btn-save-row { display:inline-block; }

    /* Column widths */
    .c-chk  { width:22px; }
    .c-date { width:76px; font-weight:600; color:#343a40; }
    .c-emp  { width:52px; }
    .c-name { width:110px; overflow:hidden; text-overflow:ellipsis; }
    .c-shift{ width:120px; }
    .c-stat { width:110px; }
    .c-time { width:80px; }
    .c-min  { width:36px; text-align:right; }
    .c-chkb { width:26px; text-align:center; }
    .c-punch{ width:52px; }
    .c-act  { width:36px; text-align:center; }

    /* Totals row */
    tr.totals-row td { background:#343a40 !important; color:#fff; font-weight:700; font-size:11px; }

    /* Bulk bar */
    #bulk-bar {
        display:none; position:fixed; bottom:0; left:0; right:0;
        background:#212529; color:#fff; padding:6px 16px; z-index:1050;
        font-size:12px;
    }
    #bulk-bar .form-select { font-size:12px; padding:2px 6px; height:26px; width:auto; display:inline-block; }
    #bulk-bar .btn { font-size:12px; padding:2px 10px; height:26px; }
</style>

{{-- FILTER BAR --}}
<div class="att-filter">
    <div class="row g-2 align-items-end">
        <div class="col-auto">
            <label class="form-label">Date</label>
            <input type="date" id="attendance_date" class="form-control form-control-sm"
                style="width:140px;" value="{{ date('Y-m-d') }}">
        </div>
        <div class="col-auto">
            <label class="form-label">Shift</label>
            <select id="shift_filter" class="form-select form-select-sm" style="width:140px;">
                <option value="">All Shifts</option>
                @foreach ($shifts as $shift)
                    <option value="{{ $shift->id }}">{{ $shift->name }}</option>
                @endforeach
            </select>
        </div>
        <div class="col-auto">
            <label class="form-label">Status</label>
            <select id="status_filter" class="form-select form-select-sm" style="width:110px;">
                <option value="">All</option>
                <option value="P">Present</option>
                <option value="A">Absent</option>
                <option value="DF">Day Off</option>
            </select>
        </div>
        <div class="col-auto">
            <label class="form-label">&nbsp;</label>
            <button id="loadAttendance" class="btn btn-primary btn-sm d-block">LOAD</button>
        </div>
        <div class="col-auto ms-auto text-end">
            <label class="form-label">&nbsp;</label>
            <div>
                <span id="rec-info" class="text-muted" style="font-size:11px;"></span>
            </div>
        </div>
    </div>
</div>

{{-- TABLE --}}
<div id="att-wrap">
    <table id="attendance-table">
        <thead>
            <tr>
                <th class="c-chk"><input type="checkbox" id="select-all"></th>
                <th class="c-date">Date</th>
                <th class="c-emp">Emp No</th>
                <th class="c-name">Name</th>
                <th class="c-shift">Shift</th>
                <th class="c-stat">Status</th>
                <th class="c-time">In Time</th>
                <th class="c-time">Out Time</th>
                <th class="c-min">Work<br>(min)</th>
                <th class="c-min">OT<br>(min)</th>
                <th class="c-min">DOT<br>(min)</th>
                <th class="c-min">Late<br>(min)</th>
                <th class="c-min">Early<br>(min)</th>
                <th class="c-min">Short<br>(min)</th>
                <th class="c-chkb">OT</th>
                <th class="c-chkb">Lnch</th>
                <th class="c-chkb">Dinr</th>
                <th class="c-punch">Punch1</th>
                <th class="c-punch">Punch2</th>
                <th class="c-punch">Punch3</th>
                <th class="c-punch">Punch4</th>
                <th class="c-act">Save</th>
            </tr>
        </thead>
        <tbody></tbody>
        <tfoot>
            <tr class="totals-row">
                <td colspan="8" class="text-end pe-2">TOTALS</td>
                <td id="tot-work" class="c-min"></td>
                <td id="tot-ot" class="c-min"></td>
                <td id="tot-dot" class="c-min"></td>
                <td id="tot-late" class="c-min"></td>
                <td id="tot-early" class="c-min"></td>
                <td id="tot-short" class="c-min"></td>
                <td colspan="8"></td>
            </tr>
        </tfoot>
    </table>
</div>

{{-- BULK BAR --}}
<div id="bulk-bar">
    <span class="me-3 fw-bold"><span id="selected-count">0</span> selected</span>
    <select id="bulk_shift" class="form-select d-inline-block me-2">
        <option value="">-- Change Shift --</option>
        @foreach ($shifts as $shift)
            <option value="{{ $shift->id }}"
                data-start-time="{{ substr($shift->work_start_time,0,5) }}"
                data-end-time="{{ substr($shift->work_end_time,0,5) }}">
                {{ $shift->name }}
            </option>
        @endforeach
    </select>
    <select id="bulk_status" class="form-select d-inline-block me-2">
        <option value="">-- Change Status --</option>
        <option value="P">Present</option>
        <option value="A">Absent</option>
        <option value="DF">Day Off</option>
        <option value="HP+HA">Half P + Half A</option>
        <option value="HA+HP">Half A + Half P</option>
    </select>
    <button class="btn btn-success btn-sm me-2" id="bulk-save-btn">Bulk Save</button>
    <button class="btn btn-outline-light btn-sm" id="clear-selection">Cancel</button>
</div>

@include('attendance::emp/partials/punch-modal')
@endsection

@section('scripts')
@php
$shiftOptions = $shifts->map(fn($s) => [
    'id'    => $s->id,
    'name'  => $s->name,
    'start' => substr($s->work_start_time, 0, 5),
    'end'   => substr($s->work_end_time,   0, 5),
])->values();
@endphp
<script>
var SHIFT_OPTIONS = @json($shiftOptions);
$(function () {
    $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });

    // ───── LOAD DATA ─────
    $('#loadAttendance').on('click', loadData);

    function loadData() {
        let date = $('#attendance_date').val();
        if (!date) {
            Swal.fire('Warning', 'Please select a date.', 'warning');
            return;
        }

        $('#attendance-table tbody').html('<tr><td colspan="22" class="text-center py-3">Loading...</td></tr>');
        clearTotals();

        $.get("{{ route('attendance.datewise.index') }}", {
            date: date,
            shift_id: $('#shift_filter').val(),
            status: $('#status_filter').val(),
        }).done(function (res) {
            renderRows(res.data ?? res);
        }).fail(function () {
            $('#attendance-table tbody').html('<tr><td colspan="22" class="text-center text-danger">Failed to load.</td></tr>');
        });
    }

    // ───── RENDER ROWS ─────
    function renderRows(rows) {
        let tbody = $('#attendance-table tbody');
        tbody.empty();

        if (!rows || rows.length === 0) {
            tbody.html('<tr><td colspan="22" class="text-center py-3 text-muted">No records found.</td></tr>');
            $('#rec-info').text('');
            return;
        }

        let totWork=0, totOt=0, totDot=0, totLate=0, totEarly=0, totShort=0;

        rows.forEach(function (r) {
            let status = r.attendance_status_raw ?? '';

            let rowClass  = statusRowClass(status);
            let inVal     = r.in_time_raw  ? r.in_time_raw.substring(11,16)  : '';
            let outVal    = r.out_time_raw ? r.out_time_raw.substring(11,16) : '';
            let workMin   = r.work_minutes ?? 0;
            let otMin     = r.ot_minutes   ?? 0;
            let dotMin    = r.dot_minutes  ?? 0;
            let lateMin   = r.late_minutes ?? 0;
            let earlyMin  = r.early_minutes ?? 0;
            let shortMin  = r.short_leave_minutes ?? 0;

            totWork  += parseInt(workMin)  || 0;
            totOt    += parseInt(otMin)    || 0;
            totDot   += parseInt(dotMin)   || 0;
            totLate  += parseInt(lateMin)  || 0;
            totEarly += parseInt(earlyMin) || 0;
            totShort += parseInt(shortMin) || 0;

            // punch times (HH:MM only)
            let punchesRaw = r.punches_raw ?? [];
            let p = [1,2,3,4].map(i => {
                let pval = punchesRaw[i] ? punchesRaw[i].substring(11,16) : '';
                return `<input type="time" class="punch-edit" data-seq="${i+1}" value="${pval}">`;
            });

            // shift select
            let shiftHtml = `<select class="shift-select">`;
            SHIFT_OPTIONS.forEach(s => {
                let sel = (r.shift_id == s.id) ? 'selected' : '';
                shiftHtml += `<option value="${s.id}" data-start-time="${s.start}" data-end-time="${s.end}" ${sel}>${s.name}</option>`;
            });
            shiftHtml += `</select>`;

            // status select
            let statuses = ['A','P','DF','HP+HA','HA+HP','HP+HDF','HDF+HP','HA+HDF','HDF+HA'];
            let statHtml = `<select class="attendance-status">`;
            statuses.forEach(s => {
                let sel = (status === s) ? 'selected' : '';
                statHtml += `<option value="${s}" ${sel}>${s}</option>`;
            });
            statHtml += `</select>`;

            let removeOtChk = r.remove_ot_raw  ? '' : 'checked';
            let lunchChk    = r.lunch_taken    ? 'checked' : '';
            let dinnerChk   = r.dinner_taken   ? 'checked' : '';

            let empNo   = r.employee_no   ?? '';
            let empName = r.employee_name ?? '';

            let tr = `<tr class="${rowClass}" data-id="${r.id}">
                <td class="c-chk"><input type="checkbox" class="row-check" data-id="${r.id}"></td>
                <td class="c-date">${r.attendance_date ?? ''}</td>
                <td class="c-emp" title="${empNo}">${empNo}</td>
                <td class="c-name" title="${empName}">${empName}</td>
                <td class="c-shift">${shiftHtml}</td>
                <td class="c-stat">${statHtml}</td>
                <td class="c-time"><input type="time" class="in-time row-input" value="${inVal}"></td>
                <td class="c-time"><input type="time" class="out-time row-input" value="${outVal}"></td>
                <td class="c-min">${workMin || ''}</td>
                <td class="c-min">${otMin || ''}</td>
                <td class="c-min">${dotMin || ''}</td>
                <td class="c-min">${lateMin || ''}</td>
                <td class="c-min">${earlyMin || ''}</td>
                <td class="c-min">${shortMin || ''}</td>
                <td class="c-chkb"><input type="checkbox" class="remove-ot" ${removeOtChk}></td>
                <td class="c-chkb"><input type="checkbox" class="lunch-check" ${lunchChk}></td>
                <td class="c-chkb"><input type="checkbox" class="dinner-check" ${dinnerChk}></td>
                <td class="c-punch">${p[0]}</td>
                <td class="c-punch">${p[1]}</td>
                <td class="c-punch">${p[2]}</td>
                <td class="c-punch">${p[3]}</td>
                <td class="c-act"><button class="btn btn-warning btn-save-row" style="font-size:10px;padding:1px 5px;">Save</button></td>
            </tr>`;

            tbody.append(tr);
        });

        $('#rec-info').text(rows.length + ' records');
        $('#tot-work').text(totWork || '');
        $('#tot-ot').text(totOt || '');
        $('#tot-dot').text(totDot || '');
        $('#tot-late').text(totLate || '');
        $('#tot-early').text(totEarly || '');
        $('#tot-short').text(totShort || '');
    }

    function statusRowClass(s) {
        if (!s) return '';
        if (s === 'P') return 'row-present';
        if (s === 'A') return 'row-absent';
        if (s === 'DF') return 'row-dayoff';
        if (s.startsWith('H')) return 'row-holiday';
        return '';
    }

    function clearTotals() {
        $('#tot-work,#tot-ot,#tot-dot,#tot-late,#tot-early,#tot-short').text('');
    }

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

    // ───── SHIFT AUTO-FILL ─────
    $(document).on('change', '.shift-select', function () {
        let row = $(this).closest('tr');
        let opt = $(this).find('option:selected');
        row.find('.in-time').val(opt.data('start-time'));
        row.find('.out-time').val(opt.data('end-time'));
    });

    // ───── STATUS AUTO-FILL ─────
    $(document).on('change', '.attendance-status', function () {
        let status = $(this).val();
        let row = $(this).closest('tr');
        let opt = row.find('.shift-select option:selected');
        let start = opt.data('start-time'), end = opt.data('end-time');

        if (status === 'P') {
            row.find('.in-time').val(start); row.find('.out-time').val(end);
        } else if (status === 'HP+HA' || status === 'HP+HDF') {
            row.find('.in-time').val(start); row.find('.out-time').val('');
        } else if (status === 'HA+HP' || status === 'HDF+HP') {
            row.find('.in-time').val(''); row.find('.out-time').val(end);
        } else {
            row.find('.in-time').val(''); row.find('.out-time').val('');
        }
    });

    // ───── SAVE ROW ─────
    function saveRowData(row) {
        if (!row.hasClass('is-dirty')) return;
        let id   = row.data('id');
        let date = row.find('.c-date').text().trim();

        let data = {
            id: id,
            shift_id: row.find('.shift-select').val(),
            status: row.find('.attendance-status').val(),
            in_time:  date && row.find('.in-time').val()  ? date + 'T' + row.find('.in-time').val()  : '',
            out_time: date && row.find('.out-time').val() ? date + 'T' + 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 () {
            let val = $(this).val();
            if (val) data.punches.push({ seq: $(this).data('seq'), datetime: date + 'T' + val });
        });

        row.removeClass('is-dirty');
        $.post("{{ route('attendance.updateRow') }}", data)
            .done(function () {
                row.addClass('row-saved');
                setTimeout(() => row.removeClass('row-saved'), 1500);
            })
            .fail(function () { row.addClass('is-dirty'); });
    }

    $(document).on('click', '.btn-save-row', function (e) {
        e.stopPropagation();
        saveRowData($(this).closest('tr'));
    });

    // Auto-save on row leave
    let activeRow = null;
    $(document).on('mousedown focusin', '#attendance-table tbody tr', function () {
        let clicked = $(this);
        if (activeRow && !activeRow.is(clicked) && activeRow.hasClass('is-dirty')) {
            saveRowData(activeRow);
        }
        activeRow = clicked;
    });

    // ───── BULK SELECTION ─────
    $('#select-all').on('change', function () {
        $('.row-check').prop('checked', this.checked);
        updateBulkBar();
    });
    $(document).on('change', '.row-check', updateBulkBar);

    function updateBulkBar() {
        let n = $('.row-check:checked').length;
        $('#selected-count').text(n);
        n > 0 ? $('#bulk-bar').fadeIn(100) : $('#bulk-bar').fadeOut(100);
    }

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

    // ───── BULK SHIFT FILL ─────
    $('#bulk_shift').on('change', function () {
        let opt = $(this).find('option:selected');
        let start = opt.data('start-time'), end = opt.data('end-time');
        let shiftId = $(this).val();
        $('.row-check:checked').each(function () {
            let row = $(this).closest('tr');
            row.find('.shift-select').val(shiftId);
            row.find('.in-time').val(start);
            row.find('.out-time').val(end);
            row.addClass('is-dirty');
        });
    });

    // ───── BULK STATUS FILL ─────
    $('#bulk_status').on('change', function () {
        let status = $(this).val(); if (!status) return;
        $('.row-check:checked').each(function () {
            let row = $(this).closest('tr');
            row.find('.attendance-status').val(status).trigger('change');
            row.addClass('is-dirty');
        });
        $(this).val('');
    });

    // ───── BULK SAVE ─────
    $('#bulk-save-btn').on('click', function () {
        let rowsData = [];
        $('.row-check:checked').each(function () {
            let row  = $(this).closest('tr');
            let id   = $(this).data('id');
            let date = row.find('td.c-date').text().trim();
            let obj = {
                id: id, shift_id: row.find('.shift-select').val(),
                status: row.find('.attendance-status').val(),
                in_time:  date && row.find('.in-time').val()  ? date + 'T' + row.find('.in-time').val()  : '',
                out_time: date && row.find('.out-time').val() ? date + 'T' + 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 () {
                let val = $(this).val();
                if (val) obj.punches.push({ seq: $(this).data('seq'), datetime: date + 'T' + val });
            });
            rowsData.push(obj);
        });

        if (!rowsData.length) return;
        $(this).prop('disabled', true).text('Saving...');

        $.post("{{ route('attendance.bulkUpdate') }}", { rows: rowsData })
            .done(function () {
                Swal.fire('Success', 'Bulk save completed.', 'success');
                $('#bulk-save-btn').prop('disabled', false).text('Bulk Save');
                $('.row-check, #select-all').prop('checked', false);
                updateBulkBar();
                loadData();
            })
            .fail(function () {
                $('#bulk-save-btn').prop('disabled', false).text('Bulk Save');
                Swal.fire('Error', 'Bulk save failed.', 'error');
            });
    });
});
</script>
@endsection
