<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/helpers.php';

$pdo = getConnection();

try {
    $where = [];
    $params = [];

    if (!empty($_GET['usuario_id'])) {
        $where[] = "a.usuario_id = ?";
        $params[] = (int)$_GET['usuario_id'];
    }
    if (!empty($_GET['modulo'])) {
        $where[] = "a.modulo = ?";
        $params[] = $_GET['modulo'];
    }
    if (!empty($_GET['accion'])) {
        $where[] = "a.accion LIKE ?";
        $params[] = '%' . $_GET['accion'] . '%';
    }
    if (!empty($_GET['fecha_desde'])) {
        $where[] = "DATE(a.created_at) >= ?";
        $params[] = $_GET['fecha_desde'];
    }
    if (!empty($_GET['fecha_hasta'])) {
        $where[] = "DATE(a.created_at) <= ?";
        $params[] = $_GET['fecha_hasta'];
    }
    if (!empty($_GET['search'])) {
        $s = '%' . $_GET['search'] . '%';
        $where[] = "(a.detalle LIKE ? OR a.usuario_nombre LIKE ? OR a.accion LIKE ?)";
        $params[] = $s; $params[] = $s; $params[] = $s;
    }

    $wc = count($where) ? 'WHERE ' . implode(' AND ', $where) : '';

    // Count
    $countSt = $pdo->prepare("SELECT COUNT(*) FROM auditoria_log a $wc");
    $countSt->execute($params);
    $total = (int)$countSt->fetchColumn();

    // Page
    $page = max(1, (int)($_GET['page'] ?? 1));
    $limit = min(200, max(10, (int)($_GET['limit'] ?? 100)));
    $offset = ($page - 1) * $limit;

    $sql = "SELECT a.id, a.usuario_id, a.usuario_nombre, a.modulo, a.accion,
                   a.tabla_afectada, a.registro_id, a.detalle, a.ip_address, a.created_at
            FROM auditoria_log a
            $wc
            ORDER BY a.created_at DESC
            LIMIT $limit OFFSET $offset";
    $st = $pdo->prepare($sql);
    $st->execute($params);
    $rows = $st->fetchAll(PDO::FETCH_ASSOC);

    // Módulos únicos para el filtro
    $mods = $pdo->query("SELECT DISTINCT modulo FROM auditoria_log ORDER BY modulo")->fetchAll(PDO::FETCH_COLUMN);
    // Usuarios únicos
    $users = $pdo->query("SELECT DISTINCT usuario_id, usuario_nombre FROM auditoria_log GROUP BY usuario_id ORDER BY usuario_nombre")->fetchAll();

    json_success([
        'rows' => $rows,
        'total' => $total,
        'page' => $page,
        'pages' => max(1, ceil($total / $limit)),
        'modulos' => $mods,
        'usuarios' => $users
    ]);
} catch (Exception $e) {
    json_error('Error: ' . $e->getMessage());
}
