<?php
require_once 'config.php';

// Asegurar Zona Horaria antes de cualquier inserci¨Žn
date_default_timezone_set('America/Caracas');

if (!isset($_SESSION['user_id'])) response(["error" => "No autorizado"], 401);

$data = json_decode(file_get_contents("php://input"), true);
if (!$data || !isset($data['action'])) response(["error" => "Acci¨Žn no definida"], 400);

try {
    // Captura de IP real considerando proxys
    $ip = $_SERVER['REMOTE_ADDR'];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; }

    $stmt = $pdo->prepare("INSERT INTO system_logs 
        (user_id, user_name, role, ip_address, action, details, created_at) 
        VALUES (?, ?, ?, ?, ?, ?, ?)");
    
    // Generamos el timestamp local America/Caracas para la base de datos
    $localTime = date('Y-m-d H:i:s');

    $stmt->execute([
        $_SESSION['user_id'],
        $_SESSION['user_name'],
        $_SESSION['user_role'],
        $ip,
        $data['action'],
        $data['details'] ?? '',
        $localTime
    ]);

    response(["success" => true, "timestamp" => $localTime]);
} catch (PDOException $e) {
    response(["error" => $e->getMessage()], 500);
}
?>