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

// Verifica login
if (!isset($_SESSION['logado'])) { header("Location: login.php"); exit; }

$isAdmin = (strtolower($_SESSION['nivel']) === 'admin');
$usuarioLogado = $_SESSION['usuario'];
$msg = ""; $msg_tipo = ""; 

// =================================================================================
// 1. TRAVA DE SEGURANÇA TOTAL (KILL SWITCH)
// =================================================================================
if (!$isAdmin) {
    $stmtCheck = $connUser->prepare("SELECT bloqueado, data_premio FROM rev WHERE usuario = ? LIMIT 1");
    $stmtCheck->execute([$usuarioLogado]);
    $me = $stmtCheck->fetch(PDO::FETCH_ASSOC);

    if ($me) {
        $isBloq = ($me['bloqueado'] == 'sim');
        $isVenc = ((int)$me['data_premio'] > 0 && (int)$me['data_premio'] < time());

        if ($isBloq || $isVenc) {
            $motivo = $isBloq ? "BLOQUEADO PELO ADMINISTRADOR" : "PLANO VENCIDO";
            die("
                <!DOCTYPE html>
                <html lang='pt-br'>
                <head>
                    <meta charset='UTF-8'><meta name='viewport' content='width=device-width, initial-scale=1.0'>
                    <title>Acesso Negado</title>
                    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
                    <style>body{background:#151521;color:#fff;display:flex;align-items:center;justify-content:center;height:100vh;text-align:center;}</style>
                </head>
                <body>
                    <div>
                        <h1 class='text-danger fw-bold' style='font-size: 3rem;'>🚫</h1>
                        <h2 class='fw-bold text-uppercase'>ACESSO SUSPENSO</h2>
                        <p class='lead text-muted'>$motivo</p>
                        <p>Entre em contato com o suporte para regularizar.</p>
                        <a href='sair.php' class='btn btn-outline-light mt-3 px-4'>Sair do Painel</a>
                    </div>
                </body>
                </html>
            ");
        }
    }
}

// --- 2. CONFIGURAÇÕES E DADOS ---
$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) { }

$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
$urlPainel = $protocol . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);

try {
    $perfis_sistema = $connGeral->query("SELECT id, nome FROM perfil WHERE bloqueado IS NULL OR bloqueado != 'sim' ORDER BY nome ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $perfis_sistema = []; }

// --- 3. PROCESSAR AÇÕES ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $acao = $_POST['acao'] ?? '';
        $id_rev = (int)($_POST['id_rev'] ?? 0);
        $filtroSeguranca = $isAdmin ? "" : " AND CadUser = '$usuarioLogado'";

        // CRIAR / EDITAR
        if ($acao === 'criar' || $acao === 'editar') {
            $user = trim($_POST['usuario']); $pass = trim($_POST['senha']); $limite = (int)$_POST['limite'];
            $venc_ts = !empty($_POST['data_premio']) ? strtotime($_POST['data_premio']) : 0;
            $perfis_salvar = !empty($_POST['perfis']) ? implode(',', $_POST['perfis']) : '';

            if ($acao === 'criar') {
                // VERIFICAÇÃO DE DUPLICIDADE (Revendedores E Clientes)
                $checkRev = $connUser->prepare("SELECT id FROM rev WHERE usuario = ?");
                $checkRev->execute([$user]);
                
                $checkCli = $connUser->prepare("SELECT id FROM usuario WHERE usuario = ?");
                $checkCli->execute([$user]);

                if($checkRev->rowCount() > 0 || $checkCli->rowCount() > 0){
                    $msg = "ERRO: O usuário '$user' já existe no sistema!";
                    $msg_tipo = "warning";
                } else {
                    $sql = "INSERT INTO rev (usuario, senha, LimiteUser, data_premio, data_cadastro, CadUser, perfil, bloqueado, inativo) VALUES (?, ?, ?, ?, NOW(), ?, ?, 'nao', 'nao')";
                    $connUser->prepare($sql)->execute([$user, $pass, $limite, $venc_ts, $usuarioLogado, $perfis_salvar]);
                    $msg = "Revendedor criado com sucesso!"; $msg_tipo = "success";
                }
            } else {
                $sql = "UPDATE rev SET usuario=?, senha=?, LimiteUser=?, data_premio=?, perfil=? WHERE id=? $filtroSeguranca";
                $connUser->prepare($sql)->execute([$user, $pass, $limite, $venc_ts, $perfis_salvar, $id_rev]);
                $msg = "Dados atualizados!"; $msg_tipo = "primary";
            }
        }

        // BLOQUEIO/DESBLOQUEIO COM CASCATA AUTOMÁTICA
        if ($acao === 'alternar_bloqueio') {
            $status_atual = $_POST['status_atual'];
            // Se estava 'sim' (bloqueado), vira 'nao' (desbloqueado). E vice-versa.
            $novo_status = ($status_atual == 'sim') ? 'nao' : 'sim';
            
            // Busca o usuário ALVO (quem estamos bloqueando/desbloqueando)
            $st = $connUser->prepare("SELECT usuario FROM rev WHERE id=? LIMIT 1");
            $st->execute([$id_rev]);
            $targetUser = $st->fetchColumn();

            if ($targetUser) {
                $targetUser = trim($targetUser);

                // 1. Atualiza o status do Próprio Revendedor
                $connUser->prepare("UPDATE rev SET bloqueado=? WHERE id=?")->execute([$novo_status, $id_rev]);

                // 2. Aplica o MESMO status ('sim' ou 'nao') para todos os dependentes
                // Isso garante que se desbloquear, desbloqueia todos. Se bloquear, bloqueia todos.
                
                // Clientes Diretos
                $connUser->prepare("UPDATE usuario SET bloqueado=? WHERE CadUser = ?")->execute([$novo_status, $targetUser]);
                // Testes Diretos
                $connUser->prepare("UPDATE teste SET bloqueado=? WHERE CadUser = ?")->execute([$novo_status, $targetUser]);
                // Sub-Revendedores
                $connUser->prepare("UPDATE rev SET bloqueado=? WHERE CadUser = ?")->execute([$novo_status, $targetUser]);

                // 3. Cascata Profunda (Clientes dos Sub-revendedores)
                $subs = $connUser->prepare("SELECT usuario FROM rev WHERE CadUser = ?");
                $subs->execute([$targetUser]);
                $sub_revs = $subs->fetchAll(PDO::FETCH_COLUMN);

                foreach ($sub_revs as $subUser) {
                    $subUser = trim($subUser);
                    $connUser->prepare("UPDATE usuario SET bloqueado=? WHERE CadUser = ?")->execute([$novo_status, $subUser]);
                    $connUser->prepare("UPDATE teste SET bloqueado=? WHERE CadUser = ?")->execute([$novo_status, $subUser]);
                }

                if ($novo_status == 'sim') {
                    $msg = "Revendedor e TODA a rede dele foram BLOQUEADOS!";
                    $msg_tipo = "danger";
                } else {
                    $msg = "Revendedor e TODA a rede dele foram DESBLOQUEADOS!";
                    $msg_tipo = "success";
                }
            }
        }

        if ($acao === 'excluir') {
            $connUser->prepare("DELETE FROM rev WHERE id=? $filtroSeguranca")->execute([$id_rev]);
            $msg = "Removido!"; $msg_tipo = "danger";
        }

    } catch (Exception $e) { $msg = "Erro: " . $e->getMessage(); $msg_tipo = "danger"; }
}

// --- 4. LISTAGEM ---
$limit_pg = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$pg = isset($_GET['pagina']) ? (int)$_GET['pagina'] : 1;
$offset = ($pg - 1) * $limit_pg;
$busca = trim($_GET['busca'] ?? '');

$where = " WHERE 1=1";
if (!$isAdmin) $where .= " AND CadUser = '$usuarioLogado'";
if ($busca) $where .= " AND usuario LIKE '%$busca%'";

$total_reg = $connUser->query("SELECT COUNT(*) FROM rev $where")->fetchColumn();
$total_paginas = ceil($total_reg / $limit_pg);
$revendas = $connUser->query("SELECT * FROM rev $where ORDER BY id DESC LIMIT $limit_pg OFFSET $offset")->fetchAll();
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Revendedores | <?= 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; }
        body { background: 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); padding: 20px; border-right: 1px solid #333; z-index: 1050; overflow-y: auto; }
        .main-content { margin-left: 260px; padding: 20px; transition: 0.3s; }
        @media (max-width: 992px) { 
            .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } 
            .main-content { margin-left: 0; padding: 10px 0; } 
            .mobile-toggle { display: block !important; margin-left: 15px; } 
            .card-custom.table-card { border-radius: 0; border: none; }
        }
        .nav-link { color: #a6a6b7; padding: 10px 12px; border-radius: 8px; margin-bottom: 2px; display: flex; align-items: center; gap: 10px; text-decoration: none; }
        .nav-link.active, .nav-link:hover { background: var(--primary); color: #fff; }
        .card-custom { background: var(--bg-card) !important; border: 1px solid #333; border-radius: 12px; margin-left: 10px; margin-right: 10px; }
        .table-card { margin-left: 0; margin-right: 0; border-radius: 0; }
        .form-control, .form-select { background: #2b2b40 !important; border: 1px solid #444 !important; color: #fff !important; }
        .table-responsive { background: var(--bg-card) !important; width: 100%; margin: 0; }
        .table-video { width: 100%; border-collapse: collapse; margin-bottom: 0; }
        .table-video thead th { background-color: #2b2b40 !important; color: #b9b9c3 !important; font-size: 0.75rem; text-transform: uppercase; padding: 15px 10px; }
        .table-video td { background-color: var(--bg-card) !important; color: #fff !important; vertical-align: middle; padding: 12px 10px; border-bottom: 1px solid #2b2b3c !important; }
        .btn-action-group { display: flex; gap: 5px; justify-content: flex-end; }
        .btn-icon-sq { width: 32px; height: 32px; border-radius: 5px; display: inline-flex; align-items: center; justify-content: center; border: none; color: #fff; }
        .bg-sq-purple { background-color: #7367f0; } .bg-sq-blue { background-color: #00cfe8; } .bg-sq-orange { background-color: #ff9f43; } .bg-sq-red { background-color: #ea5455; }    
        .status-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; margin-right: 6px; }
        .dot-online { background-color: #28c76f; box-shadow: 0 0 5px #28c76f; }
        .dot-offline { background-color: #ea5455; box-shadow: 0 0 5px #ea5455; }
        .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; }
        .badge-perfil { font-size: 0.7rem; padding: 2px 5px; border-radius: 3px; background: rgba(255,255,255,0.1); margin-right: 2px; }
    </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"><i class="fas fa-home"></i> Dashboard</a>
        <?php if ($isAdmin): ?><div class="nav-group-title">ADMIN</div><a href="gerenciar_perfis.php" class="nav-link"><i class="fas fa-layer-group"></i> Perfis</a><a href="gerenciar_dns.php" class="nav-link"><i class="fas fa-network-wired"></i> Servidores</a><a href="gerenciar_email.php" class="nav-link"><i class="fas fa-envelope"></i> E-mails</a><?php endif; ?>
        <div class="nav-group-title">MENU</div><a href="revendedores.php" class="nav-link active"><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="sair.php" class="nav-link text-danger mt-4"><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="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2 px-2">
            <h3 class="fw-bold m-0">Gestão de Revendedores</h3>
            <button onclick="new bootstrap.Modal(document.getElementById('modalCriar')).show()" class="btn btn-primary fw-bold px-4"><i class="fas fa-plus me-2"></i>Novo Revendedor</button>
        </div>

        <?php if($msg): ?><div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show mx-2"><?= $msg ?><button class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <div class="card card-custom mb-4 p-3 shadow-lg">
            <form method="GET" class="row g-2 align-items-end">
                <div class="col-md-7"><label>Pesquisar</label><input type="text" name="busca" class="form-control" placeholder="Usuário..." value="<?= htmlspecialchars($busca) ?>"></div>
                <div class="col-md-2"><label>Exibir</label><select name="limit" class="form-select"><?php foreach([10,20,50,100] as $l): ?><option value="<?= $l ?>" <?= $limit_pg == $l ? 'selected' : '' ?>><?= $l ?> linhas</option><?php endforeach; ?></select></div>
                <div class="col-md-3"><button type="submit" class="btn btn-primary w-100 fw-bold"><i class="fas fa-filter"></i> Filtrar</button></div>
            </form>
        </div>

        <div class="card card-custom table-card shadow-lg overflow-hidden">
            <div class="table-responsive">
                <table class="table table-video">
                    <thead>
                        <tr>
                            <th class="ps-3">Usuário</th>
                            <th class="text-center">Créditos</th>
                            <th>Vencimento</th>
                            <th class="text-end pe-3">Opções</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($revendas as $r): 
                            $venc_ts = (int)$r['data_premio'];
                            $isBloq = ($r['bloqueado'] == 'sim');
                            $isVenc = ($venc_ts > 0 && $venc_ts < time());

                            $perfis_display = "";
                            if(!empty($r['perfil'])){
                                $tags = explode(',', $r['perfil']);
                                foreach($tags as $t) if($t != "") $perfis_display .= "<span class='badge-perfil'>".htmlspecialchars($t)."</span>";
                            } else { $perfis_display = "<span class='text-white-50 small'>---</span>"; }
                        ?>
                        <tr>
                            <td class="ps-3">
                                <div class="d-flex align-items-center text-nowrap">
                                    <span class="status-dot <?= ($isBloq || $isVenc) ? 'dot-offline' : 'dot-online' ?>"></span>
                                    <div>
                                        <span class="fw-bold <?= ($isBloq || $isVenc) ? 'text-danger' : 'text-white' ?> me-2"><?= htmlspecialchars($r['usuario']) ?></span>
                                        <?php if($isBloq): ?><span class="badge bg-danger">BLOQUEADO</span><?php endif; ?>
                                        <?php if($isVenc): ?><span class="badge bg-warning text-dark">VENCIDO</span><?php endif; ?>
                                    </div>
                                </div>
                            </td>
                            <td class="text-center"><span class="badge bg-primary rounded-pill px-3"><?= $r['LimiteUser'] ?></span></td>
                            <td><span class="badge <?= ($isVenc) ? 'bg-danger' : 'bg-success' ?> p-2"><?= $venc_ts > 0 ? date('d/m/Y', $venc_ts) : 'Indefinido' ?></span></td>
                            <td class="pe-3">
                                <div class="btn-action-group">
                                    <button onclick='abrirVisualizar(<?= json_encode($r) ?>, "<?= date('d/m/Y', $venc_ts) ?>")' class="btn-icon-sq bg-sq-purple"><i class="fas fa-eye"></i></button>
                                    <button onclick='abrirEditar(<?= json_encode($r) ?>, "<?= date('Y-m-d', $venc_ts) ?>")' class="btn-icon-sq bg-sq-blue"><i class="fas fa-pen"></i></button>
                                    <form method="POST" class="d-inline">
                                        <input type="hidden" name="acao" value="alternar_bloqueio"><input type="hidden" name="id_rev" value="<?= $r['id'] ?>"><input type="hidden" name="status_atual" value="<?= $r['bloqueado'] ?>">
                                        <button class="btn-icon-sq bg-sq-orange" title="<?= $isBloq ? 'Desbloquear' : 'Bloquear' ?>"><i class="fas <?= $isBloq ? 'fa-lock-open' : 'fa-lock' ?>"></i></button>
                                    </form>
                                    <form method="POST" class="d-inline" onsubmit="return confirm('Excluir revendedor?')">
                                        <input type="hidden" name="acao" value="excluir"><input type="hidden" name="id_rev" value="<?= $r['id'] ?>">
                                        <button class="btn-icon-sq bg-sq-red"><i class="fas fa-trash"></i></button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</main>

<div class="modal fade" id="modalVerDados" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content bg-dark border-info text-white"><div class="modal-header"><h5>Dados da Revenda</h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body p-4"><div class="mb-2"><label>Usuário:</label><input type="text" readonly class="form-control" id="view_user"></div><div class="mb-2"><label>Senha:</label><input type="text" readonly class="form-control" id="view_pass"></div><div class="mb-2"><label>Painel:</label><input type="text" readonly class="form-control text-info" id="view_link" value="<?= $urlPainel ?>"></div><div class="mb-4"><label>Vencimento:</label><input type="text" readonly class="form-control text-warning" id="view_venc"></div><div class="d-flex gap-2"><button onclick="copiarVisualizar()" class="btn btn-outline-light w-50">COPIAR</button><button onclick="zapVisualizar()" class="btn btn-success w-50">WHATSAPP</button></div></div></div></div></div>
<div class="modal fade" id="modalCriar" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content bg-dark border-secondary text-white"><form method="POST"><input type="hidden" name="acao" value="criar"><div class="modal-header border-secondary"><h5>Nova Revenda</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body p-4"><div class="mb-3"><label>Usuário</label><input type="text" name="usuario" class="form-control" required></div><div class="mb-3"><label>Senha</label><input type="text" name="senha" class="form-control" required></div><div class="row"><div class="col-6 mb-3"><label>Limite</label><input type="number" name="limite" class="form-control" value="10"></div><div class="col-6 mb-3"><label>Vencimento</label><input type="date" name="data_premio" class="form-control"></div></div><label class="text-info fw-bold mb-2 small">LIBERAR PERFIS:</label><div style="max-height: 120px; overflow-y: auto;" class="p-2 border border-secondary rounded"><?php foreach($perfis_sistema as $p): ?><div class="form-check"><input class="form-check-input" type="checkbox" name="perfis[]" value="<?= $p['nome'] ?>" id="c_<?= $p['id'] ?>"><label class="form-check-label" for="c_<?= $p['id'] ?>"><?= $p['nome'] ?></label></div><?php endforeach; ?></div></div><div class="modal-footer border-secondary"><button type="submit" class="btn btn-primary w-100 fw-bold">CADASTRAR</button></div></form></div></div></div>
<div class="modal fade" id="modalEditar" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content bg-dark border-secondary text-white"><form method="POST"><input type="hidden" name="acao" value="editar"><input type="hidden" name="id_rev" id="edit_id"><div class="modal-header border-secondary"><h5>Editar Revenda</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body p-4"><div class="mb-3"><label>Usuário</label><input type="text" name="usuario" id="edit_user" class="form-control"></div><div class="mb-3"><label>Senha</label><input type="text" name="senha" id="edit_pass" class="form-control"></div><div class="row"><div class="col-6 mb-3"><label>Limite</label><input type="number" name="limite" id="edit_limite" class="form-control"></div><div class="col-6 mb-3"><label>Vencimento</label><input type="date" name="data_premio" id="edit_venc" class="form-control"></div></div><label class="text-info fw-bold mb-2 small">LIBERAR PERFIS:</label><div style="max-height: 120px; overflow-y: auto;" class="p-2 border border-secondary rounded"><?php foreach($perfis_sistema as $p): ?><div class="form-check"><input class="form-check-input chk-edit" type="checkbox" name="perfis[]" value="<?= $p['nome'] ?>" id="e_<?= $p['id'] ?>"><label class="form-check-label" for="e_<?= $p['id'] ?>"><?= $p['nome'] ?></label></div><?php endforeach; ?></div></div><div class="modal-footer border-secondary"><button type="submit" class="btn btn-info w-100 fw-bold">SALVAR</button></div></form></div></div></div>

<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 abrirVisualizar(r, venc) { document.getElementById('view_user').value = r.usuario; document.getElementById('view_pass').value = r.senha; document.getElementById('view_venc').value = venc; new bootstrap.Modal(document.getElementById('modalVerDados')).show(); }
    function gerarMensagem() { const user = document.getElementById('view_user').value; const pass = document.getElementById('view_pass').value; const link = document.getElementById('view_link').value; const venc = document.getElementById('view_venc').value; return `*🚀 ACESSO REVENDA*\n\n👤 *Usuário:* ${user}\n🔑 *Senha:* ${pass}\n🔗 *Painel:* ${link}\n📅 *Vencimento:* ${venc}`; }
    function copiarVisualizar() { navigator.clipboard.writeText(gerarMensagem()).then(() => alert("Copiado!")); }
    function zapVisualizar() { window.open("https://api.whatsapp.com/send?text=" + encodeURIComponent(gerarMensagem()), '_blank'); }
    function abrirEditar(r, venc) { document.getElementById('edit_id').value = r.id; document.getElementById('edit_user').value = r.usuario; document.getElementById('edit_pass').value = r.senha; document.getElementById('edit_limite').value = r.LimiteUser; document.getElementById('edit_venc').value = venc; document.querySelectorAll('.chk-edit').forEach(el => el.checked = false); if(r.perfil) { r.perfil.split(',').forEach(p_nome => { document.querySelectorAll('.chk-edit').forEach(c => { if(c.value.trim() === p_nome.trim()) c.checked = true; }); }); } new bootstrap.Modal(document.getElementById('modalEditar')).show(); }
</script>
</body>
</html>
