<?php
session_start();
require_once '../config/database.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = $_SESSION['user_id'];
    $type = $_POST['type'];
    $img = $_POST['image'];
    $lat = $_POST['lat'] ?? null; // Tangkap data Latitude
    $lng = $_POST['lng'] ?? null; // Tangkap data Longitude

    // 1. Olah Base64 Gambar
    $img = str_replace('data:image/jpeg;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);

    // 2. Buat Nama File Unik
    $filename = "absent_" . $type . "_" . $user_id . "_" . time() . ".jpg";
    $filepath = "../assets/img/attendance/" . $filename;

    try {
        // Simpan file fisik
        if (file_put_contents($filepath, $data)) {
            // Simpan ke database (Sekarang pakai Latitude & Longitude)
            $stmt = $pdo->prepare("INSERT INTO attendance (user_id, type, photo, latitude, longitude, attendance_time) VALUES (?, ?, ?, ?, ?, NOW())");
            $stmt->execute([$user_id, $type, $filename, $lat, $lng]);

            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Gagal simpan gambar ke server.']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}