@extends('admin.layouts.app')
@section('title','Staff Attendance')
@section('content')
<div class="page-head">
    <div>
        <h1 class="page-title">Staff Attendance</h1>
        <div class="page-subtitle">NFC check-in/check-out, late detection, overtime, manual correction and live attendance log</div>
    </div>
</div>

@if (session('success'))
    <div class="card panel-tight" style="border-left:4px solid #16a34a; margin-bottom:16px;">
        {{ session('success') }}
    </div>
@endif

@if ($errors->any())
    <div class="card panel-tight" style="border-left:4px solid #dc2626; margin-bottom:16px;">
        @foreach ($errors->all() as $error)
            <div>{{ $error }}</div>
        @endforeach
    </div>
@endif

<div class="card panel-tight" style="margin-bottom:16px; border:1px solid #dbeafe; background:#eff6ff;">
    <div class="page-subtitle" style="margin-bottom:10px; font-weight:700; color:#1d4ed8;">Auto NFC Scan Mode Active</div>
    <div style="font-size:14px; color:#1e3a8a; line-height:1.7;">
        This page stays ready for NFC scan. You do not need to keep the cursor inside the NFC field. Just keep the <strong>Staff Attendance</strong> page open and scan the NFC card/tag.
        The system will automatically detect the UID and save <strong>check-in</strong> or <strong>check-out</strong> based on today's attendance state.
    </div>
    <div id="scanStatusBar" style="margin-top:12px; padding:10px 12px; border-radius:10px; background:#ffffff; border:1px dashed #93c5fd; color:#334155; font-size:14px;">
        Waiting for NFC scan...
    </div>
</div>

<form method="POST" id="autoNfcForm" style="display:none;">
    @csrf
    <input type="hidden" name="action_type" value="auto_nfc_punch">
    <input type="hidden" name="nfc_uid" id="auto_nfc_uid">
    <input type="hidden" name="notes" id="auto_nfc_notes" value="Auto scan from attendance page">
</form>

<div class="grid-3" style="display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:16px; margin-bottom:16px;">
    <div class="card panel-tight">
        <div class="page-subtitle" style="margin-bottom:10px; font-weight:600;">Manual NFC Check-In</div>
        <form method="POST">
            @csrf
            <input type="hidden" name="action_type" value="nfc_check_in">
            <div style="margin-bottom:12px;">
                <label>NFC UID / Tag ID</label>
                <input name="nfc_uid" value="{{ old('nfc_uid') }}" placeholder="Scan or type NFC tag">
            </div>
            <div style="margin-bottom:12px;">
                <label>Notes</label>
                <input name="notes" placeholder="Optional note">
            </div>
            <button class="btn primary" type="submit">Check In</button>
        </form>
    </div>

    <div class="card panel-tight">
        <div class="page-subtitle" style="margin-bottom:10px; font-weight:600;">Manual NFC Check-Out</div>
        <form method="POST">
            @csrf
            <input type="hidden" name="action_type" value="nfc_check_out">
            <div style="margin-bottom:12px;">
                <label>NFC UID / Tag ID</label>
                <input name="nfc_uid" value="{{ old('nfc_uid') }}" placeholder="Scan or type NFC tag">
            </div>
            <div style="margin-bottom:12px;">
                <label>Notes</label>
                <input name="notes" placeholder="Optional note">
            </div>
            <button class="btn primary" type="submit">Check Out</button>
        </form>
    </div>

    <div class="card panel-tight">
        <div class="page-subtitle" style="margin-bottom:10px; font-weight:600;">Holiday Setup</div>
        <form method="POST">
            @csrf
            <input type="hidden" name="action_type" value="save_holiday">
            <div style="margin-bottom:12px;">
                <label>Holiday Date</label>
                <input type="date" name="holiday_date" value="{{ old('holiday_date') }}">
            </div>
            <div style="margin-bottom:12px;">
                <label>Title</label>
                <input name="title" value="{{ old('title') }}" placeholder="Holiday name">
            </div>
            <div style="margin-bottom:12px;">
                <label>Notes</label>
                <input name="notes" value="{{ old('notes') }}" placeholder="Optional notes">
            </div>
            <button class="btn" type="submit">Save Holiday</button>
        </form>
    </div>
</div>

<form method="POST" class="card panel-tight" style="margin-bottom:16px;">
    @csrf
    <input type="hidden" name="action_type" value="manual_update">
    <div class="page-subtitle" style="margin-bottom:12px; font-weight:600;">Manual Attendance Correction / Missed Punch Adjustment</div>
    <div class="grid-4" style="display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:14px;">
        <div>
            <label>Staff</label>
            <select name="staff_id" required>
                <option value="">Select staff</option>
                @foreach($staffs as $staff)
                    <option value="{{ $staff->id }}">{{ $staff->name }} - {{ $staff->employee_code }}</option>
                @endforeach
            </select>
        </div>
        <div>
            <label>Date</label>
            <input type="date" name="attendance_date" value="{{ old('attendance_date', date('Y-m-d')) }}" required>
        </div>
        <div>
            <label>Status</label>
            <select name="status">
                <option value="">Auto Detect</option>
                <option>Present</option>
                <option>Late</option>
                <option>Absent</option>
                <option>Half Day</option>
                <option>Leave</option>
                <option>Holiday</option>
                <option>Weekend</option>
            </select>
        </div>
        <div>
            <label>Missed Punch Adjusted?</label>
            <select name="is_missed_punch_adjusted">
                <option value="0">No</option>
                <option value="1">Yes</option>
            </select>
        </div>
        <div>
            <label>Check In</label>
            <input type="time" name="check_in" value="{{ old('check_in') }}">
        </div>
        <div>
            <label>Check Out</label>
            <input type="time" name="check_out" value="{{ old('check_out') }}">
        </div>
        <div style="grid-column: span 2;">
            <label>Manual Correction Reason</label>
            <input name="manual_reason" value="{{ old('manual_reason') }}" placeholder="Why attendance was manually corrected">
        </div>
        <div style="grid-column: 1 / -1;">
            <label>Notes</label>
            <input name="notes" value="{{ old('notes') }}" placeholder="Additional notes">
        </div>
    </div>
    <div class="form-actions" style="margin-top:14px;">
        <button class="btn primary" type="submit">Save Manual Attendance</button>
    </div>
</form>

<div class="grid-2" style="display:grid; grid-template-columns:2fr 1fr; gap:16px; margin-bottom:16px;">
    <div class="card panel-tight table-wrap">
        <div class="page-subtitle" style="margin-bottom:12px; font-weight:600;">Real-Time Attendance Log (Today)</div>
        <div style="overflow:auto;">
            <table class="table">
                <thead>
                    <tr>
                        <th>Staff</th>
                        <th>Status</th>
                        <th>Check In</th>
                        <th>Check Out</th>
                        <th>Late</th>
                        <th>Early Exit</th>
                        <th>Overtime</th>
                        <th>Updated</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($todayLog as $log)
                        <tr>
                            <td>{{ $log->staff->name ?? 'N/A' }}</td>
                            <td>{{ $log->status }}</td>
                            <td>{{ optional($log->check_in)->format('h:i A') ?: '—' }}</td>
                            <td>{{ optional($log->check_out)->format('h:i A') ?: '—' }}</td>
                            <td>{{ $log->late_minutes ?? 0 }} min</td>
                            <td>{{ $log->early_exit_minutes ?? 0 }} min</td>
                            <td>{{ $log->overtime_minutes ?? 0 }} min</td>
                            <td>{{ optional($log->updated_at)->format('d M, h:i A') }}</td>
                        </tr>
                    @empty
                        <tr><td colspan="8">No attendance log found for today.</td></tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>

    <div class="card panel-tight table-wrap">
        <div class="page-subtitle" style="margin-bottom:12px; font-weight:600;">Holiday List</div>
        <div style="overflow:auto; max-height:360px;">
            <table class="table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Title</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($holidays as $holiday)
                        <tr>
                            <td>{{ optional($holiday->holiday_date)->format('d M Y') }}</td>
                            <td>{{ $holiday->title }}</td>
                        </tr>
                    @empty
                        <tr><td colspan="2">No holiday set yet.</td></tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="card panel-tight table-wrap">
    <div class="page-subtitle" style="margin-bottom:12px; font-weight:600;">Attendance History</div>
    <div style="overflow:auto;">
        <table class="table">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Staff</th>
                    <th>Status</th>
                    <th>Check In</th>
                    <th>Check Out</th>
                    <th>Late</th>
                    <th>Early Exit</th>
                    <th>Overtime</th>
                    <th>NFC</th>
                    <th>Manual</th>
                    <th>Missed Punch</th>
                    <th>Notes</th>
                </tr>
            </thead>
            <tbody>
                @forelse($records as $record)
                    <tr>
                        <td>{{ optional($record->attendance_date)->format('Y-m-d') }}</td>
                        <td>{{ $record->staff->name ?? ('#'.$record->staff_id) }}</td>
                        <td>{{ $record->status }}</td>
                        <td>{{ optional($record->check_in)->format('h:i A') ?: '—' }}</td>
                        <td>{{ optional($record->check_out)->format('h:i A') ?: '—' }}</td>
                        <td>{{ $record->late_minutes ?? 0 }} min</td>
                        <td>{{ $record->early_exit_minutes ?? 0 }} min</td>
                        <td>{{ $record->overtime_minutes ?? 0 }} min</td>
                        <td>{{ $record->nfc_uid ?: '—' }}</td>
                        <td>{{ $record->is_manual ? 'Yes' : 'No' }}</td>
                        <td>{{ $record->is_missed_punch_adjusted ? 'Yes' : 'No' }}</td>
                        <td>{{ $record->notes ?: $record->manual_reason ?: '—' }}</td>
                    </tr>
                @empty
                    <tr><td colspan="12">No records found.</td></tr>
                @endforelse
            </tbody>
        </table>
    </div>
    {{ $records->links() }}
</div>

<script>
    (function () {
        const statusBar = document.getElementById('scanStatusBar');
        const form = document.getElementById('autoNfcForm');
        const uidInput = document.getElementById('auto_nfc_uid');
        const notesInput = document.getElementById('auto_nfc_notes');

        if (!statusBar || !form || !uidInput) {
            return;
        }

        let buffer = '';
        let firstKeyAt = 0;
        let lastKeyAt = 0;
        let clearTimer = null;
        let submitting = false;

        function setStatus(message, type) {
            statusBar.textContent = message;
            statusBar.style.borderStyle = 'dashed';
            statusBar.style.background = '#ffffff';
            statusBar.style.color = '#334155';

            if (type === 'success') {
                statusBar.style.background = '#ecfdf5';
                statusBar.style.color = '#166534';
                statusBar.style.borderStyle = 'solid';
                statusBar.style.borderColor = '#86efac';
            } else if (type === 'error') {
                statusBar.style.background = '#fef2f2';
                statusBar.style.color = '#b91c1c';
                statusBar.style.borderStyle = 'solid';
                statusBar.style.borderColor = '#fca5a5';
            } else if (type === 'scan') {
                statusBar.style.background = '#eff6ff';
                statusBar.style.color = '#1d4ed8';
                statusBar.style.borderStyle = 'solid';
                statusBar.style.borderColor = '#93c5fd';
            }
        }

        function resetBuffer() {
            buffer = '';
            firstKeyAt = 0;
            lastKeyAt = 0;
            if (clearTimer) {
                clearTimeout(clearTimer);
                clearTimer = null;
            }
        }

        function isTypingInManualField(target) {
            if (!target) return false;
            const tag = (target.tagName || '').toLowerCase();
            return tag === 'input' || tag === 'textarea' || tag === 'select' || target.isContentEditable;
        }

        function submitScan(uid) {
            const cleanUid = String(uid || '').trim();
            if (!cleanUid || submitting) {
                return;
            }

            submitting = true;
            uidInput.value = cleanUid;
            notesInput.value = 'Auto scan from attendance page at ' + new Date().toLocaleTimeString();
            setStatus('Scan detected: ' + cleanUid + '. Saving attendance...', 'scan');
            form.submit();
        }

        window.addEventListener('keydown', function (event) {
            if (submitting) {
                return;
            }

            if (event.ctrlKey || event.altKey || event.metaKey) {
                return;
            }

            if (isTypingInManualField(event.target) && event.target.form && event.target.form.id !== 'autoNfcForm') {
                return;
            }

            const key = event.key;

            if (key === 'Shift' || key === 'Control' || key === 'Alt' || key === 'Meta' || key === 'CapsLock' || key === 'Tab') {
                return;
            }

            const now = Date.now();

            if (!firstKeyAt || (lastKeyAt && now - lastKeyAt > 250)) {
                buffer = '';
                firstKeyAt = now;
            }

            lastKeyAt = now;

            if (clearTimer) {
                clearTimeout(clearTimer);
            }

            clearTimer = setTimeout(function () {
                if (!submitting) {
                    setStatus('Waiting for NFC scan...', 'idle');
                }
                resetBuffer();
            }, 350);

            if (key === 'Enter') {
                const scanDuration = now - firstKeyAt;
                const cleanBuffer = buffer.trim();

                if (cleanBuffer.length >= 4 && scanDuration <= 3000) {
                    event.preventDefault();
                    submitScan(cleanBuffer);
                } else {
                    setStatus('Invalid scan detected. Please scan the NFC card/tag again.', 'error');
                }

                resetBuffer();
                return;
            }

            if (key.length === 1) {
                buffer += key;
                setStatus('Reading NFC scan...', 'scan');
            }
        });

        window.addEventListener('focus', function () {
            if (!submitting) {
                setStatus('Waiting for NFC scan...', 'idle');
            }
        });
    })();

    setTimeout(function () {
        window.location.reload();
    }, 30000);
</script>
@endsection
