<?php
declare(strict_types=1);

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

$db = gpc_db();
$today = date('Y-m-d');

$totalDevices = (int) $db->query('SELECT COUNT(*) FROM devices')->fetchColumn();
$appLicenses = (int) $db->query("SELECT COUNT(*) FROM devices WHERE COALESCE(access_type,'app_license') = 'app_license'")->fetchColumn();
$partnerDevices = (int) $db->query("SELECT COUNT(*) FROM devices WHERE COALESCE(access_type,'app_license') = 'partner_code'")->fetchColumn();
$stmt = $db->prepare("SELECT COUNT(*) FROM devices WHERE COALESCE(access_type,'app_license') = 'app_license' AND expire_date >= :d");
$stmt->execute([':d' => $today]);
$activeApp = (int) $stmt->fetchColumn();
$stmt = $db->prepare("SELECT COUNT(*) FROM devices WHERE COALESCE(access_type,'app_license') = 'partner_code' AND expire_date >= :d");
$stmt->execute([':d' => $today]);
$activePartner = (int) $stmt->fetchColumn();
$totalDns = (int) $db->query('SELECT COUNT(*) FROM dns_servers')->fetchColumn();
$activeDns = (int) $db->query("SELECT COUNT(*) FROM dns_servers ds LEFT JOIN resellers r ON r.id = ds.reseller_id WHERE ds.status = 1 AND (ds.validity = '' OR ds.validity IS NULL OR ds.validity >= date('now')) AND (ds.reseller_id IS NULL OR (r.active=1 AND (r.validity='' OR r.validity IS NULL OR r.validity >= date('now'))))")->fetchColumn();
$totalResellers = (int) $db->query('SELECT COUNT(*) FROM resellers')->fetchColumn();
$activeResellers = (int) $db->query("SELECT COUNT(*) FROM resellers WHERE active=1 AND (validity='' OR validity IS NULL OR validity >= date('now'))")->fetchColumn();
$businessResellers = (int) $db->query("SELECT COUNT(*) FROM resellers WHERE reseller_plan='business'")->fetchColumn();

$logs = $db->query('SELECT * FROM registration_logs ORDER BY id DESC LIMIT 8')->fetchAll();
?>

<div class="hero-panel">
    <div>
        <span class="eyebrow">SYNTRA ADMIN V2.0</span>
        <h2>Ecossistema híbrido profissional</h2>
        <p>Controle Licenças MAC, Código Parceiro/SYNTRA ID, revendas por plano e status operacional em uma estrutura separada e organizada.</p>
    </div>
    <div class="hero-actions">
        <a class="btn" href="clients_app.php"><i data-lucide="badge-check"></i> Licenças MAC</a>
        <a class="btn btn-ghost" href="revendedores.php"><i data-lucide="users-round"></i> Revendas V2.0</a>
        <a class="btn btn-ghost" href="partner_devices.php"><i data-lucide="network"></i> MACs por Código</a>
        <a class="btn btn-ghost" href="appearance.php"><i data-lucide="palette"></i> Visual</a>
        <a class="btn btn-ghost" href="banners.php"><i data-lucide="images"></i> Banners</a>
        <a class="btn btn-ghost" href="qrcode.php"><i data-lucide="qr-code"></i> QR Code</a>
    </div>
</div>

<div class="stats stats-compact">
    <div class="stat stat-accent">
        <div class="stat-label">Licenças APP</div>
        <div class="stat-value"><?= $appLicenses ?></div>
        <div class="stat-hint"><?= $activeApp ?> ativas via MAC</div>
    </div>
    <div class="stat stat-purple">
        <div class="stat-label">MACs via Código</div>
        <div class="stat-value"><?= $partnerDevices ?></div>
        <div class="stat-hint"><?= $activePartner ?> seguindo DNS/código</div>
    </div>
    <div class="stat stat-green">
        <div class="stat-label">DNS / Códigos</div>
        <div class="stat-value"><?= $totalDns ?></div>
        <div class="stat-hint"><?= $activeDns ?> ativos</div>
    </div>
    <div class="stat">
        <div class="stat-label">Revendas</div>
        <div class="stat-value"><?= $totalResellers ?></div>
        <div class="stat-hint"><?= $activeResellers ?> ativas · <?= $businessResellers ?> Business</div>
    </div>
</div>


<div class="card">
  <div class="card-head"><h2>Status do Sistema</h2><a href="status.php" class="btn btn-sm btn-ghost">Ver detalhes</a></div>
  <div class="card-body status-grid">
    <div class="status-item"><span class="dot ok"></span><strong>Painel Admin</strong><small>Online</small></div>
    <div class="status-item"><span class="dot ok"></span><strong>API / Sync</strong><small>Operacional</small></div>
    <div class="status-item"><span class="dot <?= $activeDns>0?'ok':'warn' ?>"></span><strong>DNS Ativas</strong><small><?= $activeDns ?> liberadas</small></div>
    <div class="status-item"><span class="dot <?= $activeResellers>0?'ok':'warn' ?>"></span><strong>Revendas</strong><small><?= $activeResellers ?> ativas</small></div>
  </div>
</div>

<div class="grid-2">
    <div class="card">
        <div class="card-head">
            <h2>Atalhos de gerenciamento</h2>
        </div>
        <div class="card-body quick-grid">
            <a href="clients_app.php" class="quick-card">
                <i data-lucide="badge-check"></i>
                <strong>Clientes APP</strong>
                <span>MACs com licença própria para acessar o painel cliente.</span>
            </a>
            <a href="dns.php" class="quick-card">
                <i data-lucide="server"></i>
                <strong>Parceiros DNS</strong>
                <span>Cadastro de DNS, código, status e validade da parceria.</span>
            </a>
            <a href="partner_devices.php" class="quick-card">
                <i data-lucide="network"></i>
                <strong>MACs por Código</strong>
                <span>Dispositivos que entraram usando código + usuário + senha.</span>
            </a>
            <a href="logs.php" class="quick-card">
                <i data-lucide="history"></i>
                <strong>Registros</strong>
                <span>Histórico de login, código usado, DNS e horário.</span>
            </a>
            <a href="appearance.php" class="quick-card">
                <i data-lucide="palette"></i>
                <strong>Visual</strong>
                <span>Configurar logo e imagem de fundo usadas pelo aplicativo.</span>
            </a>
            <a href="banners.php" class="quick-card">
                <i data-lucide="images"></i>
                <strong>Banners</strong>
                <span>Adicionar, ativar, desativar e remover banners do app.</span>
            </a>
            <a href="qrcode.php" class="quick-card">
                <i data-lucide="qr-code"></i>
                <strong>QR Code de Suporte</strong>
                <span>Configurar o link do QR Code usado pelo APP e pelo endpoint /api/support_qr.php.</span>
            </a>
        </div>
    </div>

    <div class="card">
        <div class="card-head">
            <h2>Separação de licenças</h2>
        </div>
        <div class="card-body license-info">
            <div class="info-row">
                <span class="badge badge-ok">Licença APP</span>
                <p>Usada para clientes via MAC. Precisa estar ativa para acessar o painel cliente e gerenciar playlists próprias.</p>
            </div>
            <div class="info-row">
                <span class="badge badge-purple">DNS / Código</span>
                <p>Usada para parceiros. O dispositivo segue a validade da DNS/código cadastrado, sem misturar com a licença padrão do APP.</p>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-head">
        <h2>Últimos registros</h2>
        <a href="logs.php" class="btn btn-sm btn-ghost">Ver todos</a>
    </div>
    <div class="card-body flush">
        <div class="table-scroll">
            <table>
                <thead>
                    <tr><th>MAC</th><th>Usuário</th><th>Código</th><th>DNS</th><th>Data</th></tr>
                </thead>
                <tbody>
                    <?php if (!$logs): ?>
                        <tr><td colspan="5" class="empty">Sem registros</td></tr>
                    <?php else: foreach ($logs as $log): ?>
                        <tr>
                            <td><code><?= gpc_h($log['mac_address']) ?></code></td>
                            <td><?= gpc_h($log['username']) ?></td>
                            <td><span class="badge"><?= gpc_h($log['cod_revenda'] ?: '-') ?></span></td>
                            <td><code><?= gpc_h($log['dns_url']) ?></code></td>
                            <td><?= gpc_h($log['registered_at']) ?></td>
                        </tr>
                    <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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