<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['image'])) {
    // Proses upload gambar dari webcam
    $image = $_POST['image'];
    $image = str_replace('data:image/jpeg;base64,', '', $image);
    $image = str_replace(' ', '+', $image);
    $decodedImage = base64_decode($image);

    // Simpan ke folder
    $target_dir = "uploads/";
    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }

    $filename = uniqid() . ".jpg";
    $filepath = $target_dir . $filename;
    file_put_contents($filepath, $decodedImage);

    // Simpan ke database
    $conn = mysqli_connect("localhost", "u1665228", "niaga1234", "u1665228_student");
    if ($conn->connect_error) {
        die("Koneksi gagal: " . $conn->connect_error);
    }

    $sql = "INSERT INTO data_foto_keren (foto, waktu_upload) VALUES ('$filename', NOW())";
    $conn->query($sql);
    $conn->close();

    echo "Hi eternal success students you have been photographed!";
    exit;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Ambil Foto Keren</title>
    <style>
        video, canvas {
            border: 2px solid black;
            margin-bottom: 10px;
        }
        button {
            padding: 10px 20px;
            font-size: 18px;
        }
        #status {
            font-weight: bold;
            margin-top: 10px;
            color: green;
        }
    </style>
</head>
<body>
    <h2>Ambil Foto Keren HP/Laptop</h2>

    <video id="video" width="800" height="600" autoplay></video><br>
    <button onclick="ambilFoto()">Klik</button><br>
    <audio id="klikSound" src="sponge.mp3"></audio>
    <div id="status"></div>

    <script>
        const video = document.getElementById('video');
        const klikSound = document.getElementById('klikSound');

        // Akses webcam
        navigator.mediaDevices.getUserMedia({ video: true })
            .then(stream => { video.srcObject = stream; })
            .catch(err => alert("Tidak bisa akses webcam: " + err));

        function ambilFoto() {
            klikSound.play();

            const scale = 3;
            const width = 640 * scale;
            const height = 480 * scale;
            const canvas = document.createElement('canvas');
            canvas.width = width;
            canvas.height = height;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(video, 0, 0, width, height);

            const imageData = canvas.toDataURL('image/jpeg');

            const xhr = new XMLHttpRequest();
            xhr.open("POST", "", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    const status = document.getElementById("status");
                    status.innerText = xhr.responseText;

                    // Hapus pesan setelah 3 detik
                    setTimeout(() => {
                        status.innerText = "";
                    }, 3000);
                }
            };
            xhr.send("image=" + encodeURIComponent(imageData));
        }
    </script>
</body>
</html>
