<?php $__env->startSection('title', 'Verifikasi Presensi QR Terintegrasi'); ?>
<?php $__env->startSection('page-title', 'Konfirmasi Presensi QR'); ?>
<?php $__env->startSection('page-subtitle', 'Sistem sedang memverifikasi lokasi GPS dan profil kepegawaian Anda...'); ?>

<?php $__env->startPush('styles'); ?>
<style>
    .direct-card {
        border-radius: 1.5rem;
        box-shadow: 0 15px 35px rgba(0, 0, 0, 0.08);
        border: none;
        overflow: hidden;
    }
    .radar-indicator {
        display: inline-block;
        width: 12px;
        height: 12px;
        border-radius: 50%;
        animation: pulseRadar 1.5s infinite;
    }
    @keyframes pulseRadar {
        0% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); }
        70% { box-shadow: 0 0 0 10px rgba(16, 185, 129, 0); }
        100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
    }
    .profile-card-header {
        background: linear-gradient(135deg, #435ebe 0%, #25396f 100%);
    }
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
<div class="row justify-content-center">
    <div class="col-12 col-md-8 col-lg-6">
        <div class="card direct-card bg-white">
            
            <div class="profile-card-header p-4 text-white text-center">
                <div class="avatar avatar-xl mx-auto mb-3 shadow">
                    <?php if($employee->photo): ?>
                        <img src="<?php echo e(asset($employee->photo)); ?>" alt="<?php echo e($employee->name); ?>" style="width: 70px; height: 70px; border-radius: 50%; object-fit: cover; border: 3px solid #ffffff;">
                    <?php else: ?>
                        <div class="bg-white text-primary fs-3 fw-bold rounded-circle mx-auto d-flex align-items-center justify-content-center" style="width: 70px; height: 70px;">
                            <?php echo e(strtoupper(substr($employee->name, 0, 2))); ?>

                        </div>
                    <?php endif; ?>
                </div>
                <h4 class="fw-bold text-white mb-1"><?php echo e($employee->name); ?></h4>
                <p class="text-white-50 text-sm mb-2"><?php echo e($employee->nik); ?> • <?php echo e($employee->department?->name ?? 'Staff'); ?></p>
                <span class="badge bg-light text-dark px-3 py-1 rounded-pill text-xs">
                    <i class="bi bi-geo-alt-fill text-danger me-1"></i> <?php echo e($office->name); ?>

                </span>
            </div>

            <div class="card-body p-4">
                
                <div class="text-center mb-4">
                    <?php if(!$attendance || !$attendance->check_in): ?>
                        <span class="badge bg-success px-4 py-2 fs-6 rounded-pill">
                            <i class="bi bi-box-arrow-in-right me-1"></i> Presensi Masuk (Check-In)
                        </span>
                    <?php elseif(!$attendance->check_out): ?>
                        <span class="badge bg-danger px-4 py-2 fs-6 rounded-pill">
                            <i class="bi bi-box-arrow-right me-1"></i> Presensi Pulang (Check-Out)
                        </span>
                    <?php else: ?>
                        <span class="badge bg-info px-4 py-2 fs-6 rounded-pill">
                            <i class="bi bi-check2-all me-1"></i> Presensi Hari Ini Sudah Lengkap
                        </span>
                    <?php endif; ?>
                </div>

                
                <div class="bg-light p-3 rounded-4 mb-4 border">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <span class="fw-bold text-xs text-uppercase text-muted">
                            <i class="bi bi-broadcast text-primary me-1"></i> Verifikasi Lokasi GPS
                        </span>
                        <span id="gpsStatusBadge" class="badge bg-warning text-dark">
                            <span class="radar-indicator bg-warning me-1"></span> Mengambil Koordinat...
                        </span>
                    </div>

                    <div class="row g-2 text-xs">
                        <div class="col-6">
                            <span class="text-muted d-block">Jarak ke Kantor:</span>
                            <strong id="gpsDistance" class="text-dark fs-6">Menghitung...</strong>
                        </div>
                        <div class="col-6">
                            <span class="text-muted d-block">Akurasi GPS HP:</span>
                            <strong id="gpsAccuracy" class="text-dark fs-6">Menghitung...</strong>
                        </div>
                        <div class="col-6">
                            <span class="text-muted d-block">Batas Radius:</span>
                            <span class="badge bg-primary"><?php echo e($office->radius_meters); ?> Meter</span>
                        </div>
                        <div class="col-6">
                            <span class="text-muted d-block">Max Toleransi Akurasi:</span>
                            <span class="badge bg-secondary"><?php echo e($office->max_gps_accuracy ?? 30); ?> Meter</span>
                        </div>
                    </div>
                </div>

                
                <div class="d-grid gap-2">
                    <button type="button" class="btn btn-primary btn-lg fw-bold py-3 shadow" id="btnSubmitAttendance" onclick="processAttendance()" disabled>
                        <span class="spinner-border spinner-border-sm me-2" role="status" id="btnSpinner"></span>
                        <span id="btnText">Memvalidasi Koordinat GPS...</span>
                    </button>
                    <a href="<?php echo e(route('employee.dashboard')); ?>" class="btn btn-outline-secondary btn-sm mt-2">
                        <i class="bi bi-arrow-left me-1"></i> Batalkan & Kembali ke Dashboard
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
    let userCoords = null;
    const officeLat = <?php echo e($office->latitude); ?>;
    const officeLng = <?php echo e($office->longitude); ?>;
    const officeRadius = <?php echo e($office->radius_meters); ?>;
    const maxAccuracy = <?php echo e($office->max_gps_accuracy ?? 30); ?>;
    const officeId = <?php echo e($office->id); ?>;
    const qrPayload = "<?php echo e($office->id); ?>";

    function calculateDistance(lat1, lon1, lat2, lon2) {
        const R = 6371000;
        const dLat = (lat2 - lat1) * Math.PI / 180;
        const dLon = (lon2 - lon1) * Math.PI / 180;
        const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                  Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
                  Math.sin(dLon / 2) * Math.sin(dLon / 2);
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        return Math.round(R * c * 10) / 10;
    }

    let directWatchId = null;

    function initGPS() {
        if (!navigator.geolocation) {
            updateGPSStatus('error', 'Browser tidak mendukung GPS');
            return;
        }

        const geoOptions = {
            enableHighAccuracy: true,
            timeout: 15000,
            maximumAge: 0
        };

        const handleSuccess = (pos) => {
            const lat = pos.coords.latitude;
            const lng = pos.coords.longitude;
            const acc = pos.coords.accuracy;
            const dist = calculateDistance(lat, lng, officeLat, officeLng);

            userCoords = { lat, lng, acc, dist };

            document.getElementById('gpsDistance').innerText = dist + ' Meter';
            document.getElementById('gpsAccuracy').innerText = '±' + Math.round(acc) + ' Meter';

            const badge = document.getElementById('gpsStatusBadge');
            const btn = document.getElementById('btnSubmitAttendance');
            const btnSpinner = document.getElementById('btnSpinner');
            const btnText = document.getElementById('btnText');

            if (btnSpinner) btnSpinner.classList.add('d-none');

            if (dist <= officeRadius && acc <= maxAccuracy) {
                badge.className = 'badge bg-success';
                badge.innerHTML = '<span class="radar-indicator bg-white me-1"></span> Lokasi Valid & Dalam Radius';
                btn.disabled = false;
                btn.className = 'btn btn-success btn-lg fw-bold py-3 shadow';
                btnText.innerHTML = '<i class="bi bi-check-circle-fill me-2"></i> Konfirmasi Presensi Sekarang';
                
                // Auto submit automatically for seamless instant scan experience
                processAttendance();
            } else if (dist > officeRadius) {
                badge.className = 'badge bg-danger';
                badge.innerHTML = '<i class="bi bi-x-circle me-1"></i> Di Luar Radius (' + dist + 'm > ' + officeRadius + 'm)';
                btn.disabled = true;
                btn.className = 'btn btn-danger btn-lg fw-bold py-3';
                btnText.innerHTML = '<i class="bi bi-exclamation-octagon me-2"></i> Di Luar Radius Kantor';
            } else {
                // Jarak OK tapi akurasi GPS belum optimal (laptop/WiFi) — izinkan konfirmasi
                badge.className = 'badge bg-warning text-dark';
                badge.innerHTML = '<i class="bi bi-exclamation-triangle me-1"></i> Akurasi GPS ±' + Math.round(acc) + 'm (Jarak: ' + dist + 'm)';
                btn.disabled = false;
                btn.className = 'btn btn-warning btn-lg fw-bold py-3 text-dark shadow';
                btnText.innerHTML = '<i class="bi bi-send-check me-2"></i> Kirim Presensi Sekarang';
            }
        };

        const handleError = (err) => {
            console.warn('Direct Scan GPS Error:', err);
            updateGPSStatus('error', 'Izin GPS Ditolak / Tidak Terdeteksi');
        };

        navigator.geolocation.getCurrentPosition(handleSuccess, handleError, geoOptions);

        if (directWatchId !== null) {
            navigator.geolocation.clearWatch(directWatchId);
        }
        directWatchId = navigator.geolocation.watchPosition(handleSuccess, handleError, geoOptions);
    }

    function updateGPSStatus(type, msg) {
        const badge = document.getElementById('gpsStatusBadge');
        if (badge) {
            badge.className = 'badge bg-danger';
            badge.innerHTML = '<i class="bi bi-geo-alt-slash me-1"></i> ' + msg;
        }
        const spinner = document.getElementById('btnSpinner');
        if (spinner) spinner.classList.add('d-none');
        const btnText = document.getElementById('btnText');
        if (btnText) btnText.innerText = 'GPS Diperlukan';
    }

    function processAttendance() {
        if (!userCoords) return;

        Swal.fire({
            title: 'Memproses Presensi...',
            text: 'Menyinkronkan data kehadiran ke server secara real-time...',
            allowOutsideClick: false,
            didOpen: () => Swal.showLoading()
        });

        fetch("<?php echo e(route('employee.attendance.scan-qr.post')); ?>", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-CSRF-TOKEN": "<?php echo e(csrf_token()); ?>",
                "Accept": "application/json"
            },
            body: JSON.stringify({
                qr_code: String(officeId),
                latitude: userCoords.lat,
                longitude: userCoords.lng,
                accuracy: userCoords.acc
            })
        })
        .then(res => res.json().then(data => ({ status: res.status, ok: res.ok, body: data })))
        .then(res => {
            if (res.ok && res.body.success) {
                const d = res.body.data;
                const emp = d.employee;

                Swal.fire({
                    icon: 'success',
                    title: res.body.type === 'check_in' ? 'Absensi Masuk Berhasil!' : 'Absensi Pulang Berhasil!',
                    html: `
                        <div class="card border shadow-sm p-3 text-start mt-2 bg-light">
                            <div class="d-flex align-items-center mb-2 pb-2 border-bottom">
                                <div class="avatar avatar-md bg-primary text-white rounded-circle me-2 d-flex align-items-center justify-content-center" style="width: 42px; height: 42px; font-weight: bold;">
                                    ${emp.name.substring(0, 2).toUpperCase()}
                                </div>
                                <div>
                                    <h6 class="fw-bold mb-0">${emp.name}</h6>
                                    <small class="text-muted">${emp.nik} • ${emp.department}</small>
                                </div>
                            </div>
                            <div class="row g-1 text-xs">
                                <div class="col-6 text-muted">Waktu Presensi:</div>
                                <div class="col-6 fw-bold text-end text-dark">${d.time}</div>
                                <div class="col-6 text-muted">Status:</div>
                                <div class="col-6 text-end"><span class="badge ${d.status_badge}">${d.status}</span></div>
                                <div class="col-6 text-muted">Lokasi Kantor:</div>
                                <div class="col-6 text-end text-dark">${d.office_name} (${d.distance}m)</div>
                                <div class="col-6 text-muted">Akurasi GPS:</div>
                                <div class="col-6 text-end text-dark">±${d.accuracy} meter</div>
                            </div>
                        </div>
                    `,
                    confirmButtonText: 'Selesai & Ke Dashboard',
                    confirmButtonColor: '#435ebe'
                }).then(() => {
                    window.location.href = "<?php echo e(route('employee.dashboard')); ?>";
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Absensi Ditolak',
                    text: res.body.message || 'Presensi gagal diproses.',
                    confirmButtonColor: '#dc3545',
                    confirmButtonText: 'Tutup'
                });
            }
        })
        .catch(err => {
            Swal.fire('Error Jaringan', 'Gagal menghubungi server.', 'error');
        });
    }

    document.addEventListener('DOMContentLoaded', initGPS);
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\absensi\resources\views/employee/attendance/direct_scan.blade.php ENDPATH**/ ?>