<?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'])) : '';
$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; }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; padding: 0; }
        
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid #333; z-index: 1050; padding: 20px; overflow-y: auto; transition: 0.3s; }
        .nav-link { color: #a6a6b7; padding: 12px 15px; border-radius: 8px; display: flex; align-items: center; gap: 12px; text-decoration: none; margin-bottom: 5px; font-weight: 500; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 25px 0 10px 12px; letter-spacing: 1px; }
        
        .main-content { margin-left: 260px; transition: 0.3s; min-height: 100vh; }
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--primary) 100%); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; }

        .card-custom { background: var(--bg-card) !important; border: 1px solid var(--border-color); border-radius: 10px; transition: 0.3s; }
        .card-custom:hover { transform: translateY(-3px); box-shadow: 0 8px 20px rgba(0,0,0,0.4); border-color: var(--primary); }
        
        .form-control { background: #151521 !important; border: 1px solid #444 !important; color: #fff !important; font-family: monospace; font-size: 0.9rem; }
        .form-control:focus { border-color: var(--primary) !important; box-shadow: none; }
        
        .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: 12px; }
        .icon-painel { background: rgba(115, 103, 240, 0.15); color: #7367f0; }
        .icon-cliente { background: rgba(40, 199, 111, 0.15); color: #28c76f; }

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


<main class="main-content">
    <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>

    <div class="container-fluid p-3 p-md-4">
        
        <div class="row">
            <div class="col-md-6 mb-4">
                <div class="card card-custom p-3 shadow h-100">
                    <div class="icon-box icon-painel">
                        <i class="fas fa-tachometer-alt"></i>
                    </div>
                    <h5 class="fw-bold text-white mb-1">Painel Administrativo</h5>
                    <p class="text-white-50 small mb-3">Link de acesso para você e para os seus revendedores logarem no painel.</p>
                    
                    <div class="input-group mt-auto shadow-sm">
                        <span class="input-group-text bg-dark border-secondary text-white-50"><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 mb-4">
                <div class="card card-custom p-3 shadow h-100">
                    <div class="icon-box icon-cliente">
                        <i class="fas fa-user-circle"></i>
                    </div>
                    <h5 class="fw-bold text-white mb-1">Área do Cliente</h5>
                    <p class="text-white-50 small mb-3">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 bg-dark border-secondary text-white-50"><i class="fas fa-users"></i></span>
                        <input type="text" id="linkCliente" class="form-control text-success" 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>
</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>