<?php
session_start();

// Apenas o Administrador tem acesso
if (!isset($_SESSION['logado']) || $_SESSION['nivel'] !== 'admin') { 
    header("Location: index.php"); 
    exit; 
}

require_once 'conexao.php'; 

$isAdmin = true;
$msg = "";
$msg_tipo = "";
$total_msg_nao_lidas = 0; 

// --- 1. BUSCA O SERVIDOR CSP NO BANCO ---
$stmt = $connGeral->query("SELECT url, porta, usuario, senha, protocolo FROM painel LIMIT 1");
$srv = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$srv) die("ERRO: Nenhum servidor CSP configurado.");

$ip = str_replace(['http://', 'https://', '/'], '', $srv['url']);
$porta = trim($srv['porta']); 
$user_csp = trim($srv['usuario']);
$pass_csp = trim($srv['senha']);
$csp_base_url = "{$srv['protocolo']}://{$ip}:{$porta}";
$csp_auth = "{$user_csp}:{$pass_csp}";

// --- BUSCA AS OPERADORAS PARA A MENSAGEM DO WHATSAPP ---
// (Isso continua usando o Banco só para pegar a URL e a Porta bonitinhas para enviar pro cliente)
$lista_operadoras = [];
try {
    $stmtOps = $connGeral->query("SELECT id, nome, url, porta FROM perfil WHERE bloqueado IS NULL OR bloqueado != 'sim'");
    $lista_operadoras = $stmtOps->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {}

$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) { }

function getCspSession($url, $user, $pass, $auth) {
    $ch = curl_init();
    $login_xml = "<cws-status-req ver=\"1.0\"><cws-login><user name=\"{$user}\" password=\"{$pass}\"/></cws-login></cws-status-req>";
    curl_setopt($ch, CURLOPT_URL, $url . "/xmlHandler");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $login_xml);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERPWD, $auth);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    $res = curl_exec($ch);
    curl_close($ch);
    if ($res && preg_match('/session-id="([^"]+)"/i', $res, $matches)) return $matches[1];
    return false;
}

function getCspXml($url, $auth) {
    $session_id = getCspSession($url, explode(':', $auth)[0], explode(':', $auth)[1], $auth);
    $ch = curl_init($url . "/xmlHandler?command=fetch-cfg");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERPWD, $auth);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Cookie: sessionId={$session_id}"]);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}

function saveCspXml($url, $auth, $xml_content) {
    // ⚔️ EXTERMINADOR DE XML: Remove a linha chata do <?xml...
    $xml_content = preg_replace('/<\?xml[^>]*\?>\s*/i', '', $xml_content);
    $xml_content = trim($xml_content);
    
    $session_id = getCspSession($url, explode(':', $auth)[0], explode(':', $auth)[1], $auth);
    $ch = curl_init($url . "/cfgHandler");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_content);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERPWD, $auth);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: text/xml', "Cookie: sessionId={$session_id}"]);
    $res = curl_exec($ch);
    curl_close($ch);
    return true;
}

$xml_raw = getCspXml($csp_base_url, $csp_auth);
$share_data = null; 

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['acao']) && $xml_raw) {
    $dom = new DOMDocument();
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    @$dom->loadXML($xml_raw);
    $xpath = new DOMXPath($dom);
    
    $targetNode = $xpath->query('//auth-config')->item(0);
    if (!$targetNode) $targetNode = $xpath->query('//user-manager')->item(0);
    
    $acao = $_POST['acao'];

    if ($acao === 'excluir' && isset($_POST['user_name'])) {
        $name = $_POST['user_name'];
        $node = $xpath->query("//user[@name='$name']")->item(0);
        if ($node) {
            $node->parentNode->removeChild($node);
            saveCspXml($csp_base_url, $csp_auth, $dom->saveXML());
            $msg = "Usuário <b>$name</b> excluído!"; $msg_tipo = "success";
        }
    }

    if ($acao === 'renovar' && isset($_POST['user_name'])) {
        $name = $_POST['user_name'];
        $node = $xpath->query("//user[@name='$name']")->item(0);
        if ($node) {
            $nova_data = date('Y-m-d', strtotime('+30 days'));
            $node->setAttribute('expire-date', $nova_data);
            $pass = $node->getAttribute('password');
            saveCspXml($csp_base_url, $csp_auth, $dom->saveXML());
            $msg = "Usuário <b>$name</b> renovado com sucesso para $nova_data!"; 
            $msg_tipo = "success";
            $share_data = ['name' => $name, 'password' => $pass, 'vencimento' => $nova_data, 'tipo' => 'renovacao'];
        }
    }

    if ($acao === 'salvar') {
        $name = trim($_POST['name']);
        $pass = trim($_POST['password']);
        
        // Pega os perfis selecionados na caixinha e junta por vírgula
        $perfis_array = isset($_POST['perfis']) && is_array($_POST['perfis']) ? $_POST['perfis'] : [];
        $perfis = implode(',', $perfis_array); 
        
        $max_conn = $_POST['max_connections'];
        $enabled = isset($_POST['enabled']) ? 'true' : 'false';
        $vencimento = $_POST['vencimento']; 
        $is_teste = (isset($_POST['is_teste']) && $_POST['is_teste'] == '1');
        
        $node = $xpath->query("//user[@name='$name']")->item(0);
        $is_new = (!$node);
        
        if ($is_new) {
            $node = $dom->createElement('user');
            $targetNode->appendChild($node); 
        }
        
        $node->setAttribute('name', $name);
        $node->setAttribute('password', $pass);
        $node->setAttribute('profiles', $perfis); 
        $node->setAttribute('max-connections', $max_conn);
        $node->setAttribute('enabled', $enabled);
        $node->setAttribute('expire-date', $vencimento);

        saveCspXml($csp_base_url, $csp_auth, $dom->saveXML());
        $msg = "Usuário <b>$name</b> salvo na memória ativa da CSP!"; 
        $msg_tipo = "success";

        if ($is_new) {
            $tipo_msg = $is_teste ? 'teste' : 'novo';
            $share_data = ['name' => $name, 'password' => $pass, 'vencimento' => $vencimento, 'tipo' => $tipo_msg];
        }
    }
    
    // Atualiza o XML raw após alterações
    $xml_raw = getCspXml($csp_base_url, $csp_auth);
}

// --- RADAR DE PERFIS (Lê os perfis DIRETO da CSP) ---
$perfis_da_csp = [];
$usuarios = [];

if ($xml_raw) {
    $xml = @simplexml_load_string($xml_raw);
    if ($xml) {
        
        // MÁGICA 1: Busca os perfis reais da CSP
        $profiles_nodes = $xml->xpath('//profile');
        if ($profiles_nodes) {
            foreach ($profiles_nodes as $pNode) {
                $pName = (string)$pNode['name'];
                if (!empty($pName)) {
                    $perfis_da_csp[] = $pName;
                }
            }
        }
        
        // MÁGICA 2: Busca os usuários
        $todos_usuarios = $xml->xpath('//auth-config/user | //user-manager/user');
        foreach ($todos_usuarios as $u) {
            $nome_u = (string)$u['name'];
            $is_admin = (string)$u['admin'];
            
            if ($is_admin === 'true' || empty($nome_u)) { continue; }
            
            $usuarios[] = [
                'name' => $nome_u,
                'password' => (string)$u['password'],
                'perfis' => (string)$u['profiles'] ?? '',
                'max_conn' => (string)$u['max-connections'],
                'enabled' => (string)$u['enabled'] ?? 'true',
                'vencimento' => (string)$u['expire-date']
            ];
        }
    }
}
?>

<!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">
    <title>Gerenciar Usuários CSP | <?= 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: var(--bg-body); color: #fff; font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 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; transition: 0.2s; }
        .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); border: 1px solid var(--border-color); border-radius: 12px; overflow: hidden; margin-bottom: 20px; }
        .form-control, .form-select { background: #151521 !important; border: 1px solid #444 !important; color: #fff !important; }
        .table-dark { --bs-table-bg: transparent; margin-bottom: 0; }
        .table-dark th { border-bottom-color: #333; color: #a6a6b7; font-size: 0.8rem; text-transform: uppercase; }
        .table-dark td { border-bottom-color: #2b2b40; vertical-align: middle; }
        @media (max-width: 992px) { .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } .main-content { margin-left: 0; } .mobile-toggle { display: block !important; } .top-header { flex-direction: column; align-items: flex-start; gap: 15px; } }
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; margin-right: 15px; }
        .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 w-100">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title">Gestão de Usuários (Proxy-Users)</div>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <button class="btn btn-info fw-bold rounded-pill text-dark shadow-sm" onclick="gerarTeste24h()"><i class="fas fa-magic me-1"></i> TESTE 24H</button>
            <button class="btn btn-primary fw-bold rounded-pill shadow-sm" onclick="abrirModalUsuario()"><i class="fas fa-plus me-1"></i> NOVO USUÁRIO</button>
        </div>
    </div>

    <div class="container-fluid p-3 p-md-4">
        <?php if($msg): ?>
            <div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show border-0 shadow-sm"><?= $msg ?><button class="btn-close" data-bs-dismiss="alert"></button></div>
        <?php endif; ?>

        <div class="card card-custom p-3 shadow">
            <div class="table-responsive">
                <table class="table table-dark table-hover align-middle">
                    <thead><tr><th>Nome / Usuário</th><th>Senha</th><th>Perfis</th><th>Conexões</th><th>Vencimento</th><th>Status</th><th class="text-end">Ações</th></tr></thead>
                    <tbody>
                        <?php if (empty($usuarios)): ?>
                            <tr><td colspan="7" class="text-center text-white-50 py-4">Nenhum cliente cadastrado ainda.</td></tr>
                        <?php else: ?>
                            <?php foreach ($usuarios as $user): $expirado = (!empty($user['vencimento']) && strtotime($user['vencimento']) < strtotime(date('Y-m-d'))); ?>
                            <tr>
                                <td class="fw-bold text-white"><?= htmlspecialchars($user['name']) ?></td>
                                <td class="text-info font-monospace"><?= htmlspecialchars($user['password']) ?></td>
                                <td class="text-warning fw-bold">
                                    <?php 
                                        if ($user['perfis']) {
                                            $perfis_array = explode(',', $user['perfis']);
                                            foreach($perfis_array as $p) {
                                                echo '<span class="badge bg-warning text-dark me-1">' . htmlspecialchars(trim($p)) . '</span>';
                                            }
                                        } else {
                                            echo '<span class="badge bg-danger">Sem Perfil!</span>';
                                        }
                                    ?>
                                </td>
                                <td><span class="badge bg-secondary"><?= $user['max_conn'] ?></span></td>
                                <td><span class="text-<?= $expirado ? 'danger' : 'success' ?> fw-bold"><?= !empty($user['vencimento']) ? date('d/m/Y', strtotime($user['vencimento'])) : 'Sem data' ?></span></td>
                                <td><?= ($user['enabled'] === 'true') ? '<span class="badge bg-success">ATIVO</span>' : '<span class="badge bg-danger">BLOQUEADO</span>' ?></td>
                                <td class="text-end text-nowrap">
                                    <div class="btn-group">
                                        <button class="btn btn-sm btn-outline-success border-0" onclick='abrirShare(<?= json_encode(array_merge($user, ['tipo'=>'lembrete'])) ?>)'><i class="fab fa-whatsapp"></i></button>
                                        <button class="btn btn-sm btn-outline-info border-0" onclick='editarUsuario(<?= json_encode($user) ?>)'><i class="fas fa-pen"></i></button>
                                        <form method="POST" class="d-inline" onsubmit="return confirm('Deseja renovar as linhas deste usuário por mais 30 dias?')">
                                            <input type="hidden" name="acao" value="renovar"><input type="hidden" name="user_name" value="<?= $user['name'] ?>">
                                            <button class="btn btn-sm btn-outline-warning border-0"><i class="fas fa-sync-alt"></i></button>
                                        </form>
                                        <form method="POST" class="d-inline" onsubmit="return confirm('Tem a certeza que deseja excluir o usuário <?= $user['name'] ?>?')">
                                            <input type="hidden" name="acao" value="excluir"><input type="hidden" name="user_name" value="<?= $user['name'] ?>">
                                            <button class="btn btn-sm btn-outline-danger border-0"><i class="fas fa-trash"></i></button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</main>

<div class="modal fade" id="modalUsuario" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-secondary">
            <form method="POST">
                <input type="hidden" name="acao" value="salvar"><input type="hidden" name="is_teste" id="f_is_teste" value="0">
                <div class="modal-header border-secondary">
                    <h5 class="modal-title fw-bold" id="modalTitulo">Configurar Usuário</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3"><label class="form-label small text-white-50">Nome de Usuário</label><input type="text" name="name" id="f_name" class="form-control fw-bold" required></div>
                        <div class="col-md-6 mb-3"><label class="form-label small text-white-50">Senha</label><input type="text" name="password" id="f_pass" class="form-control" required></div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label small text-warning fw-bold"><i class="fas fa-tv me-1"></i> Perfis Liberados (Direto da CSP)</label>
                        <div class="bg-dark border border-secondary p-2 rounded" style="max-height: 120px; overflow-y: auto;">
                            <?php if(empty($perfis_da_csp)): ?>
                                <div class="text-danger small">Nenhum perfil encontrado dentro da CSP.</div>
                            <?php else: ?>
                                <?php foreach($perfis_da_csp as $index => $p_nome): ?>
                                    <div class="form-check">
                                        <input class="form-check-input check-perfil" type="checkbox" name="perfis[]" value="<?= htmlspecialchars($p_nome) ?>" id="perfil_csp_<?= $index ?>">
                                        <label class="form-check-label text-white font-monospace" for="perfil_csp_<?= $index ?>">
                                            <?= htmlspecialchars($p_nome) ?>
                                        </label>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3"><label class="form-label small text-white-50">Conexões</label><input type="number" name="max_connections" id="f_conn" class="form-control" value="1" required></div>
                        <div class="col-md-6 mb-3"><label class="form-label small text-white-50">Vencimento</label><input type="date" name="vencimento" id="f_venc" class="form-control" value="<?= date('Y-m-d', strtotime('+30 days')) ?>"></div>
                    </div>
                    <div class="form-check form-switch mt-2"><input class="form-check-input" type="checkbox" name="enabled" id="f_enabled" checked><label class="form-check-label text-white" for="f_enabled">Usuário Ativo</label></div>
                </div>
                <div class="modal-footer border-secondary"><button type="submit" class="btn btn-primary w-100 fw-bold py-2">SALVAR NA CSP</button></div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalShare" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-success">
            <div class="modal-header border-success bg-success bg-opacity-10 text-white">
                <h5 class="modal-title fw-bold text-success"><i class="fab fa-whatsapp me-2"></i> Mensagem do Cliente</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-white">
                <input type="hidden" id="share_user"><input type="hidden" id="share_pass"><input type="hidden" id="share_venc"><input type="hidden" id="share_tipo">
                <div class="mb-3">
                    <label class="form-label small text-warning fw-bold"><i class="fas fa-hand-pointer me-1"></i> 1º Escolha a Operadora:</label>
                    <select id="share_operadora" class="form-select border-warning" onchange="updateShareText()">
                        <?php if(empty($lista_operadoras)): ?><option value="">Nenhuma operadora configurada no Banco de Dados</option><?php endif; ?>
                        <?php foreach($lista_operadoras as $op): ?><option value="<?= $op['id'] ?>"><?= htmlspecialchars($op['nome']) ?> (Porta: <?= htmlspecialchars($op['porta']) ?>)</option><?php endforeach; ?>
                    </select>
                </div>
                <label class="form-label small text-white-50">Mensagem gerada:</label>
                <textarea id="share_textarea" class="form-control bg-dark text-white border-secondary font-monospace" rows="10" style="resize:none; font-size: 14px;"></textarea>
            </div>
            <div class="modal-footer border-success">
                <button type="button" class="btn btn-secondary fw-bold" onclick="copiarShare()"><i class="fas fa-copy me-1"></i> COPIAR</button>
                <button type="button" class="btn btn-success fw-bold" onclick="enviarWhatsApp()"><i class="fab fa-whatsapp me-1"></i> WHATSAPP</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    const operadoras = <?= json_encode($lista_operadoras) ?>;
    const modalUsuario = new bootstrap.Modal(document.getElementById('modalUsuario'));
    const modalShare = new bootstrap.Modal(document.getElementById('modalShare'));
    
    function toggleMenu() { document.getElementById('sidebar').classList.toggle('show'); document.getElementById('overlay').classList.toggle('show'); }
    
    function resetCheckboxes() { document.querySelectorAll('.check-perfil').forEach(chk => chk.checked = false); }
    
    function abrirModalUsuario() { 
        document.querySelector('#modalUsuario form').reset(); 
        document.getElementById('f_name').readOnly = false; 
        document.getElementById('f_is_teste').value = "0"; 
        resetCheckboxes();
        const firstCheck = document.querySelector('.check-perfil');
        if (firstCheck) firstCheck.checked = true;
        document.getElementById('f_venc').value = "<?= date('Y-m-d', strtotime('+30 days')) ?>"; 
        document.getElementById('modalTitulo').innerText = "Novo Usuário CSP"; 
        modalUsuario.show(); 
    }
    
    function editarUsuario(user) { 
        document.getElementById('f_name').value = user.name; 
        document.getElementById('f_name').readOnly = true; 
        document.getElementById('f_pass').value = user.password; 
        resetCheckboxes();
        if(user.perfis) {
            const perfisDoUser = user.perfis.split(',').map(p => p.trim());
            document.querySelectorAll('.check-perfil').forEach(chk => {
                if(perfisDoUser.includes(chk.value)) { chk.checked = true; }
            });
        }
        document.getElementById('f_conn').value = user.max_conn; 
        document.getElementById('f_venc').value = user.vencimento; 
        document.getElementById('f_enabled').checked = (user.enabled === 'true'); 
        document.getElementById('f_is_teste').value = "0"; 
        document.getElementById('modalTitulo').innerText = "Editar Usuário: " + user.name; 
        modalUsuario.show(); 
    }
    
    function gerarTeste24h() { 
        const rand = Math.floor(1000 + Math.random() * 9000); 
        document.getElementById('f_name').value = "teste" + rand; 
        document.getElementById('f_pass').value = rand + "test"; 
        document.getElementById('f_conn').value = 1; 
        resetCheckboxes();
        const firstCheck = document.querySelector('.check-perfil');
        if (firstCheck) firstCheck.checked = true;
        document.getElementById('f_is_teste').value = "1"; 
        const amanha = new Date(); amanha.setDate(amanha.getDate() + 1); 
        document.getElementById('f_venc').value = amanha.toISOString().split('T')[0]; 
        document.getElementById('f_enabled').checked = true; 
        document.getElementById('modalTitulo').innerText = "Gerador de Teste 24h"; 
        modalUsuario.show(); 
    }
    
    function abrirShare(data) { document.getElementById('share_user').value = data.name; document.getElementById('share_pass').value = data.password; document.getElementById('share_venc').value = data.vencimento; document.getElementById('share_tipo').value = data.tipo; updateShareText(); modalShare.show(); }
    function updateShareText() { const user = document.getElementById('share_user').value; const pass = document.getElementById('share_pass').value; let venc = document.getElementById('share_venc').value; const tipo = document.getElementById('share_tipo').value; const op_id = document.getElementById('share_operadora').value; if(venc) { const p = venc.split('-'); if(p.length === 3) venc = p[2] + '/' + p[1] + '/' + p[0]; } else { venc = "Sem Vencimento"; } let url = "SUA_URL_AQUI"; let porta = "PORTA_AQUI"; if (operadoras && operadoras.length > 0) { let op = operadoras.find(o => o.id == op_id); if (op) { url = op.url; porta = op.porta; } else { url = operadoras[0].url; porta = operadoras[0].porta; } } let texto = ""; if (tipo === 'renovacao') { texto += "✅ *SUAS LINHAS FORAM RENOVADAS COM SUCESSO!* ✅\n\n"; } else if (tipo === 'teste') { texto += "⏳ *SEU TESTE DE 24 HORAS ESTÁ LIBERADO!* ⏳\n\n"; } else if (tipo === 'novo') { texto += "✅ *SEU ACESSO FOI CRIADO COM SUCESSO!* ✅\n\n"; } else { texto += "📌 *DADOS DO SEU ACESSO CSP* 📌\n\n"; } texto += "👤 *Usuário:* " + user + "\n"; texto += "🔑 *Senha:* " + pass + "\n"; texto += "🌐 *URL:* " + url + "\n"; texto += "🚪 *Porta:* " + porta + "\n"; texto += "📅 *Vencimento:* " + venc + "\n\n"; texto += "Qualquer dúvida, estou à disposição! 🚀"; document.getElementById('share_textarea').value = texto; }
    function enviarWhatsApp() { const texto = encodeURIComponent(document.getElementById('share_textarea').value); window.open('https://api.whatsapp.com/send?text=' + texto, '_blank'); }
    function copiarShare() { const texto = document.getElementById('share_textarea').value; navigator.clipboard.writeText(texto).then(() => { alert('Mensagem copiada com sucesso!'); }); }
    <?php if(isset($share_data) && $share_data): ?> document.addEventListener("DOMContentLoaded", function() { abrirShare(<?= json_encode($share_data) ?>); }); <?php endif; ?>
</script>
</body>
</html>