<?php
include 'includes/header.php';

$db = new SQLite3('a/.eggziedb.db');
$request_json_path = './a/rtx/request.json';

// Ler dados com validação
$requests = [];
if (file_exists($request_json_path)) {
    $json_content = file_get_contents($request_json_path);
    $decoded = json_decode($json_content, true);
    if (is_array($decoded)) {
        $requests = $decoded;
    }
}

// Excluir MAC específico
if (isset($_GET['excluir_mac'])) {
    $mac_excluir = strtoupper(trim($_GET['excluir_mac']));
    $novos = [];
    foreach ($requests as $r) {
        if (strtoupper(trim($r['mac'] ?? '')) !== $mac_excluir) {
            $novos[] = $r;
        }
    }
    file_put_contents($request_json_path, json_encode($novos, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    echo "<script>window.location.href='devices.php';</script>";
    exit();
}

// Limpar todos os MACs
if (isset($_GET['clear'])) {
    file_put_contents($request_json_path, json_encode([], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    echo "<script>window.location.href='devices.php';</script>";
    exit();
}

// Obter MACs já cadastrados
$cadastrados = [];
$query = $db->query("SELECT id, mac_address FROM ibo");
if ($query) {
    while ($row = $query->fetchArray()) {
        $cadastrados[strtoupper(trim($row['mac_address']))] = $row['id'];
    }
}

// A fila de "MACs Capturados" deve mostrar somente dispositivos
// que ainda não foram ativados. Ao abrir esta página, limpamos
// automaticamente qualquer MAC que já exista em ibo.
$pendentes_lista = [];
$macs_vistos = [];

foreach ($requests as $r) {
    $mac_atual = strtoupper(trim($r['mac'] ?? ''));
    if (empty($mac_atual) || isset($cadastrados[$mac_atual]) || isset($macs_vistos[$mac_atual])) {
        continue;
    }

    $macs_vistos[$mac_atual] = true;
    $r['mac'] = $mac_atual;
    $pendentes_lista[] = $r;
}

if (count($pendentes_lista) !== count($requests)) {
    file_put_contents(
        $request_json_path,
        json_encode($pendentes_lista, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE),
        LOCK_EX
    );
}

$requests = $pendentes_lista;
$total = count($requests);
$pendentes = $total;
$ativados = count($cadastrados);
?>

<style>
    .mac-card {
        background: #1e293b;
        border: 1px solid #334155;
        border-radius: 15px;
        transition: all 0.3s ease;
        overflow: hidden;
        height: 100%;
    }
    .mac-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0,0,0,0.3);
        border-color: #0ea5e9;
    }
    .mac-header {
        background: rgba(14, 165, 233, 0.1);
        padding: 15px;
        border-bottom: 1px solid #334155;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .mac-body {
        padding: 20px;
    }
    .mac-address {
        font-family: 'Monaco', 'Consolas', monospace;
        font-size: 1.1rem;
        color: #0ea5e9;
        font-weight: bold;
    }
    .mac-info-item {
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        font-size: 0.9rem;
    }
    .mac-info-item i {
        width: 25px;
        color: #94a3b8;
    }
    .status-badge {
        padding: 5px 12px;
        border-radius: 20px;
        font-size: 0.75rem;
        font-weight: bold;
        text-transform: uppercase;
    }
    .status-pending {
        background: rgba(245, 158, 11, 0.2);
        color: #f59e0b;
    }
    .status-active {
        background: rgba(16, 185, 129, 0.2);
        color: #10b981;
    }
    .mac-footer {
        padding: 15px 20px;
        background: rgba(15, 23, 42, 0.5);
        border-top: 1px solid #334155;
        display: flex;
        gap: 10px;
    }
    .btn-action {
        flex: 1;
        border-radius: 8px;
        padding: 8px;
        font-weight: 600;
        font-size: 0.85rem;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 5px;
        transition: all 0.2s;
    }
    .empty-state {
        text-align: center;
        padding: 60px 20px;
        background: #1e293b;
        border-radius: 15px;
        border: 2px dashed #334155;
    }
</style>

<div class="container-fluid">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-white"><i class="fas fa-microchip mr-2 text-info"></i> MACs Capturados</h1>
        <div>
            <a href="?clear=1" class="btn btn-outline-danger btn-sm px-3" onclick="return confirm('Tem certeza que deseja limpar todos os MACs capturados?')">
                <i class="fas fa-trash-alt mr-2"></i> Limpar Histórico
            </a>
        </div>
    </div>

    <!-- Cards de Estatísticas -->
    <div class="row mb-4">
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card h-100 shadow-sm border-0 bg-dark text-white" style="border-left: 4px solid #0ea5e9 !important;">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Total Capturado</div>
                            <div class="h5 mb-0 font-weight-bold"><?= $total ?> Dispositivos</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-broadcast-tower fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card h-100 shadow-sm border-0 bg-dark text-white" style="border-left: 4px solid #f59e0b !important;">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Aguardando Ativação</div>
                            <div class="h5 mb-0 font-weight-bold"><?= $pendentes ?> Pendentes</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-user-clock fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card h-100 shadow-sm border-0 bg-dark text-white" style="border-left: 4px solid #10b981 !important;">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Clientes Ativos</div>
                            <div class="h5 mb-0 font-weight-bold"><?= $ativados ?> Clientes</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-user-check fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Grid de MACs -->
    <?php if (empty($requests)): ?>
        <div class="empty-state">
            <i class="fas fa-search fa-4x text-muted mb-3"></i>
            <h4 class="text-white">Nenhum MAC detectado</h4>
            <p class="text-muted">Os dispositivos aparecerão aqui automaticamente quando abrirem o aplicativo.</p>
        </div>
    <?php else: ?>
        <div class="row">
            <?php foreach (array_reverse($requests) as $mac): 
                if (empty($mac['mac'])) continue;
                $mac_atual = strtoupper(trim($mac['mac']));
                $id_cliente = $cadastrados[$mac_atual] ?? null;
                $ja_ativado = $id_cliente !== null;
            ?>
            <div class="col-xl-3 col-lg-4 col-md-6 mb-4">
                <div class="mac-card">
                    <div class="mac-header">
                        <span class="status-badge <?= $ja_ativado ? 'status-active' : 'status-pending' ?>">
                            <i class="fas <?= $ja_ativado ? 'fa-check-circle' : 'fa-clock' ?> mr-1"></i>
                            <?= $ja_ativado ? 'Ativado' : 'Pendente' ?>
                        </span>
                        <a href="?excluir_mac=<?= urlencode($mac_atual) ?>" class="text-danger" onclick="return confirm('Remover este MAC da lista?')" title="Remover">
                            <i class="fas fa-times"></i>
                        </a>
                    </div>
                    <div class="mac-body">
                        <div class="mac-address mb-3 text-center">
                            <?= htmlspecialchars($mac_atual) ?>
                        </div>
                        <div class="mac-info-item">
                            <i class="fas fa-tv"></i>
                            <span class="text-white"><?= htmlspecialchars($mac['deviceName'] ?? 'Dispositivo Desconhecido') ?></span>
                        </div>
                        <div class="mac-info-item">
                            <i class="fas fa-network-wired"></i>
                            <span class="text-muted small">IP: <?= htmlspecialchars($mac['ip'] ?? '0.0.0.0') ?></span>
                        </div>
                        <div class="mac-info-item">
                            <i class="fas fa-calendar-alt"></i>
                            <span class="text-muted small"><?= htmlspecialchars($mac['timestamp'] ?? '-') ?></span>
                        </div>
                    </div>
                    <div class="mac-footer">
                        <?php if (!$ja_ativado): ?>
                            <a href="users_create.php?mac=<?= urlencode($mac_atual) ?>" class="btn btn-success btn-action">
                                <i class="fas fa-rocket"></i> ATIVAR AGORA
                            </a>
                        <?php else: ?>
                            <a href="users_update.php?update=<?= $id_cliente ?>" class="btn btn-info btn-action">
                                <i class="fas fa-user-edit"></i> GERENCIAR
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <!-- Dica -->
    <div class="alert alert-dark border-0 shadow-sm mt-4" style="background: #1e293b;">
        <div class="d-flex align-items-center">
            <div class="icon-box bg-celeste-light mr-3 mb-0">
                <i class="fas fa-lightbulb"></i>
            </div>
            <div>
                <h6 class="mb-1 text-white font-weight-bold">Dica de Uso</h6>
                <p class="mb-0 text-muted small">Esta lista mostra os últimos dispositivos que tentaram acessar o app. Clique em <strong>Ativar Agora</strong> para criar uma conta rapidamente usando o MAC capturado.</p>
            </div>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
