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

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

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

// --- 1. CONFIGURAÇÕES ---
$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. BUSCAR DADOS ---
$mapa_perfis = [];
$lista_perfis_select = [];
$lista_revendedores = [];

try {
    $res_p = $connGeral->query("SELECT id, nome, url, porta FROM perfil WHERE (bloqueado IS NULL OR bloqueado != 'sim')")->fetchAll(PDO::FETCH_ASSOC);
    foreach ($res_p as $p) { 
        $mapa_perfis[$p['id']] = $p; 
        $lista_perfis_select[] = $p; 
    }
    if ($isAdmin) {
        $lista_revendedores = $connUser->query("SELECT usuario FROM rev ORDER BY usuario ASC")->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Exception $e) { }

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

        // 3.1 CRIAR
        if ($acao === 'criar') {
            $user = trim($_POST['usuario']); $pass = $_POST['senha']; $pid = $_POST['perfil']; $nome = $_POST['nome'];
            $venc = $_POST['data_premio'];
            $sql = "INSERT INTO usuario (CadUser, nome, usuario, senha, data_premio, perfil, bloqueado, data_cadastro, conexao) VALUES (?,?,?,?,?,?,'nao',NOW(),1)";
            $connUser->prepare($sql)->execute([$usuarioLogado, $nome, $user, $pass, $venc, $pid]);
            
            $p = $mapa_perfis[$pid] ?? [];
            $texto_zap = "*✅ NOVO CLIENTE IPTV*\n\n👤 *User:* $user\n🔑 *Senha:* $pass\n📆 *Venc:* ".date('d/m/Y', strtotime($venc))."\n\n🌐 *DNS:* ".($p['url']??'---')."\n🔌 *Porta:* ".($p['porta']??'---');
            $msg = "Cliente criado!"; $msg_tipo = "success";
        }

        // 3.2 EDITAR
        if ($acao === 'editar') {
            $sql = "UPDATE usuario SET nome=?, usuario=?, senha=?, data_premio=?, perfil=? WHERE id=? $filtroSeguranca";
            $connUser->prepare($sql)->execute([$_POST['nome'], $_POST['usuario'], $_POST['senha'], $_POST['data_premio'], $_POST['perfil'], $id_user]);
            $msg = "Dados atualizados!"; $msg_tipo = "primary";
        }

        // 3.3 RENOVAR
        if ($acao === 'renovar') {
            $stmt = $connUser->prepare("SELECT * FROM usuario WHERE id = ? $filtroSeguranca");
            $stmt->execute([$id_user]);
            $c = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($c) {
                $meses = (int)$_POST['qtd_meses'];
                $venc_raw = $c['data_premio'];
                $atual_ts = is_numeric($venc_raw) ? (int)$venc_raw : strtotime($venc_raw);
                $base = ($atual_ts > time()) ? $atual_ts : time();
                $nova_data = date('Y-m-d', strtotime("+$meses months", $base));
                
                $connUser->prepare("UPDATE usuario SET data_premio=?, bloqueado='nao' WHERE id=?")->execute([$nova_data, $id_user]);
                
                $p = $mapa_perfis[$c['perfil']] ?? [];
                $texto_zap = "*✅ PLANO RENOVADO*\n\n👤 *User:* {$c['usuario']}\n🔑 *Senha:* {$c['senha']}\n📆 *Novo Venc:* ".date('d/m/Y', strtotime($nova_data))."\n\n🌐 *DNS:* ".($p['url']??'---');
                $msg = "Renovado com sucesso!"; $msg_tipo = "success";
            }
        }

        // 3.4 BLOQUEAR
        if ($acao === 'alternar_bloqueio') {
            $status_atual = $_POST['status_atual'];
            $novo_status = ($status_atual == 'sim') ? 'nao' : 'sim';
            $connUser->prepare("UPDATE usuario SET bloqueado=? WHERE id=? $filtroSeguranca")->execute([$novo_status, $id_user]);
            $msg = ($novo_status == 'sim') ? "Usuário Bloqueado!" : "Usuário Desbloqueado!"; 
            $msg_tipo = ($novo_status == 'sim') ? "warning" : "success";
        }
        
        // 3.5 EXCLUIR
        if ($acao === 'excluir') {
            $connUser->prepare("DELETE FROM usuario WHERE id=? $filtroSeguranca")->execute([$id_user]);
            $msg = "Removido!"; $msg_tipo = "danger";
        }
    } catch (Exception $e) { $msg = "Erro: ".$e->getMessage(); $msg_tipo = "danger"; }
}

// --- 4. FILTROS E PAGINAÇÃO ---
$limit  = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$pagina = isset($_GET['pagina']) ? (int)$_GET['pagina'] : 1;
$offset = ($pagina - 1) * $limit;

$busca      = trim($_GET['busca'] ?? '');
$status     = $_GET['status'] ?? '';
$revendedor = $_GET['revendedor'] ?? '';

$where = " WHERE 1=1 ";
if (!$isAdmin) {
    $where .= " AND CadUser = '$usuarioLogado'";
} elseif (!empty($revendedor)) {
    $where .= " AND CadUser = " . $connUser->quote($revendedor);
}

if ($busca) {
    $where .= " AND (nome LIKE '%$busca%' OR usuario LIKE '%$busca%')";
}

if ($status === 'ativo') {
    $where .= " AND (data_premio >= CURDATE() OR data_premio >= UNIX_TIMESTAMP()) AND (bloqueado IS NULL OR bloqueado != 'sim')";
} elseif ($status === 'vencido') {
    $where .= " AND (data_premio < CURDATE() OR (data_premio REGEXP '^[0-9]+$' AND data_premio < UNIX_TIMESTAMP()))";
} elseif ($status === 'bloqueado') {
    $where .= " AND bloqueado = 'sim'";
}

$total_registos = $connUser->query("SELECT COUNT(*) FROM usuario $where")->fetchColumn();
$total_paginas = ceil($total_registos / $limit);
$usuarios = $connUser->query("SELECT * FROM usuario $where ORDER BY id DESC LIMIT $limit 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">
    <title>Clientes | <?= 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; }
        
        /* Layout Geral */
        .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: 30px; transition: 0.3s; }
        .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; }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 20px 0 10px 12px; }
        
        /* Cards e Inputs */
        .card-custom { background: var(--bg-card) !important; border: 1px solid #333; border-radius: 12px; }
        .form-control, .form-select { background: #2b2b40 !important; border: 1px solid #444 !important; color: #fff !important; }
        .form-control::placeholder { color: #888; }
        label { color: #ffffff !important; font-weight: 700; margin-bottom: 5px; font-size: 0.9rem; }
        
        /* --- CORREÇÃO DEFINITIVA DA TABELA ESCURA --- */
        .table-responsive {
            background: var(--bg-card) !important;
            border-radius: 12px;
            border: 1px solid #333;
        }
        
        /* Remove variaveis do Bootstrap que forçam o branco */
        .table-video {
            --bs-table-bg: transparent;
            --bs-table-color: var(--text-color);
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 0;
        }

        /* Cabeçalho */
        .table-video thead th { 
            background-color: #2b2b40 !important; 
            color: #b9b9c3 !important; 
            font-size: 0.85rem; 
            font-weight: 600; 
            text-transform: uppercase; 
            border-bottom: 1px solid #3b3b4f; 
            padding: 15px 10px; 
        }
        
        /* Corpo e Linhas - FORÇAR DARK */
        .table-video tbody tr {
            background-color: var(--bg-card) !important;
        }
        
        /* Células Individuais - FORÇAR DARK */
        .table-video td { 
            background-color: var(--bg-card) !important;
            color: #fff !important;
            vertical-align: middle; 
            padding: 12px 10px; 
            border-bottom: 1px solid #2b2b3c !important; 
        }

        /* Efeito Hover na Linha */
        .table-video tbody tr:hover td { 
            background-color: #252535 !important; 
            color: #fff !important;
        }

        /* Botões de Ação Coloridos */
        .btn-action-group { display: flex; gap: 5px; justify-content: flex-end; }
        .btn-icon-sq { width: 34px; height: 34px; border-radius: 5px; display: inline-flex; align-items: center; justify-content: center; border: none; color: #fff; transition: 0.2s; }
        .btn-icon-sq:hover { transform: translateY(-2px); filter: brightness(1.1); }
        .bg-sq-green { background-color: #28c76f; } 
        .bg-sq-blue { background-color: #00cfe8; }  
        .bg-sq-purple { background-color: #7367f0; } 
        .bg-sq-orange { background-color: #ff9f43; } 
        .bg-sq-red { background-color: #ea5455; }    

        /* Badges */
        .badge-video-date { padding: 6px 10px; border-radius: 4px; font-weight: 600; font-size: 0.8rem; letter-spacing: 0.3px; }
        .badge-green-light { background: rgba(40, 199, 111, 0.15); color: #28c76f; border: 1px solid rgba(40, 199, 111, 0.2); }
        .badge-red-light { background: rgba(234, 84, 85, 0.15); color: #ea5455; border: 1px solid rgba(234, 84, 85, 0.2); }
        
        .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; }
        
        /* Mobile */
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; margin-bottom: 20px; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1040; }
        .overlay.show { display: block; }
        @media (max-width: 992px) { .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } .main-content { margin-left: 0; } .mobile-toggle { display: block !important; } }
        
        /* Correção Paginação Dark */
        .page-link { background-color: #2b2b40 !important; border-color: #444 !important; color: #fff !important; }
        .page-item.active .page-link { background-color: var(--primary) !important; border-color: var(--primary) !important; }
    </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"><i class="fas fa-store"></i> Revendedores</a>
        <a href="clientes.php" class="nav-link active"><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="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
        <h3 class="fw-bold">Gestão de Clientes</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 Cliente</button>
    </div>

    <?php if($msg): ?><div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show"><?= $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-3">
                <label>Pesquisar</label>
                <div class="input-group">
                    <span class="input-group-text bg-dark border-secondary text-white"><i class="fas fa-search"></i></span>
                    <input type="text" name="busca" class="form-control" placeholder="Nome ou Usuário..." value="<?= htmlspecialchars($busca) ?>">
                </div>
            </div>
            
            <?php if ($isAdmin): ?>
            <div class="col-md-2">
                <label>Revendedor</label>
                <select name="revendedor" class="form-select">
                    <option value="">Todos</option>
                    <?php foreach($lista_revendedores as $rev): ?>
                        <option value="<?= $rev['usuario'] ?>" <?= $revendedor == $rev['usuario'] ? 'selected' : '' ?>><?= $rev['usuario'] ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>

            <div class="col-md-2">
                <label>Status</label>
                <select name="status" class="form-select">
                    <option value="">Todos</option>
                    <option value="ativo" <?= $status == 'ativo' ? 'selected' : '' ?>>Ativos</option>
                    <option value="vencido" <?= $status == 'vencido' ? 'selected' : '' ?>>Vencidos</option>
                    <option value="bloqueado" <?= $status == 'bloqueado' ? 'selected' : '' ?>>Bloqueados</option>
                </select>
            </div>

            <div class="col-md-2">
                <label>Exibir</label>
                <select name="limit" class="form-select">
                    <?php foreach([10,20,50,100,250,500,1000,2000,3000] as $l): ?>
                        <option value="<?= $l ?>" <?= $limit == $l ? 'selected' : '' ?>><?= $l ?> linhas</option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="col-md-2">
                <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 shadow-lg overflow-hidden">
        <div class="table-responsive">
            <table class="table table-video mb-0 w-100">
                <thead>
                    <tr>
                        <th class="ps-3">Nome</th>
                        <th>Usuário</th>
                        <th>Senha</th>
                        <th class="text-center">Conexão</th>
                        <th>Vencimento</th>
                        <th>Criado Por</th>
                        <th class="text-end pe-3">Opções</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($usuarios as $u): 
                        $venc_ts = is_numeric($u['data_premio']) ? (int)$u['data_premio'] : strtotime($u['data_premio']);
                        $p_info = $mapa_perfis[$u['perfil']] ?? ['nome' => 'S/ Perfil'];
                        $isBloq = ($u['bloqueado'] == 'sim');
                        
                        $hoje = new DateTime();
                        $dataVenc = new DateTime(date('Y-m-d', $venc_ts));
                        $diff = $hoje->diff($dataVenc);
                        $diasRestantes = $diff->days;
                        if ($venc_ts < time()) { $diasRestantes = -$diasRestantes; }
                        if ($diasRestantes == 0 && $venc_ts > time()) $diasRestantes = 0;
                    ?>
                    <tr>
                        <td class="ps-3">
                            <div class="d-flex align-items-center">
                                <span class="status-dot <?= $isBloq ? 'dot-offline' : 'dot-online' ?>"></span>
                                <div class="fw-bold text-white"><?= htmlspecialchars($u['nome']) ?></div>
                            </div>
                            <?php if($isBloq): ?><span class="badge bg-danger mt-1" style="font-size:0.65rem">BLOQUEADO</span><?php endif; ?>
                        </td>
                        
                        <td><?= htmlspecialchars($u['usuario']) ?></td>
                        
                        <td class="text-white-50"><?= htmlspecialchars($u['senha']) ?></td>
                        
                        <td class="text-center">
                            <span class="badge bg-primary rounded-pill px-2">1</span>
                        </td>
                        
                        <td>
                            <?php if ($venc_ts < time()): ?>
                                <span class="badge badge-video-date badge-red-light">
                                    Vencido (<?= date('d/m/Y', $venc_ts) ?>)
                                </span>
                            <?php else: ?>
                                <span class="badge badge-video-date badge-green-light">
                                    <?= $diasRestantes ?> dias (<?= date('d/m/Y', $venc_ts) ?>)
                                </span>
                            <?php endif; ?>
                        </td>
                        
                        <td><span class="text-white-50 small"><?= $u['CadUser'] ?></span></td>
                        
                        <td class="pe-3">
                            <div class="btn-action-group">
                                <button onclick="abrirRenovar(<?= $u['id'] ?>, '<?= $u['nome'] ?>')" class="btn-icon-sq bg-sq-green" title="Renovar">
                                    <i class="fas fa-sync-alt"></i>
                                </button>
                                <button onclick='abrirEditar(<?= json_encode($u) ?>, "<?= date('Y-m-d', $venc_ts) ?>")' class="btn-icon-sq bg-sq-blue" title="Editar">
                                    <i class="fas fa-pen"></i>
                                </button>
                                <button onclick='abrirVisualizar(<?= json_encode($u) ?>, <?= json_encode($p_info) ?>, "<?= date('d/m/Y', $venc_ts) ?>")' class="btn-icon-sq bg-sq-purple" title="Ver Dados">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <form method="POST" class="d-inline">
                                    <input type="hidden" name="acao" value="alternar_bloqueio">
                                    <input type="hidden" name="id_user" value="<?= $u['id'] ?>">
                                    <input type="hidden" name="status_atual" value="<?= $u['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('Tem certeza que deseja excluir?')">
                                    <input type="hidden" name="acao" value="excluir">
                                    <input type="hidden" name="id_user" value="<?= $u['id'] ?>">
                                    <button class="btn-icon-sq bg-sq-red" title="Excluir">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <?php if($total_paginas > 1): ?>
        <div class="p-3 border-top border-secondary">
            <ul class="pagination justify-content-center m-0">
                <?php for($i=1; $i<=$total_paginas; $i++): ?>
                    <li class="page-item <?= $pagina == $i ? 'active' : '' ?>">
                        <a class="page-link bg-dark border-secondary text-white" href="?pagina=<?= $i ?>&limit=<?= $limit ?>&busca=<?= $busca ?>&status=<?= $status ?>&revendedor=<?= $revendedor ?>"><?= $i ?></a>
                    </li>
                <?php endfor; ?>
            </ul>
        </div>
        <?php endif; ?>
    </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 border-secondary"><h5>Dados do Cliente</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>Vencimento:</label><input type="text" readonly class="form-control text-success fw-bold" id="view_venc"></div><hr class="border-secondary"><div class="mb-2"><label>URL / DNS:</label><input type="text" readonly class="form-control text-info" id="view_url"></div><div class="mb-4"><label>PORTA:</label><input type="text" readonly class="form-control text-warning" id="view_porta"></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"><h5>Novo Cliente</h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body p-4"><div class="mb-3"><label>Nome</label><input type="text" name="nome" class="form-control" required></div><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" value="<?= rand(1000,9999) ?>" required></div><div class="row"><div class="col-6 mb-3"><label>Vencimento</label><input type="date" name="data_premio" class="form-control" value="<?= date('Y-m-d', strtotime('+30 days')) ?>"></div><div class="col-6 mb-3"><label>Perfil</label><select name="perfil" class="form-select" required><?php foreach($lista_perfis_select as $ps): ?><option value="<?= $ps['id'] ?>"><?= $ps['nome'] ?></option><?php endforeach; ?></select></div></div></div><div class="modal-footer"><button type="submit" class="btn btn-success 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_user" id="edit_id"><div class="modal-header"><h5>Editar Cliente</h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body p-4"><div class="mb-3"><label>Nome</label><input type="text" name="nome" id="edit_nome" class="form-control"></div><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>Vencimento</label><input type="date" name="data_premio" id="edit_venc" class="form-control"></div><div class="col-6 mb-3"><label>Perfil</label><select name="perfil" id="edit_perfil" class="form-select"><?php foreach($lista_perfis_select as $ps): ?><option value="<?= $ps['id'] ?>"><?= $ps['nome'] ?></option><?php endforeach; ?></select></div></div></div><div class="modal-footer"><button type="submit" class="btn btn-primary w-100 fw-bold">SALVAR</button></div></form></div></div></div>

<div class="modal fade" id="modalRenovar" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content bg-dark border-success text-white"><form method="POST"><input type="hidden" name="acao" value="renovar"><input type="hidden" name="id_user" id="renovar_id"><div class="modal-header border-success"><h5>Renovar Cliente</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body text-center p-4"><h4 id="renovar_nome" class="mb-3"></h4><div class="mb-3"><label>Quantos Meses?</label><select name="qtd_meses" class="form-select text-center fw-bold text-success"><option value="1">1 Mês</option><option value="3">3 Meses</option><option value="6">6 Meses</option><option value="12">1 Ano</option></select></div><button type="submit" class="btn btn-success w-100 fw-bold">CONFIRMAR RENOVAÇÃO</button></div></form></div></div></div>

<div class="modal fade" id="modalZap" tabindex="-1"><div class="modal-dialog modal-dialog-centered text-center"><div class="modal-content bg-dark border-success text-white"><div class="modal-header border-0 pb-0"><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body p-4 pt-0"><h5 class="text-success mb-3">Concluído!</h5><textarea id="textoZapArea" class="form-control mb-3" rows="6" style="background:#111; color:#0f0; border:none; font-family:monospace;"><?= $texto_zap ?></textarea><button onclick="copiarTexto()" class="btn btn-outline-light me-2">Copiar</button><button onclick="enviarZap()" class="btn btn-success">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>
    function toggleMenu() { document.getElementById('sidebar').classList.toggle('show'); document.getElementById('overlay').classList.toggle('show'); }
    
    // JS Visualizar
    function abrirVisualizar(u, p, data_br) { document.getElementById('view_user').value = u.usuario; document.getElementById('view_pass').value = u.senha; document.getElementById('view_venc').value = data_br; document.getElementById('view_url').value = p.url; document.getElementById('view_porta').value = p.porta; new bootstrap.Modal(document.getElementById('modalVerDados')).show(); }
    function copiarVisualizar() { const m = `👤 User: ${document.getElementById('view_user').value}\n🔑 Senha: ${document.getElementById('view_pass').value}\n📅 Vencimento: ${document.getElementById('view_venc').value}\n🌐 URL: ${document.getElementById('view_url').value}\n🔌 Porta: ${document.getElementById('view_porta').value}`; navigator.clipboard.writeText(m).then(() => alert("Copiado!")); }
    function zapVisualizar() { const m = `👤 *User:* ${document.getElementById('view_user').value}\n🔑 *Senha:* ${document.getElementById('view_pass').value}\n📅 *Vencimento:* ${document.getElementById('view_venc').value}\n🌐 *URL:* ${document.getElementById('view_url').value}\n🔌 *Porta:* ${document.getElementById('view_porta').value}`; window.open("https://api.whatsapp.com/send?text=" + encodeURIComponent(m), '_blank'); }
    
    // JS Editar e Renovar
    function abrirEditar(u, data_inp) { document.getElementById('edit_id').value = u.id; document.getElementById('edit_nome').value = u.nome; document.getElementById('edit_user').value = u.usuario; document.getElementById('edit_pass').value = u.senha; document.getElementById('edit_venc').value = data_inp; document.getElementById('edit_perfil').value = u.perfil; new bootstrap.Modal(document.getElementById('modalEditar')).show(); }
    function abrirRenovar(id, nome) { document.getElementById('renovar_id').value = id; document.getElementById('renovar_nome').innerText = nome; new bootstrap.Modal(document.getElementById('modalRenovar')).show(); }
    
    // JS Zap Pós-criação
    function copiarTexto() { document.getElementById("textoZapArea").select(); document.execCommand("copy"); alert("Copiado!"); }
    function enviarZap() { window.open("https://api.whatsapp.com/send?text=" + encodeURIComponent(document.getElementById("textoZapArea").value), '_blank'); }
    window.onload = function() { if(`<?= trim($texto_zap) ?>` !== "") new bootstrap.Modal(document.getElementById('modalZap')).show(); }
</script>
</body>
</html>
