<?php
include 'verifica_login.php';
requer_admin();
include 'conexao.php';
include 'config/log_utils.php';

$conn = conectar_banco();
garantir_estrutura_logs($conn);

function bind_param_dinamico($stmt, $types, $params) {
    $bind = [$types];
    foreach ($params as $k => $v) {
        $bind[] = &$params[$k];
    }
    call_user_func_array([$stmt, 'bind_param'], $bind);
}

$filtro_data_inicial = trim((string)($_GET['data_inicial'] ?? date('Y-m-01')));
$filtro_data_final = trim((string)($_GET['data_final'] ?? date('Y-m-d')));
$filtro_operador = (int)($_GET['operador'] ?? 0);
$filtro_tipo = trim((string)($_GET['tipo_operacao'] ?? ''));
$filtro_modulo = trim((string)($_GET['modulo'] ?? ''));
$filtro_metodo = trim((string)($_GET['metodo_http'] ?? ''));
$filtro_ip = trim((string)($_GET['ip'] ?? ''));
$filtro_texto = trim((string)($_GET['texto'] ?? ''));
$pagina = max(1, (int)($_GET['pagina'] ?? 1));
$limite = 100;
$offset = ($pagina - 1) * $limite;

$where = ['1=1'];
$params = [];
$types = '';

if ($filtro_data_inicial !== '') {
    $where[] = 'l.data_hora >= ?';
    $params[] = $filtro_data_inicial . ' 00:00:00';
    $types .= 's';
}
if ($filtro_data_final !== '') {
    $where[] = 'l.data_hora <= ?';
    $params[] = $filtro_data_final . ' 23:59:59';
    $types .= 's';
}
if ($filtro_operador > 0) {
    $where[] = 'l.usuario_id = ?';
    $params[] = $filtro_operador;
    $types .= 'i';
}
if ($filtro_tipo !== '') {
    $where[] = 'l.tipo_operacao = ?';
    $params[] = $filtro_tipo;
    $types .= 's';
}
if ($filtro_modulo !== '') {
    $where[] = 'l.modulo LIKE ?';
    $params[] = '%' . $filtro_modulo . '%';
    $types .= 's';
}
if ($filtro_metodo !== '') {
    $where[] = 'l.metodo_http = ?';
    $params[] = $filtro_metodo;
    $types .= 's';
}
if ($filtro_ip !== '') {
    $where[] = 'l.ip LIKE ?';
    $params[] = '%' . $filtro_ip . '%';
    $types .= 's';
}
if ($filtro_texto !== '') {
    $where[] = '(l.usuario_nome LIKE ? OR l.usuario_login LIKE ? OR l.detalhes LIKE ? OR l.url LIKE ?)';
    $params[] = '%' . $filtro_texto . '%';
    $params[] = '%' . $filtro_texto . '%';
    $params[] = '%' . $filtro_texto . '%';
    $params[] = '%' . $filtro_texto . '%';
    $types .= 'ssss';
}

$where_sql = implode(' AND ', $where);

if (($_GET['export'] ?? '') === 'csv') {
    $sql_export = "
        SELECT
            l.id_log,
            l.data_hora,
            l.usuario_id,
            l.usuario_nome,
            l.usuario_login,
            l.usuario_nivel,
            l.tipo_operacao,
            l.modulo,
            l.metodo_http,
            l.ip,
            l.url,
            l.detalhes
        FROM logs_interacoes l
        WHERE $where_sql
        ORDER BY l.data_hora DESC, l.id_log DESC
    ";

    $stmt_export = $conn->prepare($sql_export);
    if ($types !== '') {
        bind_param_dinamico($stmt_export, $types, $params);
    }
    $stmt_export->execute();
    $res_export = $stmt_export->get_result();

    $nome_arquivo = 'logs_' . date('Ymd_His') . '.csv';
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $nome_arquivo . '"');

    $output = fopen('php://output', 'w');
    fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
    fputcsv($output, [
        'ID Log',
        'Data/Hora',
        'ID Usuario',
        'Nome Usuario',
        'Login Usuario',
        'Nivel Usuario',
        'Tipo Operacao',
        'Modulo',
        'Metodo HTTP',
        'IP',
        'URL',
        'Detalhes'
    ], ';');

    while ($row = $res_export->fetch_assoc()) {
        fputcsv($output, [
            $row['id_log'],
            $row['data_hora'],
            $row['usuario_id'],
            $row['usuario_nome'],
            $row['usuario_login'],
            $row['usuario_nivel'],
            $row['tipo_operacao'],
            $row['modulo'],
            $row['metodo_http'],
            $row['ip'],
            $row['url'],
            preg_replace("/\r\n|\r|\n/", ' ', (string)$row['detalhes'])
        ], ';');
    }

    fclose($output);
    $conn->close();
    exit;
}

$sql_total = "SELECT COUNT(*) AS total FROM logs_interacoes l WHERE $where_sql";
$stmt_total = $conn->prepare($sql_total);
if ($types !== '') {
    bind_param_dinamico($stmt_total, $types, $params);
}
$stmt_total->execute();
$res_total = $stmt_total->get_result()->fetch_assoc();
$total_registros = (int)($res_total['total'] ?? 0);
$total_paginas = max(1, (int)ceil($total_registros / $limite));
if ($pagina > $total_paginas) {
    $pagina = $total_paginas;
    $offset = ($pagina - 1) * $limite;
}

$sql_logs = "
    SELECT
        l.id_log,
        l.data_hora,
        l.usuario_id,
        l.usuario_nome,
        l.usuario_login,
        l.usuario_nivel,
        l.tipo_operacao,
        l.modulo,
        l.url,
        l.metodo_http,
        l.ip,
        l.detalhes
    FROM logs_interacoes l
    WHERE $where_sql
    ORDER BY l.data_hora DESC, l.id_log DESC
    LIMIT ?, ?
";
$stmt_logs = $conn->prepare($sql_logs);
$params_logs = $params;
$types_logs = $types . 'ii';
$params_logs[] = $offset;
$params_logs[] = $limite;
bind_param_dinamico($stmt_logs, $types_logs, $params_logs);
$stmt_logs->execute();
$res_logs = $stmt_logs->get_result();

$operadores = [];
$res_operadores = $conn->query("SELECT id, nome, usuario FROM usuarios WHERE ativo = 'S' ORDER BY nome");
if ($res_operadores) {
    while ($op = $res_operadores->fetch_assoc()) {
        $operadores[] = $op;
    }
}

$tipos_operacao = [];
$res_tipos = $conn->query("SELECT DISTINCT tipo_operacao FROM logs_interacoes ORDER BY tipo_operacao");
if ($res_tipos) {
    while ($tp = $res_tipos->fetch_assoc()) {
        $tipos_operacao[] = $tp['tipo_operacao'];
    }
}

$query_base = $_GET;
unset($query_base['pagina']);
$query_export = $_GET;
unset($query_export['pagina']);
$query_export['export'] = 'csv';
function link_paginacao($pagina_alvo, $query_base) {
    $query_base['pagina'] = $pagina_alvo;
    return 'registro_logs.php?' . http_build_query($query_base);
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registro de Logs</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 0; background: #f4f6f9; color: #222; }
        .container { max-width: 1400px; margin: 20px auto; padding: 0 16px; }
        .card { background: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,.08); padding: 18px; margin-bottom: 14px; }
        h1 { margin: 0 0 8px; color: #0f3b87; }
        .subtitle { color: #5f6b7a; margin-bottom: 10px; }
        .filters { display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: 10px; }
        label { font-size: 13px; color: #425466; display: block; margin-bottom: 4px; }
        input, select { width: 100%; padding: 8px 10px; border: 1px solid #d4dbe3; border-radius: 6px; }
        .btn-row { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 12px; }
        .btn { text-decoration: none; border: 0; border-radius: 6px; padding: 9px 13px; cursor: pointer; font-weight: bold; }
        .btn-primary { background: #0f3b87; color: #fff; }
        .btn-secondary { background: #edf1f5; color: #23313f; }
        .btn-back { background: #198754; color: #fff; }
        .table-wrap { overflow: auto; }
        table { width: 100%; border-collapse: collapse; min-width: 1200px; }
        th, td { border-bottom: 1px solid #e8edf2; text-align: left; padding: 9px 8px; font-size: 13px; vertical-align: top; }
        th { background: #f7f9fc; color: #2d3b4a; position: sticky; top: 0; }
        .muted { color: #6d7b8a; }
        .badge { display: inline-block; font-size: 11px; padding: 2px 7px; border-radius: 999px; background: #eaf2ff; color: #1f4f99; }
        .pagination { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 12px; align-items: center; }
        .pagination a { text-decoration: none; color: #0f3b87; padding: 6px 10px; border: 1px solid #d4dbe3; border-radius: 6px; background: #fff; }
        .pagination strong { padding: 6px 10px; border-radius: 6px; background: #0f3b87; color: #fff; }
        .stats { font-size: 13px; color: #4f5e6d; }
        .empty { text-align: center; color: #6d7b8a; padding: 20px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <h1>Registro de Logs</h1>
            <div class="subtitle">Monitoramento das interações dos usuários na aplicação</div>
            <form method="GET">
                <div class="filters">
                    <div>
                        <label for="data_inicial">Data inicial</label>
                        <input type="date" id="data_inicial" name="data_inicial" value="<?= htmlspecialchars($filtro_data_inicial) ?>">
                    </div>
                    <div>
                        <label for="data_final">Data final</label>
                        <input type="date" id="data_final" name="data_final" value="<?= htmlspecialchars($filtro_data_final) ?>">
                    </div>
                    <div>
                        <label for="operador">Operador</label>
                        <select id="operador" name="operador">
                            <option value="0">Todos</option>
                            <?php foreach ($operadores as $op): ?>
                                <option value="<?= (int)$op['id'] ?>" <?= $filtro_operador === (int)$op['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($op['nome']) ?> (<?= htmlspecialchars($op['usuario']) ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label for="tipo_operacao">Tipo de operação</label>
                        <select id="tipo_operacao" name="tipo_operacao">
                            <option value="">Todos</option>
                            <?php foreach ($tipos_operacao as $tp): ?>
                                <option value="<?= htmlspecialchars($tp) ?>" <?= $filtro_tipo === $tp ? 'selected' : '' ?>><?= htmlspecialchars($tp) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label for="metodo_http">Método HTTP</label>
                        <select id="metodo_http" name="metodo_http">
                            <option value="">Todos</option>
                            <?php foreach (['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as $metodo): ?>
                                <option value="<?= $metodo ?>" <?= $filtro_metodo === $metodo ? 'selected' : '' ?>><?= $metodo ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label for="modulo">Módulo/Página</label>
                        <input type="text" id="modulo" name="modulo" value="<?= htmlspecialchars($filtro_modulo) ?>" placeholder="Ex: pesquisas.php">
                    </div>
                    <div>
                        <label for="ip">IP</label>
                        <input type="text" id="ip" name="ip" value="<?= htmlspecialchars($filtro_ip) ?>" placeholder="Ex: 192.168.0.10">
                    </div>
                    <div>
                        <label for="texto">Busca livre</label>
                        <input type="text" id="texto" name="texto" value="<?= htmlspecialchars($filtro_texto) ?>" placeholder="Usuário, detalhe, URL...">
                    </div>
                </div>
                <div class="btn-row">
                    <button class="btn btn-primary" type="submit">Filtrar</button>
                    <a class="btn btn-primary" href="<?= htmlspecialchars('registro_logs.php?' . http_build_query($query_export)) ?>">Exportar CSV</a>
                    <a class="btn btn-secondary" href="registro_logs.php">Limpar filtros</a>
                    <a class="btn btn-back" href="principal_administrador.php">Voltar ao Menu</a>
                </div>
            </form>
        </div>

        <div class="card">
            <div class="stats">Total encontrado: <strong><?= $total_registros ?></strong> registro(s)</div>
            <div class="table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th>Data/Hora</th>
                            <th>Operador</th>
                            <th>Tipo</th>
                            <th>Módulo</th>
                            <th>Método</th>
                            <th>IP</th>
                            <th>Detalhes</th>
                            <th>URL</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($total_registros === 0): ?>
                            <tr><td colspan="8" class="empty">Nenhum log encontrado para os filtros informados.</td></tr>
                        <?php else: ?>
                            <?php while ($log = $res_logs->fetch_assoc()): ?>
                                <tr>
                                    <td><?= htmlspecialchars($log['data_hora']) ?></td>
                                    <td>
                                        <strong><?= htmlspecialchars($log['usuario_nome'] ?: 'N/A') ?></strong><br>
                                        <span class="muted"><?= htmlspecialchars($log['usuario_login'] ?: '-') ?></span><br>
                                        <span class="badge"><?= htmlspecialchars($log['usuario_nivel'] ?: 'sem nivel') ?></span>
                                    </td>
                                    <td><span class="badge"><?= htmlspecialchars($log['tipo_operacao']) ?></span></td>
                                    <td><?= htmlspecialchars($log['modulo']) ?></td>
                                    <td><?= htmlspecialchars($log['metodo_http'] ?: '-') ?></td>
                                    <td><?= htmlspecialchars($log['ip'] ?: '-') ?></td>
                                    <td><?= nl2br(htmlspecialchars((string)$log['detalhes'])) ?></td>
                                    <td><?= htmlspecialchars((string)$log['url']) ?></td>
                                </tr>
                            <?php endwhile; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($total_paginas > 1): ?>
                <div class="pagination">
                    <?php if ($pagina > 1): ?>
                        <a href="<?= htmlspecialchars(link_paginacao($pagina - 1, $query_base)) ?>">← Anterior</a>
                    <?php endif; ?>

                    <?php
                    $inicio = max(1, $pagina - 2);
                    $fim = min($total_paginas, $pagina + 2);
                    for ($p = $inicio; $p <= $fim; $p++):
                        if ($p === $pagina):
                    ?>
                            <strong><?= $p ?></strong>
                        <?php else: ?>
                            <a href="<?= htmlspecialchars(link_paginacao($p, $query_base)) ?>"><?= $p ?></a>
                        <?php endif; ?>
                    <?php endfor; ?>

                    <?php if ($pagina < $total_paginas): ?>
                        <a href="<?= htmlspecialchars(link_paginacao($pagina + 1, $query_base)) ?>">Próxima →</a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>

