<?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);

$user_id = isset($input["user_id"]) ? (int) $input["user_id"] : null;
$username = trim($input["username"] ?? "");
$role = trim($input["role"] ?? "");
$aksi = trim($input["aksi"] ?? "");
$target = trim($input["target"] ?? "");
$keterangan = trim($input["keterangan"] ?? "");
$ip_address = $_SERVER["REMOTE_ADDR"] ?? "";

if ($aksi === "") {
    response(false, "Aksi wajib diisi", null);
}

$sql = "
    INSERT INTO audit_log
    (
        user_id,
        username,
        role,
        aksi,
        target,
        keterangan,
        ip_address
    )
    VALUES (?, ?, ?, ?, ?, ?, ?)
";

$stmt = $conn->prepare($sql);

$stmt->bind_param(
    "issssss",
    $user_id,
    $username,
    $role,
    $aksi,
    $target,
    $keterangan,
    $ip_address
);

if ($stmt->execute()) {
    response(true, "Audit log berhasil disimpan", [
        "id" => $stmt->insert_id
    ]);
}

response(false, "Gagal menyimpan audit log", null);

?>