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

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

<!DOCTYPE html>
<html>
<head>
    <title>Absen Masuk</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container mt-4">

<h4>Absen Masuk</h4>

<form method="post" enctype="multipart/form-data">
    
    <!-- Lokasi -->
    <label class="form-label">Lokasi Absensi</label>
    <select name="lokasi" class="form-select mb-3" required>
        <option value="">-- Pilih Lokasi --</option>
        <option value="Kantor Pusat">Kantor Pusat</option>
        <option value="Gudang">Gudang</option>
        <option value="Cabang A">Cabang A</option>
        <option value="Cabang B">Cabang B</option>
        <option value="WFH">WFH</option>
    </select>

    <!-- Kamera -->
    <label class="form-label">Foto Absensi</label><br>
    <video id="video" width="300" autoplay></video><br><br>
    <button type="button" class="btn btn-warning" onclick="takePhoto()">Ambil Foto</button>

    <canvas id="canvas" style="display:none;"></canvas>
    <input type="hidden" name="foto" id="foto">

    <br><br>
    <button type="submit" name="simpan" class="btn btn-success">
        Simpan Absensi
    </button>
</form>

<script>
const video = document.getElementById("video");
navigator.mediaDevices.getUserMedia({ video: true })
    .then(stream => video.srcObject = stream);

function takePhoto() {
    const canvas = document.getElementById("canvas");
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    canvas.getContext("2d").drawImage(video, 0, 0);
    document.getElementById("foto").value = canvas.toDataURL("image/png");
    alert("Foto berhasil diambil");
}
</script>

</body>
</html>

<?php
if (isset($_POST['simpan'])) {
    $user_id = $_SESSION['user_id'];
    $tanggal = date('Y-m-d');
    $jam = date('H:i:s');
    $lokasi = $_POST['lokasi'];

    // Simpan foto
    $foto_base64 = $_POST['foto'];
    $foto_base64 = str_replace('data:image/png;base64,', '', $foto_base64);
    $foto_base64 = str_replace(' ', '+', $foto_base64);
    $data = base64_decode($foto_base64);

    $nama_foto = 'foto_' . time() . '.png';
    file_put_contents("uploads/" . $nama_foto, $data);

    mysqli_query($conn, "INSERT INTO absensi 
        (user_id, tanggal, jam_masuk, status, lokasi, foto)
        VALUES 
        ('$user_id','$tanggal','$jam','Hadir','$lokasi','$nama_foto')
    ");

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