<?php
declare(strict_types=1);

$pageTitle = 'Registros';
require_once __DIR__ . '/includes/header.php';

$db = gpc_db();
$self = basename($_SERVER['PHP_SELF']);

if (isset($_GET['clear']) && $_GET['clear'] === '1') {
    $db->exec('DELETE FROM registration_logs');
    gpc_flash('ok', 'Histórico limpo');
    header('Location: ' . $self);
    exit;
}

if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $db->prepare('DELETE FROM registration_logs WHERE id = :id')->execute([':id' => (int) $_GET['delete']]);
    gpc_flash('ok', 'Removido');
    header('Location: ' . $self);
    exit;
}

$search = trim((string) ($_GET['q'] ?? ''));
$sql = 'SELECT * FROM registration_logs';
$params = [];
if ($search !== '') {
    $sql .= ' WHERE mac_address LIKE :q OR username LIKE :q OR dns_url LIKE :q';
    $params[':q'] = '%' . $search . '%';
}
$sql .= ' ORDER BY id DESC LIMIT 500';
$stmt = $db->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();
?>

<div class="card">
    <div class="card-body">
        <form method="get" class="toolbar">
            <input type="search" name="q" placeholder="Buscar..." value="<?= gpc_h($search) ?>">
            <button type="submit" class="btn btn-sm"><i data-lucide="search"></i></button>
            <a href="?clear=1" class="btn btn-sm btn-danger" data-confirm="Limpar todo o histórico?">
                <i data-lucide="eraser"></i>
            </a>
        </form>
        <div class="table-scroll">
            <table>
                <thead>
                    <tr><th>MAC</th><th>User</th><th>DNS</th><th>Revenda</th><th>Data</th><th></th></tr>
                </thead>
                <tbody>
                    <?php foreach ($rows as $r): ?>
                    <tr>
                        <td><code><?= gpc_h($r['mac_address']) ?></code></td>
                        <td><?= gpc_h($r['username']) ?></td>
                        <td><?= gpc_h($r['dns_url']) ?></td>
                        <td><?= gpc_h($r['cod_revenda']) ?></td>
                        <td><?= gpc_h($r['registered_at']) ?></td>
                        <td class="row-actions">
                            <a class="btn btn-sm btn-danger btn-icon" href="?delete=<?= (int) $r['id'] ?>">
                                <i data-lucide="x"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (!$rows): ?>
                    <tr><td colspan="6" class="empty">Sem registros</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
