<?php
require_once(__DIR__.'/../config.php');

/**
 * REGISTRO DE AUDITORÍA SGPPBN
 */
function audit_log($action, $entity, $entity_id = null, $details = null){
    global $_settings, $conn;

    // Validar sesión
    if(!isset($_settings) || !$_settings->userdata('id')){
        return;
    }

    $user_id  = $_settings->userdata('id');
    $role     = $_settings->userdata('role');
    $ip       = $_SERVER['REMOTE_ADDR'] ?? 'N/A';

    $stmt = $conn->prepare("
        INSERT INTO audit_log
        (user_id, user_role, action, entity, entity_id, details, ip_address)
        VALUES (?,?,?,?,?,?,?)
    ");

    if(!$stmt){
        // No romper el sistema si falla auditoría
        return;
    }

    $stmt->bind_param(
        "isssiss",
        $user_id,
        $role,
        $action,
        $entity,
        $entity_id,
        $details,
        $ip
    );

    $stmt->execute();
}
