<?php
session_start();
date_default_timezone_set('America/Sao_Paulo');
$caminho_db = '../api/db/bisbilhotar.db';

if (!file_exists($caminho_db)) { die("Nenhum registro encontrado."); }
$db = new PDO("sqlite:$caminho_db");

$msg_sucesso = false;
if(isset($_GET['delete'])){
    $stmt = $db->prepare("DELETE FROM acessos_detectados WHERE id = ?");
    $stmt->execute([$_GET['delete']]);
    $msg_sucesso = true;
}

$query = $db->query("SELECT * FROM acessos_detectados ORDER BY data_acesso DESC");
$acessos = $query->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Histórico de Acessos</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-body: #020617;
            --card-bg: #0f172a;
            --border-color: #1e293b;
            --accent: #3b82f6;
            --danger: #ef4444;
            --text-main: #f8fafc;
            --text-dim: #94a3b8;
        }

        body { 
            background: var(--bg-body); 
            color: var(--text-main); 
            font-family: 'Inter', sans-serif; 
            margin: 0; 
            padding: 20px; 
        }

        .header-area {
            max-width: 800px;
            margin: 0 auto 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header-area h2 { 
            font-size: 1.5rem; 
            font-weight: 700; 
            margin: 0;
            color: var(--accent);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .logs-container {
            max-width: 800px;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        /* Design do Card */
        .log-card {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 16px;
            padding: 20px;
            position: relative;
            transition: transform 0.2s, border-color 0.2s;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }

        .log-card:hover {
            border-color: var(--accent);
            transform: translateY(-2px);
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;
            padding-bottom: 12px;
            border-bottom: 1px solid rgba(30, 41, 59, 0.5);
        }

        .user-info h3 {
            margin: 0;
            font-size: 1.1rem;
            color: #fff;
        }

        .user-info span {
            font-size: 0.8rem;
            color: var(--text-dim);
            font-family: monospace;
        }

        .card-body {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
        }

        .info-item {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .info-label {
            font-size: 0.7rem;
            text-transform: uppercase;
            color: var(--text-dim);
            font-weight: 700;
            letter-spacing: 0.5px;
        }

        .info-value {
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .badge-cep {
            background: rgba(59, 130, 246, 0.15);
            color: var(--accent);
            padding: 2px 8px;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        /* Botão Localizar */
        .btn-maps {
            background: #1e293b;
            color: #fff;
            padding: 6px 12px;
            border-radius: 8px;
            text-decoration: none;
            font-size: 0.75rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            margin-top: 5px;
            border: 1px solid var(--border-color);
            transition: 0.3s;
        }

        .btn-maps:hover {
            background: var(--accent);
            border-color: var(--accent);
        }

        /* Botão Excluir Moderno */
        .btn-delete-wrapper {
            position: absolute;
            top: 20px;
            right: 20px;
        }

        .btn-delete-modern {
            background: rgba(239, 68, 68, 0.1);
            color: var(--danger);
            border: 1px solid rgba(239, 68, 68, 0.2);
            width: 38px;
            height: 38px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: 0.3s;
        }

        .btn-delete-modern:hover {
            background: var(--danger);
            color: #fff;
            box-shadow: 0 0 15px rgba(239, 68, 68, 0.4);
        }

        /* Responsividade Mobile */
        @media (max-width: 600px) {
            .card-body { grid-template-columns: 1fr; }
            .header-area { flex-direction: column; gap: 10px; text-align: center; }
            .btn-delete-wrapper { position: static; display: flex; justify-content: flex-end; margin-top: 15px; border-top: 1px solid var(--border-color); padding-top: 15px; }
            .btn-delete-modern { width: 100%; height: 45px; gap: 8px; }
            .btn-delete-modern::after { content: 'Excluir Registro'; font-size: 0.85rem; font-weight: 600; }
        }

        /* SweetAlert Custom */
        .swal2-popup { background: var(--card-bg) !important; color: #fff !important; border: 1px solid var(--border-color) !important; border-radius: 24px !important; }
    </style>
</head>
<body>

    <div class="header-area">
        <h2><i class="fas fa-user-secret"></i> Acessos Recentes</h2>
        <div style="font-size: 0.8rem; color: var(--text-dim);">Fuso: Brasília (GMT-3)</div>
    </div>

    <div class="logs-container">
        <?php foreach($acessos as $row): ?>
        <div class="log-card">
            <div class="card-header">
                <div class="user-info">
                    <h3><?php echo htmlspecialchars($row['usuario']); ?></h3>
                    <span>IP: <?php echo $row['ip']; ?></span>
                </div>
            </div>

            <div class="card-body">
                <div class="info-item">
                    <div class="info-label">Localização</div>
                    <div class="info-value">
                        <i class="fas fa-city" style="color: var(--accent)"></i>
                        <?php echo $row['cidade'] . " - " . $row['estado']; ?>
                    </div>
                </div>

                <div class="info-item">
                    <div class="info-label">Bairro / CEP</div>
                    <div class="info-value">
                        <i class="fas fa-map-marker-alt" style="color: var(--danger)"></i>
                        <?php 
                        if (preg_match('/[0-9.-]+,[0-9.-]+/', $row['bairro'])) {
                            echo '<a href="https://www.google.com/maps/search/?api=1&query='.$row['bairro'].'" target="_blank" class="btn-maps"><i class="fas fa-location-arrow"></i> GPS</a>';
                        } else {
                            echo $row['bairro'];
                        }
                        ?>
                        <span class="badge-cep"><?php echo $row['cep']; ?></span>
                    </div>
                </div>

                <div class="info-item">
                    <div class="info-label">Data e Hora</div>
                    <div class="info-value" style="color: var(--text-dim)">
                        <i class="far fa-clock"></i>
                        <?php echo date('d/m/Y - H:i:s', strtotime($row['data_acesso'])); ?>
                    </div>
                </div>
            </div>

            <div class="btn-delete-wrapper">
                <button class="btn-delete-modern" onclick="confirmDelete(<?php echo $row['id']; ?>)">
                    <i class="far fa-trash-alt"></i>
                </button>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <script>
    function confirmDelete(id) {
        Swal.fire({
            title: 'Excluir log?',
            text: "Esta ação não pode ser revertida.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#1e293b',
            confirmButtonText: 'Sim, deletar!',
            cancelButtonText: 'Cancelar',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = 'v_logs.php?delete=' + id;
            }
        })
    }

    <?php if($msg_sucesso): ?>
    Swal.fire({
        icon: 'success',
        title: 'Deletado!',
        text: 'O registro foi removido com sucesso.',
        showConfirmButton: false,
        timer: 1500
    });
    <?php endif; ?>
    </script>

</body>
</html>
