<?php
require_once dirname(__DIR__) . '/includes/auth.php';
require_once dirname(__DIR__) . '/includes/whatsapp_helper.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);

$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;
}

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'])) {
    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;
        }
        $ownerSql = $isRev ? 'AND usuario_id = ?' : 'AND (usuario_id IS NULL OR usuario_id=0)';
        $hasUpdatedAt = false;
        try {
            $cols = $pdo->query("PRAGMA table_info(usuarios)")->fetchAll(PDO::FETCH_ASSOC);
            foreach ($cols as $c) {
                if (($c['name'] ?? '') === 'updated_at') {
                    $hasUpdatedAt = true;
                    break;
                }
            }
        } catch (Throwable $e) {
        }
        if ($hasUpdatedAt) {
            $sql = "UPDATE usuarios SET dns=?, username=?, password=?, status=?, vencimento=?, updated_at=? WHERE mac=? $ownerSql";
            $params = $isRev ? [$m3u['dns'], $m3u['username'], $m3u['password'], 'ativo', $validadeTs, time(), $mac, $revId] : [$m3u['dns'], $m3u['username'], $m3u['password'], 'ativo', $validadeTs, time(), $mac];
        } else {
            $sql = "UPDATE usuarios SET dns=?, username=?, password=?, status=?, vencimento=? WHERE mac=? $ownerSql";
            $params = $isRev ? [$m3u['dns'], $m3u['username'], $m3u['password'], 'ativo', $validadeTs, $mac, $revId] : [$m3u['dns'], $m3u['username'], $m3u['password'], 'ativo', $validadeTs, $mac];
        }
        $st = $pdo->prepare($sql);
        $st->execute($params);
        dashboard_redirect_with_message('Cliente ativado com sucesso.', true);
    } catch (Throwable $e) {
        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'))
        ORDER BY u.rowid DESC
        LIMIT 10
    ");
}

include ('./includes/header.php');
?>

<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">

<style>
.dns-wrap{
    width:100%;
    max-width:none;
    margin:0;
    padding:0 18px;
}
.dns-card{
    border-radius:18px;
    overflow:hidden;
    width:100%;
    margin-bottom:18px;
}
.dns-header{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    padding:18px 22px;
}
.dns-title{
    display:flex;
    align-items:center;
    gap:14px;
}
.dns-title .ic{
    width:44px;
    height:44px;
    min-width:44px;
    border-radius:14px;
    background:rgba(25,135,84,.10);
    border:1px solid rgba(25,135,84,.20);
    display:flex;
    align-items:center;
    justify-content:center;
}
.dns-title .ic i{
    font-size:24px;
    color:#198754;
}
.dns-title h5{
    margin:0;
    font-weight:900;
}
.dns-title span{
    display:block;
    margin-top:3px;
    font-size:13px;
    color:rgba(255,255,255,.55);
}
.badge-soft{
    display:inline-flex;
    align-items:center;
    gap:7px;
    padding:8px 12px;
    border-radius:999px;
    background:rgba(25,135,84,.10);
    border:1px solid rgba(25,135,84,.20);
    color:#198754;
    font-weight:900;
    white-space:nowrap;
}
.kpi-grid{
    display:grid;
    grid-template-columns:repeat(12,1fr);
    gap:14px;
    margin-bottom:18px;
}
.kpi{
    grid-column:span 3;
    border-radius:18px;
    overflow:hidden;
    border:1px solid rgba(0,0,0,.06);
    background:rgba(255,255,255,.02);
    position:relative;
    cursor:default;
    transition:transform .12s ease, box-shadow .12s ease;
}
.kpi:hover{
    transform:translateY(-2px);
    box-shadow:0 12px 30px rgba(0,0,0,.10);
}
.kpi.clickable{
    cursor:pointer;
}
.kpi-inner{
    padding:16px;
    display:flex;
    align-items:center;
    gap:14px;
}
.kpi-img{
    width:62px;
    height:62px;
    min-width:62px;
    border-radius:18px;
    display:flex;
    align-items:center;
    justify-content:center;
    background:rgba(0,0,0,.03);
    border:1px solid rgba(0,0,0,.05);
    overflow:hidden;
}
.kpi-img img{
    width:44px;
    height:44px;
    object-fit:contain;
    opacity:.95;
}
.kpi-meta{
    flex:1;
    display:flex;
    flex-direction:column;
    gap:2px;
}
.kpi-meta .v{
    font-size:28px;
    font-weight:1000;
    line-height:1;
}
.kpi-meta .s{
    font-size:13px;
    opacity:.75;
}
.kpi-tag{
    position:absolute;
    top:12px;
    right:12px;
    padding:6px 10px;
    border-radius:999px;
    font-weight:1000;
    font-size:11px;
    border:1px solid rgba(0,0,0,.08);
    background:rgba(0,0,0,.04);
}
.tag-danger{
    border-color:rgba(220,53,69,.22);
    background:rgba(220,53,69,.08);
    color:#dc3545;
}
.tag-success{
    border-color:rgba(25,135,84,.22);
    background:rgba(25,135,84,.08);
    color:#198754;
}
.tag-primary{
    border-color:rgba(13,110,253,.22);
    background:rgba(13,110,253,.08);
    color:#0d6efd;
}
.tag-purple{
    border-color:rgba(111,66,193,.22);
    background:rgba(111,66,193,.08);
    color:#6f42c1;
}
.table{
    margin:0;
}
.table thead th{
    font-size:12px;
    text-transform:uppercase;
    letter-spacing:.6px;
    opacity:.75;
    font-weight:1000;
    white-space:nowrap;
}
.table td{
    padding-top:14px;
    padding-bottom:14px;
    vertical-align:middle;
}
.mac{
    font-weight:1000;
    letter-spacing:.2px;
}
.user-sub{
    font-size:12px;
    opacity:.75;
    margin-top:2px;
}
.badge{
    border-radius:999px;
    padding:7px 10px;
    font-weight:1000;
    letter-spacing:.2px;
}
.actions{
    display:flex;
    gap:10px;
    justify-content:center;
}
.action-btn{
    min-width:42px;
    height:38px;
    border-radius:12px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:7px;
    text-decoration:none;
    border:1px solid rgba(0,0,0,.08);
    background:rgba(0,0,0,.03);
    transition:transform .12s ease, box-shadow .12s ease;
    font-weight:900;
    padding:0 12px;
}
.action-btn:hover{
    transform:translateY(-1px);
    box-shadow:0 10px 20px rgba(0,0,0,.12);
}
.action-btn i{
    font-size:18px;
}
.input-radius{
    border-radius:14px !important;
    min-height:48px;
}
.save-btn{
    border-radius:14px;
    min-height:46px;
    font-weight:900;
    padding-left:22px;
    padding-right:22px;
}
.back-btn{
    border-radius:14px;
    min-height:46px;
    font-weight:900;
    padding-left:22px;
    padding-right:22px;
}
.modal-content{
    border-radius:20px !important;
    overflow:hidden;
}
.modal-header{
    background:rgba(0,0,0,.02);
    border-bottom:1px solid rgba(0,0,0,.06);
}
.small-muted{
    margin-top:3px;
    font-size:13px;
    color:rgba(255,255,255,.55);
}
.alert{
    border-radius:14px;
}
@media(max-width:992px){
    .kpi{
        grid-column:span 6;
    }
}
@media(max-width:575px){
    .dns-wrap{
        padding:0 8px;
    }
    .dns-header{
        align-items:flex-start;
        padding:16px;
    }
    .dns-title .ic{
        width:40px;
        height:40px;
        min-width:40px;
    }
    .dns-title .ic i{
        font-size:22px;
    }
    .dns-title h5{
        font-size:18px;
    }
    .badge-soft{
        padding:7px 10px;
        font-size:12px;
    }
    .kpi{
        grid-column:span 12;
    }
    .save-btn,
    .back-btn{
        width:100%;
    }
}

/* SCROLLBAR CINZA - PC E MOBILE */
html{
  scrollbar-width: thin;
  scrollbar-color: #8f8f8f #1f1f1f;
}

body{
  scrollbar-width: thin;
  scrollbar-color: #8f8f8f #1f1f1f;
}

*::-webkit-scrollbar{
  width: 10px;
  height: 10px;
}

*::-webkit-scrollbar-track{
  background: #1f1f1f;
  border-radius: 999px;
}

*::-webkit-scrollbar-thumb{
  background: linear-gradient(180deg, #b8b8b8, #7c7c7c);
  border-radius: 999px;
  border: 2px solid #1f1f1f;
}

*::-webkit-scrollbar-thumb:hover{
  background: linear-gradient(180deg, #d0d0d0, #909090);
}

.table-responsive{
  scrollbar-width: thin;
  scrollbar-color: #8f8f8f #1f1f1f;
}

@media (max-width: 768px){
  *::-webkit-scrollbar{
    width: 7px;
    height: 7px;
  }
}
</style>

<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" onclick="abrirOnline()">
                        <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>

    <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 style='color:#dc3545;font-weight:1000'>".date("d/m/Y",(int)$u["vencimento"])."</span>"
                                    : "<span style='font-weight: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 style="display:flex;flex-direction:column;">
                                        <span style="font-weight: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 style="display:flex;flex-direction:column;">
                                        <span style="font-weight: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>

<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 style="font-weight:900;">MAC</label>
                            <input class="form-control input-radius" name="mac" id="dashActivateMac" readonly>
                        </div>

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

                        <div class="col-12">
                            <label style="font-weight: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>

<script>
(function(){
    function dashPad(n){
        return String(n).padStart(2, '0');
    }

    function dashDefaultDate(){
        var dt = new Date();
        dt.setDate(dt.getDate() + 30);
        return dt.getFullYear() + '-' + dashPad(dt.getMonth() + 1) + '-' + dashPad(dt.getDate()) + 'T' + dashPad(dt.getHours()) + ':' + dashPad(dt.getMinutes());
    }

    function dashGetModal(){
        return document.getElementById('dashboardActivateModal');
    }

    function dashRemoveBackdrop(){
        document.querySelectorAll('.modal-backdrop.dashboard-activate-backdrop').forEach(function(el){
            el.parentNode.removeChild(el);
        });
    }

    function dashShowModal(){
        var modal = dashGetModal();
        if (!modal) return;

        if (window.bootstrap && window.bootstrap.Modal) {
            window.bootstrap.Modal.getOrCreateInstance(modal).show();
            return;
        }

        dashRemoveBackdrop();
        modal.style.display = 'block';
        modal.removeAttribute('aria-hidden');
        modal.setAttribute('aria-modal', 'true');
        modal.setAttribute('role', 'dialog');
        modal.classList.add('show');
        document.body.classList.add('modal-open');
        document.body.style.overflow = 'hidden';
        document.body.style.paddingRight = '0px';

        var backdrop = document.createElement('div');
        backdrop.className = 'modal-backdrop fade show dashboard-activate-backdrop';
        document.body.appendChild(backdrop);
    }

    function dashHideModal(){
        var modal = dashGetModal();
        if (!modal) return;

        if (window.bootstrap && window.bootstrap.Modal) {
            var instance = window.bootstrap.Modal.getOrCreateInstance(modal);
            instance.hide();
            return;
        }

        modal.classList.remove('show');
        modal.style.display = 'none';
        modal.setAttribute('aria-hidden', 'true');
        modal.removeAttribute('aria-modal');
        modal.removeAttribute('role');
        document.body.classList.remove('modal-open');
        document.body.style.overflow = '';
        document.body.style.paddingRight = '';
        dashRemoveBackdrop();
    }

    function dashOpenActivate(btn){
        var mac = btn.getAttribute('data-mac') || '';
        var macInput = document.getElementById('dashActivateMac');
        var valInput = document.getElementById('dashActivateValidade');
        var m3uInput = document.querySelector('#dashboardActivateForm input[name="m3u_url"]');

        if (macInput) macInput.value = mac;
        if (valInput && !valInput.value) valInput.value = dashDefaultDate();

        dashShowModal();
        setTimeout(function(){
            if (m3uInput) m3uInput.focus();
        }, 150);
    }

    document.addEventListener('click', function(e){
        var activateBtn = e.target.closest('.btn-dashboard-activate');
        if (activateBtn) {
            e.preventDefault();
            e.stopPropagation();
            dashOpenActivate(activateBtn);
            return;
        }

        if (e.target.closest('#dashboardActivateModal [data-bs-dismiss="modal"]') || e.target.classList.contains('dashboard-activate-backdrop')) {
            e.preventDefault();
            dashHideModal();
        }
    }, true);

    document.addEventListener('keydown', function(e){
        if (e.key === 'Escape') dashHideModal();
    });

    document.addEventListener('DOMContentLoaded', function(){
        var form = document.getElementById('dashboardActivateForm');
        if (!form) return;

        form.addEventListener('submit', function(){
            var submit = form.querySelector('button[type="submit"]');
            if (submit) {
                submit.disabled = true;
                submit.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Ativando...';
            }
        });
    });
})();
</script>

<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" style="font-weight: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>

<script>
function abrirOnline(){
    new bootstrap.Modal(document.getElementById("modalOnline")).show();
}
</script>

<script src="./assets/js/app.min.js"></script>

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