<?php
session_start();

// Pastikan hanya menerima POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(403);
    echo json_encode(["status" => "forbidden"]);
    exit;
}

// Load koneksi
require_once __DIR__ . "/../config/koneksi.php";

// Validasi koneksi
if (!isset($koneksi) || !$koneksi) {
    http_response_code(500);
    echo json_encode(["error" => "DB Connection Failed"]);
    exit;
}

// Data akses
$ip_address  = $_SERVER['REMOTE_ADDR'] ?? "Unknown";
$user_agent  = $_SERVER['HTTP_USER_AGENT'] ?? "Unknown";
$page        = $_SERVER['HTTP_REFERER'] ?? "Unknown";

$date_access = date('Y-m-d');
$time_access = date('H:i:s');

$lat   = isset($_POST['lat']) ? floatval($_POST['lat']) : null;
$lon   = isset($_POST['lon']) ? floatval($_POST['lon']) : null;
$label = $_POST['label'] ?? "Unknown";

// Simpan Data
$stmt = mysqli_prepare($koneksi, "
    INSERT INTO access_log 
    (ip_address, user_agent, page, date_access, time_access, latitude, longitude, location_label) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
");

mysqli_stmt_bind_param(
    $stmt,
    "ssssddss",
    $ip_address,
    $user_agent,
    $page,
    $date_access,
    $time_access,
    $lat,
    $lon,
    $label
);

if (!mysqli_stmt_execute($stmt)) {
    error_log("Execute Error: " . mysqli_stmt_error($stmt));
    echo json_encode(["error" => "Insert Failed"]);
} else {
    echo json_encode(["status" => "success"]);
}

mysqli_stmt_close($stmt);
mysqli_close($koneksi);
