<?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) { }
try { $connUser->exec("ALTER TABLE usuario ADD COLUMN observacao TEXT 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) { }

// DETECÇÃO AUTOMÁTICA DA URL BASE + PASTA DO SISTEMA
$protocolo_atual = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$pasta_sistema = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
$base_url_painel = $protocolo_atual . $_SERVER['HTTP_HOST'] . $pasta_sistema;

$mapa_perfis = []; $lista_perfis_select = []; $lista_revendedores = [];
$total_msg_nao_lidas = 0; 
$confZapGlobal = []; 
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();
    
    $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; }
}

// --- FUNÇÕES GLOBAIS DE E-MAIL SMTP ---
if(!function_exists('ler_resposta_smtp')) {
    function ler_resposta_smtp($socket) {
        $res = '';
        while($str = @fgets($socket, 515)) {
            $res .= $str;
            if(substr($str, 3, 1) == ' ') break;
        }
        return $res;
    }
}

if(!function_exists('dispararEmailSMTP')) {
    function dispararEmailSMTP($para, $assunto, $mensagem, $nomePainel, $user, $pass, $host, $port) {
        if(empty($user) || empty($pass)) return false;
        $crlf = "\r\n";
        $headers = "From: =?UTF-8?B?".base64_encode($nomePainel)."?= <$user>$crlf";
        $headers .= "To: <$para>$crlf";
        $headers .= "Subject: =?UTF-8?B?".base64_encode($assunto)."?=$crlf";
        $headers .= "MIME-Version: 1.0$crlf";
        $headers .= "Content-Type: text/html; charset=utf-8$crlf";

        $host_con = ($port == 465 && strpos($host, 'ssl://') === false) ? 'ssl://' . $host : $host;
        $clean_host = str_replace('ssl://', '', $host);

        $socket = @fsockopen($host_con, $port, $errno, $errstr, 10);
        if(!$socket) return false;

        ler_resposta_smtp($socket);
        @fputs($socket, "EHLO $clean_host$crlf"); ler_resposta_smtp($socket);
        
        if ($port == 587) {
            @fputs($socket, "STARTTLS$crlf"); ler_resposta_smtp($socket);
            @stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
            @fputs($socket, "EHLO $clean_host$crlf"); ler_resposta_smtp($socket);
        }

        @fputs($socket, "AUTH LOGIN$crlf"); ler_resposta_smtp($socket);
        @fputs($socket, base64_encode($user).$crlf); ler_resposta_smtp($socket);
        @fputs($socket, base64_encode(trim($pass)).$crlf); 
        
        $auth_res = ler_resposta_smtp($socket);
        if(substr($auth_res, 0, 3) != '235') { @fclose($socket); return false; } 

        @fputs($socket, "MAIL FROM: <$user>$crlf"); ler_resposta_smtp($socket);
        @fputs($socket, "RCPT TO: <$para>$crlf"); ler_resposta_smtp($socket);
        @fputs($socket, "DATA$crlf"); ler_resposta_smtp($socket);
        @fputs($socket, $headers . $crlf . $mensagem . $crlf . ".$crlf"); ler_resposta_smtp($socket);
        @fputs($socket, "QUIT$crlf");
        @fclose($socket);

        return true;
    }
}
// ---------------------------------------------

// --- 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'";
        
        $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');
                $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');
            $email = trim($_POST['email'] ?? ''); 
            $whatsapp = trim($_POST['whatsapp'] ?? ''); 
            $observacao = trim($_POST['observacao'] ?? '');
            $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, observacao) VALUES (?,?,?,?,?,?,?,'nao',NOW(),?,?,?)";
                $connUser->prepare($sql)->execute([$usuarioLogado, $nome, $user, $pass, $email, $venc, $pid, $conexoes, $whatsapp, $observacao]);
                
                $p = $mapa_perfis[$pid] ?? [];
                $link_cli = $base_url_painel . '/clientes';
                
                // GERAÇÃO DO LINK AUTOMÁTICO DE RENOVAÇÃO
                $r_b64 = base64_encode($usuarioLogado);
                $c_b64 = base64_encode($user);
                $link_renovacao = $base_url_painel . '/checkout.php?r=' . $r_b64 . '&c=' . $c_b64;

                $txt_zap = "";
                
                if(!empty($confZap['msg_novo'])) {
                    $template = $confZap['msg_novo'];
                    if (strpos($template, '{link_renovacao}') !== false) {
                        $txt_zap = str_replace(
                            ['{nome}', '{usuario}', '{senha}', '{vencimento}', '{dns}', '{porta}', '{link_cliente}', '{link_renovacao}'], 
                            [$nome, $user, $pass, date('d/m/Y', strtotime($venc)), ($p['url']??'---'), ($p['porta']??'---'), $link_cli, $link_renovacao], 
                            $template
                        );
                    } else {
                        $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], 
                            $template
                        ) . "\n\n💳 *Link para Renovação:* " . $link_renovacao;
                    }
                } 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']??'---')."\n\n💳 *Link para Renovação:* $link_renovacao";
                }

                if(!empty($whatsapp)) { enviarZapPainel($whatsapp, $txt_zap, $connGeral, $usuarioLogado); }
                
                // --- LÓGICA DE E-MAIL COM MENSAGEM DO BANCO DE DADOS ---
                if(!empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    $remetente_email = ''; $remetente_senha = '';
                    try {
                        $stmtConfEmail = $connUser->prepare("SELECT email, senha_app FROM circular_config WHERE usuario = ? LIMIT 1");
                        $stmtConfEmail->execute([$usuarioLogado]);
                        if ($rowE = $stmtConfEmail->fetch(PDO::FETCH_ASSOC)) {
                            $remetente_email = $rowE['email']; $remetente_senha = $rowE['senha_app'];
                        } else {
                            $stmtG = $connGeral->query("SELECT email, senha FROM smtp LIMIT 1");
                            if($rowG = $stmtG->fetch(PDO::FETCH_ASSOC)) {
                                $remetente_email = $rowG['email'] ?? ''; $remetente_senha = $rowG['senha'] ?? '';
                            }
                        }
                    } catch(Exception $e) {}

                    if(!empty($remetente_email) && !empty($remetente_senha)) {
                        $assuntoEmail = "Seu Acesso foi Liberado! - " . $nomePainel;
                        
                        $template_email_bd = $confZap['msg_email_novo'] ?? '';
                        
                        if(!empty($template_email_bd)) {
                            $txt_email = str_replace(
                                ['{nome}', '{usuario}', '{senha}', '{vencimento}', '{dns}', '{porta}', '{link_cliente}', '{link_renovacao}'], 
                                [$nome, $user, $pass, date('d/m/Y', strtotime($venc)), ($p['url']??'---'), ($p['porta']??'---'), $link_cli, $link_renovacao], 
                                $template_email_bd
                            );
                            if (strpos($template_email_bd, '{link_renovacao}') === false) {
                                $txt_email .= "<br><br><b>Link de Pagamento:</b> <a href='{$link_renovacao}'>Pagar / Renovar</a>";
                            }
                            $msgEmailHTML = "<div style='font-family: Arial, sans-serif; color: #333; max-width: 600px; margin: 0 auto;'>" . nl2br($txt_email) . "</div>";
                        } else {
                            $msgEmailHTML = "
                            <div style='font-family: Arial, sans-serif; color: #333; max-width: 600px; margin: 0 auto; border: 1px solid #ddd; padding: 20px; border-radius: 10px;'>
                                <h2 style='color: #7367f0; text-align: center;'>Acesso Criado com Sucesso!</h2>
                                <p>Olá <b>{$nome}</b>, aqui estão os dados para você acessar o nosso servidor:</p>
                                <div style='background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px;'>
                                    <p style='margin: 5px 0;'><b>Usuário:</b> {$user}</p>
                                    <p style='margin: 5px 0;'><b>Senha:</b> {$pass}</p>
                                    <p style='margin: 5px 0;'><b>Expira em:</b> " . date('d/m/Y', strtotime($venc)) . "</p>
                                    <hr style='border: 0; border-top: 1px solid #ddd; margin: 15px 0;'>
                                    <p style='margin: 5px 0;'><b>URL/DNS:</b> " . ($p['url']??'---') . "</p>
                                    <p style='margin: 5px 0;'><b>Porta:</b> " . ($p['porta']??'---') . "</p>
                                    <p style='margin: 5px 0;'><b>Link de Pagamento:</b> <a href='{$link_renovacao}'>Pagar / Renovar</a></p>
                                </div>
                                <p style='text-align: center; font-size: 0.9rem; color: #777;'>Aproveite o seu acesso!<br>Equipe {$nomePainel}</p>
                            </div>";
                        }

                        dispararEmailSMTP($email, $assuntoEmail, $msgEmailHTML, $nomePainel, $remetente_email, $remetente_senha, 'smtp.gmail.com', 465);
                    }
                }
                // --------------------------------------------------------
                
                $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'] ?? '');
            $observacao = trim($_POST['observacao'] ?? '');
            $conexoes = isset($_POST['conexao']) ? (int)$_POST['conexao'] : 1;
            
            $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=?, observacao=? WHERE id=? $filtroSeguranca";
            $connUser->prepare($sql)->execute([$_POST['nome'], $_POST['usuario'], $_POST['senha'], $email, $nova_data_edit, $_POST['perfil'], $conexoes, $whatsapp, $observacao, $id_user]);
            $msg = "Dados updated!"; $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();
                
                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 = $base_url_painel . '/clientes';
                
                $r_b64 = base64_encode($c['CadUser'] ?? $usuarioLogado);
                $c_b64 = base64_encode($c['usuario']);
                $link_renovacao = $base_url_painel . '/checkout.php?r=' . $r_b64 . '&c=' . $c_b64;

                $txt_zap = "";
                if(!empty($confZap['msg_renovacao'])) {
                    $template = $confZap['msg_renovacao'];
                    if (strpos($template, '{link_renovacao}') !== false) {
                        $txt_zap = str_replace(
                            ['{nome}', '{usuario}', '{senha}', '{vencimento}', '{dns}', '{porta}', '{link_cliente}', '{link_renovacao}'], 
                            [$c['nome'], $c['usuario'], $c['senha'], date('d/m/Y', strtotime($nova_data)), ($p['url']??'---'), ($p['porta']??'---'), $link_cli, $link_renovacao], 
                            $template
                        );
                    } else {
                        $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], 
                            $template
                        ) . "\n\n💳 *Link para Próximas Renovações:* " . $link_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))."\n\n💳 *Link de Pagamento:* $link_renovacao";
                }

                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']);
}

// --- 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'; 

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%' OR observacao 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')"; }

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'); 
        $isVenc = ($venc_ts <= time());
        $isProximoVenc = (!$isVenc && ($venc_ts - time()) <= 172800);
        
        $p_info = $mapa_perfis[$u['perfil']] ?? ['nome' => '---', 'url' => '', 'porta' => ''];
        $per_nome_low = mb_strtolower($p_info['nome']);
        $data_venc_br = date('d/m/Y', $venc_ts) . "<br><small class='text-white-50'>" . date('H:i:s', $venc_ts) . "</small>";
        $status_text = $isBloq ? 'BLOQUEADO' : ($isVenc ? 'VENCIDO' : 'ATIVO');
        
        $img_op = "<span class='text-white-50 small fw-bold'>".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_venc = "<span class='badge ".($isVenc ? 'bg-danger' : ($isProximoVenc ? 'bg-warning text-dark' : '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>";
        elseif($isProximoVenc) $badge_venc .= "<br><small class='text-warning fw-bold'>EXPIRA EM BREVE</small>";

        $btn_admin = ""; $btn_admin_card = "";
        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>"; 
            $btn_admin_card = "<div class='cs-action-item' onclick='abrirAlterarDono({$u['id']}, ".htmlspecialchars(json_encode($u['usuario']), ENT_QUOTES, 'UTF-8').", ".htmlspecialchars(json_encode($u['CadUser']), ENT_QUOTES, 'UTF-8').")'><div class='cs-icon bg-sq-gray'><i class='fas fa-exchange-alt'></i></div><span class='cs-action-text'>Revenda</span></div>";
        }

        $icon_bloq = $isBloq ? 'fa-lock-open' : 'fa-lock';
        $json_u = htmlspecialchars(json_encode($u), ENT_QUOTES, 'UTF-8');
        $json_p = htmlspecialchars(json_encode($p_info), ENT_QUOTES, 'UTF-8');
        $venc_str = date('Y-m-d', $venc_ts);
        $venc_str_full = date('d/m/Y - H:i', $venc_ts);
        $style_aviso = $isProximoVenc ? "style='background: #ffc107; color: #000; padding: 2px 6px; border-radius: 4px; display: inline-block;'" : "";

        echo "<tr>
            <td class='text-center td-checkbox'><input type='checkbox' name='ids_massa[]' value='{$u['id']}' class='form-check-input check-item' style='cursor:pointer;'></td>
            <td class='traditional-content'>
                <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 traditional-content ".($isBloq ? 'text-danger fw-bold' : 'text-info')."'>".($isBloq ? '🚫 BLOQUEADO' : htmlspecialchars($u['usuario']))."</td>
            <td class='text-center text-white-50 small traditional-content'>".htmlspecialchars($u['senha'])."</td>
            <td class='text-center text-white-50 small traditional-content'>".htmlspecialchars($u['whatsapp'] ?? '')."</td>
            <td class='text-center traditional-content'>{$img_op}</td>
            <td class='text-center traditional-content'><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 traditional-content'>{$badge_venc}</td>
            <td class='text-center small text-secondary fw-bold traditional-content'>".htmlspecialchars($u['CadUser'])."</td>
            <td class='pe-3 traditional-content'>
                <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({$json_u}, \"{$venc_str}\")' class='btn-sq bg-sq-blue' title='Editar'><i class='fas fa-pen'></i></button>
                    <button type='button' onclick='abrirVisualizar({$json_u}, {$json_p}, \"{$venc_str_full}\")' 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>
            
            <td class='card-content' colspan='10'>
                <div class='card-sigma'>
                    <div class='cs-id'>".htmlspecialchars($u['usuario'])."</div>
                    <div class='cs-nome'>".htmlspecialchars($u['nome'])."</div>
                    
                    <div class='cs-perfil'>{$img_op}</div>
                    
                    <div class='cs-user'>Conexões: ".(isset($u['conexao']) ? htmlspecialchars($u['conexao']) : '1')."</div>

                    <div class='cs-info-box'>
                        <div class='cs-info-col'>
                            <span class='cs-info-label'>Vencimento</span>
                            <span class='cs-info-val fw-bold' {$style_aviso}>{$data_venc_br}</span>
                        </div>
                        <div class='cs-info-col text-end'>
                            <span class='cs-info-label'>WhatsApp</span>
                            <span class='cs-info-val'>".(empty($u['whatsapp']) ? '---' : htmlspecialchars($u['whatsapp']))."</span>
                        </div>
                    </div>

                    <div class='cs-badges'>
                        <div class='cs-badge ".($isBloq || $isVenc ? 'vencido' : 'ativo')."'>{$status_text}</div>
                        <div class='cs-badge dono'>Dono: ".htmlspecialchars($u['CadUser'])."</div>
                    </div>

                    <button type='button' class='cs-btn-zap btn-zap-direto' data-caduser='".htmlspecialchars($u['CadUser'], ENT_QUOTES)."' data-nome='".htmlspecialchars($u['nome'] ?? '', ENT_QUOTES)."' data-usuario='".htmlspecialchars($u['usuario'], ENT_QUOTES)."' data-senha='".htmlspecialchars($u['senha'], ENT_QUOTES)."' data-venc='{$venc_str_full}' data-dns='".htmlspecialchars($p_info['url'] ?? '', ENT_QUOTES)."' data-porta='".htmlspecialchars($p_info['porta'] ?? '', ENT_QUOTES)."' data-whatsapp='".htmlspecialchars($u['whatsapp'] ?? '', ENT_QUOTES)."'>
                        <i class='fab fa-whatsapp me-2'></i> WhatsApp
                    </button>

                    <div class='cs-actions-grid'>
                        <div class='cs-action-item btn-editar' data-u='{$json_u}' data-venc='{$venc_str}'>
                            <div class='cs-icon bg-sq-blue'><i class='fas fa-pen'></i></div>
                            <span class='cs-action-text'>Editar</span>
                        </div>
                        <div class='cs-action-item' onclick='abrirRenovar({$u['id']}, ".htmlspecialchars(json_encode($u['nome']), ENT_QUOTES, 'UTF-8').")'>
                            <div class='cs-icon bg-sq-green'><i class='fas fa-sync-alt'></i></div>
                            <span class='cs-action-text'>Renovar</span>
                        </div>
                        <div class='cs-action-item btn-ver-dados' data-u='{$json_u}' data-p='{$json_p}' data-venc='{$venc_str_full}'>
                            <div class='cs-icon bg-sq-purple'><i class='fas fa-eye'></i></div>
                            <span class='cs-action-text'>Dados</span>
                        </div>
                        {$btn_admin_card}
                        <div class='cs-action-item' onclick='acaoRapidaAlternar({$u['id']}, \"{$u['bloqueado']}\")'>
                            <div class='cs-icon bg-sq-orange'><i class='fas {$icon_bloq}'></i></div>
                            <span class='cs-action-text'>Status</span>
                        </div>
                        <div class='cs-action-item' onclick='acaoRapidaExcluir({$u['id']})'>
                            <div class='cs-icon bg-sq-red'><i class='fas fa-trash'></i></div>
                            <span class='cs-action-text'>Excluir</span>
                        </div>
                    </div>
                </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>
    
    <?php include 'tema_global.php'; ?>

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

        .card-custom { background: var(--bg-card) !important; border: 1px solid var(--border-color); border-radius: 12px; }
        
        /* Ajustes dos Campos de Filtro */
        .form-control, .form-select { border-radius: 8px !important; transition: 0.2s; }
        .form-control:focus, .form-select:focus { border-color: var(--primary) !important; box-shadow: 0 0 0 0.25rem rgba(115, 103, 240, 0.25) !important; }
        .filter-label { color: #ffffff !important; font-weight: 700; text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.5px; margin-bottom: 6px; display: block; }
        .filter-small { font-size: 0.7rem; margin-top: 6px; color: #a6a6b7; }
        
        .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; }
        
        .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; }

        /* ======== SISTEMA DE VISUALIZAÇÃO DUPLA (TABELA vs CARDS) ======== */
        .modo-table .card-content { display: none !important; }
        .modo-table .traditional-content { display: table-cell; }
        .modo-table .td-checkbox { display: table-cell; }

        .modo-cards .table-video, .modo-cards .table-video tbody { 
            display: block; width: 100%; border: none; background: transparent !important;
        }
        .modo-cards .table-video thead { display: none; }
        .modo-cards .table-video tbody { 
            display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 15px; padding: 10px 0;
        }
        .modo-cards .table-video tr { 
            display: flex; flex-direction: column; width: 100%; height: 100%;
            background: transparent !important; border: none !important; padding: 0 !important; margin: 0 !important; position: relative;
        }
        .modo-cards .table-video td { display: none !important; }
        
        .modo-cards .table-video td.td-checkbox { 
            display: block !important; position: absolute; top: 15px; right: 15px; padding: 0 !important; border: none !important; z-index: 10; background: transparent !important; width: auto !important;
        }
        
        .modo-cards .table-video td.card-content { 
            display: block !important; width: 100% !important; max-width: 100% !important; padding: 0 !important; border: none !important; white-space: normal !important; background: transparent !important; 
        }

        /* ESTILIZAÇÃO DO CARD SIGMA */
        .card-sigma {
            background: #1e1e2d; border: 1px solid #2b2b40; border-radius: 12px; padding: 18px; text-align: left; position: relative; box-shadow: 0 4px 10px rgba(0,0,0,0.15); transition: transform 0.2s; height: 100%; display: flex; flex-direction: column;
        }
        .card-sigma:hover { transform: translateY(-3px); }

        .cs-id { color: #00cfe8; font-size: 0.9rem; font-weight: bold; margin-bottom: 2px; }
        .cs-nome { color: #ffffff; font-size: 1.1rem; font-weight: bold; margin-bottom: 2px; padding-right: 25px; }
        .cs-perfil { margin-bottom: 8px; font-weight: 500; }
        .cs-perfil img { height: 22px; filter: drop-shadow(0 0 2px rgba(0,0,0,0.5)); }

        .cs-user { color: #a6a6b7; font-size: 0.85rem; margin-bottom: 15px; }
        .cs-info-box { background: #151521; border: 1px solid #2b2b40; border-radius: 8px; padding: 12px; display: flex; justify-content: space-between; margin-bottom: 12px; }
        .cs-info-col { display: flex; flex-direction: column; }
        .cs-info-label { font-size: 0.65rem; color: #a6a6b7; text-transform: uppercase; font-weight: bold; margin-bottom: 4px; }
        .cs-info-val { font-size: 0.8rem; color: #d0d2d6; }
        
        .cs-badges { display: flex; gap: 8px; margin-bottom: 12px; flex-wrap: wrap; }
        .cs-badge { padding: 4px 10px; border-radius: 6px; font-size: 0.7rem; font-weight: 700; background: transparent; text-transform: uppercase; }
        .cs-badge.ativo { border: 1px solid #28c76f; color: #28c76f; }
        .cs-badge.vencido { border: 1px solid #ea5455; color: #ea5455; }
        .cs-badge.bloqueado { border: 1px solid #ff9f43; color: #ff9f43; }
        .cs-badge.dono { border: 1px solid #6c757d; color: #6c757d; text-transform: none; }

        .cs-btn-zap { display: block; width: 100%; background: #28c76f; color: #fff; text-align: center; padding: 10px; border-radius: 8px; font-weight: bold; margin-bottom: 15px; text-decoration: none; border: none; transition: 0.2s; cursor: pointer; }
        .cs-btn-zap:hover { background: #24b263; color: #fff; }
        
        .cs-actions-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(65px, 1fr)); gap: 12px; margin-top: auto; }
        .cs-action-item { display: flex; flex-direction: column; align-items: center; justify-content: flex-start; cursor: pointer; text-align: center; gap: 6px; }
        .cs-icon { width: 42px; height: 42px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 1.1rem; color: #fff; box-shadow: 0 4px 8px rgba(0,0,0,0.15); transition: transform 0.2s; }
        .cs-action-item:hover .cs-icon { transform: scale(1.05); }
        .cs-action-text { font-size: 0.7rem; color: #a6a6b7; font-weight: 500; }
    </style>
</head>
<body>

<?php include 'menu.php'; ?>

<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 fw-bold px-4 rounded-pill shadow-sm" style="letter-spacing: 0.5px;"><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; ?>

        <!-- NOVA ÁREA DE FILTRO PROFISSIONAL -->
        <div class="card card-custom mb-4 p-4 shadow-sm border-0">
            <form method="GET" id="formFiltro" class="row g-3">
                
                <!-- ROW 1 -->
                <div class="col-12 col-md-6 col-xl-3">
                    <label class="filter-label">PESQUISAR (Ao Vivo)</label>
                    <input type="text" name="busca" id="inputPesquisaLive" class="form-control bg-dark border-secondary text-white p-2" placeholder="Login, Nome ou E-mail..." value="<?= htmlspecialchars($busca) ?>">
                    <div class="filter-small"><i class="fas fa-info-circle me-1"></i> Busque pelo nome, login ou e-mail cadastrado.</div>
                </div>
                
                <div class="col-6 col-md-3 col-xl-2">
                    <label class="filter-label 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 bg-dark border-secondary text-white p-2" value="<?= htmlspecialchars($data_inicio) ?>">
                    <div class="filter-small"><i class="fas fa-info-circle me-1"></i> Data inicial de vencimento.</div>
                </div>
                
                <div class="col-6 col-md-3 col-xl-2">
                    <label class="filter-label 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 bg-dark border-secondary text-white p-2" value="<?= htmlspecialchars($data_fim) ?>">
                    <div class="filter-small"><i class="fas fa-info-circle me-1"></i> Data limite de vencimento.</div>
                </div>
                
                <?php if ($isAdmin): ?>
                <div class="col-12 col-md-6 col-xl-2">
                    <label class="filter-label">REVENDEDOR</label>
                    <select name="revendedor" id="filtroRev" class="form-select bg-dark border-secondary text-white p-2">
                        <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 class="filter-small"><i class="fas fa-info-circle me-1"></i> Filtre pelos clientes de um dono.</div>
                </div>
                <?php endif; ?>
                
                <div class="col-12 col-md-6 col-xl-2">
                    <label class="filter-label">STATUS</label>
                    <select name="status" id="filtroStatus" class="form-select bg-dark border-secondary text-white p-2">
                        <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>
                    <div class="filter-small"><i class="fas fa-info-circle me-1"></i> Situação da conexão.</div>
                </div>

                <!-- ROW 2 -->
                <div class="col-6 col-md-4 col-xl-3">
                    <label class="filter-label text-info">ORDENAR POR</label>
                    <select name="ordem" id="filtroOrdem" class="form-select bg-dark border-info text-white p-2">
                        <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>
                    <div class="filter-small"><i class="fas fa-info-circle me-1"></i> Forma de organizar a lista.</div>
                </div>
                
                <div class="col-6 col-md-4 col-xl-2">
                    <label class="filter-label">EXIBIR</label>
                    <select name="limit" id="filtroLimit" class="form-select bg-dark border-secondary text-white p-2">
                        <?php foreach([10,20,50,100,500] as $l): ?>
                            <option value="<?= $l ?>" <?= $limit == $l ? 'selected' : '' ?>><?= $l ?> linhas</option>
                        <?php endforeach; ?>
                    </select>
                    <div class="filter-small"><i class="fas fa-info-circle me-1"></i> Itens por página.</div>
                </div>

                <!-- BOTÕES -->
                <div class="col-12 col-md-12 col-xl-auto ms-xl-auto d-flex flex-column flex-md-row gap-2 mt-4 mt-xl-0" id="btnFiltrarNormal">
                    <label class="filter-label d-none d-xl-block" style="color:transparent !important;">.</label>
                    <button type="submit" class="btn btn-primary fw-bold px-4 py-2 shadow-sm w-100"><i class="fas fa-filter me-1"></i> FILTRAR</button>
                    <button type="button" class="btn btn-info fw-bold px-4 py-2 shadow-sm text-white w-100" onclick="toggleViewMode()"><i class="fas fa-th-large me-1"></i> VISUALIZAÇÃO</button>
                </div>

                <!-- AÇÕES EM MASSA (Oculto por padrão) -->
                <div class="col-12 col-xl-auto ms-xl-auto mt-4 mt-xl-0" id="divOpcoesMassa" style="display: none;">
                    <label class="filter-label text-warning d-none d-xl-block">AÇÕES EM MASSA</label>
                    <div class="dropdown h-100">
                        <button class="btn btn-warning w-100 h-100 fw-bold dropdown-toggle shadow-sm text-dark px-4" 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>
            </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 border-0">
                <div class="table-responsive modo-table" id="tableViewContainer">
                    <table class="table table-video">
                        <thead>
                            <tr>
                                <th class="text-center" style="width: 1%;"><input type="checkbox" id="checkAll" class="form-check-input bg-dark border-secondary" 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');
                                $isVenc = ($venc_ts <= time());
                                $isProximoVenc = (!$isVenc && ($venc_ts - time()) <= 172800);
                                
                                $p_info = $mapa_perfis[$u['perfil']] ?? ['nome' => '---', 'url' => '', 'porta' => ''];
                                $per_nome_low = mb_strtolower($p_info['nome']);
                                $data_venc_br = date('d/m/Y', $venc_ts) . "<br><small class='text-white-50'>" . date('H:i:s', $venc_ts) . "</small>";
                                $status_text = $isBloq ? 'BLOQUEADO' : ($isVenc ? 'VENCIDO' : 'ATIVO');
                                
                                $img_op = "<span class='text-white-50 small fw-bold'>".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_venc = "<span class='badge ".($isVenc ? 'bg-danger' : ($isProximoVenc ? 'bg-warning text-dark' : '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>";
                                elseif($isProximoVenc) $badge_venc .= "<br><small class='text-warning fw-bold'>EXPIRA EM BREVE</small>";

                                $btn_admin = ""; $btn_admin_card = "";
                                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>"; 
                                    $btn_admin_card = "<div class='cs-action-item' onclick='abrirAlterarDono({$u['id']}, ".htmlspecialchars(json_encode($u['usuario']), ENT_QUOTES, 'UTF-8').", ".htmlspecialchars(json_encode($u['CadUser']), ENT_QUOTES, 'UTF-8').")'><div class='cs-icon bg-sq-gray'><i class='fas fa-exchange-alt'></i></div><span class='cs-action-text'>Revenda</span></div>";
                                }

                                $icon_bloq = $isBloq ? 'fa-lock-open' : 'fa-lock';
                                $json_u = htmlspecialchars(json_encode($u), ENT_QUOTES, 'UTF-8');
                                $json_p = htmlspecialchars(json_encode($p_info), ENT_QUOTES, 'UTF-8');
                                $venc_str = date('Y-m-d', $venc_ts);
                                $venc_str_full = date('d/m/Y - H:i', $venc_ts);
                                $style_aviso = $isProximoVenc ? "style='background: #ffc107; color: #000; padding: 2px 6px; border-radius: 4px; display: inline-block;'" : "";
                            ?>
                            <tr>
                                <td class="text-center td-checkbox"><input type="checkbox" name="ids_massa[]" value="<?= $u['id'] ?>" class="form-check-input bg-dark border-secondary check-item" style="cursor:pointer;"></td>
                                <td class="traditional-content">
                                    <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 traditional-content <?= $isBloq ? 'text-danger fw-bold' : 'text-info' ?>"><?= $isBloq ? '🚫 BLOQUEADO' : htmlspecialchars($u['usuario']) ?></td>
                                <td class="text-center text-white-50 small traditional-content"><?= htmlspecialchars($u['senha']) ?></td>
                                <td class="text-center text-white-50 small traditional-content"><?= htmlspecialchars($u['whatsapp'] ?? '') ?></td>
                                <td class="text-center traditional-content"><?= $img_op ?></td>
                                <td class="text-center traditional-content"><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 traditional-content"><?= $badge_venc ?></td>
                                <td class="text-center small text-secondary fw-bold traditional-content"><?= htmlspecialchars($u['CadUser']) ?></td>
                                <td class="pe-3 traditional-content">
                                    <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(<?= $json_u ?>, "<?= $venc_str ?>")' class="btn-sq bg-sq-blue" title="Editar"><i class="fas fa-pen"></i></button>
                                        <button type="button" onclick='abrirVisualizar(<?= $json_u ?>, <?= $json_p ?>, "<?= $venc_str_full ?>")' 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>
                                
                                <td class="card-content" colspan="10">
                                    <div class="card-sigma">
                                        <div class="cs-id"><?= htmlspecialchars($u['usuario']) ?></div>
                                        <div class="cs-nome"><?= htmlspecialchars($u['nome']) ?></div>
                                        
                                        <div class="cs-perfil"><?= $img_op ?></div>
                                        
                                        <div class="cs-user">Conexões: <?= isset($u['conexao']) ? htmlspecialchars($u['conexao']) : '1' ?></div>

                                        <div class="cs-info-box">
                                            <div class="cs-info-col">
                                                <span class="cs-info-label">Vencimento</span>
                                                <span class="cs-info-val fw-bold" <?= $style_aviso ?>><?= $data_venc_br ?></span>
                                            </div>
                                            <div class="cs-info-col text-end">
                                                <span class="cs-info-label">WhatsApp</span>
                                                <span class="cs-info-val"><?= empty($u['whatsapp']) ? '---' : htmlspecialchars($u['whatsapp']) ?></span>
                                            </div>
                                        </div>

                                        <div class="cs-badges">
                                            <div class="cs-badge <?= ($isBloq || $isVenc) ? 'vencido' : 'ativo' ?>"><?= $status_text ?></div>
                                            <div class="cs-badge dono">Dono: <?= htmlspecialchars($u['CadUser']) ?></div>
                                        </div>

                                        <button type="button" class="cs-btn-zap btn-zap-direto" data-caduser="<?= htmlspecialchars($u['CadUser'], ENT_QUOTES) ?>" data-nome="<?= htmlspecialchars($u['nome'] ?? '', ENT_QUOTES) ?>" data-usuario="<?= htmlspecialchars($u['usuario'], ENT_QUOTES) ?>" data-senha="<?= htmlspecialchars($u['senha'], ENT_QUOTES) ?>" data-venc="<?= $venc_str_full ?>" data-dns="<?= htmlspecialchars($p_info['url'] ?? '', ENT_QUOTES) ?>" data-porta="<?= htmlspecialchars($p_info['porta'] ?? '', ENT_QUOTES) ?>" data-whatsapp="<?= htmlspecialchars($u['whatsapp'] ?? '', ENT_QUOTES) ?>">
                                            <i class='fab fa-whatsapp me-2'></i> WhatsApp
                                        </button>

                                        <div class="cs-actions-grid">
                                            <div class="cs-action-item btn-editar" data-u='<?= $json_u ?>' data-venc='<?= $venc_str ?>'>
                                                <div class="cs-icon bg-sq-blue"><i class="fas fa-pen"></i></div>
                                                <span class="cs-action-text">Editar</span>
                                            </div>
                                            <div class="cs-action-item" onclick='abrirRenovar(<?= $u['id'] ?>, <?= htmlspecialchars(json_encode($u['nome']), ENT_QUOTES, 'UTF-8') ?>)'>
                                                <div class="cs-icon bg-sq-green"><i class="fas fa-sync-alt"></i></div>
                                                <span class="cs-action-text">Renovar</span>
                                            </div>
                                            <div class="cs-action-item btn-ver-dados" data-u='<?= $json_u ?>' data-p='<?= $json_p ?>' data-venc='<?= $venc_str_full ?>'>
                                                <div class="cs-icon bg-sq-purple"><i class="fas fa-eye"></i></div>
                                                <span class="cs-action-text">Dados</span>
                                            </div>
                                            <?= $btn_admin_card ?>
                                            <div class="cs-action-item" onclick="acaoRapidaAlternar(<?= $u['id'] ?>, '<?= $u['bloqueado'] ?>')">
                                                <div class="cs-icon bg-sq-orange"><i class="fas <?= $icon_bloq ?>"></i></div>
                                                <span class="cs-action-text">Status</span>
                                            </div>
                                            <div class="cs-action-item" onclick="acaoRapidaExcluir(<?= $u['id'] ?>)">
                                                <div class="cs-icon bg-sq-red"><i class="fas fa-trash"></i></div>
                                                <span class="cs-action-text">Excluir</span>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </form>
    </div>
    <?php include 'rodape.php'; ?>
</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 bg-dark border-secondary text-white">
                    <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 bg-dark border-secondary text-white">
                        <?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">
                <input type="hidden" id="view_caduser">
                <div class="mb-2"><label class="small text-white-50">Usuário:</label><input type="text" readonly class="form-control bg-dark text-white border-secondary" id="view_user"></div>
                <div class="mb-2"><label class="small text-white-50">Senha:</label><input type="text" readonly class="form-control bg-dark text-white border-secondary" id="view_pass"></div>
                <div class="mb-2"><label class="small text-white-50">E-mail:</label><input type="text" readonly class="form-control bg-dark text-white border-secondary" id="view_email"></div>
                <div class="mb-2"><label class="small text-white-50">WhatsApp:</label><input type="text" readonly class="form-control bg-dark text-white border-secondary" 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 bg-dark border-secondary" 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 bg-dark border-secondary" id="view_url"></div>
                <div class="mb-2"><label class="small text-white-50">Porta:</label><input type="text" readonly class="form-control text-warning bg-dark border-secondary" id="view_porta"></div>
                <div class="mb-4"><label class="small text-white-50">Link de Renovação:</label><input type="text" readonly class="form-control text-success bg-dark border-secondary" id="view_link_renovacao"></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 border-secondary">
                    <h5>Novo Cliente</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">NOME</label>
                        <input type="text" name="nome" class="form-control bg-dark border-secondary text-white" 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.</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 bg-dark border-secondary text-white" placeholder="Ex: joao123" required>
                            <button class="btn btn-outline-info" type="button" onclick="gerarAleatorio('cria_user', 6, false)" title="Gerar Usuário"><i class="fas fa-random"></i></button>
                        </div>
                    </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 bg-dark border-secondary text-white" value="<?= rand(1000,9999) ?>" required>
                            <button class="btn btn-outline-info" type="button" onclick="gerarAleatorio('cria_pass', 6, true)" title="Gerar Senha"><i class="fas fa-random"></i></button>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">WHATSAPP</label>
                        <input type="text" name="whatsapp" class="form-control bg-dark border-secondary text-white" placeholder="Ex: 5511999999999">
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">E-MAIL (Opcional)</label>
                        <input type="email" name="email" class="form-control bg-dark border-secondary text-white" placeholder="cliente@email.com">
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">OBSERVAÇÃO</label>
                        <textarea name="observacao" class="form-control bg-dark border-secondary text-white" rows="2" placeholder="Anotações internas..."></textarea>
                    </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 bg-dark border-secondary text-white" value="<?= date('Y-m-d', strtotime('+30 days')) ?>">
                        </div>
                        <div class="col-6 mb-3">
                            <label class="small fw-bold">PERFIL</label>
                            <select name="perfil" class="form-select bg-dark border-secondary text-white" required>
                                <?php foreach($lista_perfis_select as $ps): ?>
                                    <option value="<?= $ps['id'] ?>"><?= $ps['nome'] ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">QTD. TELAS</label>
                        <input type="number" name="conexao" class="form-control bg-dark border-secondary text-white text-center" value="1" min="1" required>
                    </div>
                </div>
                <div class="modal-footer border-secondary">
                    <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 border-secondary">
                    <h5>Editar Cliente</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">NOME</label>
                        <input type="text" name="nome" id="edit_nome" class="form-control bg-dark border-secondary text-white">
                    </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 bg-dark border-secondary text-white">
                            <button class="btn btn-outline-info" type="button" onclick="gerarAleatorio('edit_user', 6, false)"><i class="fas fa-random"></i></button>
                        </div>
                    </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 bg-dark border-secondary text-white">
                            <button class="btn btn-outline-info" type="button" onclick="gerarAleatorio('edit_pass', 6, true)"><i class="fas fa-random"></i></button>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">WHATSAPP</label>
                        <input type="text" name="whatsapp" id="edit_whatsapp" class="form-control bg-dark border-secondary text-white">
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">E-MAIL</label>
                        <input type="email" name="email" id="edit_email" class="form-control bg-dark border-secondary text-white">
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">OBSERVAÇÃO</label>
                        <textarea name="observacao" id="edit_observacao" class="form-control bg-dark border-secondary text-white" rows="2"></textarea>
                    </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 bg-dark border-secondary text-white">
                        </div>
                        <div class="col-6 mb-3">
                            <label class="small fw-bold">PERFIL</label>
                            <select name="perfil" id="edit_perfil" class="form-select bg-dark border-secondary text-white">
                                <?php foreach($lista_perfis_select as $ps): ?>
                                    <option value="<?= $ps['id'] ?>"><?= $ps['nome'] ?></option>
                                <?php endforeach; ?>
                            </select>
                        </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 bg-dark border-secondary text-white text-center" min="1" required>
                    </div>
                </div>
                <div class="modal-footer border-secondary">
                    <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 text-info"></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 bg-dark border-secondary text-white 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 bg-dark border-secondary 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 shadow">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 border-secondary">
                    <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-info"></strong>.</p>
                    <div class="mb-3">
                        <label class="small fw-bold">NOVO REVENDEDOR</label>
                        <select name="novo_dono" id="dono_select" class="form-select bg-dark border-secondary text-white" 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>
                    </div>
                </div>
                <div class="modal-footer border-secondary">
                    <button type="submit" class="btn btn-warning w-100 fw-bold shadow text-dark">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'); }
    
    // ======== SISTEMA DE TROCA DE VISUALIZAÇÃO ========
    function toggleViewMode() {
        const wrapper = document.getElementById('tableViewContainer');
        if (wrapper.classList.contains('modo-table')) {
            wrapper.classList.remove('modo-table');
            wrapper.classList.add('modo-cards');
            localStorage.setItem('clientesViewMode', 'cards');
        } else {
            wrapper.classList.remove('modo-cards');
            wrapper.classList.add('modo-table');
            localStorage.setItem('clientesViewMode', 'table');
        }
    }

    document.addEventListener('DOMContentLoaded', () => {
        const savedMode = localStorage.getItem('clientesViewMode');
        const wrapper = document.getElementById('tableViewContainer');
        if (savedMode === 'cards') {
            wrapper.classList.remove('modo-table');
            wrapper.classList.add('modo-cards');
        }
    });
    // ==================================================

    // Ligar eventos dinâmicos usando delegação (para o JavaScript funcionar nos Cards e no Ajax)
    document.addEventListener('click', function(e) {
        if (e.target.closest('.btn-ver-dados')) {
            const btn = e.target.closest('.btn-ver-dados');
            const u = JSON.parse(btn.getAttribute('data-u'));
            const p = JSON.parse(btn.getAttribute('data-p'));
            abrirVisualizar(u, p, btn.getAttribute('data-venc'));
        }
        if (e.target.closest('.btn-editar')) {
            const btn = e.target.closest('.btn-editar');
            const u = JSON.parse(btn.getAttribute('data-u'));
            abrirEditar(u, btn.getAttribute('data-venc'));
        }
        if (e.target.closest('.btn-zap-direto')) {
            const btn = e.target.closest('.btn-zap-direto');
            enviarZapDireto(
                btn.getAttribute('data-nome'), 
                btn.getAttribute('data-usuario'), 
                btn.getAttribute('data-senha'), 
                btn.getAttribute('data-venc'), 
                btn.getAttribute('data-dns'), 
                btn.getAttribute('data-porta'), 
                btn.getAttribute('data-whatsapp'),
                btn.getAttribute('data-caduser')
            );
        }
    });

    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.classList.remove('d-flex'); 
                btnFiltrarNormal.style.display = 'none'; 
                if (countMassa) countMassa.innerText = selecionados; 
            } else { 
                divOpcoesMassa.style.display = 'none'; 
                btnFiltrarNormal.style.display = ''; 
                btnFiltrarNormal.classList.add('d-flex'); 
            }
        }
    } 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 = ''; document.getElementById('btnFiltrarNormal').classList.add('d-flex'); 
            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 obterBaseUrlJS() {
        let path = window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/'));
        return window.location.origin + path;
    }

    function gerarMensagemPronta(nome, usuario, senha, vencimento, dns, porta, caduser) {
        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}\n\n💳 *Pagamento:* {link_renovacao}") ?>;
        
        let linkRenovacao = obterBaseUrlJS() + '/checkout.php?r=' + btoa(caduser || '') + '&c=' + btoa(usuario || '');

        if (txt.indexOf('{link_renovacao}') !== -1) {
            txt = txt.replace(/{link_renovacao}/g, linkRenovacao);
        } else {
            txt += "\n\n💳 *Link para Renovação:* " + linkRenovacao;
        }

        txt = txt.replace(/{nome}/g, nome || '');
        txt = txt.replace(/{usuario}/g, usuario || '');
        txt = txt.replace(/{senha}/g, senha || '');
        txt = txt.replace(/{vencimento}/g, vencimento || '');
        txt = txt.replace(/{dns}/g, dns || '');
        txt = txt.replace(/{porta}/g, porta || '');
        txt = txt.replace(/{link_cliente}/g, obterBaseUrlJS() + '/clientes');
        return txt;
    }

    // Funcionalidade de enviar Zap diretamente do card
    function enviarZapDireto(nome, usuario, senha, vencimento, dns, porta, whatsapp, caduser) {
        const msg = gerarMensagemPronta(nome, usuario, senha, vencimento, dns, porta, caduser);
        const num = whatsapp ? whatsapp.replace(/\D/g, '') : '';
        const urlFinal = num ? "https://api.whatsapp.com/send?phone=" + num + "&text=" : "https://api.whatsapp.com/send?text=";
        window.open(urlFinal + encodeURIComponent(msg), '_blank');
    }

    function abrirVisualizar(u, p, data_br) { 
        document.getElementById('view_nome').value = u.nome || '';
        document.getElementById('view_caduser').value = u.CadUser || '';
        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 || ''; 
        
        let linkRenovacao = obterBaseUrlJS() + '/checkout.php?r=' + btoa(u.CadUser || '') + '&c=' + btoa(u.usuario || '');
        document.getElementById('view_link_renovacao').value = linkRenovacao;

        new bootstrap.Modal(document.getElementById('modalVerDados')).show(); 
    }
    
    function copiarVisualizar() { 
        const caduser = document.getElementById('view_caduser').value || '<?= $usuarioLogado ?>';
        const m = gerarMensagemPronta(
            document.getElementById('view_nome').value, 
            document.getElementById('view_user').value, 
            document.getElementById('view_pass').value, 
            document.getElementById('view_venc').value, 
            document.getElementById('view_url').value, 
            document.getElementById('view_porta').value, 
            caduser
        );
        navigator.clipboard.writeText(m).then(() => alert("Copiado com Sucesso!")); 
    }
    
    function zapVisualizar() { 
        const caduser = document.getElementById('view_caduser').value || '<?= $usuarioLogado ?>';
        const m = gerarMensagemPronta(
            document.getElementById('view_nome').value, 
            document.getElementById('view_user').value, 
            document.getElementById('view_pass').value, 
            document.getElementById('view_venc').value, 
            document.getElementById('view_url').value, 
            document.getElementById('view_porta').value, 
            caduser
        );
        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_observacao').value = u.observacao ? u.observacao : '';
        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>