<?php
require_once '../../includes/auth_middleware.php';
require_once '../../config/database.php';
require_once '../../includes/header.php';
checkRole(['staff', 'admin']);

$stmt = $pdo->prepare("SELECT type FROM attendance WHERE user_id = ? AND DATE(attendance_time) = CURDATE() ORDER BY attendance_time DESC LIMIT 1");
$stmt->execute([$_SESSION['user_id']]);
$last_absent = $stmt->fetch();

$status_teks = "Belum Absen Hari Ini";
$next_type = "in"; 

if ($last_absent) {
    if ($last_absent['type'] == 'in') {
        $status_teks = "Sudah Absen Masuk (Siap Jualan)";
        $next_type = "out";
    } else {
        $status_teks = "Sudah Absen Keluar (Shift Selesai)";
        $next_type = "done";
    }
}
?>

<div class="container" style="max-width: 500px; text-align: center;">
    <header style="margin-bottom: 1.5rem;">
        <h2 style="margin:0;">ABSENSI SELFIE & GPS</h2>
        <p style="color: #6b7280; margin:0;"><?= $status_teks ?></p>
    </header>

    <?php if ($next_type != 'done'): ?>
        <div class="card" style="padding: 10px; background: #000; border-radius: 15px; overflow: hidden; position: relative;">
            <video id="video" width="100%" autoplay playsinline style="border-radius: 10px; transform: scaleX(-1);"></video>
            <canvas id="canvas" style="display:none;"></canvas>
            
            <div style="margin-top: 15px;">
                <button type="button" onclick="startAbsen()" id="btn-absen" class="btn-primary" style="width: 100%; padding: 15px; font-size: 1.1rem; background: <?= $next_type == 'in' ? '#10b981' : '#ef4444' ?>;">
                    📸 KLIK: ABSEN <?= strtoupper($next_type == 'in' ? 'MASUK' : 'KELUAR') ?>
                </button>
            </div>
        </div>
        <p style="font-size: 0.8rem; color: #6b7280; margin-top: 10px;">*Pastikan fitur GPS/Lokasi di HP Anda menyala.</p>
    <?php else: ?>
        <div class="card" style="background: #f3f4f6; color: #6b7280; padding: 40px;">
            🎉 Tugas hari ini selesai. Sampai jumpa besok!
        </div>
    <?php endif; ?>

    <a href="production_input.php" style="display: block; margin-top: 20px; color: #3b82f6; text-decoration: none; font-weight: bold;">← Kembali ke Input Jualan</a>
</div>

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

// 1. Aktifkan Kamera
navigator.mediaDevices.getUserMedia({ video: { facingMode: "user" }, audio: false })
    .then(stream => { video.srcObject = stream; })
    .catch(err => { alert("Gagal akses kamera: " + err); });

// 2. Fungsi Utama: Cek GPS dulu, baru jepret foto
function startAbsen() {
    if (!navigator.geolocation) {
        alert("Browser Anda tidak mendukung fitur lokasi GPS.");
        return;
    }

    btnAbsen.disabled = true;
    btnAbsen.innerHTML = "📍 Mencari Lokasi GPS...";

    // Ambil titik koordinat akurasi tinggi
    navigator.geolocation.getCurrentPosition(
        (position) => {
            const lat = position.coords.latitude;
            const lng = position.coords.longitude;
            kirimDataAbsen(lat, lng);
        },
        (error) => {
            alert("GAGAL: Mohon izinkan akses Lokasi (GPS) pada browser Anda untuk bisa absen!");
            btnAbsen.disabled = false;
            btnAbsen.innerHTML = "📸 COBA LAGI";
        },
        { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 }
    );
}

// 3. Jepret Foto dan Kirim ke API bersama Data GPS
function kirimDataAbsen(lat, lng) {
    btnAbsen.innerHTML = "⏳ Mengirim Data & Foto...";

    const context = canvas.getContext('2d');
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    
    context.translate(canvas.width, 0);
    context.scale(-1, 1);
    context.drawImage(video, 0, 0, canvas.width, canvas.height);
    
    const imageData = canvas.toDataURL('image/jpeg');

    fetch('../../api/submit_attendance.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'image=' + encodeURIComponent(imageData) + '&type=<?= $next_type ?>&lat=' + lat + '&lng=' + lng
    })
    .then(res => res.json())
    .then(data => {
        if(data.success) {
            alert("Absensi & Lokasi Berhasil Tersimpan!");
            location.reload();
        } else {
            alert("Gagal: " + data.message);
            btnAbsen.disabled = false;
            btnAbsen.innerHTML = "📸 COBA LAGI";
        }
    });
}
</script>