<?php
session_start();
include 'config.php';

$user_id = $_SESSION['user_id'];
$tanggal = date('Y-m-d');
$jam = date('H:i:s');

if(isset($_POST['foto'])) {

    $foto = $_POST['foto'];

    $foto = str_replace('data:image/png;base64,', '', $foto);
    $foto = str_replace(' ', '+', $foto);

    $data = base64_decode($foto);

    $namaFile = 'pulang_' . time() . '.png';

    file_put_contents('uploads/' . $namaFile, $data);

    mysqli_query($conn, "
        UPDATE absensi
        SET
        jam_pulang='$jam',
        foto_pulang='$namaFile'
        WHERE user_id='$user_id'
        AND tanggal='$tanggal'
    ");

    echo "
    <script>
        alert('Absen pulang berhasil');
        window.location='dashboard.php';
    </script>
    ";
}
?>

<h2>Absen Pulang + Foto</h2>

<video id="video" width="300" autoplay></video>
<br><br>

<canvas id="canvas" style="display:none;"></canvas>

<form method="POST">

    <input type="hidden" name="foto" id="foto">

    <button type="button" onclick="ambilFoto()">
        Ambil Foto
    </button>

    <button type="submit">
        Absen Pulang
    </button>

</form>

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

navigator.mediaDevices.getUserMedia({
    video: true
})
.then(stream => {
    video.srcObject = stream;
});

function ambilFoto() {

    const canvas = document.getElementById('canvas');

    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;

    const ctx = canvas.getContext('2d');

    ctx.drawImage(video, 0, 0);

    const image = canvas.toDataURL('image/png');

    document.getElementById('foto').value = image;

    alert('Foto berhasil diambil');
}
</script>