<?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';

// Verifica se é Admin
$isAdmin = (strtolower($_SESSION['nivel']) === 'admin');
$usuarioLogado = $_SESSION['usuario'];

// --- BUSCA CONFIGURAÇÕES DO SITE (NOME E COR DO PAINEL) ---
$nomePainel = "IPTV PANEL"; 
$corPrimaria = "#7367f0"; // Cor padrão caso não exista no banco

try {
    // Puxa o nome e o tema (cor) do banco geral
    $conf = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($conf) {
        if (!empty($conf['NomePainel'])) $nomePainel = $conf['NomePainel'];
        if (!empty($conf['TemaPainel'])) $corPrimaria = $conf['TemaPainel'];
    }
} catch (Exception $e) { }

// --- FUNÇÕES AUXILIARES ---
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', (int)$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. MONITORIZAÇÃO ONLINE (CSP SCRAPING)
// ==========================================================
$online_count = 0;
$csp_status_icon = 'text-secondary'; 

try {
    $sql_serv = "SELECT url, porta, usuario, senha FROM servidor ORDER BY id DESC LIMIT 1";
    $stmt_serv = $connGeral->query($sql_serv);
    $servidor = $stmt_serv->fetch(PDO::FETCH_ASSOC);
    
    if ($servidor) {
        $url_csp = "http://{$servidor['url']}:{$servidor['porta']}/";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url_csp);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
        curl_setopt($ch, CURLOPT_USERPWD, "{$servidor['usuario']}:{$servidor['senha']}");
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        $html = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($http_code == 200 && !empty($html)) {
            $csp_status_icon = 'text-success';
            $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') {
                        $stmt_check = $connUser->prepare("SELECT CadUser FROM usuario WHERE usuario = ? UNION SELECT CadUser FROM teste WHERE usuario = ?");
                        $stmt_check->execute([$nome_user, $nome_user]);
                        $dono = $stmt_check->fetchColumn();
                        if ($isAdmin || $dono === $usuarioLogado) { $online_count++; }
                    }
                }
            }
        } else { $csp_status_icon = 'text-danger'; }
    }
} catch (Exception $e) { }

// ==========================================================
// 2. ESTATÍSTICAS E VENCIMENTOS
// ==========================================================
$total_clientes = 0; $ativos = 0; $vencidos = 0;
$lista_proximos = []; 

try {
    $sql_u = $isAdmin ? "SELECT * FROM usuario" : "SELECT * FROM usuario WHERE CadUser = :u";
    $stmt_u = $connUser->prepare($sql_u);
    $isAdmin ? $stmt_u->execute() : $stmt_u->execute([':u' => $usuarioLogado]);
    $usuarios_res = $stmt_u->fetchAll();

    $hoje = date('Y-m-d');
    $alerta_venc = date('Y-m-d', strtotime('+7 days'));

    foreach ($usuarios_res as $u) {
        $total_clientes++;
        $venc = dataISO_dash($u['data_premio']);
        if ($u['bloqueado'] !== 'sim') {
            if ($venc < $hoje) { $vencidos++; } else { $ativos++; }
            if ($venc >= $hoje && $venc <= $alerta_venc) {
                $lista_proximos[] = ['nome' => $u['nome'], 'user' => $u['usuario'], 'data' => $venc];
            }
        }
    }
    usort($lista_proximos, function($a, $b) { return strtotime($a['data']) - strtotime($b['data']); });
    $lista_servidores = $connGeral->query("SELECT nome, url, porta FROM perfil WHERE bloqueado != 'sim' OR bloqueado IS NULL LIMIT 10")->fetchAll(PDO::FETCH_ASSOC);

} catch (Exception $e) { }
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard | <?= htmlspecialchars($nomePainel) ?></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 { 
            /* APLICANDO A COR DO BANCO DE DADOS */
            --primary: <?= $corPrimaria ?>; 
            --bg-body: #151521; 
            --bg-card: #1e1e2d; 
        }
        body { background: var(--bg-body); color: #fff; font-family: 'Segoe UI', sans-serif; overflow-x: hidden; }
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); padding: 20px; border-right: 1px solid #333; transition: 0.3s; z-index: 1050; overflow-y: auto; }
        .main-content { margin-left: 260px; padding: 30px; transition: 0.3s; }
        .nav-link { color: #a6a6b7; padding: 10px 12px; border-radius: 8px; margin-bottom: 2px; display: flex; align-items: center; gap: 10px; transition: 0.2s; text-decoration: none; font-size: 0.9rem; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 20px 0 10px 12px; }
        .stat-card { background: var(--bg-card); border-radius: 12px; padding: 20px; border: 1px solid rgba(255,255,255,0.05); }
        .pag-btn { background: #33334d; border: 1px solid #444; color: #fff; padding: 2px 10px; border-radius: 5px; cursor: pointer; transition: 0.2s; }
        .pag-btn:hover:not(:disabled) { background: var(--primary); border-color: var(--primary); }
        .pag-btn:disabled { opacity: 0.3; cursor: not-allowed; }
        @media (max-width: 992px) { .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; background: none; border: none; color: #fff; font-size: 1.5rem; margin-bottom: 20px; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1040; }
        .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 text-center"><i class="fas fa-tv text-primary"></i> <?= htmlspecialchars($nomePainel) ?></h4>
    <div class="nav flex-column">
        <a href="index.php" class="nav-link active"><i class="fas fa-home"></i> Dashboard</a>
        <?php if ($isAdmin): ?>
            <div class="nav-group-title">Administração</div>
            <a href="gerenciar_perfis.php" class="nav-link"><i class="fas fa-layer-group"></i> Gerenciar Perfis</a>
            <a href="gerenciar_dns.php" class="nav-link"><i class="fas fa-network-wired"></i> Servidores DNS</a>
            <a href="gerenciar_admins.php" class="nav-link"><i class="fas fa-user-shield"></i> Gestão de Admins</a>
            <a href="gerenciar_permissoes.php" class="nav-link"><i class="fas fa-lock"></i> Permissões</a>
            <a href="personalizar_painel.php" class="nav-link"><i class="fas fa-paint-brush"></i> Personalizar</a>
            <a href="gerenciar_backups.php" class="nav-link"><i class="fas fa-database"></i> Backups</a>
            <a href="config_geral.php" class="nav-link"><i class="fas fa-cogs"></i> Config. Geral</a>
        <?php endif; ?>
        
        <div class="nav-group-title">Operacional</div>
        <a href="revendedores.php" class="nav-link"><i class="fas fa-store"></i> Revendedores</a>
        <a href="clientes.php" class="nav-link"><i class="fas fa-users"></i> Clientes</a>
        <a href="testes.php" class="nav-link"><i class="fas fa-stopwatch"></i> Testes</a>
        <a href="gerenciar_email.php" class="nav-link"><i class="fas fa-envelope"></i> Config. E-mail</a>
        <a href="status_online.php" class="nav-link"><i class="fas fa-wifi"></i> Monitor Online</a>
        
        <hr class="border-secondary mt-4"><a href="sair.php" class="nav-link text-danger"><i class="fas fa-sign-out-alt"></i> Sair</a>
    </div>
</nav>

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

    <div class="mb-4">
        <h3 class="fw-bold">Visão Geral</h3>
        <p class="text-white-50 small">Logado como: <span class="text-white fw-bold"><?= $usuarioLogado ?></span></p>
    </div>

    <div class="row g-3 mb-4">
        <div class="col-6 col-md-3"><div class="stat-card border-bottom border-success border-3"><p class="text-white-50 small mb-1">ONLINE</p><h3 class="fw-bold m-0"><?= $online_count ?></h3><i class="fas fa-wifi position-absolute top-0 end-0 m-3 opacity-25 <?= $csp_status_icon ?>"></i></div></div>
        <div class="col-6 col-md-3"><div class="stat-card"><p class="text-white-50 small mb-1">CLIENTES</p><h3 class="fw-bold m-0"><?= $total_clientes ?></h3></div></div>
        <div class="col-6 col-md-3"><div class="stat-card"><p class="text-white-50 small mb-1 text-success">ATIVOS</p><h3 class="fw-bold m-0 text-success"><?= $ativos ?></h3></div></div>
        <div class="col-6 col-md-3"><div class="stat-card"><p class="text-white-50 small mb-1 text-danger">VENCIDOS</p><h3 class="fw-bold m-0 text-danger"><?= $vencidos ?></h3></div></div>
    </div>

    <div class="card bg-dark border-secondary mb-4 shadow-sm">
        <div class="card-body d-flex justify-content-between align-items-center flex-wrap gap-2">
            <div>
                <h6 class="fw-bold text-primary mb-1"><i class="fas fa-bolt me-1"></i>Link de Teste Automático</h6>
                <small class="text-white-50">Seus clientes podem gerar os próprios testes.</small>
            </div>
            <div class="input-group" style="max-width: 450px;">
                <?php 
                    $protocolo = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http");
                    $diretorio = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
                    $link_auto = $protocolo . "://" . $_SERVER['HTTP_HOST'] . $diretorio . "/cadtest.php?r=" . base64_encode($usuarioLogado); 
                ?>
                <input type="text" class="form-control bg-dark border-secondary text-white small" value="<?= $link_auto ?>" id="linkTesteAuto" readonly>
                <button class="btn btn-primary" onclick="copiarLinkAuto()"><i class="fas fa-copy"></i></button>
            </div>
        </div>
    </div>

    <div class="row g-4">
        <div class="col-12 col-lg-7">
            <div class="card stat-card p-0 overflow-hidden h-100">
                <div class="card-header bg-transparent border-secondary p-3"><h6 class="m-0 text-info"><i class="fas fa-server me-2"></i>Servidores Ativos</h6></div>
                <div class="table-responsive">
                    <table class="table table-dark table-hover mb-0 align-middle small">
                        <thead><tr class="text-white-50"><th class="ps-3">NOME</th><th>DNS / URL</th><th class="text-center">PORTA</th></tr></thead>
                        <tbody>
                            <?php foreach($lista_servidores as $s): ?>
                            <tr><td class="ps-3 fw-bold"><?= $s['nome'] ?></td><td class="text-info"><?= $s['url'] ?></td><td class="text-center"><span class="badge bg-dark border border-secondary text-warning px-3"><?= $s['porta'] ?></span></td></tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="col-12 col-lg-5">
            <div class="card stat-card p-0 overflow-hidden h-100">
                <div class="card-header bg-transparent border-secondary p-3 d-flex justify-content-between align-items-center">
                    <h6 class="m-0 text-warning"><i class="fas fa-clock me-2"></i>Vencendo em 7 Dias</h6>
                    <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 small">
                        <thead><tr class="text-white-50"><th class="ps-3">CLIENTE / USUÁRIO</th><th class="text-end pe-3">DATA</th></tr></thead>
                        <tbody>
                            <?php if(empty($lista_proximos)): ?>
                                <tr><td colspan="2" class="p-4 text-center text-white-50">Tudo em dia!</td></tr>
                            <?php else: ?>
                                <?php foreach($lista_proximos as $p): ?>
                                <tr class="venc-row" style="display: none;"><td class="ps-3"><div class="fw-bold"><?= $p['nome'] ?></div><div class="text-white-50" style="font-size: 0.75rem;">Usuário: <span class="text-info"><?= $p['user'] ?></span></div></td><td class="text-end pe-3"><span class="badge bg-warning text-dark"><?= date('d/m', strtotime($p['data'])) ?></span></td></tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</main>

<script>
    function toggleMenu() { document.getElementById('sidebar').classList.toggle('show'); document.getElementById('overlay').classList.toggle('show'); }
    function copiarLinkAuto() { var copyText = document.getElementById("linkTesteAuto"); copyText.select(); navigator.clipboard.writeText(copyText.value).then(() => alert("Link copiado!")); }
    let paginaAtual = 1; const itensPorPagina = 5; const rows = document.querySelectorAll('.venc-row'); const totalPaginas = Math.ceil(rows.length / itensPorPagina);
    function atualizarLista() { if(rows.length === 0) return; rows.forEach((row, idx) => { row.style.display = (idx >= (paginaAtual-1)*itensPorPagina && idx < paginaAtual*itensPorPagina) ? 'table-row' : 'none'; }); document.getElementById('pagIndicador').innerText = `${paginaAtual}/${totalPaginas}`; document.getElementById('btnPrev').disabled = (paginaAtual === 1); document.getElementById('btnNext').disabled = (paginaAtual === totalPaginas || totalPaginas === 0); }
    function mudarPagina(dir) { if(dir === 1 && paginaAtual < totalPaginas) paginaAtual++; else if(dir === -1 && paginaAtual > 1) paginaAtual--; atualizarLista(); }
    window.onload = atualizarLista;
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
