<?php 
session_start();
if (!isset($_SESSION["login"])) {
    header("Location: login.php");
    exit;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Ambil Foto</title>
    <link rel="shortcut icon" href="idea.png">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body { font-family: Arial, sans-serif; padding: 10px; }
        h1 { font-size: 20px; text-align: center; }
        .container { max-width: 800px; margin: auto; text-align: center; }
        video { width: 100%; border: 1px solid #ccc; margin-bottom: 10px; }
        button { margin-top: 10px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Ambil Foto dengan Kamera</h1>
        <video id="video" autoplay></video>
        <br>
        <button id="capture" class="btn btn-primary">Ambil Foto</button>
        <br><br>
        <canvas id="canvas" style="display: none;"></canvas>
        <button id="save" class="btn btn-success" style="display: none;">Simpan Foto</button>
    </div>

    <script>
        // Akses kamera
        const video = document.getElementById('video');
        const captureButton = document.getElementById('capture');
        const saveButton = document.getElementById('save');
        const canvas = document.getElementById('canvas');
        const context = canvas.getContext('2d');

        // Fungsi untuk memulai stream video
        async function startCamera() {
            const stream = await navigator.mediaDevices.getUserMedia({ video: true });
            video.srcObject = stream;
        }

        // Mulai kamera ketika halaman dimuat
        window.onload = startCamera;

        // Ambil foto dari video dan simpan ke canvas
        captureButton.addEventListener('click', function() {
            const width = video.videoWidth;
            const height = video.videoHeight;
            canvas.width = width;
            canvas.height = height;
            context.drawImage(video, 0, 0, width, height);
            saveButton.style.display = 'block';
        });

        // Simpan foto ke localStorage dan tutup jendela setelahnya
        saveButton.addEventListener('click', function() {
            const fotoData = canvas.toDataURL('image/png'); // Mengambil data gambar dalam format Base64
            localStorage.setItem('foto_data', fotoData); // Simpan foto pertama ke localStorage
            alert("Foto berhasil disimpan!");
            window.opener.location.reload(); // Memuat ulang halaman sebelumnya (tambah.php)
            window.close(); // Tutup jendela foto
        });
    </script>
</body>
</html>
