<?php

// /admin/api/user_logs.php
// Admin-only (roleId=1) endpoint to view editor activity logs.

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

// IMPORTANT: this is a JSON endpoint. Do not redirect to HTML login.
$user = $_SESSION['user'] ?? null;
if (!is_array($user)) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Sesión expirada. Inicia sesión nuevamente.']);
    exit;
}

$roleId = is_array($user) && isset($user['roleId']) ? (int)$user['roleId'] : 0;
if ($roleId !== 1) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'No autorizado']);
    exit;
}

require_once __DIR__ . '/../../db/db.php';
if (!isset($conn) || !($conn instanceof mysqli)) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'No hay conexión a base de datos']);
    exit;
}

$action = isset($_GET['action']) ? (string)$_GET['action'] : '';

if ($action === 'meta') {
    $sections = [];
    $events = [];
    $users = [];

    $r1 = $conn->query('SELECT DISTINCT section FROM tb_usuarios_admin_log ORDER BY section');
    if ($r1) {
        while ($row = $r1->fetch_assoc()) {
            if (!empty($row['section'])) $sections[] = $row['section'];
        }
        $r1->free();
    }

    $r2 = $conn->query('SELECT DISTINCT eventKey FROM tb_usuarios_admin_log ORDER BY eventKey');
    if ($r2) {
        while ($row = $r2->fetch_assoc()) {
            if (!empty($row['eventKey'])) $events[] = $row['eventKey'];
        }
        $r2->free();
    }

    $r3 = $conn->query('SELECT DISTINCT idUsuarioAdmin, usuarioNombre FROM tb_usuarios_admin_log ORDER BY usuarioNombre');
    if ($r3) {
        while ($row = $r3->fetch_assoc()) {
            $id = isset($row['idUsuarioAdmin']) ? (int)$row['idUsuarioAdmin'] : 0;
            $name = isset($row['usuarioNombre']) ? (string)$row['usuarioNombre'] : '';
            if ($id > 0 && $name !== '') {
                $users[] = ['id' => $id, 'text' => $name];
            }
        }
        $r3->free();
    }

    echo json_encode(['ok' => true, 'data' => ['sections' => $sections, 'events' => $events, 'users' => $users]]);
    exit;
}

$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$limit = isset($_GET['limit']) ? max(10, min(200, (int)$_GET['limit'])) : 50;
$offset = ($page - 1) * $limit;

$filterSection = trim((string)($_GET['section'] ?? ''));
$filterEvent = trim((string)($_GET['eventKey'] ?? ''));
$filterUserId = isset($_GET['userId']) ? (int)$_GET['userId'] : 0;
$filterQ = trim((string)($_GET['q'] ?? ''));
$from = trim((string)($_GET['from'] ?? ''));
$to = trim((string)($_GET['to'] ?? ''));

$clauses = [];
$params = [];
$types = '';

if ($filterSection !== '') {
    $clauses[] = 'section = ?';
    $types .= 's';
    $params[] = $filterSection;
}
if ($filterEvent !== '') {
    $clauses[] = 'eventKey = ?';
    $types .= 's';
    $params[] = $filterEvent;
}
if ($filterUserId > 0) {
    $clauses[] = 'idUsuarioAdmin = ?';
    $types .= 'i';
    $params[] = $filterUserId;
}
if ($filterQ !== '') {
    $clauses[] = '(message LIKE ? OR usuarioNombre LIKE ? OR eventKey LIKE ? OR section LIKE ?)';
    $like = '%' . $filterQ . '%';
    $types .= 'ssss';
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}
if ($from !== '') {
    $clauses[] = 'fecha >= ?';
    $types .= 's';
    $params[] = $from . ' 00:00:00';
}
if ($to !== '') {
    $clauses[] = 'fecha <= ?';
    $types .= 's';
    $params[] = $to . ' 23:59:59';
}

$where = $clauses ? ('WHERE ' . implode(' AND ', $clauses)) : '';

// Count
$countSql = 'SELECT COUNT(*) AS cnt FROM tb_usuarios_admin_log ' . $where;
$countStmt = $conn->prepare($countSql);
if (!$countStmt) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Error preparando consulta']);
    exit;
}
if ($types !== '') {
    $countStmt->bind_param($types, ...$params);
}
$countStmt->execute();
$countRes = $countStmt->get_result();
$totalCount = 0;
if ($countRes) {
    $row = $countRes->fetch_assoc();
    $totalCount = isset($row['cnt']) ? (int)$row['cnt'] : 0;
}
$countStmt->close();

$totalPages = max(1, (int)ceil($totalCount / $limit));

// Rows
$rowsSql = 'SELECT id, fecha, idUsuarioAdmin, usuarioNombre, section, eventKey, entityType, entityId, message ' .
    'FROM tb_usuarios_admin_log ' . $where . ' ORDER BY fecha DESC, id DESC LIMIT ? OFFSET ?';

$rowsStmt = $conn->prepare($rowsSql);
if (!$rowsStmt) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Error preparando consulta']);
    exit;
}

$rowsTypes = $types . 'ii';
$rowsParams = $params;
$rowsParams[] = $limit;
$rowsParams[] = $offset;

$rowsStmt->bind_param($rowsTypes, ...$rowsParams);
$rowsStmt->execute();
$res = $rowsStmt->get_result();
$outRows = [];
if ($res) {
    while ($r = $res->fetch_assoc()) {
        $outRows[] = $r;
    }
}
$rowsStmt->close();

echo json_encode([
    'ok' => true,
    'data' => [
        'rows' => $outRows,
        'totalCount' => $totalCount,
        'totalPages' => $totalPages,
        'page' => $page,
        'limit' => $limit,
    ],
]);
