<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") exit;

require "../../config/database.php";
require "../../helpers/response.php";

$input = json_decode(file_get_contents("php://input"), true);
$visitorId = trim($input["visitor_id"] ?? "");
$pageUrl = trim($input["page_url"] ?? "/");
$role = trim($input["role"] ?? "publik");

$allowedRoles = ["publik", "admin", "sppg", "validator", "pemerintah"];

if ($visitorId === "") response(false, "Visitor ID tidak valid", null);
if (!in_array($role, $allowedRoles)) $role = "publik";
if ($pageUrl === "") $pageUrl = "/";
if (strlen($pageUrl) > 255) $pageUrl = substr($pageUrl, 0, 255);

$ipAddress = $_SERVER["REMOTE_ADDR"] ?? "";
$userAgent = $_SERVER["HTTP_USER_AGENT"] ?? "";

$sql = "INSERT INTO visitor_logs (visitor_id, role, page_url, ip_address, user_agent, created_at, last_active)
        VALUES (?, ?, ?, ?, ?, NOW(), NOW())";
$stmt = $conn->prepare($sql);
if (!$stmt) response(false, "Query gagal disiapkan", null);

$stmt->bind_param("sssss", $visitorId, $role, $pageUrl, $ipAddress, $userAgent);
if (!$stmt->execute()) response(false, "Gagal menyimpan data pengunjung", null);

response(true, "Data pengunjung berhasil dicatat", [
  "visitor_id" => $visitorId,
  "role" => $role,
  "page_url" => $pageUrl
]);
?>
