<?php
session_start();
include 'auth.php';
date_default_timezone_set('America/Sao_Paulo');

$db_path = __DIR__ . '/api/db/logs.db';
try {
    $db = new PDO("sqlite:" . $db_path);
    // Buscamos os logs para exibir
    $logs = $db->query("SELECT * FROM logs ORDER BY id DESC LIMIT 100")->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) { $logs = []; }

include ('includes/header.php');
?>

<style>
    body { background-color: #020617 !important; color: #e2e8f0; font-family: 'Inter', sans-serif; }
    .section-title { color: #fff; font-weight: 800; margin: 25px 0 15px; display: flex; align-items: center; font-size: 1.1rem; text-transform: uppercase; }
    .logs-toolbar { display: flex; gap: 10px; margin-bottom: 20px; position: sticky; top: 0; z-index: 100; background: #020617; padding: 10px 0; }
    .btn-tool { flex: 1; border: none; padding: 12px; border-radius: 12px; font-size: 0.75rem; font-weight: 800; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 8px; transition: 0.3s; text-decoration: none !important; }
    .btn-clear { background: rgba(239, 68, 68, 0.1); color: #ef4444 !important; border: 1px solid rgba(239, 68, 68, 0.2); }
    .btn-delete-sel { background: #3b82f6; color: #fff !important; box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3); border: none; }
    .log-card { background: #070e1b; border: 1px solid #1e293b; border-radius: 20px; padding: 20px; margin-bottom: 20px; position: relative; }
    .check-container { position: absolute; top: 20px; right: 20px; }
    .log-checkbox { width: 22px; height: 22px; cursor: pointer; accent-color: #3b82f6; }
    .log-item { display: flex; flex-direction: column; gap: 4px; padding: 12px; background: rgba(30, 41, 59, 0.3); border-radius: 12px; margin-bottom: 10px; border: 1px solid rgba(255,255,255,0.02); }
    .log-label { font-size: 0.65rem; font-weight: 800; text-transform: uppercase; color: #3b82f6; display: flex; align-items: center; gap: 6px; }
    .log-value { font-size: 0.85rem; font-weight: 600; color: #f1f5f9; line-height: 1.5; word-wrap: break-word; overflow-wrap: break-word; word-break: break-all; display: block; white-space: normal; }
    .status-badge { display: inline-block; padding: 4px 12px; border-radius: 8px; font-size: 0.75rem; font-weight: 800; text-transform: uppercase; }
    .bg-create { background: rgba(16, 185, 129, 0.1); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.2); }
    .bg-delete { background: rgba(239, 68, 68, 0.1); color: #ef4444; border: 1px solid rgba(239, 68, 68, 0.2); }
    .bg-edit { background: rgba(245, 158, 11, 0.1); color: #f59e0b; border: 1px solid rgba(245, 158, 11, 0.2); }
    .btn-voltar { display: flex; align-items: center; justify-content: center; gap: 8px; margin: 30px auto; color: #64748b; font-weight: 700; text-transform: uppercase; font-size: 0.8rem; text-decoration: none; }
</style>

<div class="container-fluid" style="padding: 15px; max-width: 700px; margin: 0 auto;">
    <div class="section-title">
        <i class="fas fa-history" style="color: #3b82f6; margin-right: 10px;"></i> Logs do Sistema
    </div>

    <form action="processar_logs.php" method="POST" id="formLogs">
        <div class="logs-toolbar">
            <button type="button" onclick="confirmarLimpeza()" class="btn-tool btn-clear">
                <i class="fas fa-broom"></i> LIMPAR TUDO
            </button>
            <button type="submit" name="delete_selected" class="btn-tool btn-delete-sel">
                <i class="fas fa-trash"></i> EXCLUIR MARCADOS
            </button>
        </div>

        <?php if (empty($logs)): ?>
            <div style="text-align: center; padding: 50px 20px;">
                <p style="color: #64748b;">Nenhum registro encontrado.</p>
            </div>
        <?php endif; ?>

        <?php foreach ($logs as $log): 
            $partes = explode('|', $log['acao']);
            $acao_topo = strtolower($partes[0]);
            $status_class = "bg-edit"; $icon = "fa-edit";
            if (strpos($acao_topo, 'criou') !== false || strpos($acao_topo, 'ativou') !== false || strpos($acao_topo, 'cadastrou') !== false) { $status_class = "bg-create"; $icon = "fa-plus-circle"; }
            elseif (strpos($acao_topo, 'excluiu') !== false || strpos($acao_topo, 'removeu') !== false) { $status_class = "bg-delete"; $icon = "fa-trash-alt"; }
        ?>
        <div class="log-card">
            <div class="check-container">
                <input type="checkbox" name="selected_logs[]" value="<?= $log['id'] ?>" class="log-checkbox">
            </div>
            <div class="log-item">
                <span class="log-label"><i class="fas fa-user-tie"></i> Responsável</span>
                <span class="log-value"><?= htmlspecialchars($log['usuario']) ?></span>
            </div>
            <div class="log-item">
                <span class="log-label"><i class="fas fa-clock"></i> Data</span>
                <span class="log-value"><?= htmlspecialchars($log['data']) ?></span>
            </div>
            <div class="log-item">
                <span class="log-label"><i class="fas <?= $icon ?>"></i> Atividade</span>
                <span class="status-badge <?= $status_class ?>"><?= htmlspecialchars(trim($partes[0])) ?></span>
            </div>
            <?php if(count($partes) > 1): ?>
            <div class="log-item">
                <span class="log-label"><i class="fas fa-info-circle"></i> Detalhes</span>
                <span class="log-value" style="color: #94a3b8; font-family: monospace;">
                    <?php for($i=1; $i < count($partes); $i++) { echo htmlspecialchars($partes[$i]) . "<br>"; } ?>
                </span>
            </div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </form>

    <a href="index.php" class="btn-voltar"><i class="fas fa-chevron-left"></i> Voltar ao Painel</a>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
function confirmarLimpeza() {
    Swal.fire({
        title: 'Limpar tudo?',
        text: "Isso apagará permanentemente todos os registros!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#1e293b',
        confirmButtonText: 'Sim, deletar tudo!',
        cancelButtonText: 'Cancelar',
        background: '#0f172a',
        color: '#fff'
    }).then((result) => {
        if (result.isConfirmed) {
            // Redireciona com o parâmetro de ação
            window.location.href = 'processar_logs.php?action=clear_all';
        }
    })
}

// Alertas de feedback
<?php if(isset($_GET['status'])): ?>
    Swal.fire({
        icon: 'success',
        title: '<?= ($_GET['status'] == 'cleared') ? "Banco de Dados Limpo!" : "Registros Excluídos!" ?>',
        showConfirmButton: false,
        timer: 1500,
        background: '#0f172a',
        color: '#fff'
    });
<?php endif; ?>
</script>
<?php include ('includes/footer.php'); ?>
