<?php
// 1. SEGURANÇA E SESSÃO
session_start();
if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== true) {
    header("Location: login.php");
    exit;
}

require_once 'conexao.php';

// --- FUNÇÕES AUXILIARES ---
function limpar_dash($dado) {
    if (!$dado) return "";
    $d = json_decode('"'.$dado.'"');
    if($d) $dado = $d;
    $dado = strip_tags($dado);
    return (strlen($dado) > 25) ? substr($dado, 0, 25) . "..." : $dado;
}

function dataISO_dash($data) {
    if (!$data) return date('Y-m-d');
    $data = trim($data);
    if (is_numeric($data) && strlen($data) > 8) return date('Y-m-d', $data);
    if (strpos($data, '/') !== false) {
        $d = DateTime::createFromFormat('d/m/Y', substr($data, 0, 10));
        return $d ? $d->format('Y-m-d') : date('Y-m-d');
    }
    return substr($data, 0, 10);
}

// ==========================================================
// 1. LÓGICA DE USUÁRIOS ONLINE (MÉTODO HTML/SCRAPING)
// ==========================================================
$online_count = 0;
$csp_status_icon = 'text-secondary'; 

// Busca dados do servidor
$csp_ip = '127.0.0.1'; $csp_port = '8080'; $csp_user = 'admin'; $csp_pass = '';
try {
    $sql = "SELECT url, porta, usuario, senha FROM servidor ORDER BY id DESC LIMIT 1";
    $stmt = $connGeral->query($sql);
    $servidor = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($servidor) {
        $csp_ip = $servidor['url']; $csp_port = $servidor['porta']; 
        $csp_user = $servidor['usuario']; $csp_pass = $servidor['senha'];
    }
} catch (Exception $e) { }

// Função que lê a página inicial do CSP (HTML)
function contarOnlineHTML($ip, $port, $user, $pass) {
    $url = "http://$ip:$port/"; // Acessa a raiz
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_USERPWD, "$user:$pass");
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)');
    curl_setopt($ch, CURLOPT_TIMEOUT, 3); // Timeout rápido
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    
    $html = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $qtd = 0;
    if ($http_code == 200 && !empty($html)) {
        $dom = new DOMDocument();
        @$dom->loadHTML($html);
        $xpath = new DOMXPath($dom);
        $linhas = $xpath->query("//tr");

        foreach ($linhas as $linha) {
            $colunas = $linha->getElementsByTagName('td');
            if ($colunas->length >= 4) {
                $nome_user = trim($colunas->item(0)->nodeValue);
                if (!empty($nome_user) && $nome_user != 'User') {
                    $revenda = "---";
                    try {
                        global $connUser;
                        $stmt = $connUser->prepare("SELECT CadUser FROM usuario WHERE usuario = ? UNION SELECT CadUser FROM teste WHERE usuario = ?");
                        $stmt->execute([$nome_user, $nome_user]);
                        $dado = $stmt->fetchColumn();
                        if($dado) $revenda = $dado;
                    } catch(Exception $e){}

                    if ($_SESSION['nivel'] === 'admin' || $revenda === $_SESSION['usuario']) {
                        $qtd++;
                    }
                }
            }
        }
        return ['qtd' => $qtd, 'status' => 'online'];
    }
    return ['qtd' => 0, 'status' => 'offline'];
}

// Executa a contagem
$resultado_online = contarOnlineHTML($csp_ip, $csp_port, $csp_user, $csp_pass);
$online_count = $resultado_online['qtd'];
$csp_status_icon = ($resultado_online['status'] == 'online') ? 'text-success' : 'text-danger';


// ==========================================================
// 2. LÓGICA DE DADOS LOCAL
// ==========================================================
$total_clientes = 0; $ativos = 0; $vencidos = 0; $faturamento = 0.00;
$lista_proximos_vencimentos = []; $lista_final_servidores = []; $lista_ultimos = [];

try {
    if ($_SESSION['nivel'] === 'admin') {
        $sql = "SELECT * FROM usuario WHERE nome NOT LIKE '%Formas de Pagamento%' ORDER BY id DESC";
        $stmt = $connUser->query($sql);
    } else {
        $sql = "SELECT * FROM usuario WHERE CadUser = :user AND nome NOT LIKE '%Formas de Pagamento%' ORDER BY id DESC";
        $stmt = $connUser->prepare($sql);
        $stmt->execute([':user' => $_SESSION['usuario']]);
    }
    
    $todos_usuarios = $stmt->fetchAll();
    $hoje = date('Y-m-d');
    $limite_7_dias = date('Y-m-d', strtotime('+7 days'));

    foreach ($todos_usuarios as $u) {
        $total_clientes++;
        $data_premio = dataISO_dash($u['data_premio']);
        $is_bloqueado = ($u['bloqueado'] == 'sim');
        $is_vencido = ($data_premio < $hoje);

        if (!$is_bloqueado) {
            if ($is_vencido) { $vencidos++; } else { 
                $ativos++; 
                $valor = str_replace(['R$', ' ', '.'], '', $u['ValorCobrado'] ?? '0');
                $valor = str_replace(',', '.', $valor);
                $faturamento += (float) $valor;
            }
        }
        if (!$is_bloqueado && $data_premio >= $hoje && $data_premio <= $limite_7_dias) {
            $lista_proximos_vencimentos[] = [
                'nome' => limpar_dash($u['nome']),
                'usuario' => limpar_dash($u['usuario']),
                'data' => $data_premio,
                'dias_restantes' => (strtotime($data_premio) - strtotime($hoje)) / (60 * 60 * 24),
                'telefone' => $u['celular']
            ];
        }
        if (count($lista_ultimos) < 5) {
            $st = 'ativo'; if($is_bloqueado) $st='bloqueado'; elseif($is_vencido) $st='vencido';
            $lista_ultimos[] = ['nome'=>$u['nome'], 'usuario'=>$u['usuario'], 'data'=>$data_premio, 'status'=>$st];
        }
    }
    usort($lista_proximos_vencimentos, function($a, $b) { return strtotime($a['data']) - strtotime($b['data']); });

    try {
        $sql_perfis = "SELECT nome, url, porta, tipo FROM perfil WHERE (bloqueado IS NULL OR bloqueado != 'sim')";
        $stmt_p = $connGeral->query($sql_perfis);
        $perfis = $stmt_p ? $stmt_p->fetchAll(PDO::FETCH_ASSOC) : [];
        $lista_final_servidores = $perfis;
    } catch (Exception $e) { }

} catch (Exception $e) { die("Erro: " . $e->getMessage()); }

// --- PERMISSÃO DO LINK TESTE ---
$mostrar_link_auto = false;
if (in_array($_SESSION['usuario'], ['admin', 'jeanrs', 'Admin']) || $_SESSION['nivel'] === 'admin') {
    $mostrar_link_auto = true;
} else {
    if(isset($connAcessos)) {
        $idg = $_SESSION['id_grupo'] ?? 2;
        $p = $connAcessos->query("SELECT OpcoesEmailTeste FROM opcoes WHERE id=$idg")->fetch();
        if($p && $p['OpcoesEmailTeste']=='sim') $mostrar_link_auto = true;
    } else $mostrar_link_auto = true;
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard | Painel IPTV</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root { --sidebar-width: 260px; --bg-body: #151521; --bg-card: #1e1e2d; --primary: #7367f0; }
        body { background: var(--bg-body); color: #e0e0e0; font-family: 'Segoe UI', sans-serif; overflow-x: hidden; padding-bottom: 60px; }
        
        .sidebar { width: 260px; height: 100vh; position: fixed; top: 0; left: 0; background: #1e1e2d; padding: 20px; z-index: 1000; border-right: 1px solid #333; transition: 0.3s; overflow-y: auto; }
        .main-content { margin-left: 260px; padding: 30px; transition: 0.3s; }
        .nav-link { color: #a6a6b7; padding: 12px; border-radius: 8px; margin-bottom: 5px; display: flex; align-items: center; gap: 10px; text-decoration: none; transition: 0.2s; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; }
        .submenu-link { padding-left: 20px; font-size: 0.9rem; color: #b0b0c0; }
        .submenu-link:hover { color: #fff; background: rgba(255,255,255,0.05); }
        .stat-card { background: var(--bg-card); border-radius: 15px; padding: 25px; position: relative; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.2); border: 1px solid rgba(255,255,255,0.02); }
        .table-dark { background: var(--bg-card); --bs-table-bg: var(--bg-card); color: #fff; }
        .copy-click { cursor: pointer; color: #ffffff !important; font-weight: 500; }
        .copy-click:hover { color: #0dcaf0 !important; }
        .table thead th { color: #ffffff !important; opacity: 0.9; }
        .online-dot { width: 10px; height: 10px; background: #28c76f; border-radius: 50%; display: inline-block; box-shadow: 0 0 10px #28c76f; animation: pulse 2s infinite; }
        @keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(40, 199, 111, 0.7); } 70% { box-shadow: 0 0 0 10px rgba(40, 199, 111, 0); } 100% { box-shadow: 0 0 0 0 rgba(40, 199, 111, 0); } }
        
        .pag-btn { background: #33334d; border: 1px solid #444; color: #fff; padding: 2px 10px; border-radius: 5px; cursor: pointer; transition: 0.2s; }
        .pag-btn:hover { background: #7367f0; border-color: #7367f0; }
        .pag-btn:disabled { opacity: 0.5; cursor: not-allowed; }

        @media (max-width: 768px) { .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } .main-content { margin-left: 0; padding: 15px; } .mobile-toggle { display: block !important; } }
        .mobile-toggle { display: none; font-size: 1.5rem; color: #fff; background: none; border: none; margin-bottom: 20px; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 999; }
        .overlay.show { display: block; }
    </style>
</head>
<body>

<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<nav class="sidebar" id="sidebar">
    <h4 class="mb-4 fw-bold text-white"><i class="fas fa-tv text-primary"></i> Painel v3.0</h4>
    <div class="nav flex-column gap-2">
        <a href="index.php" class="nav-link active"><i class="fas fa-home"></i> Dashboard</a>
        
        <?php if ($_SESSION['nivel'] === 'admin'): ?>
            <div class="mt-2 mb-1 px-3 text-uppercase fw-bold text-light" style="font-size: 0.75rem; opacity: 0.7;">Administração</div>
            <a class="nav-link text-white d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#submenuPainel" role="button" aria-expanded="false">
                <span><i class="fas fa-sliders-h text-info me-2"></i> Painel</span> <i class="fas fa-chevron-down small"></i>
            </a>
            <div class="collapse" id="submenuPainel">
                <div class="bg-dark rounded border border-secondary p-2 ms-2 mb-2">
                    <a href="personalizar_painel.php" class="nav-link submenu-link"><i class="fas fa-paint-brush me-2 text-danger"></i> Personalizar</a>
                    <a href="config_geral.php" class="nav-link submenu-link"><i class="fas fa-cogs me-2 text-warning"></i> Config. Geral</a>
                    <a href="gerenciar_dns.php" class="nav-link submenu-link"><i class="fas fa-network-wired me-2 text-success"></i> Servidores DNS</a>
                    <a href="gerenciar_perfis.php" class="nav-link submenu-link"><i class="fas fa-layer-group me-2 text-primary"></i> Perfis</a>
                </div>
            </div>
            
            <a href="gerenciar_admins.php" class="nav-link text-white"><i class="fas fa-user-shield text-danger"></i> Gerenciar Admins</a>
            <a href="gerenciar_permissoes.php" class="nav-link text-white"><i class="fas fa-lock text-info"></i> Permissões</a>
            <a href="gerenciar_status.php" class="nav-link text-white"><i class="fas fa-signal text-success"></i> Config. Status</a>
            <a href="gerenciar_email.php" class="nav-link text-white"><i class="fas fa-envelope text-warning"></i> Gateway E-mail</a>
            
            <a href="gerenciar_backups.php" class="nav-link text-white"><i class="fas fa-database text-warning"></i> Gerenciar Backups</a>
            
            <a href="permissoes_server.php" class="nav-link text-white"><i class="fas fa-server text-white"></i> Permissões CSP</a>
            <a href="revendedores.php" class="nav-link text-white"><i class="fas fa-store"></i> Revendedores</a>
            <a href="configuracoes.php" class="nav-link text-white"><i class="fas fa-wallet"></i> Pagamentos (Global)</a>
            <div class="mb-2 border-bottom border-secondary opacity-50"></div>
        <?php else: ?>
            <a href="configuracoes.php" class="nav-link text-white"><i class="fas fa-wallet"></i> Meus Pagamentos</a>
            <a href="gerenciar_email.php" class="nav-link text-white"><i class="fas fa-envelope text-warning"></i> Config. E-mail</a>
        <?php endif; ?>

        <a href="status_online.php" class="nav-link text-white"><i class="fas fa-wifi text-success"></i> Monitor Online</a>
        <a href="clientes.php" class="nav-link text-white"><i class="fas fa-users"></i> Clientes</a>
        <a href="testes.php" class="nav-link text-white"><i class="fas fa-stopwatch"></i> Testes</a>
        <a href="criar_cliente.php" class="nav-link text-white"><i class="fas fa-user-plus"></i> Novo Cliente</a>
        
        <hr class="border-secondary my-2">
        <a href="sair.php" class="nav-link text-danger"><i class="fas fa-sign-out-alt"></i> Sair do Painel</a>
        <div class="pb-5"></div>
    </div>
</nav>

<main class="main-content">
    <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="fw-bold text-white">Visão Geral</h3>
            <p class="text-white-50 m-0">Bem-vindo, <b class="text-white"><?= $_SESSION['usuario'] ?></b></p>
        </div>
    </div>

    <div class="row g-4 mb-4">
        <div class="col-12 col-md-4 col-lg-3">
            <a href="status_online.php" class="text-decoration-none">
                <div class="stat-card border-bottom border-3 border-success">
                    <div>
                        <p class="text-white-50 small text-uppercase fw-bold"><span class="online-dot me-1"></span> Online Agora</p>
                        <h3 class="text-white"><?= $online_count ?></h3>
                    </div>
                    <i class="fas fa-wifi fs-2 <?= $csp_status_icon ?> position-absolute" style="right:15px; top:15px; opacity:0.2"></i>
                </div>
            </a>
        </div>
        <div class="col-12 col-md-4 col-lg-3">
            <div class="stat-card"><div><p class="text-white-50 small text-uppercase fw-bold">Total Clientes</p><h3 class="text-white"><?= $total_clientes ?></h3></div><i class="fas fa-users fs-2 text-primary position-absolute" style="right:15px; top:15px; opacity:0.1"></i></div>
        </div>
        <div class="col-12 col-md-4 col-lg-3">
            <div class="stat-card"><div><p class="text-white-50 small text-uppercase fw-bold">Ativos</p><h3 class="text-success"><?= $ativos ?></h3></div><i class="fas fa-check-circle fs-2 text-success position-absolute" style="right:15px; top:15px; opacity:0.1"></i></div>
        </div>
        <div class="col-12 col-md-6 col-lg-3">
            <div class="stat-card"><div><p class="text-white-50 small text-uppercase fw-bold">Vencidos</p><h3 class="text-danger"><?= $vencidos ?></h3></div><i class="fas fa-user-times fs-2 text-danger position-absolute" style="right:15px; top:15px; opacity:0.1"></i></div>
        </div>
    </div>

    <?php if($mostrar_link_auto): ?>
    <div class="card border-0 mb-4 shadow-sm" style="background: linear-gradient(90deg, #1e1e2d 0%, #252540 100%); border-left: 5px solid #7367f0 !important;">
        <div class="card-body d-flex justify-content-between align-items-center flex-wrap gap-3">
            <div><h5 class="text-primary fw-bold mb-1"><i class="fas fa-bolt me-2"></i>Link de Teste Automático</h5><p class="text-white-50 small mb-0">Envie este link para seu cliente gerar o teste sozinho.</p></div>
            <div class="input-group" style="max-width: 500px;">
                <?php $link_auto = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']==='on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]".dirname($_SERVER['PHP_SELF'])."/cadtest.php?r=".base64_encode($_SESSION['usuario']); ?>
                <input type="text" class="form-control bg-dark border-secondary text-white" value="<?= $link_auto ?>" id="linkTesteAuto" readonly>
                <button class="btn btn-primary fw-bold" onclick="copiarLink()"><i class="fas fa-copy me-2"></i> Copiar</button>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div class="card stat-card mb-4 p-0 border-info" style="border-left: 5px solid #0dcaf0;">
        <div class="card-header bg-transparent border-0 p-3"><h5 class="mb-0 text-info"><i class="fas fa-server me-2"></i>DNS / Servidores</h5></div>
        <div class="table-responsive"><table class="table table-dark table-hover mb-0 align-middle"><thead><tr class="text-white-50 small text-uppercase"><th class="ps-4">Nome / Perfil</th><th>DNS / URL</th><th>Porta</th><th>Tipo</th></tr></thead><tbody><?php if(empty($lista_final_servidores)): ?><tr><td colspan="4" class="text-center text-white py-3">Nenhum perfil ativo.</td></tr><?php else: ?><?php foreach($lista_final_servidores as $item): ?><tr><td class="ps-4 fw-bold text-white"><?= $item['nome'] ?></td><td class="copy-click" onclick="alert('Copiado!')"><?= $item['url'] ?></td><td class="text-info fw-bold"><?= $item['porta'] ?></td><td><span class="badge bg-secondary"><?= $item['tipo'] ?? '---' ?></span></td></tr><?php endforeach; ?><?php endif; ?></tbody></table></div>
    </div>

    <?php if(!empty($lista_proximos_vencimentos)): ?>
    <div class="card stat-card mb-4 p-0 border-warning" style="border-left: 5px solid #ffc107;">
        <div class="card-header bg-transparent border-0 p-3 d-flex justify-content-between align-items-center">
            <h5 class="mb-0 text-warning">Vencendo em 7 Dias (<?= count($lista_proximos_vencimentos) ?>)</h5>
            
            <div class="d-flex align-items-center gap-2">
                <button class="pag-btn" onclick="mudarPagina(-1)" id="btnPrev"><i class="fas fa-chevron-left"></i></button>
                <span class="text-white small" id="pagIndicador">1/1</span>
                <button class="pag-btn" onclick="mudarPagina(1)" id="btnNext"><i class="fas fa-chevron-right"></i></button>
            </div>
        </div>
        <div class="table-responsive">
            <table class="table table-dark table-hover mb-0 align-middle">
                <thead><tr class="text-white-50 small text-uppercase"><th class="ps-4">Cliente</th><th>Vence em</th><th>Ação</th></tr></thead>
                <tbody>
                    <?php foreach($lista_proximos_vencimentos as $index => $row): $d=(int)$row['dias_restantes']; ?>
                    <tr class="vencimento-row" style="display: none;">
                        <td class="ps-4 fw-bold text-white"><?= $row['nome'] ?> <small class="d-block text-white-50 fw-normal"><?= $row['usuario'] ?></small></td>
                        <td><span class="badge <?= ($d<=1)?'bg-danger':'bg-warning text-dark' ?>"><?= ($d==0)?"HOJE":($d==1?"Amanhã":"$d dias") ?></span></td>
                        <td class="text-end pe-4"><a href="clientes.php?busca=<?= $row['usuario'] ?>" class="btn btn-sm btn-primary rounded-circle"><i class="fas fa-eye"></i></a></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleMenu() { document.getElementById('sidebar').classList.toggle('show'); document.getElementById('overlay').classList.toggle('show'); }
    function copingLink() { var c = document.getElementById("linkTesteAuto"); c.select(); navigator.clipboard.writeText(c.value).then(() => alert("Copiado!")); }

    // --- SCRIPT DE PAGINAÇÃO ---
    let pg = 1; 
    const limit = 5; 
    const rows = document.querySelectorAll('.vencimento-row'); 
    const total = rows.length; 
    const totalPages = Math.ceil(total / limit);

    function updatePagination() { 
        if(total === 0) return; 
        rows.forEach(l => l.style.display = 'none'); 
        let start = (pg - 1) * limit; 
        let end = start + limit; 
        for (let j = start; j < end && j < total; j++) { rows[j].style.display = 'table-row'; }
        const indic = document.getElementById('pagIndicador');
        const btnPrev = document.getElementById('btnPrev');
        const btnNext = document.getElementById('btnNext');
        if(indic) {
            indic.innerText = pg + '/' + totalPages; 
            btnPrev.disabled = (pg === 1); 
            btnNext.disabled = (pg === totalPages || totalPages === 0);
        }
    }
    function mudarPagina(dir) { if(dir === 1 && pg < totalPages) pg++; if(dir === -1 && pg > 1) pg--; updatePagination(); } 
    updatePagination();
</script>
</body>
</html>
