<?php
$title = $title ?? 'Logs Gestor-Y';
?>

<div class="page-header" style="display:flex;align-items:center;justify-content:space-between;gap:1rem;flex-wrap:wrap;">
    <div>
        <h1>📊 Logs Gestor-Y</h1>
        <p class="muted">Histórico de pesquisas, importações e erros</p>
    </div>
    <a href="/gestor-y" class="btn btn-secondary">Voltar</a>
</div>

<div style="display: flex; gap: 1rem; margin-bottom: 1.5rem; flex-wrap: wrap;">
    <button class="btn" onclick="filterLogs('all')" id="filter-all">Todos</button>
    <button class="btn btn-secondary" onclick="filterLogs('pesquisa')" id="filter-pesquisa">Pesquisas</button>
    <button class="btn btn-secondary" onclick="filterLogs('importacao')" id="filter-importacao">Importações</button>
    <button class="btn btn-secondary" onclick="filterLogs('erro')" id="filter-erro">Erros</button>
</div>

<div class="card">
    <div id="logs-container">
        <p class="muted">Carregando logs...</p>
    </div>
</div>

<script>
let currentFilter = 'all';
let currentPage = 1;

function filterLogs(tipo) {
    currentFilter = tipo;
    currentPage = 1;
    
    // Atualizar botões
    document.querySelectorAll('[id^="filter-"]').forEach(btn => {
        btn.classList.remove('btn');
        btn.classList.add('btn-secondary');
    });
    document.getElementById(`filter-${tipo}`).classList.remove('btn-secondary');
    document.getElementById(`filter-${tipo}`).classList.add('btn');
    
    loadLogs();
}

async function loadLogs() {
    const container = document.getElementById('logs-container');
    container.innerHTML = '<p class="muted">Carregando logs...</p>';
    
    try {
        const params = new URLSearchParams({
            page: currentPage,
            per_page: 20
        });
        
        if (currentFilter !== 'all') {
            params.append('tipo', currentFilter);
        }
        
        const response = await fetch(`/api/gestor-y/logs?${params}`);
        const data = await response.json();
        
        if (response.ok) {
            renderLogs(data.data || []);
        } else {
            container.innerHTML = '<p class="alert alert-error">Erro ao carregar logs</p>';
        }
    } catch (error) {
        console.error('Erro:', error);
        container.innerHTML = '<p class="alert alert-error">Erro ao carregar logs</p>';
    }
}

function renderLogs(logs) {
    const container = document.getElementById('logs-container');
    
    if (logs.length === 0) {
        container.innerHTML = '<p class="muted">Nenhum log encontrado.</p>';
        return;
    }
    
    const tipoColors = {
        'pesquisa': '#3b82f6',
        'importacao': '#10b981',
        'atualizacao': '#8b5cf6',
        'erro': '#ef4444',
        'aviso': '#f59e0b'
    };
    
    container.innerHTML = `
        <table class="table">
            <thead>
                <tr>
                    <th>Data/Hora</th>
                    <th>Tipo</th>
                    <th>Ação</th>
                    <th>Código Peça</th>
                    <th>Mensagem</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                ${logs.map(log => `
                    <tr>
                        <td>${new Date(log.created_at).toLocaleString('pt-BR')}</td>
                        <td>
                            <span style="background: ${tipoColors[log.tipo] || '#6b7280'}; color: white; padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.875rem;">
                                ${log.tipo}
                            </span>
                        </td>
                        <td>${log.acao}</td>
                        <td>${log.codigo_peca || '-'}</td>
                        <td>${log.mensagem || '-'}</td>
                        <td>
                            ${log.sucesso 
                                ? '<span style="color: #10b981;">✓ Sucesso</span>' 
                                : '<span style="color: #ef4444;">✗ Erro</span>'}
                        </td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    `;
}

document.addEventListener('DOMContentLoaded', () => {
    loadLogs();
});
</script>

