<?php
session_start(); // Memulai session

// Jika token CSRF belum ada di session, buat token baru
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); // Menghasilkan token acak
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ambil Foto KTP dengan Kamera</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        body {
            background-color: #f8f9fa;
        }
        .container {
            max-width: 600px;
        }
        .btn-primary {
            background-color: #007bff;
            border-color: #007bff;
        }
        .btn-primary:hover {
            background-color: #0056b3;
            border-color: #0056b3;
        }
        #video {
            width: 100%;
            height: auto;
            border: 2px solid #ddd;
            border-radius: 8px;
        }
        #captureButton {
            display: block;
            width: 100%;
            margin-top: 20px;
            background-color: #28a745;
            border-color: #28a745;
            color: white;
        }
        #loadingSpinner {
            display: none;
            text-align: center;
        }
    </style>
</head>
<body>

<div class="container mt-5 p-4 bg-white rounded shadow-sm">
    <h2 class="text-center mb-4">Ambil Gambar KTP dengan Kamera</h2>
 <!-- Loading Spinner -->
    <div id="loadingSpinner">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
        <p>Memproses gambar, harap tunggu...</p>
    </div>
    <!-- Video Feed dari Kamera -->
    <div class="preview-container">
        <video id="video" autoplay></video>
    </div>

    <!-- Tombol untuk mengambil foto -->
    <button id="captureButton" class="btn btn-success w-100">Ambil Foto</button>

   
</div>

<script>
    // Mengakses kamera belakang secara otomatis saat halaman dimuat
    async function startCamera() {
        try {
            // Meminta izin dan mengakses kamera belakang
            const stream = await navigator.mediaDevices.getUserMedia({
                video: { facingMode: "environment" }
            });

            // Menampilkan video stream dari kamera ke elemen <video>
            const videoElement = document.getElementById("video");
            videoElement.srcObject = stream;
        } catch (error) {
            alert("Gagal mengakses kamera. Pastikan kamera terpasang dan periksa izin akses.");
        }
    }

    // Mengambil snapshot dari video feed saat tombol "Ambil Foto" diklik
    document.getElementById('captureButton').addEventListener('click', function() {
        const video = document.getElementById('video');
        const canvas = document.createElement('canvas');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;

        const context = canvas.getContext('2d');
        context.drawImage(video, 0, 0, canvas.width, canvas.height);

        // Mengonversi gambar yang diambil ke dalam format Data URL (gambar)
        const imageDataUrl = canvas.toDataURL('image/png');

        // Menghentikan video stream setelah mengambil foto
        const stream = video.srcObject;
        const tracks = stream.getTracks();
        tracks.forEach(track => track.stop());

        // Tampilkan loading spinner
        document.getElementById('loadingSpinner').style.display = 'block';
        document.getElementById('captureButton').disabled = true; // Nonaktifkan tombol saat proses berlangsung

        // Kirim gambar ke server untuk diproses OCR
        $.ajax({
            url: 'process_image.php', // Server-side script untuk memproses gambar
            type: 'POST',
            data: {
                image: imageDataUrl,
                csrf_token: '<?php echo $_SESSION["csrf_token"]; ?>' // Token CSRF yang dihasilkan di server
            },
            success: function(response) {
                if (response.success) {
                    // Jika berhasil, arahkan ke halaman berikutnya dengan data hasil OCR
                    window.location.href = 'form-sawit.php?data=' + encodeURIComponent(JSON.stringify(response));
                } else {
                    alert("Gagal memproses gambar.");
                }
            },
            error: function() {
                alert("Terjadi kesalahan saat memproses gambar.");
            },
            complete: function() {
                // Sembunyikan spinner dan aktifkan kembali tombol setelah proses selesai
                document.getElementById('loadingSpinner').style.display = 'none';
                document.getElementById('captureButton').disabled = false;
            }
        });
    });

    // Mulai kamera saat halaman dimuat
    window.onload = startCamera;
</script>

</body>
</html>
