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

// --- 1. TRAVA DE SEGURANÇA TOTAL (KILL SWITCH) ---
if (!isset($_SESSION['logado'])) { header("Location: login.php"); exit; }

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

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'><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: 4rem;'>🚫</h1><h2 class='fw-bold text-uppercase'>ACESSO SUSPENSO</h2><p class='lead text-muted'>$motivo</p><a href='sair.php' class='btn btn-outline-light mt-4 px-5'>Sair do Painel</a></div></body></html>");
        }
    }
}

try { $connUser->exec("ALTER TABLE usuario ADD COLUMN whatsapp VARCHAR(20) DEFAULT NULL"); } 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) { $nomePainel = $conf['NomePainel'] ?? $nomePainel; $corPrimaria = $conf['TemaPainel'] ?? $corPrimaria; }
} catch (Exception $e) { }

$mapa_perfis = []; $lista_perfis_select = []; $lista_revendedores = [];
$total_msg_nao_lidas = 0; 
$confZapGlobal = []; // Variável para armazenar as mensagens personalizadas globais da página
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); }
    $stmtMsg = $connUser->prepare("SELECT COUNT(*) FROM chamados_suporte WHERE destinatario = ? AND lida = 'nao'");
    $stmtMsg->execute([$usuarioLogado]);
    $total_msg_nao_lidas = $stmtMsg->fetchColumn();
    
    // Pegar as mensagens personalizadas do usuário logado para usar no botão VISUALIZAR (Olho)
    $stmtConfWpp = $connGeral->prepare("SELECT * FROM config_api_whatsapp WHERE usuario = ? LIMIT 1");
    $stmtConfWpp->execute([$usuarioLogado]);
    $confZapGlobal = $stmtConfWpp->fetch(PDO::FETCH_ASSOC);
    if(!$confZapGlobal) $confZapGlobal = [];
} catch (Exception $e) { }

// --- FUNÇÃO GLOBAL DE ENVIO WHATSAPP (EVOLUTION API) ---
function enviarZapPainel($numero, $mensagem, $connGeral, $userLogado) {
    try {
        $stmt = $connGeral->prepare("SELECT * FROM config_api_whatsapp WHERE usuario = ? LIMIT 1");
        $stmt->execute([$userLogado]);
        $conf = $stmt->fetch(PDO::FETCH_ASSOC);
        if(!$conf || empty($conf['api_url']) || empty($numero) || empty($conf['instancia'])) return false;
        
        $numero = preg_replace("/[^0-9]/", "", $numero);
        if (strlen($numero) == 10 || strlen($numero) == 11) { $numero = "55" . $numero; }
        if (strlen($numero) < 12) return false;
        
        $curl = curl_init();
        curl_setopt_array($curl, array(
          CURLOPT_URL => rtrim($conf['api_url'], '/') . "/message/sendText/" . trim($conf['instancia']),
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
          CURLOPT_POSTFIELDS => json_encode([
              "number" => $numero,
              "options" => ["delay" => 1200, "presence" => "composing", "linkPreview" => false],
              "textMessage" => ["text" => $mensagem]
          ]),
          CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'apikey: ' . trim($conf['api_key'])],
        ));
        curl_exec($curl); 
        curl_close($curl);
        return true;
    } catch (Exception $e) { return false; }
}

// --- 4. PROCESSAR AÇÕES (POST) ---
$msg = ""; $msg_tipo = ""; $texto_zap = "";
$redirecionar_limpo = false; 

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $acao = $_POST['acao'] ?? '';
        $id_user = (int)($_POST['id_user'] ?? 0);
        $ids_massa = $_POST['ids_massa'] ?? []; 
        $filtroSeguranca = $isAdmin ? "" : " AND CadUser = '$usuarioLogado'";
        
        // Puxar config_api_whatsapp baseada no usuário logado
        $stmtConfPost = $connGeral->prepare("SELECT * FROM config_api_whatsapp WHERE usuario = ? LIMIT 1");
        $stmtConfPost->execute([$usuarioLogado]);
        $confZap = $stmtConfPost->fetch(PDO::FETCH_ASSOC);

        if (!empty($ids_massa)) {
            $lista_ids = implode(',', array_map('intval', $ids_massa));
            if ($acao === 'vencimento_massa') {
                $nova_data = $_POST['data_massa'] . ' ' . date('H:i:s'); // Adiciona a hora atual para o vencimento em massa
                $connUser->query("UPDATE usuario SET data_premio = '$nova_data' WHERE id IN ($lista_ids) $filtroSeguranca");
                $msg = "Vencimento alterado para " . count($ids_massa) . " clientes!"; $msg_tipo = "success"; $redirecionar_limpo = true;
            } elseif ($acao === 'perfil_massa') {
                $novo_perfil = $_POST['perfil_massa'];
                $connUser->query("UPDATE usuario SET perfil = '$novo_perfil' WHERE id IN ($lista_ids) $filtroSeguranca");
                $msg = "Perfil alterado para " . count($ids_massa) . " clientes!"; $msg_tipo = "success"; $redirecionar_limpo = true;
            } elseif ($acao === 'bloquear_massa') {
                $connUser->query("UPDATE usuario SET bloqueado = 'sim' WHERE id IN ($lista_ids) $filtroSeguranca");
                $msg = count($ids_massa) . " clientes bloqueados!"; $msg_tipo = "warning"; $redirecionar_limpo = true;
            } elseif ($acao === 'desbloquear_massa') {
                $connUser->query("UPDATE usuario SET bloqueado = 'nao' WHERE id IN ($lista_ids) $filtroSeguranca");
                $msg = count($ids_massa) . " clientes desbloqueados!"; $msg_tipo = "success"; $redirecionar_limpo = true;
            } elseif ($acao === 'excluir_massa') {
                $connUser->query("DELETE FROM usuario WHERE id IN ($lista_ids) $filtroSeguranca");
                $msg = count($ids_massa) . " clientes removidos!"; $msg_tipo = "danger"; $redirecionar_limpo = true;
            }
        }

        if ($acao === 'criar') {
            $user = trim($_POST['usuario']); $pass = $_POST['senha']; $pid = $_POST['perfil']; $nome = $_POST['nome'];
            $venc = $_POST['data_premio'] . ' ' . date('H:i:s'); // Adiciona a exata hora de criação
            $email = trim($_POST['email'] ?? ''); 
            $whatsapp = trim($_POST['whatsapp'] ?? ''); 
            $conexoes = isset($_POST['conexao']) ? (int)$_POST['conexao'] : 1; 

            $check = $connUser->prepare("SELECT id FROM usuario WHERE usuario = ? LIMIT 1");
            $check->execute([$user]);
            if ($check->rowCount() > 0) {
                $msg = "ERRO: O usuário '<b>$user</b>' já existe!"; $msg_tipo = "warning";
            } else {
                $sql = "INSERT INTO usuario (CadUser, nome, usuario, senha, email, data_premio, perfil, bloqueado, data_cadastro, conexao, whatsapp) VALUES (?,?,?,?,?,?,?,'nao',NOW(),?,?)";
                $connUser->prepare($sql)->execute([$usuarioLogado, $nome, $user, $pass, $email, $venc, $pid, $conexoes, $whatsapp]);
                
                $p = $mapa_perfis[$pid] ?? [];
                $link_cli = 'https://'.$_SERVER['HTTP_HOST'].'/clientes';
                $txt_zap = "";
                
                if(!empty($confZap['msg_novo'])) {
                    $txt_zap = str_replace(
                        ['{nome}', '{usuario}', '{senha}', '{vencimento}', '{dns}', '{porta}', '{link_cliente}'], 
                        [$nome, $user, $pass, date('d/m/Y', strtotime($venc)), ($p['url']??'---'), ($p['porta']??'---'), $link_cli], 
                        $confZap['msg_novo']
                    );
                } else {
                    $txt_zap = "*✅ CLIENTE CRIADO COM SUCESSO*\n\n👤 *User:* $user\n🔑 *Senha:* $pass\n📆 *Venc:* ".date('d/m/Y', strtotime($venc))."\n🌐 *DNS:* ".($p['url']??'---');
                }

                if(!empty($whatsapp)) { enviarZapPainel($whatsapp, $txt_zap, $connGeral, $usuarioLogado); }
                
                $texto_zap = $txt_zap; 
                $msg = "Cliente criado com sucesso!"; $msg_tipo = "success";
                $redirecionar_limpo = true;
            }
        }
        
        if ($acao === 'editar') {
            $email = trim($_POST['email'] ?? '');
            $whatsapp = trim($_POST['whatsapp'] ?? '');
            $conexoes = isset($_POST['conexao']) ? (int)$_POST['conexao'] : 1;
            
            // Puxar o horário antigo para manter a mesma hora mesmo quando alterar a data
            $stmt_time = $connUser->prepare("SELECT data_premio FROM usuario WHERE id=?");
            $stmt_time->execute([$id_user]);
            $old_dp = $stmt_time->fetchColumn();
            $old_time = (strlen($old_dp) > 10) ? date('H:i:s', strtotime($old_dp)) : date('H:i:s');
            $nova_data_edit = $_POST['data_premio'] . ' ' . $old_time;

            $sql = "UPDATE usuario SET nome=?, usuario=?, senha=?, email=?, data_premio=?, perfil=?, conexao=?, whatsapp=? WHERE id=? $filtroSeguranca";
            $connUser->prepare($sql)->execute([$_POST['nome'], $_POST['usuario'], $_POST['senha'], $email, $nova_data_edit, $_POST['perfil'], $conexoes, $whatsapp, $id_user]);
            $msg = "Dados atualizados!"; $msg_tipo = "primary";
            $redirecionar_limpo = true;
        }
        
        if ($acao === 'renovar') {
            $stmt = $connUser->prepare("SELECT * FROM usuario WHERE id = ? $filtroSeguranca");
            $stmt->execute([$id_user]);
            $c = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($c) {
                $venc_raw = $c['data_premio'];
                $atual_ts = is_numeric($venc_raw) ? (int)$venc_raw : strtotime($venc_raw);
                $base = ($atual_ts > time()) ? $atual_ts : time();
                
                // Mantém a hora exata da criação ao renovar
                if (!empty($_POST['data_manual'])) { 
                    $nova_data = date('Y-m-d', strtotime($_POST['data_manual'])) . ' ' . date('H:i:s', $atual_ts); 
                } else { 
                    $meses = (int)$_POST['qtd_meses']; 
                    $nova_data = date('Y-m-d H:i:s', 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']] ?? [];
                $link_cli = 'https://'.$_SERVER['HTTP_HOST'].'/clientes';
                
                $txt_zap = "";
                if(!empty($confZap['msg_renovacao'])) {
                    $txt_zap = str_replace(
                        ['{nome}', '{usuario}', '{senha}', '{vencimento}', '{dns}', '{porta}', '{link_cliente}'], 
                        [$c['nome'], $c['usuario'], $c['senha'], date('d/m/Y', strtotime($nova_data)), ($p['url']??'---'), ($p['porta']??'---'), $link_cli], 
                        $confZap['msg_renovacao']
                    );
                } else {
                    $txt_zap = "*✅ PLANO RENOVADO COM SUCESSO*\n\n👤 *User:* {$c['usuario']}\n🔑 *Senha:* {$c['senha']}\n📆 *Novo Vencimento:* ".date('d/m/Y', strtotime($nova_data));
                }

                if(!empty($c['whatsapp'])) { enviarZapPainel($c['whatsapp'], $txt_zap, $connGeral, $usuarioLogado); }
                
                $texto_zap = $txt_zap; 
                $msg = "Renovado com sucesso!"; $msg_tipo = "success";
                $redirecionar_limpo = true;
            }
        }
        
        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";
            $redirecionar_limpo = true;
        }
        
        if ($acao === 'alterar_dono' && $isAdmin) {
            $novo_dono = $_POST['novo_dono'];
            $connUser->prepare("UPDATE usuario SET CadUser=? WHERE id=?")->execute([$novo_dono, $id_user]);
            $msg = "Usuário transferido!"; $msg_tipo = "success"; $redirecionar_limpo = true;
        }

        if ($acao === 'excluir') {
            $connUser->prepare("DELETE FROM usuario WHERE id=? $filtroSeguranca")->execute([$id_user]);
            $msg = "Removido!"; $msg_tipo = "danger"; $redirecionar_limpo = true;
        }
        
        if ($redirecionar_limpo && empty($texto_zap)) {
            $_SESSION['temp_msg'] = $msg;
            $_SESSION['temp_msg_tipo'] = $msg_tipo;
            header("Location: clientes.php");
            exit;
        }

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

if (isset($_SESSION['temp_msg'])) {
    $msg = $_SESSION['temp_msg']; $msg_tipo = $_SESSION['temp_msg_tipo'];
    unset($_SESSION['temp_msg']); unset($_SESSION['temp_msg_tipo']);
}

// --- 5. FILTROS E PAGINAÇÃO ---
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$pg = isset($_GET['pagina']) ? (int)$_GET['pagina'] : 1;
$offset = ($pg - 1) * $limit;
$busca = trim($_GET['busca'] ?? ''); 
$data_inicio = trim($_GET['data_inicio'] ?? ''); 
$data_fim = trim($_GET['data_fim'] ?? ''); 
$ordem = trim($_GET['ordem'] ?? 'padrao'); 
$status = isset($_GET['status']) ? $_GET['status'] : 'ativo'; 

// --- REGRAS DO DASHBOARD ADICIONADAS AQUI ---
if ($status === 'esgotados') { $status = 'vencido'; }
if ($status === 'bloqueados') { $status = 'bloqueado'; }
// ---------------------------------------------

if ($busca !== '') { $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%' OR email LIKE '%$busca%' OR whatsapp LIKE '%$busca%')"; }
if (!empty($data_inicio)) { $where .= " AND (IF(data_premio REGEXP '^[0-9]+$', FROM_UNIXTIME(data_premio), data_premio) >= '$data_inicio')"; }
if (!empty($data_fim)) { $where .= " AND (IF(data_premio REGEXP '^[0-9]+$', FROM_UNIXTIME(data_premio), data_premio) <= '$data_fim 23:59:59')"; }

// Filtro utilizando NOW() para bater a hora exata
if ($status === 'ativo') { $where .= " AND (data_premio > NOW() OR (data_premio REGEXP '^[0-9]+$' AND FROM_UNIXTIME(data_premio) > NOW())) AND (bloqueado IS NULL OR bloqueado != 'sim')"; } 
elseif ($status === 'vencido') { $where .= " AND (data_premio <= NOW() OR (data_premio REGEXP '^[0-9]+$' AND FROM_UNIXTIME(data_premio) <= NOW()))"; } 
elseif ($status === 'bloqueado') { $where .= " AND bloqueado = 'sim'"; }

$sql_ordem = "ORDER BY id DESC"; 
if ($ordem === 'venc_asc') { $sql_ordem = "ORDER BY CAST(IF(data_premio REGEXP '^[0-9]+$', data_premio, UNIX_TIMESTAMP(data_premio)) AS SIGNED) ASC"; } 
elseif ($ordem === 'venc_desc') { $sql_ordem = "ORDER BY CAST(IF(data_premio REGEXP '^[0-9]+$', data_premio, UNIX_TIMESTAMP(data_premio)) AS SIGNED) DESC"; }

$usuarios = $connUser->query("SELECT * FROM usuario $where $sql_ordem LIMIT $limit OFFSET $offset")->fetchAll();

// --- AJAX LIVE SEARCH ---
if (isset($_GET['ajax']) && $_GET['ajax'] == 'true') {
    if (count($usuarios) == 0) { echo "<tr><td colspan='10' class='text-center py-4 text-white-50'>Nenhum cliente encontrado.</td></tr>"; exit; }
    foreach ($usuarios as $u) {
        $venc_ts = is_numeric($u['data_premio']) ? (int)$u['data_premio'] : strtotime($u['data_premio']);
        $isBloq = ($u['bloqueado'] == 'sim'); 
        
        // Verifica a hora exata via time()
        $isVenc = ($venc_ts <= time());
        
        $p_info = $mapa_perfis[$u['perfil']] ?? ['nome' => '---', 'url' => '', 'porta' => ''];
        $per_nome_low = mb_strtolower($p_info['nome']);
        
        $img_op = "<span class='text-white-50 small'>".htmlspecialchars($p_info['nome'])."</span>";
        if (strpos($per_nome_low, 'claro') !== false) $img_op = "<img src='img/claro.png' class='img-perfil'>";
        elseif (strpos($per_nome_low, 'net') !== false) $img_op = "<img src='img/net.png' class='img-perfil'>";

        // Badge exibe a data, e ao passar o mouse em cima mostra a hora do corte no titulo.
        $badge_venc = "<span class='badge ".($isVenc ? 'bg-danger' : 'bg-success')." p-2 shadow-sm' title='Corta às ".date('H:i:s', $venc_ts)."'>".date('d/m/Y', $venc_ts)."</span>";
        if($isVenc) $badge_venc .= "<br><small class='text-danger fw-bold'>VENCIDO</small>";

        $btn_admin = "";
        if($isAdmin) { $btn_admin = "<button type='button' onclick='abrirAlterarDono({$u['id']}, ".htmlspecialchars(json_encode($u['usuario']), ENT_QUOTES, 'UTF-8').", ".htmlspecialchars(json_encode($u['CadUser']), ENT_QUOTES, 'UTF-8').")' class='btn-sq bg-sq-gray' title='Alterar Revendedor'><i class='fas fa-exchange-alt'></i></button>"; }

        $icon_bloq = $isBloq ? 'fa-lock-open' : 'fa-lock';

        echo "<tr>
            <td class='text-center'><input type='checkbox' name='ids_massa[]' value='{$u['id']}' class='form-check-input check-item' style='cursor:pointer;'></td>
            <td>
                <div class='d-flex align-items-center'>
                    <span class='status-dot ".($isBloq || $isVenc ? 'offline' : 'online')."'></span>
                    <div class='nome-destaque ".($isBloq || $isVenc ? 'text-danger' : '')."'>".htmlspecialchars($u['nome'])."</div>
                </div>
            </td>
            <td class='text-center small ".($isBloq ? 'text-danger fw-bold' : 'text-info')."'>".($isBloq ? '🚫 BLOQUEADO' : htmlspecialchars($u['usuario']))."</td>
            <td class='text-center text-white-50 small'>".htmlspecialchars($u['senha'])."</td>
            <td class='text-center text-white-50 small'>".htmlspecialchars($u['whatsapp'] ?? '')."</td>
            <td class='text-center'>{$img_op}</td>
            <td class='text-center'><span class='badge bg-primary px-2 py-1'><i class='fas fa-desktop me-1'></i> ".(isset($u['conexao']) ? htmlspecialchars($u['conexao']) : '1')."</span></td>
            <td class='text-center'>{$badge_venc}</td>
            <td class='text-center small text-secondary fw-bold'>".htmlspecialchars($u['CadUser'])."</td>
            <td class='pe-3'>
                <div class='d-flex gap-1 justify-content-end'>
                    <button type='button' onclick='abrirRenovar({$u['id']}, ".htmlspecialchars(json_encode($u['nome']), ENT_QUOTES, 'UTF-8').")' class='btn-sq bg-sq-green' title='Renovar'><i class='fas fa-sync-alt'></i></button>
                    <button type='button' onclick='abrirEditar(".htmlspecialchars(json_encode($u), ENT_QUOTES, 'UTF-8').", \"".date('Y-m-d', $venc_ts)."\")' class='btn-sq bg-sq-blue' title='Editar'><i class='fas fa-pen'></i></button>
                    <button type='button' onclick='abrirVisualizar(".htmlspecialchars(json_encode($u), ENT_QUOTES, 'UTF-8').", ".htmlspecialchars(json_encode($p_info), ENT_QUOTES, 'UTF-8').", \"".date('d/m/Y - H:i', $venc_ts)."\")' class='btn-sq bg-sq-purple' title='Ver Dados'><i class='fas fa-eye'></i></button>
                    {$btn_admin}
                    <button type='button' class='btn-sq bg-sq-orange' title='Bloquear/Desbloquear' onclick='acaoRapidaAlternar({$u['id']}, \"{$u['bloqueado']}\")'><i class='fas {$icon_bloq}'></i></button>
                    <button type='button' class='btn-sq bg-sq-red' title='Excluir' onclick='acaoRapidaExcluir({$u['id']})'><i class='fas fa-trash'></i></button>
                </div>
            </td>
        </tr>";
    } exit;
}
?>

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

        .card-custom { background: var(--bg-card) !important; border: 1px solid var(--border-color); border-radius: 12px; }
        .form-control, .form-select { background: #151521 !important; border: 1px solid #444 !important; color: #fff !important; }
        .table-responsive { background: var(--bg-card) !important; -webkit-overflow-scrolling: touch; }
        .table-video { width: 100%; border-collapse: collapse; white-space: nowrap; }
        .table-video thead th { background: rgba(0,0,0,0.2) !important; color: #ffffff; text-transform: uppercase; font-weight: 700; font-size: 0.75rem; padding: 15px 12px; border-bottom: 1px solid var(--border-color); }
        
        .table-video th, .table-video td { width: 1% !important; white-space: nowrap !important; padding: 12px !important; border-bottom: 1px solid var(--border-color) !important; background: var(--bg-card) !important; color: #fff !important; vertical-align: middle !important; }
        
        .label-visivel { color: #ffffff !important; font-weight: 700; text-transform: uppercase; font-size: 0.75rem; }
        .nome-destaque { color: #ffffff !important; font-weight: 700; }
        
        .img-perfil { height: 22px !important; width: auto !important; filter: drop-shadow(0 0 2px rgba(0,0,0,0.5)); }

        .btn-sq { width: 32px; height: 32px; border-radius: 6px; border: none; color: #fff !important; display: inline-flex; align-items: center; justify-content: center; transition: 0.2s; box-shadow: 0 2px 4px rgba(0,0,0,0.3); }
        .bg-sq-green { background-color: #28c76f !important; } .bg-sq-blue { background-color: #00cfe8 !important; } 
        .bg-sq-purple { background-color: #7367f0 !important; } .bg-sq-orange { background-color: #ff9f43 !important; } 
        .bg-sq-red { background-color: #ea5455 !important; } .bg-sq-gray { background-color: #6c757d !important; } 
        
        .status-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; margin-right: 6px; }
        .online { background-color: #28c76f; box-shadow: 0 0 8px #28c76f; }
        .offline { background-color: #ea5455; box-shadow: 0 0 8px #ea5455; }

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

<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<nav class="sidebar" id="sidebar">
    <div class="text-center mb-4"><h4 class="fw-bold text-white"><?= htmlspecialchars($nomePainel) ?></h4></div>
    <div class="nav flex-column">
        <a href="index.php" class="nav-link active"><i class="fas fa-home"></i> Dashboard</a>
        <?php if ($isAdmin): ?>
            <div class="nav-group-title">ADMINISTRATIVO</div>
            <a href="#submenuCsp" data-bs-toggle="collapse" class="nav-link d-flex justify-content-between align-items-center" aria-expanded="true">
                <span><i class="fas fa-server"></i> Gerenciar CSP</span>
                <i class="fas fa-chevron-down submenu-icon"></i>
            </a>
            <div class="collapse show" id="submenuCsp">
                <div class="ms-3 ps-2 border-start border-secondary">
                    <a href="gerenciar_dns.php" class="nav-link"><i class="fas fa-network-wired"></i> Servidores</a>
                    <a href="gerenciar_perfis.php" class="nav-link"><i class="fas fa-layer-group"></i> Perfis</a>
                    <a href="gerenciar_linhas_csp.php" class="nav-link"><i class="fas fa-plug"></i> Linhas CSP</a>
                    <a href="gerenciar_usuarios_csp.php" class="nav-link"><i class="fas fa-users-cog"></i> Usuários CSP</a>
                    <a href="gerenciar_backups_csp.php" class="nav-link"><i class="fas fa-save"></i> Backups CSP</a>
                </div>
            </div>
            <a href="gerenciar_admins.php" class="nav-link"><i class="fas fa-user-shield"></i> Admins</a>
            <a href="personalizar_painel.php" class="nav-link"><i class="fas fa-paint-brush"></i> Personalizar</a>
            <a href="config_geral.php" class="nav-link"><i class="fas fa-cogs"></i> Configurações</a>
            
            <div class="nav-group-title">SISTEMA SAAS</div>
            <a href="painel_mestre.php" class="nav-link"><i class="fas fa-crown"></i> Gerenciar Licenças</a>
            
            <div class="nav-group-title">ADMIN</div>
            <a href="gerenciar_ips.php" class="nav-link"><i class="fas fa-user-shield"></i> Firewall IPs</a>
            <a href="gerenciar_backups.php" class="nav-link"><i class="fas fa-database"></i> Backup</a>
            <a href="ferramentas_migracao.php" class="nav-link"><i class="fas fa-exchange-alt"></i> Exportar/Importar</a>
        <?php endif; ?>
        
        <div class="nav-group-title">Gestao de Clientes</div>
        <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="monitor.php" class="nav-link"><i class="fas fa-bell"></i> Clientes Online</a>
        <div class="nav-group-title">Gestao de Revendedores</div>
        <a href="revendedores.php" class="nav-link"><i class="fas fa-store"></i> Revendedores</a>
        
        <div class="nav-group-title">ChatBot</div>
        <li style="list-style: none;">
            <a href="gerador_robo.php" class="nav-link" style="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;">
                <i class="fa fa-robot"></i> <span>ChatBot</span>
            </a>
        </li>
        
        <div class="nav-group-title">Api WhatsApp</div>
        <li style="list-style: none;">
           <a href="automacao_whatsapp.php" class="nav-link"><i class="fab fa-whatsapp"></i> Automação Zap</a>
           <a href="config_whatsapp.php" class="nav-link"><i class="fas fa-cogs"></i> Config. API Zap</a> 
           
        <div class="nav-group-title">Ferramentas</div>
        <a href="meus_links.php" class="nav-link"><i class="fas fa-link"></i> Central Links</a>
        <a href="gerenciar_mascara.php" class="nav-link"><i class="fas fa-mask"></i> Máscaras URL</a>        
        <a href="config_mp_revenda.php" class="nav-link"><i class="fas fa-wallet"></i> Config. Pagamento</a>
        <a href="gerenciar_planos.php" class="nav-link"><i class="fas fa-tags"></i> Planos de Venda</a>
        <a href="gerenciar_email.php" class="nav-link"><i class="fas fa-envelope"></i> SMTP Email</a>
        <a href="relatorio.php" class="nav-link"><i class="fas fa-file-invoice-dollar"></i> Relatório de Faturas</a>
        <a href="suporte.php" class="nav-link"><i class="fas fa-headset"></i> Suporte <?php if($total_msg_nao_lidas > 0): ?><span class="badge bg-danger ms-auto rounded-pill"><?= $total_msg_nao_lidas ?></span><?php endif; ?></a>
        <a href="enviar_circular.php" class="nav-link"><i class="fas fa-paper-plane"></i> Enviar Circular</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">
    <div class="top-header">
        <div class="d-flex align-items-center">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title">Gestão de Clientes</div>
        </div>
        <div class="d-flex gap-2">
            <button onclick="new bootstrap.Modal(document.getElementById('modalCriar')).show()" class="btn btn-light btn-sm fw-bold px-3 rounded-pill shadow-sm"><i class="fas fa-plus me-1"></i> NOVO</button>
        </div>
    </div>

    <div class="container-fluid p-2 p-md-4">
        <?php if($msg): ?><div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show border-0 shadow-sm mb-4 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" id="formFiltro" class="row g-2 align-items-end">
                <div class="col-md-3">
                    <label class="label-visivel mb-1">PESQUISAR (Ao Vivo)</label>
                    <input type="text" name="busca" id="inputPesquisaLive" class="form-control" placeholder="Login, Nome ou E-mail..." value="<?= htmlspecialchars($busca) ?>">
                    <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Busque pelo nome, login ou e-mail cadastrado.</small>
                </div>
                <div class="col-md-2">
                    <label class="label-visivel mb-1 text-white-50"><i class="fas fa-calendar-alt me-1"></i> VENCE DE:</label>
                    <input type="date" name="data_inicio" id="filtroDataDe" class="form-control" value="<?= htmlspecialchars($data_inicio) ?>">
                    <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Data inicial de vencimento.</small>
                </div>
                <div class="col-md-2">
                    <label class="label-visivel mb-1 text-white-50"><i class="fas fa-calendar-alt me-1"></i> ATÉ:</label>
                    <input type="date" name="data_fim" id="filtroDataAte" class="form-control" value="<?= htmlspecialchars($data_fim) ?>">
                    <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Data limite de vencimento.</small>
                </div>
                <?php if ($isAdmin): ?>
                <div class="col-md-2">
                    <label class="label-visivel mb-1">REVENDEDOR</label>
                    <select name="revendedor" id="filtroRev" 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>
                    <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Filtre pelos clientes de um dono.</small>
                </div>
                <?php endif; ?>
                <div class="col-md-2">
                    <label class="label-visivel mb-1">STATUS</label>
                    <select name="status" id="filtroStatus" class="form-select">
                        <option value="" <?= $status == '' ? 'selected' : '' ?>>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>
                    <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Situação da conexão.</small>
                </div>
                <div class="col-md-2">
                    <label class="label-visivel mb-1 text-info">ORDENAR POR</label>
                    <select name="ordem" id="filtroOrdem" class="form-select border-info">
                        <option value="padrao" <?= $ordem == 'padrao' ? 'selected' : '' ?>>Cadastro (Padrão)</option>
                        <option value="venc_asc" <?= $ordem == 'venc_asc' ? 'selected' : '' ?>>Vencimento (Próximos)</option>
                        <option value="venc_desc" <?= $ordem == 'venc_desc' ? 'selected' : '' ?>>Vencimento (Longe)</option>
                    </select>
                    <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Forma de organizar a lista.</small>
                </div>
                <div class="col-md-2">
                    <label class="label-visivel mb-1">EXIBIR</label>
                    <select name="limit" id="filtroLimit" class="form-select">
                        <?php foreach([10,20,50,100,500] as $l): ?>
                            <option value="<?= $l ?>" <?= $limit == $l ? 'selected' : '' ?>><?= $l ?> linhas</option>
                        <?php endforeach; ?>
                    </select>
                    <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Itens por página.</small>
                </div>
                
                <div class="col-md-2" id="divOpcoesMassa" style="display: none;">
                    <label class="label-visivel mb-1 text-warning">AÇÕES EM MASSA</label>
                    <div class="dropdown">
                        <button class="btn btn-warning w-100 fw-bold dropdown-toggle py-2 shadow text-dark" type="button" data-bs-toggle="dropdown">OPÇÕES (<span id="countMassa">0</span>)</button>
                        <ul class="dropdown-menu dropdown-menu-dark w-100 shadow-lg">
                            <li><a class="dropdown-item" href="javascript:void(0)" onclick="abrirVencMassa()"><i class="fas fa-calendar-alt me-2 text-info"></i> Alterar Vencimento</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0)" onclick="abrirPerfilMassa()"><i class="fas fa-layer-group me-2 text-warning"></i> Alterar Perfil</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="javascript:void(0)" onclick="confirmarMassa('bloquear_massa')"><i class="fas fa-lock me-2 text-danger"></i> Bloquear Todos</a></li>
                            <li><a class="dropdown-item" href="javascript:void(0)" onclick="confirmarMassa('desbloquear_massa')"><i class="fas fa-lock-open me-2 text-success"></i> Desbloquear Todos</a></li>
                            <li><a class="dropdown-item text-danger" href="javascript:void(0)" onclick="confirmarMassa('excluir_massa')"><i class="fas fa-trash me-2"></i> Excluir Todos</a></li>
                        </ul>
                    </div>
                </div>

                <div class="col-md-2" id="btnFiltrarNormal">
                    <label class="label-visivel mb-1 text-transparent" style="color:transparent;">.</label>
                    <button type="submit" class="btn btn-primary w-100 fw-bold py-2 shadow"><i class="fas fa-filter me-1"></i> FILTRAR</button>
                    <small class="text-info mt-1 d-block" style="font-size: 0.75rem; color:transparent!important;">.</small>
                </div>
            </form>
        </div>

        <form id="formMassa" method="POST">
            <input type="hidden" name="acao" id="acaoMassaInput">
            <input type="hidden" name="data_massa" id="dataMassaInput">
            <input type="hidden" name="perfil_massa" id="perfilMassaInput">

            <div class="card card-custom shadow-lg overflow-hidden">
                <div class="table-responsive">
                    <table class="table table-video">
                        <thead>
                            <tr>
                                <th class="text-center" style="width: 1%;"><input type="checkbox" id="checkAll" class="form-check-input" style="cursor:pointer;"></th>
                                <th>Nome</th>
                                <th class="text-center">Usuário</th>
                                <th class="text-center">Senha</th>
                                <th class="text-center">WhatsApp</th>
                                <th class="text-center">Operadora</th>
                                <th class="text-center">Conexão</th>
                                <th class="text-center">Vencimento</th>
                                <th class="text-center">Criado Por</th>
                                <th class="text-end pe-3">Opções</th>
                            </tr>
                        </thead>
                        <tbody id="corpoTabelaClientes">
                            <?php foreach($usuarios as $u): 
                                $venc_ts = is_numeric($u['data_premio']) ? (int)$u['data_premio'] : strtotime($u['data_premio']);
                                $isBloq = ($u['bloqueado'] == 'sim');
                                
                                // Agora respeita o tempo real!
                                $isVenc = ($venc_ts <= time());
                                
                                $p_info = $mapa_perfis[$u['perfil']] ?? ['nome' => '---', 'url' => '', 'porta' => ''];
                                $per_nome_low = mb_strtolower($p_info['nome']);
                            ?>
                            <tr>
                                <td class="text-center"><input type="checkbox" name="ids_massa[]" value="<?= $u['id'] ?>" class="form-check-input check-item" style="cursor:pointer;"></td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <span class="status-dot <?= ($isBloq || $isVenc) ? 'offline' : 'online' ?>"></span>
                                        <div class="nome-destaque <?= ($isBloq || $isVenc) ? 'text-danger' : '' ?>"><?= htmlspecialchars($u['nome']) ?></div>
                                    </div>
                                </td>
                                <td class="text-center small <?= $isBloq ? 'text-danger fw-bold' : 'text-info' ?>"><?= $isBloq ? '🚫 BLOQUEADO' : htmlspecialchars($u['usuario']) ?></td>
                                <td class="text-center text-white-50 small"><?= htmlspecialchars($u['senha']) ?></td>
                                <td class="text-center text-white-50 small"><?= htmlspecialchars($u['whatsapp'] ?? '') ?></td>
                                <td class="text-center">
                                    <?php 
                                        if (strpos($per_nome_low, 'claro') !== false) { echo '<img src="img/claro.png" class="img-perfil" alt="Claro">'; } 
                                        elseif (strpos($per_nome_low, 'net') !== false) { echo '<img src="img/net.png" class="img-perfil" alt="Net">'; } 
                                        else { echo '<span class="text-white-50 small">'.htmlspecialchars($p_info['nome']).'</span>'; }
                                    ?>
                                </td>
                                <td class="text-center"><span class="badge bg-primary px-2 py-1"><i class="fas fa-desktop me-1"></i> <?= isset($u['conexao']) ? htmlspecialchars($u['conexao']) : '1' ?></span></td>
                                <td class="text-center">
                                    <span class="badge <?= $isVenc ? 'bg-danger' : 'bg-success' ?> p-2 shadow-sm" title="Hora do corte: <?= date('H:i:s', $venc_ts) ?>"><?= date('d/m/Y', $venc_ts) ?></span>
                                    <?php if($isVenc): ?><br><small class="text-danger fw-bold">VENCIDO</small><?php endif; ?>
                                </td>
                                <td class="text-center small text-secondary fw-bold"><?= htmlspecialchars($u['CadUser']) ?></td>
                                <td class="pe-3">
                                    <div class="d-flex gap-1 justify-content-end">
                                        <button type="button" onclick="abrirRenovar(<?= $u['id'] ?>, <?= htmlspecialchars(json_encode($u['nome']), ENT_QUOTES, 'UTF-8') ?>)" class="btn-sq bg-sq-green" title="Renovar"><i class="fas fa-sync-alt"></i></button>
                                        <button type="button" onclick='abrirEditar(<?= htmlspecialchars(json_encode($u), ENT_QUOTES, 'UTF-8') ?>, "<?= date('Y-m-d', $venc_ts) ?>")' class="btn-sq bg-sq-blue" title="Editar"><i class="fas fa-pen"></i></button>
                                        <button type="button" onclick='abrirVisualizar(<?= htmlspecialchars(json_encode($u), ENT_QUOTES, 'UTF-8') ?>, <?= htmlspecialchars(json_encode($p_info), ENT_QUOTES, 'UTF-8') ?>, "<?= date('d/m/Y - H:i', $venc_ts) ?>")' class="btn-sq bg-sq-purple" title="Ver Dados"><i class="fas fa-eye"></i></button>
                                        <?php if ($isAdmin): ?>
                                        <button type="button" onclick='abrirAlterarDono(<?= $u['id'] ?>, <?= htmlspecialchars(json_encode($u['usuario']), ENT_QUOTES, 'UTF-8') ?>, <?= htmlspecialchars(json_encode($u['CadUser']), ENT_QUOTES, 'UTF-8') ?>)' class="btn-sq bg-sq-gray" title="Alterar Revendedor"><i class="fas fa-exchange-alt"></i></button>
                                        <?php endif; ?>
                                        <button type="button" class="btn-sq bg-sq-orange" title="Bloquear/Desbloquear" onclick="acaoRapidaAlternar(<?= $u['id'] ?>, '<?= $u['bloqueado'] ?>')"><i class="fas <?= $isBloq ? 'fa-lock-open' : 'fa-lock' ?>"></i></button>
                                        <button type="button" class="btn-sq bg-sq-red" title="Excluir" onclick="acaoRapidaExcluir(<?= $u['id'] ?>)"><i class="fas fa-trash"></i></button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </form>
    </div>
</main>

<form id="formAcaoIndividual" method="POST" style="display:none;"><input type="hidden" name="acao" id="acaoIndividual"><input type="hidden" name="id_user" id="idIndividual"><input type="hidden" name="status_atual" id="statusIndividual"></form>

<div class="modal fade" id="modalVencMassa" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-secondary text-white">
            <div class="modal-header border-secondary">
                <h5>Alterar Vencimento em Massa</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 class="small fw-bold mb-2">NOVA DATA DE VENCIMENTO</label>
                    <input type="date" id="inputVencMassa" class="form-control">
                    <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Selecione a nova data de vencimento para os clientes marcados.</small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary w-100 fw-bold shadow" onclick="submitVencMassa()">APLICAR ALTERAÇÃO</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalPerfilMassa" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-secondary text-white">
            <div class="modal-header border-secondary">
                <h5>Alterar Perfil em Massa</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 class="small fw-bold mb-2">NOVO PERFIL</label>
                    <select id="inputPerfilMassa" class="form-select">
                        <?php foreach($lista_perfis_select as $ps): ?>
                            <option value="<?= $ps['id'] ?>"><?= $ps['nome'] ?></option>
                        <?php endforeach; ?>
                    </select>
                    <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Defina o novo pacote de conteúdos que os clientes selecionados terão acesso.</small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary w-100 fw-bold shadow" onclick="submitPerfilMassa()">TROCAR PERFIL DE TODOS</button>
            </div>
        </div>
    </div>
</div>

<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"><input type="hidden" id="view_nome"><div class="mb-2"><label class="small text-white-50">Usuário:</label><input type="text" readonly class="form-control" id="view_user"></div><div class="mb-2"><label class="small text-white-50">Senha:</label><input type="text" readonly class="form-control" id="view_pass"></div><div class="mb-2"><label class="small text-white-50">E-mail:</label><input type="text" readonly class="form-control" id="view_email"></div><div class="mb-2"><label class="small text-white-50">WhatsApp:</label><input type="text" readonly class="form-control" id="view_whatsapp"></div><div class="mb-2"><label class="small text-white-50">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 class="small text-white-50">URL / DNS:</label><input type="text" readonly class="form-control text-info" id="view_url"></div><div class="mb-4"><label class="small text-white-50">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 fw-bold">COPIAR</button><button onclick="zapVisualizar()" class="btn btn-success w-50 fw-bold">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 class="small fw-bold">NOME</label>
                        <input type="text" name="nome" class="form-control" placeholder="Ex: João da Silva" required>
                        <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Nome completo para identificação do cliente no painel.</small>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">USUÁRIO</label>
                        <div class="input-group">
                            <input type="text" name="usuario" id="cria_user" class="form-control" placeholder="Ex: joao123" required>
                            <button class="btn btn-outline-info" type="button" onclick="gerarAleatorio('cria_user', 6, false)" title="Gerar Usuário Aleatório"><i class="fas fa-random"></i></button>
                        </div>
                        <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Login de acesso que o cliente usará no aplicativo.</small>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">SENHA</label>
                        <div class="input-group">
                            <input type="text" name="senha" id="cria_pass" class="form-control" value="<?= rand(1000,9999) ?>" required>
                            <button class="btn btn-outline-info" type="button" onclick="gerarAleatorio('cria_pass', 6, true)" title="Gerar Senha Aleatória"><i class="fas fa-random"></i></button>
                        </div>
                        <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Senha para conectar ao servidor (pode ser gerada automaticamente).</small>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">WHATSAPP</label>
                        <input type="text" name="whatsapp" class="form-control" placeholder="Ex: 5511999999999">
                        <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Digite apenas números com DDI+DDD. Essencial para envio automático de cobranças.</small>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">E-MAIL (Opcional)</label>
                        <input type="email" name="email" class="form-control" placeholder="cliente@email.com">
                        <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Endereço de e-mail secundário do cliente.</small>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="small fw-bold">VENCIMENTO</label>
                            <input type="date" name="data_premio" class="form-control" value="<?= date('Y-m-d', strtotime('+30 days')) ?>">
                            <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Data limite de acesso.</small>
                        </div>
                        <div class="col-6 mb-3">
                            <label class="small fw-bold">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>
                            <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Operadora/DNS liberada.</small>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">QTD. TELAS</label>
                        <input type="number" name="conexao" class="form-control text-center" value="1" min="1" required>
                        <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Total de conexões simultâneas permitidas (1, 2, 3...).</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-success w-100 fw-bold shadow">CADASTRAR E ENVIAR WHATSAPP</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 class="small fw-bold">NOME</label>
                        <input type="text" name="nome" id="edit_nome" class="form-control">
                        <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Atualize o nome de identificação do cliente no painel.</small>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">USUÁRIO</label>
                        <div class="input-group">
                            <input type="text" name="usuario" id="edit_user" class="form-control">
                            <button class="btn btn-outline-info" type="button" onclick="gerarAleatorio('edit_user', 6, false)"><i class="fas fa-random"></i></button>
                        </div>
                        <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Login de acesso que o cliente usará no aplicativo.</small>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">SENHA</label>
                        <div class="input-group">
                            <input type="text" name="senha" id="edit_pass" class="form-control">
                            <button class="btn btn-outline-info" type="button" onclick="gerarAleatorio('edit_pass', 6, true)"><i class="fas fa-random"></i></button>
                        </div>
                        <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Senha para conectar ao servidor.</small>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">WHATSAPP</label>
                        <input type="text" name="whatsapp" id="edit_whatsapp" class="form-control">
                        <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Digite apenas números com DDI+DDD para garantir a automação de cobranças.</small>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">E-MAIL</label>
                        <input type="email" name="email" id="edit_email" class="form-control">
                        <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Endereço de e-mail secundário do cliente.</small>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="small fw-bold">VENCIMENTO</label>
                            <input type="date" name="data_premio" id="edit_venc" class="form-control">
                            <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Data exata do corte do sinal.</small>
                        </div>
                        <div class="col-6 mb-3">
                            <label class="small fw-bold">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>
                            <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Operadora/DNS liberada.</small>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">QTD. TELAS</label>
                        <input type="number" name="conexao" id="edit_conexao" class="form-control text-center" min="1" required>
                        <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Total de conexões simultâneas permitidas (1, 2, 3...).</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary w-100 fw-bold shadow">SALVAR ALTERAÇÕES</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 text-start">
                        <label class="small fw-bold text-white-50">DATA EXATA (OPCIONAL):</label>
                        <input type="date" name="data_manual" class="form-control mb-1">
                        <small class="text-info mt-1 d-block text-start" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Defina uma data específica ou deixe em branco.</small>
                    </div>
                    <div class="mb-3 text-start">
                        <label class="small fw-bold text-white-50">OU SELECIONE OS MESES:</label>
                        <select name="qtd_meses" class="form-select text-center fw-bold text-success mb-1">
                            <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>
                        <small class="text-info mt-1 d-block text-start" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Adiciona X meses a partir do vencimento atual.</small>
                    </div>
                    <button type="submit" class="btn btn-success w-100 fw-bold mt-2">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" id="btnCloseZap"></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;"></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>

<?php if ($isAdmin): ?>
<div class="modal fade" id="modalAlterarDono" 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="alterar_dono">
                <input type="hidden" name="id_user" id="dono_id_user">
                <div class="modal-header">
                    <h5>Alterar Revendedor</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-4">
                    <p class="text-white-50 small mb-3">Transferir o usuário <strong id="dono_nome_user" class="text-white"></strong>.</p>
                    <div class="mb-3">
                        <label class="small fw-bold">NOVO REVENDEDOR</label>
                        <select name="novo_dono" id="dono_select" class="form-select" required>
                            <option value="<?= htmlspecialchars($_SESSION['usuario']) ?>">Administrador (Eu)</option>
                            <?php foreach($lista_revendedores as $rev): ?>
                                <option value="<?= htmlspecialchars($rev['usuario']) ?>"><?= htmlspecialchars($rev['usuario']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <small class="text-info mt-1 d-block" style="font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Selecione o usuário que passará a administrar este cliente.</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-warning w-100 fw-bold">ALTERAR</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endif; ?>

<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'); }
    
    const checkAll = document.getElementById('checkAll');
    function refazerCheckboxes() {
        const checkItems = document.querySelectorAll('.check-item');
        const divOpcoesMassa = document.getElementById('divOpcoesMassa');
        const btnFiltrarNormal = document.getElementById('btnFiltrarNormal');
        const countMassa = document.getElementById('countMassa');
        if(checkAll) { checkAll.onchange = function() { checkItems.forEach(item => item.checked = checkAll.checked); atualizarLayoutMassa(); }; }
        checkItems.forEach(item => { item.onchange = atualizarLayoutMassa; });
        function atualizarLayoutMassa() {
            const selecionados = document.querySelectorAll('.check-item:checked').length;
            if (selecionados > 0) { divOpcoesMassa.style.display = 'block'; btnFiltrarNormal.style.display = 'none'; if (countMassa) countMassa.innerText = selecionados; } 
            else { divOpcoesMassa.style.display = 'none'; btnFiltrarNormal.style.display = 'block'; }
        }
    } refazerCheckboxes(); 

    let timeoutPesquisa;
    const inputsFiltro = ['inputPesquisaLive', 'filtroDataDe', 'filtroDataAte', 'filtroRev', 'filtroStatus', 'filtroOrdem', 'filtroLimit'];
    inputsFiltro.forEach(id => {
        const elemento = document.getElementById(id);
        if(elemento) { elemento.addEventListener('input', function() { clearTimeout(timeoutPesquisa); timeoutPesquisa = setTimeout(fazerPesquisaAjax, 400); }); }
    });

    function fazerPesquisaAjax() {
        const inputBusca = document.getElementById('inputPesquisaLive');
        const selectStatus = document.getElementById('filtroStatus');
        if (inputBusca.value.trim() !== '') { selectStatus.value = ''; }
        const busca = inputBusca.value; const data_inicio = document.getElementById('filtroDataDe').value; const data_fim = document.getElementById('filtroDataAte').value;
        const revendedor = document.getElementById('filtroRev') ? document.getElementById('filtroRev').value : '';
        const status = selectStatus.value; const ordem = document.getElementById('filtroOrdem').value; const limit = document.getElementById('filtroLimit').value;
        const url = `clientes.php?ajax=true&busca=${encodeURIComponent(busca)}&data_inicio=${data_inicio}&data_fim=${data_fim}&revendedor=${revendedor}&status=${status}&ordem=${ordem}&limit=${limit}`;
        document.getElementById('corpoTabelaClientes').style.opacity = '0.5';
        fetch(url).then(response => response.text()).then(html => {
            document.getElementById('corpoTabelaClientes').innerHTML = html; document.getElementById('corpoTabelaClientes').style.opacity = '1';
            if(checkAll) checkAll.checked = false; document.getElementById('divOpcoesMassa').style.display = 'none'; document.getElementById('btnFiltrarNormal').style.display = 'block'; refazerCheckboxes();
        }).catch(err => console.error("Erro na pesquisa:", err));
    }

    function abrirVencMassa() { new bootstrap.Modal(document.getElementById('modalVencMassa')).show(); }
    function abrirPerfilMassa() { new bootstrap.Modal(document.getElementById('modalPerfilMassa')).show(); }
    function submitVencMassa() {
        const data = document.getElementById('inputVencMassa').value; if(!data) return alert("Selecione uma data!");
        document.getElementById('acaoMassaInput').value = 'vencimento_massa'; document.getElementById('dataMassaInput').value = data; document.getElementById('formMassa').submit();
    }
    function submitPerfilMassa() {
        const perfil = document.getElementById('inputPerfilMassa').value;
        document.getElementById('acaoMassaInput').value = 'perfil_massa'; document.getElementById('perfilMassaInput').value = perfil; document.getElementById('formMassa').submit();
    }
    function confirmarMassa(tipo) {
        if(confirm("Deseja aplicar esta ação em todos os selecionados?")) { document.getElementById('acaoMassaInput').value = tipo; document.getElementById('formMassa').submit(); }
    }
    function acaoRapidaAlternar(id, statusAtual) {
        document.getElementById('acaoIndividual').value = 'alternar_bloqueio'; document.getElementById('idIndividual').value = id; document.getElementById('statusIndividual').value = statusAtual; document.getElementById('formAcaoIndividual').submit();
    }
    function acaoRapidaExcluir(id) {
        if(confirm('Excluir este cliente?')) { document.getElementById('acaoIndividual').value = 'excluir'; document.getElementById('idIndividual').value = id; document.getElementById('formAcaoIndividual').submit(); }
    }
    
    function abrirVisualizar(u, p, data_br) { 
        document.getElementById('view_nome').value = u.nome || '';
        document.getElementById('view_user').value = u.usuario; document.getElementById('view_pass').value = u.senha; 
        document.getElementById('view_email').value = u.email ? u.email : ''; document.getElementById('view_whatsapp').value = u.whatsapp ? u.whatsapp : ''; 
        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 gerarMensagemPronta() {
        let txt = <?= json_encode(!empty($confZapGlobal['msg_novo']) ? $confZapGlobal['msg_novo'] : "*✅ DADOS DO CLIENTE*\n\n👤 *User:* {usuario}\n🔑 *Senha:* {senha}\n📅 *Vencimento:* {vencimento}\n🌐 *DNS:* {dns}\n🔌 *Porta:* {porta}") ?>;
        txt = txt.replace(/{nome}/g, document.getElementById('view_nome').value);
        txt = txt.replace(/{usuario}/g, document.getElementById('view_user').value);
        txt = txt.replace(/{senha}/g, document.getElementById('view_pass').value);
        txt = txt.replace(/{vencimento}/g, document.getElementById('view_venc').value);
        txt = txt.replace(/{dns}/g, document.getElementById('view_url').value);
        txt = txt.replace(/{porta}/g, document.getElementById('view_porta').value);
        txt = txt.replace(/{link_cliente}/g, 'https://' + window.location.hostname + '/clientes');
        return txt;
    }

    function copiarVisualizar() { 
        const m = gerarMensagemPronta();
        navigator.clipboard.writeText(m).then(() => alert("Copiado com Sucesso!")); 
    }
    
    function zapVisualizar() { 
        const m = gerarMensagemPronta();
        const zapVal = document.getElementById('view_whatsapp').value; 
        const num = zapVal.replace(/\D/g, ''); 
        const urlFinal = num ? "https://api.whatsapp.com/send?phone=" + num + "&text=" : "https://api.whatsapp.com/send?text=";
        window.open(urlFinal + encodeURIComponent(m), '_blank'); 
    }

    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_email').value = u.email ? u.email : ''; document.getElementById('edit_whatsapp').value = u.whatsapp ? u.whatsapp : ''; 
        document.getElementById('edit_venc').value = data_inp; document.getElementById('edit_perfil').value = u.perfil; 
        let connSelect = document.getElementById('edit_conexao'); if(connSelect) { connSelect.value = u.conexao ? u.conexao : 1; }
        new bootstrap.Modal(document.getElementById('modalEditar')).show(); 
    }
    function abrirRenovar(id, nome) { 
        document.getElementById('renovar_id').value = id; document.getElementById('renovar_nome').innerText = nome; 
        const dataManualInput = document.querySelector('input[name="data_manual"]'); if(dataManualInput) dataManualInput.value = '';
        new bootstrap.Modal(document.getElementById('modalRenovar')).show(); 
    }
    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'); }
    
    <?php if ($isAdmin): ?>
    function abrirAlterarDono(id, usuario, donoAtual) { document.getElementById('dono_id_user').value = id; document.getElementById('dono_nome_user').innerText = usuario; document.getElementById('dono_select').value = donoAtual; new bootstrap.Modal(document.getElementById('modalAlterarDono')).show(); }
    <?php endif; ?>

    function gerarAleatorio(idInput, tamanho, apenasNumeros = false) {
        const caracteres = apenasNumeros ? '0123456789' : 'abcdefghijklmnopqrstuvwxyz0123456789'; let resultado = '';
        for (let i = 0; i < tamanho; i++) { resultado += caracteres.charAt(Math.floor(Math.random() * caracteres.length)); } document.getElementById(idInput).value = resultado;
    }

    window.onload = function() { 
        var zapMsg = <?= json_encode(trim($texto_zap)) ?>;
        if(zapMsg !== "") { 
            document.getElementById("textoZapArea").value = zapMsg; 
            new bootstrap.Modal(document.getElementById('modalZap')).show(); 
            <?php if($redirecionar_limpo): ?> 
                const redir = () => { window.location.href = 'clientes.php'; }; 
                document.getElementById('modalZap').addEventListener('hidden.bs.modal', redir); 
                document.getElementById('btnCloseZap').onclick = redir; 
            <?php endif; ?> 
        } 
    }
</script>
</body>
</html>