<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Absen Selfie & Lokasi</title>
    <meta name="csrf-token" content="{{ csrf_token() }}"> 
    <style>
        body { font-family: sans-serif; text-align: center; margin-top: 50px; }
        #webcam { border: 2px solid #ccc; border-radius: 8px; width: 100%; max-width: 400px; }
        button { padding: 15px 30px; font-size: 16px; background-color: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; margin-top: 15px; }
    </style>
</head>
<body>

    <h2>Absen Harian Guru</h2>
    <p>Pastikan wajah terlihat jelas dan GPS aktif.</p>

    <div>
        <video id="webcam" autoplay playsinline></video>
        <canvas id="canvas" style="display:none;"></canvas>
    </div>

    <button id="btn-absen" onclick="prosesAbsen()">📸 Ambil Foto & Absen</button>

    <script>
        const video = document.getElementById('webcam');
        const canvas = document.getElementById('canvas');
        const btnAbsen = document.getElementById('btn-absen');

        // Nyalakan Web Cam Otomatis
        navigator.mediaDevices.getUserMedia({ video: { facingMode: "user" } })
            .then(stream => { video.srcObject = stream; })
            .catch(err => { alert("Kamera tidak dapat diakses. Mohon beri izin browser!"); });

        function prosesAbsen() {
            btnAbsen.innerHTML = "Memproses...";
            btnAbsen.disabled = true;

            // 1. Minta Lokasi GPS
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(kirimDataKeLaravel, function(error) {
                    alert("Gagal mendapatkan lokasi. Pastikan GPS HP/Laptop menyala.");
                    btnAbsen.innerHTML = "📸 Ambil Foto & Absen";
                    btnAbsen.disabled = false;
                });
            } else {
                alert("Browser ini tidak mendukung GPS.");
            }
        }

        function kirimDataKeLaravel(position) {
            let lat = position.coords.latitude;
            let lng = position.coords.longitude;

            // 2. Ambil Gambar dari Video (Snapshot)
            const context = canvas.getContext('2d');
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            context.drawImage(video, 0, 0, canvas.width, canvas.height);
            let fotoBase64 = canvas.toDataURL('image/jpeg'); // Format Base64

            // 3. Kirim via Fetch API ke Controller Laravel
            fetch("{{ route('absen.store') }}", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                body: JSON.stringify({
                    foto: fotoBase64,
                    latitude: lat,
                    longitude: lng
                })
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                if(data.success) {
                    window.location.reload(); // Refresh halaman jika sukses
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert("Terjadi kesalahan sistem saat absen.");
                btnAbsen.innerHTML = "📸 Ambil Foto & Absen";
                btnAbsen.disabled = false;
            });
        }
    </script>
</body>
</html>