<?php 
include ('includes/header.php');
$db = new SQLite3("a/.logs.db");

// Configurações de paginação
$limit = 500;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Consulta para contar o total de registros
$total_res = $db->query("SELECT COUNT(*) as total FROM logs");
$total_row = $total_res->fetchArray();
$total_logs = $total_row['total'];

// Consulta para selecionar os registros para a página atual
$res = $db->query("SELECT * FROM logs ORDER by id DESC LIMIT $limit OFFSET $offset");

// Ativar a exibição de erros para depuração
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $db->exec("DELETE FROM logs WHERE id = '$id'");
}

// Adição da exclusão em massa
if (isset($_GET['delete_selected'])) {
    $ids_to_delete = isset($_GET['delete_check']) ? $_GET['delete_check'] : [];
    
    if (!empty($ids_to_delete)) {
        $chunk_size = 500;
        $chunks = array_chunk($ids_to_delete, $chunk_size);

        foreach ($chunks as $chunk) {
            $ids_string = implode(',', array_map('intval', $chunk));
            $db->exec("DELETE FROM logs WHERE id IN ($ids_string)");
        }
    } else {
        echo "<script>alert('Nenhum registro selecionado para exclusão.');</script>";
    }

    echo '<script>window.location.replace("snoop.php");</script>';
    exit();
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Logs - Sistema</title>
    <style>
        /* === DESIGN FUTURISTA MODERNO === */
        :root {
            --primary: #00D4FF;
            --primary-dark: #0099CC;
            --secondary: #FF6B9D;
            --accent: #00FF88;
            --surface: #0A0F1C;
            --surface-light: #1A1F2C;
            --surface-lighter: #2A2F3C;
            --text-primary: #FFFFFF;
            --text-secondary: #B0B7C3;
            --text-muted: #6B7280;
            --border: rgba(255,255,255,0.1);
            --glow: 0 0 20px rgba(0, 212, 255, 0.3);
            --glow-accent: 0 0 20px rgba(0, 255, 136, 0.3);
            --glow-danger: 0 0 20px rgba(255, 107, 157, 0.3);
        }

        body {
            background: var(--surface) !important;
            color: var(--text-primary) !important;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
        }

        .main-content {
            background: transparent !important;
            padding: 20px;
        }

        .card {
            background: var(--surface-light) !important;
            border: 1px solid var(--border) !important;
            border-radius: 20px !important;
            box-shadow: 0 8px 40px rgba(0,0,0,0.4) !important;
            color: var(--text-primary) !important;
            overflow: hidden;
            position: relative;
            margin-top: 20px;
        }

        .card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, var(--primary), var(--accent), var(--secondary));
            animation: borderGlow 3s ease-in-out infinite;
        }

        @keyframes borderGlow {
            0%, 100% { opacity: 0.7; }
            50% { opacity: 1; }
        }

        .card-header {
            background: linear-gradient(135deg, var(--surface-light), var(--surface-lighter)) !important;
            border-bottom: 1px solid var(--border) !important;
            color: var(--text-primary) !important;
            font-weight: 700 !important;
            padding: 20px !important;
        }

        .card-body {
            background: transparent !important;
            color: var(--text-primary) !important;
            padding: 30px !important;
        }

        /* Títulos futuristas */
        h1 {
            color: var(--text-primary) !important;
            font-weight: 700;
            text-align: center;
            margin-bottom: 30px;
            background: linear-gradient(135deg, var(--primary), var(--accent));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            font-size: 2.5rem;
            text-shadow: 0 0 30px rgba(0, 212, 255, 0.5);
        }

        /* Botões futuristas */
        .btn-danger {
            background: linear-gradient(135deg, var(--secondary), #ff4d8d) !important;
            border: none !important;
            border-radius: 12px !important;
            box-shadow: var(--glow-danger) !important;
            padding: 14px 30px !important;
            font-weight: 600 !important;
            transition: all 0.3s ease !important;
            text-transform: uppercase;
            letter-spacing: 1px;
            font-size: 1rem;
            color: white !important;
            margin-bottom: 20px;
        }

        .btn-danger:hover {
            transform: translateY(-3px) !important;
            box-shadow: 0 8px 25px rgba(255, 107, 157, 0.5) !important;
        }

        /* Tabela futurista */
        .table {
            width: 100%;
            border-collapse: collapse;
            background: var(--surface-lighter);
            border-radius: 16px;
            overflow: hidden;
            margin: 20px 0;
            box-shadow: 0 8px 30px rgba(0,0,0,0.3);
        }

        .table thead {
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
        }

        .table th {
            color: #000;
            font-weight: 700;
            padding: 18px 12px;
            text-align: center;
            text-transform: uppercase;
            letter-spacing: 1px;
            font-size: 0.9rem;
        }

        .table td {
            padding: 15px 12px;
            text-align: center;
            border-bottom: 1px solid var(--border);
            color: var(--text-primary);
            transition: all 0.3s ease;
        }

        .table tbody tr {
            background: rgba(255, 255, 255, 0.02);
            transition: all 0.3s ease;
        }

        .table tbody tr:hover {
            background: rgba(0, 212, 255, 0.1);
            transform: translateX(5px);
        }

        /* Checkboxes personalizados */
        input[type="checkbox"] {
            width: 20px;
            height: 20px;
            accent-color: var(--accent);
            cursor: pointer;
            border-radius: 4px;
            transition: all 0.3s ease;
        }

        input[type="checkbox"]:checked {
            transform: scale(1.1);
        }

        /* Ícones de lixeira */
        .fa-trash {
            color: var(--secondary);
            font-size: 18px;
            transition: all 0.3s ease;
            cursor: pointer;
            padding: 8px;
            border-radius: 6px;
            background: rgba(255, 107, 157, 0.1);
        }

        .fa-trash:hover {
            color: #ff1a68;
            transform: scale(1.2);
            background: rgba(255, 107, 157, 0.2);
            box-shadow: var(--glow-danger);
        }

        /* Paginação futurista */
        .pagination {
            list-style: none;
            display: flex;
            justify-content: center;
            padding: 0;
            margin-top: 30px;
            gap: 8px;
        }

        .pagination li {
            margin: 0;
        }

        .pagination a {
            background: var(--surface-lighter);
            color: var(--text-primary);
            padding: 12px 18px;
            border-radius: 10px;
            border: 1px solid var(--border);
            text-decoration: none;
            transition: all 0.3s ease;
            font-weight: 600;
            min-width: 45px;
            text-align: center;
            display: block;
        }

        .pagination a:hover {
            background: var(--primary);
            color: #000;
            transform: translateY(-2px);
            box-shadow: var(--glow);
        }

        .pagination .active a {
            background: linear-gradient(135deg, var(--accent), #00cc7a);
            color: #000;
            box-shadow: var(--glow-accent);
        }

        /* Container da tabela */
        .table-responsive {
            border-radius: 16px;
            overflow: hidden;
        }

        /* Efeito de partículas */
        @keyframes moveParticles {
            from { transform: translateY(0); opacity: 0.7; }
            to { transform: translateY(-1000px); opacity: 0; }
        }

        .particle {
            position: fixed;
            bottom: 0;
            width: 2px;
            height: 2px;
            background: var(--primary);
            opacity: 0.5;
            animation: moveParticles linear infinite;
            z-index: -1;
        }

        .particle:nth-child(odd) { background: var(--accent); }

        /* Responsividade */
        @media (max-width: 768px) {
            .main-content {
                padding: 10px !important;
            }
            
            .card-body {
                padding: 20px !important;
            }
            
            .table {
                font-size: 0.8rem;
            }
            
            .table th, .table td {
                padding: 10px 8px;
            }
            
            .btn-danger {
                padding: 12px 20px !important;
                font-size: 0.9rem !important;
            }
            
            .pagination a {
                padding: 8px 12px;
                min-width: 35px;
            }
        }

        /* Estilo para o centro */
        .center-content {
            text-align: center;
            padding: 20px;
        }

        /* Badge de contador */
        .logs-count {
            background: linear-gradient(135deg, var(--accent), #00cc7a);
            color: #000;
            padding: 8px 16px;
            border-radius: 20px;
            font-weight: 700;
            font-size: 0.9rem;
            margin-left: 15px;
            box-shadow: var(--glow-accent);
        }
    </style>
</head>
<body>

<main role="main" class="col-12 pt-4 px-4 main-content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-12">
                <div class="card border-left-primary shadow h-100 card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary2">
                            <i class="fas fa-list-alt me-2"></i>Sistema de Logs
                            <span class="logs-count">Total: <?php echo $total_logs; ?> registros</span>
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="center-content">
                            <h1>
                                <i class="fas fa-database me-2"></i>LOGS DO SISTEMA
                            </h1>
                        </div>

                        <div class="table-responsive">
                            <form method="get">
                                <div class="form-group text-center">
                                    <button type="submit" class="btn btn-danger" name="delete_selected">
                                        <i class="fas fa-trash me-2"></i>Excluir Selecionados
                                    </button>
                                </div>
                                <table class="table">
                                    <thead>
                                        <tr>
                                            <th style="width: 50px;">
                                                <input type="checkbox" id="selecionarTodos">
                                            </th>
                                            <th>ID</th>
                                            <th>Data</th>
                                            <th>IP Address</th>
                                            <th style="width: 100px;">Ações</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php while ($row = $res->fetchArray()) { ?>
                                        <tr>
                                            <td>
                                                <input type="checkbox" class="checkbox" name="delete_check[]" value="<?php echo $row['id']; ?>">
                                            </td>
                                            <td>
                                                <span style="color: var(--accent); font-weight: 600;">#<?= $row['id'] ?></span>
                                            </td>
                                            <td><?= $row['date'] ?></td>
                                            <td>
                                                <span style="color: var(--primary); font-family: monospace;"><?= $row['ipaddress'] ?></span>
                                            </td>
                                            <td>
                                                <a href="snoop.php?delete=<?php echo $row['id']; ?>" onclick="return confirm('Tem certeza que deseja excluir este registro?')">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                            </form>

                            <!-- Paginação -->
                            <div>
                                <nav>
                                    <ul class="pagination">
                                        <?php 
                                        $total_pages = ceil($total_logs / $limit); 
                                        for ($i = 1; $i <= $total_pages; $i++) { 
                                            $active = $i == $page ? "active" : "";
                                            echo "<li class='$active'><a href='snoop.php?page=$i'>$i</a></li>";
                                        } 
                                        ?>
                                    </ul>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<script>
document.addEventListener("DOMContentLoaded", function() {
    // Partículas animadas
    const numParticles = 20;
    const particlesContainer = document.createElement('div');
    particlesContainer.style.position = 'fixed';
    particlesContainer.style.top = '0';
    particlesContainer.style.left = '0';
    particlesContainer.style.width = '100%';
    particlesContainer.style.height = '100%';
    particlesContainer.style.pointerEvents = 'none';
    particlesContainer.style.zIndex = '-1';
    
    for (let i = 0; i < numParticles; i++) {
        const particle = document.createElement('div');
        particle.classList.add('particle');
        particle.style.left = Math.random() * 100 + 'vw';
        particle.style.animationDuration = (2 + Math.random() * 8) + 's';
        particle.style.animationDelay = Math.random() * 10 + 's';
        particle.style.width = particle.style.height = (1 + Math.random() * 3) + 'px';
        particlesContainer.appendChild(particle);
    }
    
    document.body.appendChild(particlesContainer);

    // Selecionar todos os checkboxes
    document.getElementById('selecionarTodos').addEventListener('change', function() {
        var checkboxes = document.getElementsByClassName('checkbox');
        for (var i = 0; i < checkboxes.length; i++) {
            checkboxes[i].checked = this.checked;
        }
    });

    // Confirmação para exclusão em massa
    const deleteForm = document.querySelector('form');
    deleteForm.addEventListener('submit', function(e) {
        const checkboxes = document.querySelectorAll('.checkbox:checked');
        if (checkboxes.length === 0 && e.submitter.name === 'delete_selected') {
            e.preventDefault();
            alert('Selecione pelo menos um registro para excluir.');
            return false;
        }
        
        if (checkboxes.length > 0 && e.submitter.name === 'delete_selected') {
            if (!confirm(`Tem certeza que deseja excluir ${checkboxes.length} registro(s)?`)) {
                e.preventDefault();
                return false;
            }
        }
    });
});
</script>

<?php include ('includes/footer.php'); ?>
</body>
</html>