<?php
ini_set('pcre.jit', '0');
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;
$usuarioLogado = $_SESSION['usuario'] ?? '';
$msg = "";
$msg_tipo = "";

// --- CORREÇÃO DO ERRO DO MENU LATERAL ---
$total_msg_nao_lidas = 0; 
// ----------------------------------------

// --- 1. 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) { }

// --- 2. PROCURAR O SERVIDOR CSP NA BASE DE DADOS ---
$stmt = $connGeral->query("SELECT url, porta, usuario, senha, protocolo FROM painel WHERE block != 'sim' OR block IS NULL LIMIT 1");
$srv = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$srv) {
    die("ERRO: Nenhum servidor CSP configurado ou ativo na tabela 'painel'.");
}

$ip = str_replace(['http://', 'https://', '/'], '', $srv['url']);
$porta = trim($srv['porta']); 
$user_csp = trim($srv['usuario']);
$pass_csp = trim($srv['senha']);
$protocolo = !empty($srv['protocolo']) ? $srv['protocolo'] : 'http';

$csp_base_url = "{$protocolo}://{$ip}:{$porta}";
$csp_auth = "{$user_csp}:{$pass_csp}";

// --- BUSCA AS OPERADORAS PARA A MENSAGEM DO WHATSAPP ---
$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) {}

// --- FUNÇÃO PARA CRIAR SESSÃO NA CSP (LOGIN REAL) ---
function getCspSession($url, $user, $pass, $auth) {
    $ch = curl_init();
    $login_xml = "<cws-status-req ver=\"1.0\">\n<cws-login>\n<user name=\"{$user}\" password=\"{$pass}\"/>\n</cws-login>\n</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_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERPWD, $auth);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: text/xml']);

    $res = curl_exec($ch);
    curl_close($ch);

    if ($res && preg_match('/state="loggedIn"/i', $res) && preg_match('/session-id="([^"]+)"/i', $res, $matches)) {
        return $matches[1]; 
    }
    return false;
}

// --- FUNÇÃO PARA LER O FICHEIRO XML DE CONFIGURAÇÃO ---
function getCspXml($url, $auth) {
    $session_id = getCspSession($url, explode(':', $auth)[0], explode(':', $auth)[1], $auth);
    if (!$session_id) return false;
    
    $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);
    if (!$session_id) return false;
    
    $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; 
            --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; }
        
        /* Sidebar Restourada */
        .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; }
        
        /* Main Content Ajustado (Flexbox + min-vh-100 para colar rodapé no chão) */
        .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; }
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; margin: 0; }

        /* Elementos Premium */
        .card-custom { background-color: var(--bg-card) !important; border: 1px solid var(--border-color) !important; border-radius: 12px; overflow: hidden; margin-bottom: 20px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        
        /* Tabela Dinâmica que respeita Tema Claro/Escuro DE VERDADE */
        .table-custom { width: 100%; margin-bottom: 0; border-collapse: separate; border-spacing: 0; background: transparent !important; }
        .table-custom th { background-color: var(--bg-card) !important; border-bottom: 1px solid var(--border-color) !important; color: #a6a6b7 !important; font-size: 0.8rem; text-transform: uppercase; font-weight: 700; padding: 15px; white-space: nowrap; }
        .table-custom td { background-color: var(--bg-card) !important; border-bottom: 1px solid var(--border-color) !important; color: var(--text-color) !important; vertical-align: middle; padding: 15px; font-size: 0.95rem; }
        .table-custom tbody tr:hover td { background-color: rgba(115, 103, 240, 0.08) !important; }

        /* Inputs Customizados Dinâmicos */
        .form-control, .form-select { background-color: rgba(0,0,0,0.1) !important; border: 1px solid var(--border-color) !important; color: var(--text-color) !important; border-radius: 8px; padding: 10px 15px; transition: 0.2s; }
        body.light-mode .form-control, body.light-mode .form-select { background-color: rgba(0,0,0,0.03) !important; }
        .form-control:focus, .form-select:focus { border-color: var(--primary) !important; box-shadow: 0 0 0 0.25rem rgba(115, 103, 240, 0.25) !important; background-color: transparent !important;}

        @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: column; align-items: flex-start; gap: 15px; 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; }
        .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 w-100">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title"><i class="fas fa-users-cog me-2"></i> Gestão de Usuários (Proxy)</div>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <button class="btn btn-info fw-bold rounded-pill text-dark shadow-sm px-4" onclick="gerarTeste24h()"><i class="fas fa-magic me-1"></i> TESTE 24H</button>
            <button class="btn btn-light fw-bold rounded-pill shadow-sm px-4 text-primary" 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 flex-grow-1">
        
        <?php if($msg): ?>
            <div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show border-0 shadow-sm fw-bold">
                <?= $msg ?>
                <button class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="card card-custom shadow-lg">
            <div class="table-responsive">
                <table class="table table-custom table-hover align-middle">
                    <thead>
                        <tr>
                            <th class="ps-4">Nome / Usuário</th>
                            <th>Senha</th>
                            <th>Perfis Liberados</th>
                            <th>Conexões</th>
                            <th>Vencimento</th>
                            <th>Status</th>
                            <th class="text-end pe-4">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($usuarios)): ?>
                            <tr><td colspan="7" class="text-center py-5 text-muted">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="ps-4 fw-bold" style="color: var(--text-color);"><?= htmlspecialchars($user['name']) ?></td>
                                <td class="text-info font-monospace fw-bold"><?= htmlspecialchars($user['password']) ?></td>
                                <td class="fw-bold">
                                    <?php 
                                        if ($user['perfis']) {
                                            $perfis_array = explode(',', $user['perfis']);
                                            foreach($perfis_array as $p) {
                                                echo '<span class="badge bg-warning bg-opacity-10 border border-warning text-warning me-1 px-2 py-1 shadow-sm">' . htmlspecialchars(trim($p)) . '</span>';
                                            }
                                        } else {
                                            echo '<span class="badge bg-danger bg-opacity-10 text-danger border border-danger px-2 py-1">Sem Perfil!</span>';
                                        }
                                    ?>
                                </td>
                                <td><span class="badge bg-dark border border-secondary shadow-sm px-2 py-1 fs-6 text-white"><?= $user['max_conn'] ?></span></td>
                                <td>
                                    <span class="fw-bold <?= $expirado ? 'text-danger' : 'text-success' ?>">
                                        <?= !empty($user['vencimento']) ? date('d/m/Y', strtotime($user['vencimento'])) : 'Sem data' ?>
                                    </span>
                                </td>
                                <td>
                                    <?= ($user['enabled'] === 'true') ? 
                                    '<span class="badge bg-success bg-opacity-10 text-success border border-success px-2 py-1">ATIVO</span>' : 
                                    '<span class="badge bg-danger bg-opacity-10 text-danger border border-danger px-2 py-1">BLOQUEADO</span>' ?>
                                </td>
                                <td class="text-end pe-4 text-nowrap">
                                    <div class="d-flex gap-2 justify-content-end">
                                        <button class="btn btn-sm btn-outline-success shadow-sm rounded-3" onclick='abrirShare(<?= json_encode(array_merge($user, ['tipo'=>'lembrete'])) ?>)' title="Enviar WhatsApp">
                                            <i class="fab fa-whatsapp"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-info shadow-sm rounded-3" onclick='editarUsuario(<?= json_encode($user) ?>)' title="Editar Usuário">
                                            <i class="fas fa-pen"></i>
                                        </button>
                                        <form method="POST" class="m-0" 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 shadow-sm rounded-3" title="Renovar 30 Dias"><i class="fas fa-sync-alt"></i></button>
                                        </form>
                                        <form method="POST" class="m-0" 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 shadow-sm rounded-3" title="Excluir Usuário"><i class="fas fa-trash"></i></button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <div class="mt-auto w-100">
        <?php include 'rodape.php'; ?>
    </div>
</main>

<div class="modal fade" id="modalUsuario" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-secondary" style="background-color: var(--bg-card);">
            <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" style="color: var(--text-color);" id="modalTitulo"><i class="fas fa-user-plus text-primary me-2"></i> Configurar Usuário</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1) grayscale(100%) brightness(200%);"></button>
                </div>
                <div class="modal-body p-4">
                    <div class="row g-3">
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">NOME DE USUÁRIO</label>
                            <input type="text" name="name" id="f_name" class="form-control fw-bold text-primary" required>
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">SENHA</label>
                            <input type="text" name="password" id="f_pass" class="form-control" required>
                        </div>
                    </div>
                    
                    <div class="mb-3 mt-2">
                        <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="border border-secondary p-3 rounded" style="background-color: rgba(0,0,0,0.1); max-height: 150px; overflow-y: auto;">
                            <?php if(empty($perfis_da_csp)): ?>
                                <div class="text-danger small fw-bold"><i class="fas fa-exclamation-triangle me-1"></i> Nenhum perfil encontrado dentro da CSP.</div>
                            <?php else: ?>
                                <?php foreach($perfis_da_csp as $index => $p_nome): ?>
                                    <div class="form-check mb-1">
                                        <input class="form-check-input check-perfil" type="checkbox" name="perfis[]" value="<?= htmlspecialchars($p_nome) ?>" id="perfil_csp_<?= $index ?>" style="cursor: pointer;">
                                        <label class="form-check-label font-monospace ms-1" for="perfil_csp_<?= $index ?>" style="color: var(--text-color); cursor: pointer;">
                                            <?= htmlspecialchars($p_nome) ?>
                                        </label>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="row g-3">
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">CONEXÕES</label>
                            <input type="number" name="max_connections" id="f_conn" class="form-control text-center" value="1" required>
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">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-3 d-flex align-items-center gap-2">
                        <label class="small fw-bold mb-0" style="color: var(--text-color);">USUÁRIO ATIVO</label>
                        <input class="form-check-input m-0" type="checkbox" name="enabled" id="f_enabled" style="width: 40px; height: 20px; cursor:pointer;" checked>
                    </div>
                </div>
                <div class="modal-footer border-secondary">
                    <button type="submit" class="btn btn-primary w-100 fw-bold py-2 shadow-sm rounded-pill">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 border-success" style="background-color: var(--bg-card);">
            <div class="modal-header border-success bg-success bg-opacity-10">
                <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" data-bs-dismiss="modal" style="filter: invert(1) grayscale(100%) brightness(200%);"></button>
            </div>
            <div class="modal-body p-4">
                <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-4">
                    <label class="form-label small text-warning fw-bold"><i class="fas fa-hand-pointer me-1"></i> 1º ESCOLHA A OPERADORA PARA O LINK:</label>
                    <select id="share_operadora" class="form-select border-warning" onchange="updateShareText()" style="background-color: rgba(255, 159, 67, 0.05) !important;">
                        <?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-success fw-bold"><i class="fas fa-envelope-open-text me-1"></i> MENSAGEM GERADA:</label>
                <textarea id="share_textarea" class="form-control text-success border-success font-monospace" rows="10" style="resize:none; font-size: 14px; background-color: rgba(40, 199, 111, 0.05) !important;"></textarea>
            </div>
            <div class="modal-footer border-success">
                <button type="button" class="btn btn-outline-light fw-bold w-50 shadow-sm" style="color: var(--text-color); border-color: var(--border-color);" onclick="copiarShare()"><i class="fas fa-copy me-1"></i> COPIAR</button>
                <button type="button" class="btn btn-success fw-bold w-50 shadow-sm" 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').innerHTML = "<i class='fas fa-user-plus text-primary me-2'></i> 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').innerHTML = "<i class='fas fa-pen text-warning me-2'></i> 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_name').readOnly = false;
        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').innerHTML = "<i class='fas fa-magic text-info me-2'></i> 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>
