<?php
require_once 'config.php';
$data = json_decode(file_get_contents("php://input"), true);
$ip = $_SERVER['REMOTE_ADDR'];

// Capturar IP real tras proxy si existe
if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; }
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; }

$stmt = $pdo->prepare("INSERT INTO system_logs (user_id, username, role, action, module, ip_address, details) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([
    $_SESSION['user_id'] ?? null,
    $_SESSION['user_name'] ?? 'Invitado',
    $_SESSION['user_role'] ?? 'guest',
    $data['action'],
    $data['module'],
    $ip,
    isset($data['details']) ? json_encode($data['details']) : null
]);
response(["success" => true]);
?>