<?php
session_start();
require_once 'conexao.php';

// --- TRAVA DE SEGURANÇA ---
if (!isset($_SESSION['logado'])) { header("Location: login.php"); exit; }

$nivel_sessao = isset($_SESSION['nivel']) ? strtolower(trim($_SESSION['nivel'])) : '';
// CORREÇÃO DO ERRO DA LINHA 8 AQUI (removido o \vert{}\vert{} e colocado || )
$isAdmin = ($nivel_sessao === 'admin' || $nivel_sessao === 'administrador' || $nivel_sessao === 'master' || $nivel_sessao === 'dono');
$usuarioLogado = $_SESSION['usuario'];

// --- CONFIGURAÇÕES VISUAIS ---
$nomePainel = "IPTV PANEL"; $corPrimaria = "#7367f0"; 
try {
    $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) { }

// --- MENSAGENS NÃO LIDAS (SUPORTE MENU) ---
$total_msg_nao_lidas = 0;
try {
    $stmtMsg = $connUser->prepare("SELECT COUNT(*) FROM chamados_suporte WHERE destinatario = ? AND lida = 'nao'");
    $stmtMsg->execute([$usuarioLogado]);
    $total_msg_nao_lidas = $stmtMsg->fetchColumn();
} catch (Exception $e) { }

// --- GERAR OS LINKS AUTOMATICAMENTE ---
$protocolo = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https://" : "http://";
$dominio = $_SERVER['HTTP_HOST'];
$pasta = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');

// Link base do painel (ex: https://dominio.com/pasta)
$link_painel = $protocolo . $dominio . $pasta;

// ATUALIZADO: Link do cliente agora herda a pasta do painel (ex: https://dominio.com/pasta/clientes)
$link_cliente = $link_painel . "/clientes"; 
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>

<?php include 'tema_global.php'; ?>

    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Meus Links | <?= 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 { 
            --primary: <?= $corPrimaria ?>; 
            --bg-body: #151521; 
            --bg-card: #1e1e2d; 
            --text-color: #d0d2d6; 
            --border-color: #2b2b40;
            --overlay-desk: rgba(0, 0, 0, 0.65); 
            --overlay-mob: rgba(0, 0, 0, 0.85); 
        }
        body.light-mode { 
            --bg-body: #f4f5f8; 
            --bg-card: #ffffff; 
            --text-color: #5e5873; 
            --border-color: #ebe9f1; 
            --overlay-desk: rgba(255, 255, 255, 0.1); 
            --overlay-mob: rgba(255, 255, 255, 0); 
        }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; padding: 0; }
        
        /* Sidebar Premium */
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid var(--border-color); z-index: 1050; padding: 20px; overflow-y: auto; transition: transform 0.3s ease, box-shadow 0.3s ease; }
        .sidebar .nav-link { white-space: nowrap !important; overflow: hidden; text-overflow: ellipsis; display: flex; align-items: center; color: #a6a6b7; padding: 12px 15px; border-radius: 8px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s; }
        .sidebar .nav-link:hover, .sidebar .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .sidebar .nav-link i.fa-fw { margin-right: 8px; text-align: center; }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 25px 0 10px 12px; letter-spacing: 1px; }
        
        /* Layout Flexbox Ajustado para forçar Rodapé no Final */
        .main-content { margin-left: 260px; transition: 0.3s; display: flex; flex-direction: column; min-height: 100vh; }
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--overlay-desk) 100%), var(--primary); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); margin-bottom: 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.3); }
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; margin: 0; }

        /* Cards Premium */
        .card-custom { background-color: var(--bg-card) !important; border: 1px solid var(--border-color) !important; border-radius: 12px; transition: 0.3s; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        .card-custom:hover { transform: translateY(-3px); box-shadow: 0 8px 20px rgba(0,0,0,0.1); border-color: var(--primary) !important; }
        
        /* Inputs Dinâmicos */
        .form-control { background-color: rgba(0,0,0,0.1) !important; border: 1px solid var(--border-color) !important; color: var(--text-color) !important; font-family: monospace; font-size: 0.95rem; padding: 12px 15px; transition: 0.2s;}
        body.light-mode .form-control { background-color: rgba(0,0,0,0.03) !important; }
        .form-control:focus { border-color: var(--primary) !important; box-shadow: 0 0 0 0.25rem rgba(115, 103, 240, 0.25) !important; background-color: transparent !important;}
        
        .input-group-text { background-color: rgba(0,0,0,0.1) !important; border: 1px solid var(--border-color) !important; color: var(--text-color) !important; opacity: 0.7;}
        body.light-mode .input-group-text { background-color: rgba(0,0,0,0.03) !important; }

        .btn-copy { background: var(--primary); color: #fff; border: none; font-weight: bold; font-size: 0.85rem; padding: 8px 20px; transition: 0.3s; }
        .btn-copy:hover { background: #5a52d5; color: #fff; }
        .btn-copied { background: #28c76f !important; color: #fff !important; }

        .icon-box { width: 45px; height: 45px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 20px; margin-bottom: 15px; }
        .icon-painel { background: rgba(115, 103, 240, 0.15); color: #7367f0; border: 1px solid rgba(115, 103, 240, 0.3); }
        .icon-cliente { background: rgba(40, 199, 111, 0.15); color: #28c76f; border: 1px solid rgba(40, 199, 111, 0.3); }

        @media (max-width: 992px) { 
            .sidebar { transform: translateX(-100%); box-shadow: none; z-index: 1050; } 
            .sidebar.show { transform: translateX(0); box-shadow: 5px 0 30px rgba(0,0,0,0.9); } 
            .main-content { margin-left: 0; } 
            .mobile-toggle { display: block !important; margin-right: 15px; } 
            .top-header { flex-direction: row; padding: 15px 20px; background: linear-gradient(var(--overlay-mob), var(--overlay-mob)), var(--primary); border-bottom: none; }
        }
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; cursor: pointer; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.7); z-index: 1040; backdrop-filter: blur(3px); }
        .overlay.show { display: block; }
    </style>
</head>
<body>
<?php include 'menu.php'; ?>
<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<main class="main-content d-flex flex-column min-vh-100">
    <div class="top-header">
        <div class="d-flex align-items-center">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title"><i class="fas fa-link me-2 text-warning"></i> Links do Sistema</div>
        </div>
    </div>

    <!-- Container flex-grow-1 estica o meio, empurrando o Rodapé para baixo -->
    <div class="container-fluid p-3 p-md-4 flex-grow-1">
        
        <div class="row g-4">
            <div class="col-md-6">
                <div class="card card-custom p-4 shadow h-100">
                    <div class="icon-box icon-painel shadow-sm">
                        <i class="fas fa-tachometer-alt"></i>
                    </div>
                    <h5 class="fw-bold mb-2" style="color: var(--text-color);">Painel Administrativo</h5>
                    <p class="small mb-4" style="color: var(--text-color); opacity: 0.7;">Link de acesso para você e para os seus revendedores efetuarem login no painel.</p>
                    
                    <div class="input-group mt-auto shadow-sm">
                        <span class="input-group-text"><i class="fas fa-globe"></i></span>
                        <input type="text" id="linkPainel" class="form-control" value="<?= htmlspecialchars($link_painel) ?>" readonly>
                        <button class="btn btn-copy" type="button" onclick="copiarLink('linkPainel', this)" title="Copiar Link do Painel">
                            <i class="fas fa-copy me-1"></i> <span>COPIAR</span>
                        </button>
                    </div>
                </div>
            </div>

            <div class="col-md-6">
                <div class="card card-custom p-4 shadow h-100">
                    <div class="icon-box icon-cliente shadow-sm">
                        <i class="fas fa-user-circle"></i>
                    </div>
                    <h5 class="fw-bold mb-2" style="color: var(--text-color);">Área do Cliente</h5>
                    <p class="small mb-4" style="color: var(--text-color); opacity: 0.7;">Envie este link para os seus clientes. Lá eles podem ver a data de vencimento e renovar planos.</p>
                    
                    <div class="input-group mt-auto shadow-sm">
                        <span class="input-group-text"><i class="fas fa-users"></i></span>
                        <!-- Cor customizada no input via estilo inline e variável para garantir destaque nos 2 temas -->
                        <input type="text" id="linkCliente" class="form-control fw-bold" style="color: #28c76f !important;" value="<?= htmlspecialchars($link_cliente) ?>" readonly>
                        <button class="btn btn-copy" type="button" onclick="copiarLink('linkCliente', this)" title="Copiar Link do Cliente">
                            <i class="fas fa-copy me-1"></i> <span>COPIAR</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>

    </div>
    
    <!-- Rodapé protegido no chão pela div mt-auto -->
    <div class="mt-auto w-100">
        <?php include 'rodape.php'; ?>
    </div>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Menu Mobile
    function toggleMenu() { 
        document.getElementById('sidebar').classList.toggle('show'); 
        document.getElementById('overlay').classList.toggle('show'); 
    }

    // Função Avançada para Copiar Links
    function copiarLink(inputId, btnElement) {
        var copyText = document.getElementById(inputId);
        var originalText = btnElement.innerHTML;
        
        // Seleciona e Copia
        copyText.select();
        copyText.setSelectionRange(0, 99999); /* Para mobile */
        navigator.clipboard.writeText(copyText.value).then(() => {
            // Efeito Visual de Sucesso
            btnElement.classList.add('btn-copied');
            btnElement.innerHTML = '<i class="fas fa-check me-1"></i> <span>COPIADO!</span>';
            
            // Retorna ao normal após 2 segundos
            setTimeout(function() {
                btnElement.classList.remove('btn-copied');
                btnElement.innerHTML = originalText;
            }, 2000);
        }).catch(err => {
            alert('Erro ao copiar o link!');
        });
    }
</script>
</body>
</html>
