@extends('layouts.app')

@section('title', 'QR Code Absensi Terintegrasi & Live Monitor')
@section('page-title', 'QR Code Absensi & Live Monitor Real-Time')
@section('page-subtitle', 'QR Code terintegrasi langsung ke sistem presensi. Scan via kamera HP atau browser untuk presensi otomatis.')

@push('styles')
<style>
    .live-dot {
        width: 10px;
        height: 10px;
        background-color: #10b981;
        border-radius: 50%;
        display: inline-block;
        animation: pulseLive 1.5s infinite;
    }
    @keyframes pulseLive {
        0% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); }
        70% { box-shadow: 0 0 0 8px rgba(16, 185, 129, 0); }
        100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
    }
    .qr-card {
        border-radius: 1.25rem;
        transition: all 0.3s ease;
    }
    .feed-item {
        transition: all 0.4s ease;
    }
    .feed-item.new-entry {
        background-color: #ecfdf5 !important;
        border-left: 4px solid #10b981 !important;
    }
    .live-clock-kiosk {
        font-family: 'Courier New', Courier, monospace;
        font-size: 1.3rem;
        font-weight: 800;
        letter-spacing: 2px;
    }
</style>
@endpush

@section('content')
<div class="row">
    {{-- Left Column: Integrated QR Code Cards --}}
    <div class="col-12 col-xl-5 mb-4">
        @forelse($locations as $loc)
            @php
                $scanUrl = $loc->scan_url;
            @endphp
            <div class="card qr-card shadow-sm border-0 mb-4 text-center">
                <div class="card-header bg-white py-3 border-bottom d-flex justify-content-between align-items-center">
                    <div>
                        <span class="badge bg-success bg-opacity-10 text-success px-3 py-1 rounded-pill mb-1">Kantor Resmi</span>
                        <h5 class="fw-bold mb-0 text-dark">{{ $loc->name }}</h5>
                    </div>
                    <div class="badge bg-light-primary text-primary px-3 py-2 live-clock-kiosk" id="liveClock">--:--:--</div>
                </div>
                <div class="card-body p-4 d-flex flex-column align-items-center justify-content-center">
                    {{-- QR Code Image encoding the actual direct system URL --}}
                    <div class="p-3 bg-white border rounded-4 shadow-sm mb-3 d-inline-block" id="qr-container-{{ $loc->id }}">
                        <img src="https://api.qrserver.com/v1/create-qr-code/?size=260x260&data={{ urlencode($scanUrl) }}&margin=10" 
                             alt="QR Code {{ $loc->name }}" 
                             class="img-fluid rounded-3" 
                             style="width: 220px; height: 220px;">
                    </div>

                    <div class="alert alert-light border py-2 px-3 text-start w-100 mb-3 text-xs">
                        <div class="d-flex align-items-center mb-1 text-primary fw-bold">
                            <i class="bi bi-link-45deg fs-5 me-1"></i> URL Terintegrasi Sistem:
                        </div>
                        <div class="font-monospace text-truncate text-muted bg-white p-2 rounded border">
                            {{ $scanUrl }}
                        </div>
                    </div>

                    <div class="bg-light p-3 rounded-3 text-start w-100 mb-3 text-xs">
                        <div class="row g-2">
                            <div class="col-6"><span class="text-muted d-block">Titik Koordinat:</span><strong class="font-monospace">{{ $loc->latitude }}, {{ $loc->longitude }}</strong></div>
                            <div class="col-6"><span class="text-muted d-block">Radius Absensi:</span><span class="badge bg-primary">{{ $loc->radius_meters }} Meter</span></div>
                            <div class="col-6"><span class="text-muted d-block">Max Akurasi GPS:</span><span class="badge bg-secondary">{{ $loc->max_gps_accuracy ?? 30 }} Meter</span></div>
                            <div class="col-6"><span class="text-muted d-block">Sistem Sync:</span><span class="badge bg-success"><i class="bi bi-lightning-charge-fill"></i> Real-Time</span></div>
                        </div>
                    </div>

                    <div class="d-flex gap-2 w-100">
                        <button type="button" class="btn btn-outline-primary btn-sm flex-fill" onclick="printQR('{{ $loc->name }}', '{{ $scanUrl }}', '{{ $loc->radius_meters }}', '{{ $loc->address }}')">
                            <i class="bi bi-printer me-1"></i> Cetak Lembar QR
                        </button>
                        <a href="{{ $scanUrl }}" target="_blank" class="btn btn-outline-success btn-sm flex-fill">
                            <i class="bi bi-box-arrow-up-right me-1"></i> Uji URL Langsung
                        </a>
                    </div>
                </div>
            </div>
        @empty
            <div class="alert alert-warning text-center py-4">
                <i class="bi bi-exclamation-triangle fs-2 d-block mb-2"></i>
                Belum ada lokasi kantor yang aktif.
            </div>
        @endforelse
    </div>

    {{-- Right Column: Live Synchronized Real-Time Attendance Stream --}}
    <div class="col-12 col-xl-7">
        <div class="card shadow-sm border-0 mb-4">
            <div class="card-header bg-white py-3 border-bottom d-flex justify-content-between align-items-center">
                <div class="d-flex align-items-center">
                    <span class="live-dot me-2"></span>
                    <div>
                        <h5 class="fw-bold mb-0 text-dark">Live Stream Presensi Hari Ini</h5>
                        <small class="text-muted">Tersinkronisasi otomatis secara real-time saat karyawan scan</small>
                    </div>
                </div>
                <div class="form-check form-switch mb-0">
                    <input class="form-check-input" type="checkbox" id="soundToggle" checked>
                    <label class="form-check-label text-xs fw-bold" for="soundToggle"><i class="bi bi-volume-up me-1"></i> Suara Notif</label>
                </div>
            </div>

            {{-- Stat Cards --}}
            <div class="card-body border-bottom bg-light py-3">
                <div class="row g-2 text-center">
                    <div class="col-6 col-md-4">
                        <div class="bg-white p-2 rounded-3 border shadow-sm">
                            <span class="text-muted text-xs d-block">TOTAL HADIR</span>
                            <h4 class="fw-bold text-success mb-0" id="statPresent">0</h4>
                        </div>
                    </div>
                    <div class="col-6 col-md-4">
                        <div class="bg-white p-2 rounded-3 border shadow-sm">
                            <span class="text-muted text-xs d-block">TERLAMBAT</span>
                            <h4 class="fw-bold text-warning mb-0" id="statLate">0</h4>
                        </div>
                    </div>
                    <div class="col-12 col-md-4">
                        <div class="bg-white p-2 rounded-3 border shadow-sm">
                            <span class="text-muted text-xs d-block">STATUS SYNC</span>
                            <h6 class="fw-bold text-primary mb-0 mt-1"><i class="bi bi-arrow-repeat spin-sync me-1"></i> Terhubung</h6>
                        </div>
                    </div>
                </div>
            </div>

            {{-- Live Feed List --}}
            <div class="card-body p-0" style="max-height: 520px; overflow-y: auto;">
                <div id="attendanceLiveFeed" class="list-group list-group-flush">
                    <div class="text-center py-5 text-muted" id="emptyNotice">
                        <i class="bi bi-inbox fs-1 d-block mb-2"></i>
                        Menunggu karyawan memindai QR Code hari ini...
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

{{-- Hidden Printable Area --}}
<div id="printArea" class="d-none">
    <div style="text-align: center; font-family: 'Nunito', sans-serif; padding: 40px; border: 4px solid #435ebe; border-radius: 20px; max-width: 600px; margin: 0 auto;">
        <h2 style="color: #435ebe; margin-bottom: 5px; font-weight: 800;">SISTEM ABSENSI KARYAWAN</h2>
        <h4 id="printOfficeName" style="margin-top: 0; color: #333;"></h4>
        <p id="printOfficeAddress" style="color: #666; font-size: 13px; margin-bottom: 20px;"></p>
        
        <div style="margin: 20px 0;">
            <img id="printQrImg" src="" alt="QR Absensi" style="width: 280px; height: 280px; border: 2px solid #ddd; border-radius: 15px; padding: 10px;">
        </div>

        <div style="background: #f8f9fa; padding: 15px; border-radius: 10px; margin: 15px 0; display: inline-block;">
            <span style="font-size: 14px; color: #444;">Batas Radius Absensi GPS: <strong id="printRadius"></strong></span>
        </div>

        <div style="margin-top: 20px; color: #555; font-size: 13px; line-height: 1.6; text-align: left; background: #eef2ff; padding: 15px; border-radius: 10px;">
            <strong>Petunjuk Absensi:</strong><br>
            1. Buka Kamera HP / Google Lens / Menu <strong>Scan QR</strong> pada aplikasi.<br>
            2. Arahkan kamera ke QR Code di atas.<br>
            3. Pastikan <strong>GPS lokasi aktif</strong> agar sistem memverifikasi kehadiran Anda secara otomatis.
        </div>
    </div>
</div>

@push('scripts')
<script>
    let knownAttendanceIds = new Set();
    let isInitialLoad = true;

    // Web Audio Chime on real-time attendance
    function playChime() {
        if (!document.getElementById('soundToggle').checked) return;
        try {
            const ctx = new (window.AudioContext || window.webkitAudioContext)();
            const osc = ctx.createOscillator();
            const gain = ctx.createGain();
            osc.connect(gain);
            gain.connect(ctx.destination);
            osc.frequency.setValueAtTime(587.33, ctx.currentTime); // D5
            osc.frequency.setValueAtTime(880, ctx.currentTime + 0.12); // A5
            gain.gain.setValueAtTime(0.3, ctx.currentTime);
            gain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.4);
            osc.start(ctx.currentTime);
            osc.stop(ctx.currentTime + 0.4);
        } catch(e) {}
    }

    // Live Clock
    function updateClock() {
        const now = new Date();
        const str = now.toTimeString().split(' ')[0];
        const el = document.getElementById('liveClock');
        if (el) el.innerText = str + ' WIB';
    }
    setInterval(updateClock, 1000);
    updateClock();

    // Print QR
    function printQR(name, scanUrl, radius, address) {
        document.getElementById('printOfficeName').innerText = name;
        document.getElementById('printOfficeAddress').innerText = address || 'Area Kantor Resmi';
        document.getElementById('printRadius').innerText = radius + ' Meter';
        document.getElementById('printQrImg').src = 'https://api.qrserver.com/v1/create-qr-code/?size=350x350&data=' + encodeURIComponent(scanUrl) + '&margin=10';

        setTimeout(() => {
            const printContent = document.getElementById('printArea').innerHTML;
            const originalContent = document.body.innerHTML;
            document.body.innerHTML = printContent;
            window.print();
            document.body.innerHTML = originalContent;
            window.location.reload();
        }, 500);
    }

    // Real-Time Live Feed Polling
    function fetchLiveFeed() {
        fetch("{{ route('admin.qr.live-stream') }}")
            .then(res => res.json())
            .then(data => {
                if (!data.success) return;

                document.getElementById('statPresent').innerText = data.stats.total_present;
                document.getElementById('statLate').innerText = data.stats.total_late;

                const feedContainer = document.getElementById('attendanceLiveFeed');
                const emptyNotice = document.getElementById('emptyNotice');

                if (data.attendances.length === 0) {
                    if (emptyNotice) emptyNotice.style.display = 'block';
                    return;
                }

                if (emptyNotice) emptyNotice.style.display = 'none';

                let hasNew = false;
                let html = '';

                data.attendances.forEach(att => {
                    const isNew = !knownAttendanceIds.has(att.id) && !isInitialLoad;
                    if (isNew) hasNew = true;
                    knownAttendanceIds.add(att.id);

                    html += `
                        <div class="list-group-item p-3 feed-item ${isNew ? 'new-entry' : ''}">
                            <div class="d-flex align-items-center justify-content-between">
                                <div class="d-flex align-items-center">
                                    <div class="avatar avatar-md me-3">
                                        <div class="avatar-content bg-primary text-white fs-6 fw-bold" style="width: 42px; height: 42px; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                                            ${att.employee_name.substring(0, 2).toUpperCase()}
                                        </div>
                                    </div>
                                    <div>
                                        <h6 class="fw-bold mb-0 text-dark">${att.employee_name}</h6>
                                        <small class="text-muted">${att.employee_nik} • ${att.department}</small>
                                        <div class="text-xs text-muted mt-1">
                                            <i class="bi bi-geo-alt me-1 text-danger"></i> ${att.office_name} (${att.distance})
                                        </div>
                                    </div>
                                </div>
                                <div class="text-end">
                                    <span class="badge ${att.status_badge} mb-1">${att.status}</span>
                                    <div class="fw-bold font-monospace text-dark text-xs">${att.check_in || '-'}</div>
                                    <small class="text-muted text-xs">${att.updated_at_human}</small>
                                </div>
                            </div>
                        </div>
                    `;
                });

                feedContainer.innerHTML = html;

                if (hasNew) {
                    playChime();
                }

                isInitialLoad = false;
            })
            .catch(err => console.warn('Sync error:', err));
    }

    document.addEventListener('DOMContentLoaded', function() {
        fetchLiveFeed();
        // Poll every 3 seconds for seamless real-time synchronization
        setInterval(fetchLiveFeed, 3000);
    });
</script>
@endpush
@endsection
