<?php
require_once dirname(__DIR__) . '/includes/auth.php';
require_once dirname(__DIR__) . '/includes/whatsapp_helper.php';
require_once dirname(__DIR__) . '/includes/profile_pairing.php';
require_once dirname(__DIR__) . '/api/_multiserver.php';

$db = new SQLite3('./api/db.db', SQLITE3_OPEN_READONLY);
$dbw = new SQLite3('./api/db.db');
$pdo = new PDO('sqlite:' . dirname(__DIR__) . '/api/db.db');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
wa_ensure_schema($pdo);
pp_ensure_schema($pdo);

$agora = time();
$tipoUser = (string)($_SESSION["tipo_user"] ?? "");
$isAdmin = ($tipoUser === "admin");
$isRev = ($tipoUser === "revendedor");
$revId = (int)($_SESSION["revendedor_id"] ?? 0);

function dashboard_table_columns(SQLite3 $db, string $table): array {
    $cols = [];
    $safeTable = preg_replace('/[^a-zA-Z0-9_]/', '', $table);
    if ($safeTable === '') return $cols;
    $res = @$db->query("PRAGMA table_info($safeTable)");
    if ($res) {
        while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
            if (isset($row['name'])) $cols[] = (string)$row['name'];
        }
    }
    return $cols;
}

function dashboard_has_column(SQLite3 $db, string $table, string $column): bool {
    return in_array($column, dashboard_table_columns($db, $table), true);
}

function dashboard_redirect_with_message(string $message, bool $ok = true): void {
    $type = $ok ? 'success' : 'error';
    header('Location: dashboard.php?wa_status=' . urlencode($type) . '&wa_message=' . urlencode($message));
    exit;
}

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST' && isset($_POST['claim_pairing_code'])) {
    if (!$isAdmin && (!$isRev || $revId <= 0)) {
        dashboard_redirect_with_message('Sessão sem permissão para ativar por código.', false);
    }
    try {
        $claimOwnerId = $isRev ? $revId : 0;
        $claimed = pp_claim_pairing($pdo, (string)($_POST['pairing_code'] ?? ''), $claimOwnerId, $isAdmin);
        header('Location: dashboard.php?wa_status=success&wa_message=' . urlencode('Cliente vinculado. Informe o link M3U para concluir a ativação.') . '&activate_mac=' . urlencode((string)($claimed['mac'] ?? '')));
        exit;
    } catch (Throwable $e) {
        dashboard_redirect_with_message($e->getMessage(), false);
    }
}

function dashboard_fetch_user_row(PDO $pdo, string $mac, bool $isRev, int $revId): ?array {
    if ($isRev) {
        $st = $pdo->prepare('SELECT * FROM usuarios WHERE mac=? AND usuario_id=? LIMIT 1');
        $st->execute([$mac, $revId]);
    } else {
        $st = $pdo->prepare('SELECT * FROM usuarios WHERE mac=? AND (usuario_id IS NULL OR usuario_id=0) LIMIT 1');
        $st->execute([$mac]);
    }
    $row = $st->fetch(PDO::FETCH_ASSOC);
    return $row ?: null;
}

function parseM3uUrl(string $url): array {
    $url = trim($url);
    $parts = parse_url($url);
    if (empty($parts['scheme']) || empty($parts['host']) || !in_array(strtolower($parts['scheme']), ['http','https'], true)) {
        throw new RuntimeException('URL M3U inválida.');
    }
    parse_str((string)($parts['query'] ?? ''), $query);
    $username = trim((string)($query['username'] ?? ''));
    $password = trim((string)($query['password'] ?? ''));
    if ($username === '' || $password === '') {
        throw new RuntimeException('A URL precisa conter username e password.');
    }
    $port = isset($parts['port']) ? ':' . (int)$parts['port'] : '';
    $dns = strtolower((string)$parts['scheme']) . '://' . $parts['host'] . $port;
    return ['dns' => $dns, 'username' => $username, 'password' => $password];
}

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST' && isset($_POST['activate_pending_mac'])) {
    $txStarted = false;
    try {
        $mac = trim((string)($_POST['mac'] ?? ''));
        $m3u = parseM3uUrl((string)($_POST['m3u_url'] ?? ''));
        $validadeRaw = trim((string)($_POST['validade'] ?? ''));
        $validadeTs = $validadeRaw !== '' ? strtotime($validadeRaw) : false;
        if ($validadeTs === false || $validadeTs <= 0) {
            $validadeTs = time() + 30 * 86400;
        }

        $pdo->exec('BEGIN IMMEDIATE');
        $txStarted = true;

        $stCurrent = $pdo->prepare('SELECT rowid AS _rowid, * FROM usuarios WHERE mac=? LIMIT 1');
        $stCurrent->execute([$mac]);
        $current = $stCurrent->fetch(PDO::FETCH_ASSOC);
        if (!$current) throw new RuntimeException('Cliente pendente não encontrado.');

        $currentOwner = (int)($current['usuario_id'] ?? 0);
        $currentStatus = mb_strtolower(trim((string)($current['status'] ?? '')), 'UTF-8');
        $hasCreds = trim((string)($current['dns'] ?? '')) !== ''
            && trim((string)($current['username'] ?? '')) !== ''
            && trim((string)($current['password'] ?? '')) !== '';
        $isPending = !$hasCreds || in_array($currentStatus, ['pending','pendente','aguardando','waiting'], true);
        if (!$isPending) throw new RuntimeException('Este MAC já está ativado.');

        $ownerId = 0;
        if ($isRev) {
            if ($currentOwner !== $revId) {
                throw new RuntimeException('Este cliente ainda não foi vinculado à sua revenda. Use o botão Ativar por código.');
            }
            $ownerId = $revId;
        } elseif ($currentOwner > 0) {
            throw new RuntimeException('Este MAC pertence a uma revenda.');
        }

        $hasUpdatedAt = false;
        $cols = $pdo->query("PRAGMA table_info(usuarios)")->fetchAll(PDO::FETCH_ASSOC);
        foreach ($cols as $c) {
            if (($c['name'] ?? '') === 'updated_at') { $hasUpdatedAt = true; break; }
        }

        $fields = 'dns=?, username=?, password=?, status=?, vencimento=?, usuario_id=?';
        $params = [$m3u['dns'], $m3u['username'], $m3u['password'], 'ativo', (int)$validadeTs, $ownerId];
        if ($hasUpdatedAt) {
            $fields .= ', updated_at=?';
            $params[] = time();
        }
        $rowId = (int)($current['_rowid'] ?? 0);
        if ($rowId <= 0) {
            throw new RuntimeException('Não foi possível identificar o registro do MAC pendente.');
        }
        $params[] = $rowId;

        // BEGIN IMMEDIATE impede outra ativação concorrente. Não usamos rowCount()
        // como detector de conflito porque o PDO/SQLite pode retornar zero em uma
        // atualização válida; o estado final é confirmado por releitura.
        $st = $pdo->prepare("UPDATE usuarios SET {$fields} WHERE rowid=?");
        $st->execute($params);

        $stVerify = $pdo->prepare('SELECT usuario_id, status, dns, username, password FROM usuarios WHERE rowid=? LIMIT 1');
        $stVerify->execute([$rowId]);
        $verified = $stVerify->fetch(PDO::FETCH_ASSOC);
        $activationOk = $verified
            && (int)($verified['usuario_id'] ?? 0) === $ownerId
            && mb_strtolower(trim((string)($verified['status'] ?? '')), 'UTF-8') === 'ativo'
            && trim((string)($verified['dns'] ?? '')) === $m3u['dns']
            && trim((string)($verified['username'] ?? '')) === $m3u['username']
            && trim((string)($verified['password'] ?? '')) === $m3u['password'];

        if (!$activationOk) {
            throw new RuntimeException('Não foi possível confirmar a ativação do MAC. Atualize a página e tente novamente.');
        }

        if ($isRev) {
            $pdo->prepare('DELETE FROM revendedor_clientes WHERE mac=?')->execute([$mac]);
            $pdo->prepare('INSERT OR IGNORE INTO revendedor_clientes (mac,revendedor_id,created_at) VALUES (?,?,?)')
                ->execute([$mac,$revId,time()]);
        }

        $pdo->exec('COMMIT');
        $txStarted = false;

        try {
            ms_save_servers($pdo, $mac, $ownerId, [[
                'name' => 'Servidor principal',
                'dns' => $m3u['dns'],
                'username' => $m3u['username'],
                'password' => $m3u['password'],
            ]]);
        } catch (Throwable $syncError) {
            error_log('[dashboard] Falha ao sincronizar servidor do MAC ' . $mac . ': ' . $syncError->getMessage());
        }

        dashboard_redirect_with_message('Cliente ativado e vinculado com sucesso.', true);
    } catch (Throwable $e) {
        if ($txStarted) {
            try { $pdo->exec('ROLLBACK'); } catch (Throwable $ignored) {}
        }
        dashboard_redirect_with_message($e->getMessage(), false);
    }
}

if(isset($_GET["renew"]) && trim((string)$_GET["renew"]) !== ''){
    $macAction = trim((string)$_GET["renew"]);
    if ($isRev) {
        $stUp = $pdo->prepare("UPDATE usuarios SET vencimento = CASE WHEN vencimento IS NULL OR vencimento < strftime('%s','now') THEN strftime('%s','now') + (30*86400) ELSE vencimento + (30*86400) END, whatsapp_activated_at = strftime('%s','now') WHERE mac=? AND usuario_id=?");
        $stUp->execute([$macAction, $revId]);
    } else {
        $stUp = $pdo->prepare("UPDATE usuarios SET vencimento = CASE WHEN vencimento IS NULL OR vencimento < strftime('%s','now') THEN strftime('%s','now') + (30*86400) ELSE vencimento + (30*86400) END, whatsapp_activated_at = strftime('%s','now') WHERE mac=? AND (usuario_id IS NULL OR usuario_id=0)");
        $stUp->execute([$macAction]);
    }
    $userRow = dashboard_fetch_user_row($pdo, $macAction, $isRev, $revId);
    if (!$userRow) dashboard_redirect_with_message('Usuário não encontrado.', false);
    if (empty($userRow['whatsapp'])) dashboard_redirect_with_message('Cliente sem WhatsApp cadastrado.', false);
    $sendResult = wa_send_template_to_user($pdo, $userRow, 'confirmacao_renovacao', [], '30 dias');
    dashboard_redirect_with_message($sendResult['ok'] ? 'Renovação concluída e mensagem enviada.' : ($sendResult['message'] ?: 'Renovação concluída, mas houve falha ao enviar a mensagem.'), (bool)$sendResult['ok']);
}

if(isset($_GET["send_manual_due"]) && trim((string)$_GET["send_manual_due"]) !== ''){
    $macAction = trim((string)$_GET["send_manual_due"]);
    $userRow = dashboard_fetch_user_row($pdo, $macAction, $isRev, $revId);
    if (!$userRow) dashboard_redirect_with_message('Usuário não encontrado.', false);
    if (empty($userRow['whatsapp'])) dashboard_redirect_with_message('Cliente sem WhatsApp cadastrado.', false);
    $sendResult = wa_send_template_to_user($pdo, $userRow, 'cobranca_manual');
    dashboard_redirect_with_message($sendResult['ok'] ? 'Cobrança enviada com sucesso.' : ($sendResult['message'] ?: 'Falha ao enviar cobrança.'), (bool)$sendResult['ok']);
}

if(isset($_GET["delete_expired"]) && $isAdmin){
    $dbDel = new SQLite3('./api/db.db');
    $dbDel->exec("
        DELETE FROM usuarios
        WHERE vencimento IS NOT NULL
        AND vencimento > 0
        AND vencimento < $agora
        AND (usuario_id IS NULL OR usuario_id=0)
    ");
    dashboard_redirect_with_message('Usuários vencidos apagados com sucesso.', true);
}

$timeout = $agora - 60;

if($isRev && $revId <= 0){
    header("Location: sair.php");
    exit;
}

$res_online = $db->query("
    SELECT COUNT(*) AS total 
    FROM online_status os
    INNER JOIN usuarios u ON u.mac = os.mac
    WHERE os.is_online = 1 
    AND os.last_seen >= $timeout
    AND (u.usuario_id IS NULL OR u.usuario_id=0)
");
$row_online = $res_online ? $res_online->fetchArray(SQLITE3_ASSOC) : ["total"=>0];
$total_online_users = intval($row_online["total"] ?? 0);

$res_total = $db->query("SELECT COUNT(*) AS total FROM usuarios WHERE (usuario_id IS NULL OR usuario_id=0)");
$row_total = $res_total ? $res_total->fetchArray(SQLITE3_ASSOC) : ["total"=>0];
$total_users = intval($row_total["total"] ?? 0);

$res_vencidos = $db->query("
    SELECT COUNT(*) AS total 
    FROM usuarios 
    WHERE vencimento IS NOT NULL 
    AND vencimento > 0 
    AND vencimento < $agora
    AND (usuario_id IS NULL OR usuario_id=0)
");
$row_vencidos = $res_vencidos ? $res_vencidos->fetchArray(SQLITE3_ASSOC) : ["total"=>0];
$total_vencidos = intval($row_vencidos["total"] ?? 0);

$res_lista_online = $db->query("
    SELECT os.mac, os.content_type, os.content_title, os.is_playing, os.last_seen
    FROM online_status os
    INNER JOIN usuarios u ON u.mac = os.mac
    WHERE os.is_online = 1 
    AND os.last_seen >= $timeout
    AND (u.usuario_id IS NULL OR u.usuario_id=0)
    ORDER BY os.last_seen DESC
");

$res_users = $db->query("
    SELECT rowid, *
    FROM usuarios
    WHERE (usuario_id IS NULL OR usuario_id=0)
    AND mac IS NOT NULL AND mac<>''
    AND (dns IS NULL OR dns='' OR username IS NULL OR username='' OR password IS NULL OR password='' OR lower(COALESCE(status,'')) IN ('pending','pendente','aguardando'))
    ORDER BY rowid DESC
    LIMIT 10
");

$precoPlano = 0.0;
$stPlanoMensal = $db->query("
    SELECT valor FROM pagamentos_app
    WHERE lower(nome) LIKE '%mensal%'
    ORDER BY valor ASC
    LIMIT 1
");
if ($stPlanoMensal) {
    $rowPlano = $stPlanoMensal->fetchArray(SQLITE3_ASSOC);
    if ($rowPlano && isset($rowPlano["valor"])) $precoPlano = (float)$rowPlano["valor"];
}
if ($precoPlano <= 0) {
    $stPlano = $db->query("SELECT valor FROM pagamentos_app ORDER BY valor ASC LIMIT 1");
    $rowPlano = $stPlano ? $stPlano->fetchArray(SQLITE3_ASSOC) : null;
    if ($rowPlano && isset($rowPlano["valor"])) $precoPlano = (float)$rowPlano["valor"];
}

$limite30 = $agora + (30 * 86400);

$res_vencer_30 = $db->query("
    SELECT COUNT(*) AS total 
    FROM usuarios
    WHERE vencimento IS NOT NULL
    AND vencimento > 0
    AND vencimento >= $agora
    AND vencimento <= $limite30
    AND (usuario_id IS NULL OR usuario_id=0)
");
$row_vencer_30 = $res_vencer_30 ? $res_vencer_30->fetchArray(SQLITE3_ASSOC) : ["total"=>0];
$total_vencer_30 = intval($row_vencer_30["total"] ?? 0);

$valor_previsto_30 = $total_vencer_30 * $precoPlano;

$total_testes_gerados = 0;
$usuariosColumnsForTests = dashboard_table_columns($db, 'usuarios');
$testConditions = [];

if (in_array('teste', $usuariosColumnsForTests, true)) {
    $testConditions[] = "CAST(COALESCE(teste,'0') AS TEXT) IN ('1','true','sim','teste')";
}
if (in_array('teste_criado_at', $usuariosColumnsForTests, true)) {
    $testConditions[] = "COALESCE(teste_criado_at,0) > 0";
}
if (in_array('tipo_registro', $usuariosColumnsForTests, true)) {
    $testConditions[] = "lower(COALESCE(tipo_registro,'')) = 'teste'";
}
if (in_array('tipo', $usuariosColumnsForTests, true)) {
    $testConditions[] = "lower(COALESCE(tipo,'')) = 'teste'";
}
if (!empty($testConditions)) {
    $whereTest = implode(' OR ', $testConditions);
    $total_testes_gerados = (int)@$db->querySingle("
        SELECT COUNT(*)
        FROM usuarios
        WHERE (usuario_id IS NULL OR usuario_id=0)
        AND ($whereTest)
    ");
}

$rev_mac_limit = 0;
$rev_usados = 0;
$rev_restantes = 0;
$rev_vencimento = "";
$rev_status = "";
$rev_nome = "";
$rev_total_vencidos = 0;
$rev_total_users = 0;
$rev_total_online_users = 0;
$rev_total_vencer_30 = 0;
$rev_valor_previsto_30 = 0;

$res_lista_online_rev = null;
$res_users_rev = null;

if($isRev){
    if($revId <= 0){
        header("Location: sair.php");
        exit;
    }

    $rev = $db->querySingle("SELECT * FROM revendedores WHERE id=".$revId." LIMIT 1", true);
    if(!$rev){
        header("Location: sair.php");
        exit;
    }

    $rev_nome = (string)($rev["nome"] ?? "");
    $rev_status = (string)($rev["status"] ?? "");
    $rev_vencimento = (string)($rev["vencimento"] ?? "");
    $rev_mac_limit = (int)($rev["mac_limit"] ?? 0);

    $rev_usados = (int)$db->querySingle("SELECT COUNT(*) FROM usuarios WHERE usuario_id=".$revId);
    $rev_restantes = max(0, $rev_mac_limit - $rev_usados);

    $rev_total_online_users = (int)$db->querySingle("
        SELECT COUNT(*)
        FROM online_status os
        INNER JOIN usuarios u ON u.mac = os.mac
        WHERE u.usuario_id = $revId
        AND os.is_online = 1
        AND os.last_seen >= $timeout
    ");

    $rev_total_users = (int)$db->querySingle("
        SELECT COUNT(*)
        FROM usuarios
        WHERE usuario_id = $revId
    ");

    $rev_total_vencidos = (int)$db->querySingle("
        SELECT COUNT(*)
        FROM usuarios u
        WHERE u.usuario_id = $revId
        AND u.vencimento IS NOT NULL
        AND u.vencimento > 0
        AND u.vencimento < $agora
    ");

    $rev_limite30 = $agora + (30 * 86400);

    $rev_total_vencer_30 = (int)$db->querySingle("
        SELECT COUNT(*)
        FROM usuarios u
        WHERE u.usuario_id = $revId
        AND u.vencimento IS NOT NULL
        AND u.vencimento > 0
        AND u.vencimento >= $agora
        AND u.vencimento <= $rev_limite30
    ");

    $rev_valor_previsto_30 = $rev_total_vencer_30 * $precoPlano;

    $res_lista_online_rev = $db->query("
        SELECT os.mac, os.content_type, os.content_title, os.is_playing, os.last_seen
        FROM online_status os
        INNER JOIN usuarios u ON u.mac = os.mac
        WHERE u.usuario_id = $revId
        AND os.is_online = 1 
        AND os.last_seen >= $timeout
        ORDER BY os.last_seen DESC
    ");

    $res_users_rev = $db->query("
        SELECT u.rowid, u.*
        FROM usuarios u
        WHERE u.usuario_id = $revId
        AND u.mac IS NOT NULL AND u.mac<>''
        AND (u.dns IS NULL OR u.dns='' OR u.username IS NULL OR u.username='' OR u.password IS NULL OR u.password='' OR lower(COALESCE(u.status,'')) IN ('pending','pendente','aguardando','waiting'))
        ORDER BY u.rowid DESC
        LIMIT 30
    ");
}

require_once __DIR__ . '/../includes/header.php';
?>
<div class="dns-wrap">

    <div class="card radius-10 dns-card">
        <div class="card-header bg-transparent dns-header">
            <div class="dns-title">
                <div class="ic"><i class="bi bi-speedometer2"></i></div>
                <div>
                    <h5><?= $isRev ? "Painel Revenda" : "Painel Admin" ?></h5>
                    <span><?= $isRev ? "Monitoramento e ações rápidas da sua revenda" : "Monitoramento em tempo real e ações rápidas" ?></span>
                </div>
            </div>

            <div class="dns-actions">
                <span class="badge-soft"><i class="bi bi-activity"></i> Dashboard</span>
            </div>
        </div>

        <div class="card-body">
            <?php if(!$isRev){ ?>
                <div class="kpi-grid">
                    <div class="kpi">
                        <span class="kpi-tag tag-danger"><i class="bi bi-exclamation-triangle-fill"></i> vencidos</span>
                        <div class="kpi-inner">
                            <div class="kpi-img"><img src="assets/images/8943377.png"></div>
                            <div class="kpi-meta">
                                <div class="v"><?= $total_vencidos ?></div>
                                <div class="s">Acesso expirado</div>
                            </div>
                        </div>
                    </div>

                    <div class="kpi clickable" data-open-modal="modalOnline" role="button" tabindex="0">
                        <span class="kpi-tag tag-success"><i class="bi bi-wifi"></i> online</span>
                        <div class="kpi-inner">
                            <div class="kpi-img"><img src="assets/images/6073874.png"></div>
                            <div class="kpi-meta">
                                <div class="v"><?= $total_online_users ?></div>
                                <div class="s">Tempo real</div>
                            </div>
                        </div>
                    </div>

                    <div class="kpi">
                        <span class="kpi-tag tag-primary"><i class="bi bi-people-fill"></i> total</span>
                        <div class="kpi-inner">
                            <div class="kpi-img"><img src="assets/images/9255685.png"></div>
                            <div class="kpi-meta">
                                <div class="v"><?= $total_users ?></div>
                                <div class="s">MACs cadastrados</div>
                            </div>
                        </div>
                    </div>

                    <div class="kpi">
                        <span class="kpi-tag tag-primary"><i class="bi bi-hourglass-split"></i> testes</span>
                        <div class="kpi-inner">
                            <div class="kpi-img"><img src="assets/images/icons/testes-gerados.svg" alt="Total de testes gerados"></div>
                            <div class="kpi-meta">
                                <div class="v"><?= $total_testes_gerados ?></div>
                                <div class="s">Total de testes gerados</div>
                            </div>
                        </div>
                    </div>
                </div>
            <?php } ?>

            <?php if($isRev){ ?>
                <div class="kpi-grid">
                    <div class="kpi">
                        <span class="kpi-tag tag-primary"><i class="bi bi-hdd-network-fill"></i> limite</span>
                        <div class="kpi-inner">
                            <div class="kpi-img"><img src="assets/images/9255685.png"></div>
                            <div class="kpi-meta">
                                <div class="v"><?= (int)$rev_mac_limit ?></div>
                                <div class="s">MACs permitidos</div>
                            </div>
                        </div>
                    </div>

                    <div class="kpi">
                        <span class="kpi-tag tag-success"><i class="bi bi-graph-up-arrow"></i> usados</span>
                        <div class="kpi-inner">
                            <div class="kpi-img"><img src="assets/images/6073874.png"></div>
                            <div class="kpi-meta">
                                <div class="v"><?= (int)$rev_usados ?></div>
                                <div class="s">Clientes cadastrados</div>
                            </div>
                        </div>
                    </div>

                    <div class="kpi">
                        <span class="kpi-tag tag-purple"><i class="bi bi-box-arrow-in-down"></i> restantes</span>
                        <div class="kpi-inner">
                            <div class="kpi-img"><img src="assets/images/8928591.png"></div>
                            <div class="kpi-meta">
                                <div class="v"><?= (int)$rev_restantes ?></div>
                                <div class="s">Disponível</div>
                            </div>
                        </div>
                    </div>

                    <div class="kpi">
                        <div class="kpi-inner">
                            <div class="kpi-img"><img src="assets/images/8943377.png"></div>
                            <div class="kpi-meta">
                                <div class="v"><?= $rev_vencimento ? date("d/m/Y", strtotime($rev_vencimento)) : "-" ?></div>
                                <div class="s"><?= $rev_nome ? htmlspecialchars($rev_nome, ENT_QUOTES, 'UTF-8') : "Revenda" ?></div>
                            </div>
                        </div>
                    </div>
                </div>
            <?php } ?>
        </div>
    </div>


    <?php if($isAdmin || $isRev){ ?>
    <div class="card radius-10 dns-card pairing-card">
        <div class="pairing-body">
            <div class="pairing-copy">
                <span class="badge-soft mb-2"><i class="bi bi-link-45deg"></i> Vincular pelo código</span>
                <h5>Adicionar cliente pelo código de 4 dígitos</h5>
                <p>No aplicativo, o cliente toca em <strong>Entrar por código do revendedor</strong> e envia o código exibido. Digite-o aqui para vincular o MAC automaticamente a <?= $isAdmin ? 'conta do administrador' : 'sua revenda' ?>.</p>
            </div>
            <div class="pairing-form">
                <button type="button" class="btn btn-primary pairing-submit w-100" data-bs-toggle="modal" data-bs-target="#dashboardPairingModal" id="btnDashboardPairing">
                    <i class="bi bi-key-fill"></i> Ativar por código
                </button>
            </div>
        </div>
    </div>
    <?php } ?>

    <div class="card radius-10 dns-card">
        <div class="card-header bg-transparent dns-header">
            <div class="dns-title">
                <div class="ic"><i class="bi bi-person-plus-fill"></i></div>
                <div>
                    <h5>Clientes aguardando ativação</h5>
                    <span>MACs cadastrados no app que ainda precisam receber DNS, usuário e senha</span>
                </div>
            </div>

            <div class="dns-actions">
                <span class="badge-soft"><i class="bi bi-hourglass-split"></i> Pendentes</span>
            </div>
        </div>

        <div class="card-body table-responsive p-0">
            <table class="table table-hover table-sm align-middle">
                <thead>
                    <tr>
                        <th>MAC</th>
                        <th>Cliente</th>
                        <th>Usuário</th>
                        <th>Status</th>
                        <th>Vencimento</th>
                        <th class="text-center">Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $lista = $isRev ? $res_users_rev : $res_users;
                    $temPendente = false;

                    if ($lista) {
                        while ($u = $lista->fetchArray(SQLITE3_ASSOC)) {
                            $temPendente = true;

                            $vencTxt = "—";
                            if (!empty($u["vencimento"])) {
                                $vencTxt = $u["vencimento"] < $agora
                                    ? "<span class='text-danger fw-1000'>".date("d/m/Y",(int)$u["vencimento"])."</span>"
                                    : "<span class='fw-1000'>".date("d/m/Y",(int)$u["vencimento"])."</span>";
                            }

                            $online = $db->querySingle("
                                SELECT COUNT(*) FROM online_status
                                WHERE mac = '".$db->escapeString($u["mac"])."'
                                AND is_online = 1 
                                AND last_seen >= $timeout
                            ") > 0;

                            $nomeCli = $u["nome_cliente"] ?? "—";
                            $whats = (string)($u["whatsapp"] ?? "");
                            $msg = urlencode("Olá {$nomeCli}, seu acesso venceu ou está próximo do vencimento. Renove para continuar 👍");
                            $zap = "https://wa.me/55".preg_replace('/\D/','',$whats)."?text=".$msg;
                    ?>
                            <tr>
                                <td class="mac"><?= htmlspecialchars((string)$u["mac"], ENT_QUOTES, 'UTF-8') ?></td>

                                <td>
                                    <div class="d-flex flex-column">
                                        <span class="fw-1000"><?= htmlspecialchars((string)$nomeCli, ENT_QUOTES, 'UTF-8') ?></span>
                                        <span class="user-sub">
                                            <i class="bi bi-telephone-fill"></i>
                                            <?= $whats ? htmlspecialchars($whats, ENT_QUOTES, 'UTF-8') : "—" ?>
                                        </span>
                                    </div>
                                </td>

                                <td>
                                    <div class="d-flex flex-column">
                                        <span class="fw-1000"><?= htmlspecialchars((string)$u["username"], ENT_QUOTES, 'UTF-8') ?></span>
                                        <span class="user-sub">
                                            <i class="bi bi-hdd-network-fill"></i>
                                            <?= htmlspecialchars((string)($u["dns"] ?? "—"), ENT_QUOTES, 'UTF-8') ?>
                                        </span>
                                    </div>
                                </td>

                                <td>
                                    <span class='badge bg-warning text-dark'><i class='bi bi-hourglass-split'></i> Aguardando</span>
                                </td>

                                <td><?= $vencTxt ?></td>

                                <td class="text-center">
                                    <div class="actions">
                                        <button type="button" class="action-btn btn-dashboard-activate"
                                            data-mac="<?= htmlspecialchars((string)$u["mac"], ENT_QUOTES, 'UTF-8') ?>"
                                            title="Ativar">
                                            <i class="bi bi-lightning-charge-fill text-success"></i><span>Ativar</span>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                    <?php
                        }
                    }
                    ?>

                    <?php if(!$temPendente): ?>
                        <tr>
                            <td colspan="6" class="text-center text-muted py-4">Nenhum cliente aguardando ativação.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php if ($isAdmin || $isRev): ?>
<div class="modal fade" id="dashboardPairingModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form method="post" autocomplete="off" id="dashboardPairingForm">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-key-fill"></i> Ativar cliente por código</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="claim_pairing_code" value="1">
                    <label class="fw-900">Código exibido no aplicativo</label>
                    <input class="form-control pairing-code mt-2" id="dashboardPairingCode" name="pairing_code" inputmode="numeric" pattern="[0-9]{4}" maxlength="4" placeholder="0000" required>
                    <div class="alert alert-info mt-3 mb-0">O cliente será vinculado <?= $isAdmin ? 'ao administrador' : 'somente à sua revenda' ?>. Em seguida, informe o link M3U para liberar o acesso.</div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary back-btn" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary save-btn"><i class="bi bi-person-check-fill"></i> Salvar e vincular</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="modal fade" id="dashboardActivateModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <form method="post" id="dashboardActivateForm">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-lightning-charge-fill"></i> Ativar cliente</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body">
                    <input type="hidden" name="activate_pending_mac" value="1">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="fw-900">MAC</label>
                            <input class="form-control input-radius" name="mac" id="dashActivateMac" readonly>
                        </div>

                        <div class="col-md-6">
                            <label class="fw-900">Validade da conta</label>
                            <input type="datetime-local" class="form-control input-radius" name="validade" id="dashActivateValidade">
                        </div>

                        <div class="col-12">
                            <label class="fw-900">Link M3U</label>
                            <input type="url" class="form-control input-radius" name="m3u_url" placeholder="http://thefull.top/get.php?username=usuario&password=senha&type=m3u&output=ts" required>
                        </div>

                        <div class="col-12">
                            <div class="alert alert-info mb-0">O painel vai separar DNS, usuário e senha automaticamente e liberar o MAC no app.</div>
                        </div>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary back-btn" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-success save-btn"><i class="bi bi-check2-circle"></i> Ativar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div id="dashboardRuntime" hidden data-auto-mac="<?= htmlspecialchars(pp_normalize_mac((string)($_GET['activate_mac'] ?? '')), ENT_QUOTES, 'UTF-8') ?>"></div>
<div class="modal fade" id="modalOnline" tabindex="-1">
    <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-1000"><i class="bi bi-broadcast"></i> Clientes Online Agora</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body table-responsive">
                <table class="table table-hover table-sm align-middle">
                    <thead>
                        <tr>
                            <th>MAC</th>
                            <th>Tipo</th>
                            <th>Assistindo</th>
                            <th>Status</th>
                            <th>Última Atividade</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $tem = false;
                        $listaOnline = $isRev ? $res_lista_online_rev : $res_lista_online;

                        if ($listaOnline) {
                            while ($o = $listaOnline->fetchArray(SQLITE3_ASSOC)) {
                                $tem = true;
                        ?>
                                <tr>
                                    <td class="mac"><?= htmlspecialchars((string)$o["mac"], ENT_QUOTES, 'UTF-8') ?></td>
                                    <td><span class="badge bg-dark"><?= strtoupper((string)$o["content_type"]) ?></span></td>
                                    <td><?= htmlspecialchars((string)($o["content_title"] ?: "—"), ENT_QUOTES, 'UTF-8') ?></td>
                                    <td>
                                        <?= $o["is_playing"]
                                            ? "<span class='badge bg-success'><i class='bi bi-play-fill'></i> Tocando</span>"
                                            : "<span class='badge bg-warning text-dark'><i class='bi bi-pause-fill'></i> Pausado</span>"
                                        ?>
                                    </td>
                                    <td><?= date("d/m/Y H:i:s",(int)$o["last_seen"]) ?></td>
                                </tr>
                        <?php
                            }
                        }
                        ?>

                        <?php if(!$tem){ ?>
                            <tr><td colspan="5" class="text-center text-muted">Nenhum usuário online</td></tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>