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

$pdo = getConexaoAtiva(); // Banco Principal (Onde ficam os clientes)
$pdo_int = getConexaoInterna(); // Banco Local (Onde ficam as configs e os créditos do painel)

$pdo->exec("SET NAMES utf8mb4");
$pdo_int->exec("SET NAMES utf8mb4");

// ====================================================================
// INTELIGÊNCIA ARTIFICIAL: DETECTA SE É XUI ONE OU XTREAM UI
// ====================================================================
$modo_ativo = 'interno';
try {
    $modo_ativo = $pdo_int->query("SELECT modo_ativo FROM configuracoes LIMIT 1")->fetchColumn() ?: 'interno';
} catch (Exception $e) {}

$tabela_clientes = ($modo_ativo === 'xui') ? '`lines`' : '`users`';
$tabela_revendedores = ($modo_ativo === 'xui') ? '`users`' : '`reg_users`';

// --- LÓGICA DE AUTO-CORREÇÃO DO BANCO EXTERNO E INTERNO ---
try {
    // Altera o banco externo para suportar P2P
    $pdo->exec("ALTER TABLE $tabela_clientes ADD COLUMN IF NOT EXISTS `is_p2p` INT DEFAULT 0");
    $pdo->exec("ALTER TABLE $tabela_clientes ADD COLUMN IF NOT EXISTS `whatsapp` VARCHAR(255) DEFAULT NULL");
    
    // Altera o banco interno para as configs
    $pdo_int->exec("ALTER TABLE `painel_config` ADD COLUMN IF NOT EXISTS `senha_p2p` VARCHAR(255) DEFAULT '123456'");
    $pdo_int->exec("ALTER TABLE `painel_config` ADD COLUMN IF NOT EXISTS `api_p2p_url` VARCHAR(255) DEFAULT ''");
    $pdo_int->exec("ALTER TABLE `painel_config` ADD COLUMN IF NOT EXISTS `api_p2p_key` VARCHAR(255) DEFAULT ''");
    
    // Auto-correção para garantir que a coluna de permissão de teste exista
    $check_perm_teste = $pdo_int->query("SHOW COLUMNS FROM `painel_config` LIKE 'permitir_teste_revenda'");
    if (!$check_perm_teste->fetch()) {
        $pdo_int->exec("ALTER TABLE `painel_config` ADD COLUMN `permitir_teste_revenda` TINYINT(1) DEFAULT 1");
    }
} catch (Exception $e) {}

// --- BUSCA DE CONFIGURAÇÕES (NO BANCO INTERNO) ---
$nome_painel = 'TOP IPTV';
$logo_url = '';
$cor_primaria = '#007bff';
$senha_p2p_universal = '123456';
$link_loja_p2p = "https://tvsbr.top/loja"; // ALTERE AQUI O LINK DA SUA LOJA
$url_api_p2p = "";
$token_p2p = "";
$api_conf = ['api_binstream_url' => '']; 
$permitir_teste_revenda = 1; // Padrão: Liberado

try {
    $config_painel = $pdo_int->query("SELECT * FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($config_painel) {
        $nome_painel = $config_painel['nome_painel'] ?: $nome_painel;
        $logo_url = $config_painel['logo_url'] ?: $logo_url;
        $cor_primaria = $config_painel['cor_primaria'] ?: $cor_primaria;
        $senha_p2p_universal = $config_painel['senha_p2p'] ?: '123456';
        $url_api_p2p = $config_painel['api_p2p_url'] ?? '';
        $token_p2p = $config_painel['api_p2p_key'] ?? '';
        $api_conf['api_binstream_url'] = $config_painel['api_binstream_url'] ?? '';
        if (isset($config_painel['permitir_teste_revenda'])) { $permitir_teste_revenda = (int)$config_painel['permitir_teste_revenda']; }
    }
} catch (Exception $e) {}

if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }
$role = $_SESSION['user_role'] ?? 'reseller';
$my_id = $_SESSION['user_id'];
$nome_usuario = $_SESSION['username'] ?? 'Usuário';
$mensagem = "";

// AVISO DO RADAR DE ERROS DA API
$mensagem_api = "";
if (isset($_SESSION['api_err'])) {
    $mensagem_api = "<div class='alert danger'><i class='fas fa-exclamation-triangle'></i> <strong>Aviso da Integração Remota:</strong> " . htmlspecialchars($_SESSION['api_err']) . "</div>";
    unset($_SESSION['api_err']);
}

// Busca saldo no Banco Interno
try {
    $user_credits = $pdo_int->query("SELECT credits FROM reg_users WHERE id = $my_id")->fetchColumn() ?: 0;
} catch (Exception $e) { $user_credits = 0; }

// ==============================================================================
// --- INTEGRAÇÃO API P2P REMOTA ---
// ==============================================================================
function syncApiP2P($dados) {
    global $url_api_p2p, $token_p2p;
    if(empty($url_api_p2p)) return false; 
    
    $dados['token'] = $token_p2p;
    $ch = curl_init($url_api_p2p);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($dados));
    curl_setopt($ch, CURLOPT_TIMEOUT, 8); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $res = curl_exec($ch);
    
    if(curl_errno($ch)){
        $err = curl_error($ch);
        curl_close($ch);
        return json_encode(['status' => 'error', 'message' => 'CURL ERRO DE CONEXÃO: ' . $err]);
    }
    
    curl_close($ch);
    return $res;
}
// ==============================================================================

// --- LISTA DE REVENDEDORES PARA AÇÕES EM MASSA (SÓ ADMIN, DO BANCO EXTERNO) ---
$lista_revendedores = [];
if ($role === 'admin') {
    // member_group_id != 1 pega os revendedores do Xtream/XUI
    $lista_revendedores = $pdo->query("SELECT id, username FROM $tabela_revendedores WHERE member_group_id != 1 ORDER BY username ASC")->fetchAll(PDO::FETCH_ASSOC);
}

// --- LISTA DE BOUQUETS PARA EDIÇÃO DO P2P ---
$bouquets_lista = [];
try {
    $bouquets_lista = $pdo->query("SELECT id, bouquet_name FROM bouquets ORDER BY bouquet_order ASC, bouquet_name ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {}

// --- TEMPLATE EXCLUSIVO P2P ---
$template_p2p = "🚀 *DADOS DE ACESSO P2P*\n\n🔑 *Código:* #username#\n📅 *Vencimento:* #exp_date#\n\n📥 *BAIXE O APLICATIVO AQUI:*\n#link_loja#";

// --- FUNÇÃO PARA GERAR MENSAGEM P2P ---
function prepararMsgP2P($username, $password, $whatsapp, $exp_date, $titulo = "DADOS DE ACESSO P2P") {
    global $template_p2p, $link_loja_p2p;
    
    $data_formatada = $exp_date ? date('d/m/Y H:i', $exp_date) : 'Ilimitado';

    $texto = str_replace("🚀 *DADOS DE ACESSO P2P*", "🚀 *{$titulo}*", $template_p2p);
    
    $texto = str_replace(
        ['#username#', '#password#', '#exp_date#', '#link_loja#'],
        [$username, $password, $data_formatada, $link_loja_p2p],
        $texto
    );
    
    return [
        'msg' => $texto,
        'url' => "https://wa.me/".preg_replace('/\D/', '', (string)$whatsapp)."?text=".urlencode($texto)
    ];
}

// ==============================================================================
// --- PROCESSAMENTO DE AÇÕES ---
// ==============================================================================

// 0. ALTERAR SENHA UNIVERSAL P2P (SÓ ADMIN)
if (isset($_POST['action_change_p2p_pass']) && $role === 'admin') {
    $nova_senha = trim($_POST['nova_senha_p2p']);
    if (!empty($nova_senha)) {
        $pdo_int->prepare("UPDATE painel_config SET senha_p2p = ?")->execute([$nova_senha]);
        $pdo->prepare("UPDATE $tabela_clientes SET password = ? WHERE is_p2p = 1")->execute([$nova_senha]);
        $senha_p2p_universal = $nova_senha;
        $mensagem = "<div class='alert success'>Senha Universal P2P alterada com sucesso! Todos os clientes P2P foram atualizados.</div>";
    }
}

// 0.1 SALVAR CONEXÃO DA API REMOTA (SÓ ADMIN)
if (isset($_POST['action_save_api_p2p']) && $role === 'admin') {
    $nova_url = trim($_POST['api_p2p_url']);
    $novo_token = trim($_POST['api_p2p_key']);
    $pdo_int->prepare("UPDATE painel_config SET api_p2p_url = ?, api_p2p_key = ?")->execute([$nova_url, $novo_token]);
    $url_api_p2p = $nova_url;
    $token_p2p = $novo_token;
    $mensagem = "<div class='alert success'>Conexão da API P2P Remota salva com sucesso!</div>";
}

// 0.2 AÇÕES EM MASSA P2P (SÓ ADMIN)
if (isset($_POST['action_bulk_p2p']) && $role === 'admin') {
    $tipo_acao = $_POST['bulk_action_type'];
    $ids_raw = isset($_POST['bulk_ids']) ? explode(',', $_POST['bulk_ids']) : [];
    $clean_ids = []; foreach($ids_raw as $i) { if(intval($i) > 0) $clean_ids[] = intval($i); }

    if (!empty($clean_ids)) {
        $id_list = implode(',', $clean_ids);
        
        if ($tipo_acao === 'delete') {
            $names_to_del = $pdo->query("SELECT username FROM $tabela_clientes WHERE id IN ($id_list) AND is_p2p = 1")->fetchAll(PDO::FETCH_COLUMN);
            foreach($names_to_del as $nm) {
                syncApiP2P(['acao' => 'apagar', 'nome' => $nm]);
            }
            $pdo->exec("DELETE FROM $tabela_clientes WHERE id IN ($id_list) AND is_p2p = 1");
            $mensagem = "<div class='alert success'>Usuários excluídos permanentemente com sucesso!</div>";
        } elseif ($tipo_acao === 'block') {
            $pdo->exec("UPDATE $tabela_clientes SET enabled = IF(enabled=1, 0, 1) WHERE id IN ($id_list) AND is_p2p = 1");
            $mensagem = "<div class='alert success'>Status de bloqueio/desbloqueio alterado com sucesso!</div>";
        } elseif ($tipo_acao === 'renew') {
            $meses = intval($_POST['bulk_months']);
            $segundos = $meses * 30 * 86400;
            $pdo->exec("UPDATE $tabela_clientes SET exp_date = IF(exp_date > UNIX_TIMESTAMP(), exp_date + $segundos, UNIX_TIMESTAMP() + $segundos), enabled = 1 WHERE id IN ($id_list) AND is_p2p = 1");
            
            $names_to_renew = $pdo->query("SELECT username FROM $tabela_clientes WHERE id IN ($id_list) AND is_p2p = 1")->fetchAll(PDO::FETCH_COLUMN);
            foreach($names_to_renew as $nm) {
                for($i=0; $i<$meses; $i++) {
                    syncApiP2P(['acao' => 'renovar', 'nome' => $nm]);
                }
            }
            $mensagem = "<div class='alert success'>Renovação em massa aplicada com sucesso! ($meses Meses)</div>";
        } elseif ($tipo_acao === 'transfer') {
            $new_owner = intval($_POST['bulk_reseller']);
            $pdo->exec("UPDATE $tabela_clientes SET member_id = $new_owner WHERE id IN ($id_list) AND is_p2p = 1");
            $mensagem = "<div class='alert success'>Revendedor alterado com sucesso para os clientes selecionados!</div>";
        }
    }
}

// 1. CRIAR TESTE DE 4 HORAS
if (isset($_GET['create_test'])) {
    if ($role !== 'admin' && $permitir_teste_revenda == 0) {
        $mensagem = "<div class='alert danger'>A criação de testes por revendedores está desativada no momento.</div>";
    } elseif ($role !== 'admin' && $user_credits < 1) {
        $mensagem = "<div class='alert danger'>Saldo insuficiente! Você precisa de pelo menos 1 crédito na conta para gerar um Teste P2P.</div>";
    } else {
        $codigo = mt_rand(10000000, 99999999);
        $exp = time() + 14400; 
        $sql = "INSERT INTO $tabela_clientes (username, password, exp_date, enabled, member_id, is_p2p) VALUES (?, ?, ?, 1, ?, 1)";
        if($pdo->prepare($sql)->execute([$codigo, $senha_p2p_universal, $exp, $my_id])) {
            
            $res = syncApiP2P([
                'acao' => 'salvar',
                'nome' => $codigo,
                'senha' => $senha_p2p_universal,
                'tipo_conta' => 'teste',
                'bouquet_id' => 1
            ]);
            if ($res) {
                $dec = json_decode($res, true);
                if (isset($dec['status']) && $dec['status'] === 'error') {
                    $_SESSION['api_err'] = "O teste foi criado no seu painel, mas o remoto recusou: " . $dec['message'];
                } elseif (!$dec) {
                    $_SESSION['api_err'] = "URL inválida ou arquivo da API não encontrado no servidor remoto (Erro 404/500).";
                }
            }
            
            $_SESSION['comprovante'] = prepararMsgP2P($codigo, $senha_p2p_universal, '', $exp, "TESTE P2P (4 HORAS)");
            header("Location: p2p_clientes.php"); exit;
        }
    }
}

// 2. CRIAR CLIENTE (COBRA CRÉDITO)
if (isset($_POST['action_create_p2p'])) {
    $zap = $_POST['whatsapp'] ?? '';
    $meses = intval($_POST['meses'] ?? 1);
    if ($role !== 'admin' && $user_credits < $meses) {
        $mensagem = "<div class='alert danger'>Saldo insuficiente!</div>";
    } else {
        $codigo = mt_rand(10000000, 99999999);
        $exp = time() + ($meses * 30 * 86400);
        
        // Desconta saldo no banco local
        if ($role !== 'admin') $pdo_int->prepare("UPDATE reg_users SET credits = credits - ? WHERE id = ?")->execute([$meses, $my_id]);
        
        $pdo->prepare("INSERT INTO $tabela_clientes (username, password, whatsapp, exp_date, enabled, member_id, is_p2p) VALUES (?, ?, ?, ?, 1, ?, 1)")->execute([$codigo, $senha_p2p_universal, $zap, $exp, $my_id]);
        
        $res = syncApiP2P([
            'acao' => 'salvar',
            'nome' => $codigo,
            'senha' => $senha_p2p_universal,
            'whatsapp' => $zap,
            'tipo_conta' => 'oficial',
            'bouquet_id' => 1
        ]);
        if ($res) {
            $dec = json_decode($res, true);
            if (isset($dec['status']) && $dec['status'] === 'error') {
                $_SESSION['api_err'] = "O oficial foi criado no seu painel, mas o remoto recusou: " . $dec['message'];
            } elseif (!$dec) {
                $_SESSION['api_err'] = "URL inválida ou arquivo da API não encontrado no servidor remoto (Erro 404/500).";
            }
        }
        
        if($meses > 1) {
            for($i=1; $i<$meses; $i++) {
                syncApiP2P(['acao' => 'renovar', 'nome' => $codigo]);
            }
        }
        
        $_SESSION['comprovante'] = prepararMsgP2P($codigo, $senha_p2p_universal, $zap, $exp);
        header("Location: p2p_clientes.php"); exit;
    }
}

// 3. RENOVAÇÃO / TRANSFORMAR TESTE EM CLIENTE
if (isset($_POST['action_renew_p2p'])) {
    $id = intval($_POST['renew_user_id']);
    $meses = intval($_POST['renew_months']);
    
    if ($role === 'admin' || $user_credits >= $meses) {
        if ($role !== 'admin') $pdo_int->prepare("UPDATE reg_users SET credits = credits - ? WHERE id = ?")->execute([$meses, $my_id]);
        
        $segundos = $meses * 30 * 86400;
        $pdo->prepare("UPDATE $tabela_clientes SET exp_date = IF(exp_date > UNIX_TIMESTAMP(), exp_date + ?, UNIX_TIMESTAMP() + ?), enabled = 1 WHERE id = ?")->execute([$segundos, $segundos, $id]);
        $u = $pdo->query("SELECT * FROM $tabela_clientes WHERE id = $id")->fetch();
        
        for($i=0; $i<$meses; $i++) {
            $res = syncApiP2P(['acao' => 'renovar', 'nome' => $u['username']]);
            if ($res && $i===0) { 
                $dec = json_decode($res, true);
                if (isset($dec['status']) && $dec['status'] === 'error') $_SESSION['api_err'] = "A renovação local funcionou, mas a remota recusou: " . $dec['message'];
            }
        }
        
        $_SESSION['comprovante'] = prepararMsgP2P($u['username'], $senha_p2p_universal, $u['whatsapp'], $u['exp_date'], "P2P RENOVADO");
        header("Location: p2p_clientes.php"); exit;
    } else {
        $mensagem = "<div class='alert danger'>Saldo insuficiente para renovar.</div>";
    }
}

// 4. EDITAR CLIENTE P2P (BOUQUET E WHATSAPP)
if (isset($_POST['action_edit_p2p'])) {
    $id = intval($_POST['edit_user_id']);
    $whatsapp = trim($_POST['whatsapp']);
    $bouquet_val = $_POST['bouquet'];
    
    $bouquet_json = '[]';
    if (!empty($bouquet_val)) {
        // Se for XUI ONE salva como [1], se for Xtream salva como ["1"]
        $bouquet_json = ($modo_ativo === 'xui') ? json_encode([(int)$bouquet_val]) : json_encode([(string)$bouquet_val]);
    }
    
    $stmt_chk = $pdo->prepare("SELECT member_id FROM $tabela_clientes WHERE id = ? AND is_p2p = 1");
    $stmt_chk->execute([$id]);
    $dono = $stmt_chk->fetchColumn();
    
    if ($role === 'admin' || $dono == $my_id) {
        $pdo->prepare("UPDATE $tabela_clientes SET whatsapp = ?, bouquet = ? WHERE id = ?")->execute([$whatsapp, $bouquet_json, $id]);
        
        $u_edit = $pdo->query("SELECT username, exp_date FROM $tabela_clientes WHERE id = $id")->fetch();
        $res = syncApiP2P([
            'acao' => 'editar',
            'nome_antigo' => $u_edit['username'],
            'nome' => $u_edit['username'],
            'whatsapp' => $whatsapp,
            'vencimento' => date('Y-m-d H:i:s', $u_edit['exp_date']),
            'bouquet_id' => $bouquet_val
        ]);
        
        if ($res) {
            $dec = json_decode($res, true);
            if (isset($dec['status']) && $dec['status'] === 'error') {
                $_SESSION['api_err'] = "A edição local funcionou, mas a remota recusou: " . $dec['message'];
            }
        }

        $mensagem = "<div class='alert success'>Cliente P2P editado com sucesso!</div>";
    } else {
        $mensagem = "<div class='alert danger'>Acesso negado para editar este cliente.</div>";
    }
}

if (isset($_GET['block'])) { $pdo->prepare("UPDATE $tabela_clientes SET enabled = IF(enabled=1, 0, 1) WHERE id = ?")->execute([$_GET['block']]); header("Location: p2p_clientes.php"); exit; }

// 5. APAGAR CLIENTE INDIVIDUAL
if (isset($_GET['delete'])) { 
    $u_del = $pdo->query("SELECT username FROM $tabela_clientes WHERE id = " . intval($_GET['delete']))->fetchColumn();
    if($u_del) syncApiP2P(['acao' => 'apagar', 'nome' => $u_del]); // API APAGAR
    
    $pdo->prepare("DELETE FROM $tabela_clientes WHERE id = ?")->execute([$_GET['delete']]); 
    header("Location: p2p_clientes.php"); exit; 
}

$search = $_GET['search'] ?? '';
$query = "SELECT u.*, r.username AS reseller_name FROM $tabela_clientes u LEFT JOIN $tabela_revendedores r ON u.member_id = r.id WHERE u.is_p2p = 1 ";
if ($role !== 'admin') $query .= "AND u.member_id = $my_id ";
if (!empty($search)) $query .= "AND u.username LIKE '%$search%' ";
$query .= "ORDER BY u.id DESC LIMIT 50";
$usuarios_p2p = $pdo->query($query)->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <link rel="stylesheet" href="tema.css">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>P2P - <?php echo htmlspecialchars($nome_painel); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        :root { --bg-dark: #121519; --bg-sidebar: #1e2227; --bg-card: #272c33; --text-main: #d1d5da; --text-muted: #8a94a1; --accent: <?php echo $cor_primaria; ?>; --border-color: #3a4149; --success: #28a745; --danger: #dc3545; --warning: #f39c12; --info: #17a2b8; }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background-color: var(--bg-dark); color: var(--text-main); display: flex; height: 100vh; overflow: hidden; }
        
        .sidebar { width: 260px; background-color: var(--bg-sidebar); border-right: 1px solid var(--border-color); display: flex; flex-direction: column; transition: 0.3s; z-index: 1001; flex-shrink: 0; }
        .sidebar-header { padding: 25px 20px; text-align: center; font-size: 22px; font-weight: bold; color: white; border-bottom: 1px solid var(--border-color); }
        .sidebar-logo { max-width: 180px; max-height: 55px; object-fit: contain; }
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .user-info .badge { background: rgba(255, 255, 255, 0.05); color: var(--accent); padding: 4px 10px; border-radius: 4px; font-size: 11px; text-transform: uppercase; font-weight: bold; margin-top: 5px; display: inline-block; }
        .credits-badge { display: block; margin-top: 10px; color: var(--success); font-weight: bold; font-size: 13px; }
        
        .menu-list { list-style: none; padding: 0; margin: 0; overflow-y: auto; flex: 1; }
        .menu-item { padding: 14px 20px; color: var(--text-main); text-decoration: none; display: flex; align-items: center; transition: 0.2s; border-left: 3px solid transparent; font-size: 14px; cursor: pointer; }
        .menu-item i:first-child { margin-right: 12px; width: 20px; text-align: center; color: var(--text-muted); }
        .menu-item:hover, .menu-item.active { background-color: #2c3138; color: white; border-left-color: var(--accent); }
        .menu-item.active i:first-child { color: var(--accent); }
        
        .submenu { display: none; background: #16191d; list-style: none; padding: 0; margin: 0; }
        .submenu .menu-item { padding-left: 52px; font-size: 13px; border-left: none; }
        .arrow-icon { margin-left: auto; transition: 0.3s; font-size: 11px; }
        .rotate { transform: rotate(180deg); }
        .menu-category { padding: 20px 20px 8px; font-size: 10px; text-transform: uppercase; color: var(--text-muted); font-weight: bold; letter-spacing: 1px; }
        .logout-btn { padding: 15px; background-color: #dc3545; color: white; text-align: center; text-decoration: none; font-weight: bold; margin-top: auto; }

        .main-content { flex: 1; display: flex; flex-direction: column; overflow-y: auto; width: 100%; position: relative; }
        .topbar { display: flex; justify-content: space-between; align-items: center; padding: 15px 30px; background-color: var(--bg-sidebar); border-bottom: 1px solid var(--border-color); }
        .menu-toggle { display: none; background: none; border: none; color: white; font-size: 22px; cursor: pointer; padding: 5px; }
        .mode-badge { padding: 6px 15px; background: rgba(40, 167, 69, 0.15); color: var(--success); border-radius: 20px; font-size: 12px; font-weight: bold; border: 1px solid var(--success); white-space: nowrap; }
        
        .content-area { padding: 30px; flex: 1; }
        
        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-weight: bold; }
        .alert.success { background: rgba(40, 167, 69, 0.1); border: 1px solid var(--success); color: var(--success); }
        .alert.danger { background: rgba(220, 53, 69, 0.1); border: 1px solid var(--danger); color: var(--danger); }

        .admin-box { background: rgba(243, 156, 18, 0.1); border: 1px dashed var(--warning); padding: 20px; border-radius: 10px; margin-bottom: 25px; display: flex; flex-wrap: wrap; gap: 20px; align-items: center; }
        .btn-filter { background: var(--accent); color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; font-weight: bold; }
        
        .card-table { background: var(--bg-card); border-radius: 10px; border: 1px solid var(--border-color); overflow-x: auto; }
        table { width: 100%; border-collapse: collapse; min-width: 700px; }
        th { background: #16191d; padding: 12px 15px; text-align: left; color: var(--text-muted); font-size: 11px; text-transform: uppercase; }
        td { padding: 12px 15px; border-bottom: 1px solid var(--border-color); font-size: 14px; }
        .badge { padding: 3px 8px; border-radius: 4px; font-size: 10px; font-weight: bold; text-transform: uppercase; }
        .bg-success { background: rgba(46, 204, 113, 0.2); color: #2ecc71; }
        .bg-danger { background: rgba(231, 76, 60, 0.2); color: #e74c3c; }
        
        .btn-action { width: 32px; height: 32px; border-radius: 4px; border: none; cursor: pointer; color: white; display: inline-flex; align-items: center; justify-content: center; text-decoration: none; margin-right: 2px; }
        
        .comprovante-box { background: rgba(40, 167, 69, 0.15); border: 1px solid var(--success); padding: 15px; border-radius: 10px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; }
        
        .modal { display: none; position: fixed; z-index: 2000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.85); align-items: center; justify-content: center; }
        .modal-content { background: var(--bg-card); width: 90%; max-width: 400px; padding: 25px; border-radius: 12px; border: 1px solid var(--border-color); position: relative; }
        .form-group-modal { margin-bottom: 15px; }
        .form-group-modal label { display: block; margin-bottom: 5px; font-size: 12px; color: var(--text-muted); }
        .form-group-modal input, .form-group-modal select { width: 100%; padding: 12px; background: #121519; border: 1px solid var(--border-color); color: white; border-radius: 6px; box-sizing: border-box; }
        .btn-save-modal { width: 100%; padding: 12px; background: var(--accent); border: none; color: white; border-radius: 6px; font-weight: bold; cursor: pointer; margin-top: 5px; }
        
        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; }

        @media (max-width: 768px) {
            .menu-toggle { display: block; }
            .sidebar { position: fixed; left: -260px; height: 100%; box-shadow: 10px 0 20px rgba(0,0,0,0.5); }
            .sidebar.active { left: 0; }
            .sidebar-overlay.active { display: block; }
            .topbar { padding: 15px 20px; flex-wrap: nowrap; }
            .topbar h2 { font-size: 15px !important; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 50%; }
            .topbar-right { margin-left: auto; padding-left: 5px; }
            .mode-badge { font-size: 10px; padding: 5px 10px; }
            .content-area { padding: 15px; }
            .admin-box { flex-direction: column; align-items: flex-start; }
        }
    </style>
</head>
<body>

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

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

    <div class="main-content">
        <header class="topbar">
            <div style="display:flex; align-items:center;">
                <button class="menu-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
                <h2 style="margin:0; font-size: 18px; color:white; margin-left:10px;">Clientes P2P</h2>
            </div>
            <div class="topbar-right">
                <span class="mode-badge"><i class="fas fa-tv"></i> MODO: <?php echo strtoupper($modo_ativo); ?></span>
            </div>
        </header>

        <div class="content-area">
            <?php echo $mensagem_api; ?>
            <?php echo $mensagem; ?>

            <?php if($role === 'admin'): ?>
            <div class="admin-box">
                <div style="flex:1; min-width:300px;">
                    <h4 style="margin: 0 0 5px 0; color: var(--warning);"><i class="fas fa-key"></i> Senha Universal P2P</h4>
                    <p style="margin: 0; font-size: 12px; color: var(--text-muted);">Esta senha oculta é usada para autenticar todos os códigos P2P no aplicativo.</p>
                    <form method="POST" style="display: flex; gap: 10px; margin-top: 10px;">
                        <input type="hidden" name="action_change_p2p_pass" value="1">
                        <input type="text" name="nova_senha_p2p" value="<?php echo htmlspecialchars($senha_p2p_universal); ?>" class="form-control" style="width: 150px; padding: 10px; background: #16191d; border: 1px solid var(--border-color); color: white; border-radius: 5px;" required>
                        <button type="submit" class="btn-filter" style="background: var(--warning); color: #000;">Alterar</button>
                    </form>
                </div>
                
                <div style="flex:1; min-width:300px;">
                    <h4 style="margin: 0 0 5px 0; color: var(--info);"><i class="fas fa-network-wired"></i> Conexão com Painel Remoto P2P</h4>
                    <p style="margin: 0; font-size: 12px; color: var(--text-muted); margin-bottom:10px;">Integre os clientes automaticamente em outro servidor P2P.</p>
                    <button type="button" class="btn-filter" style="background: var(--info);" onclick="openModal('modalApiP2P')">
                        <i class="fas fa-link"></i> Configurar API
                    </button>
                </div>
            </div>
            
            <div id="bulkBarP2P" style="display:none; background: rgba(30, 34, 39, 0.95); padding: 15px 20px; border-radius: 10px; border: 1px dashed var(--accent); margin-bottom: 20px; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 10px;">
                <span style="color: white; font-weight: bold; font-size:14px;"><span id="countP2P" style="color:var(--accent); font-size: 16px;">0</span> Selecionados</span>
                <button type="button" class="btn-filter" style="background:var(--accent);" onclick="openBulkModalP2P()"><i class="fas fa-cogs"></i> OPÇÕES EM MASSA</button>
            </div>
            <?php endif; ?>

            <?php if(isset($_SESSION['comprovante'])): ?>
            <div class="comprovante-box">
                <div><span style="color:var(--success); font-weight:bold;"><i class="fas fa-check-circle"></i> Ação Concluída!</span></div>
                <div>
                    <a href="<?php echo $_SESSION['comprovante']['url']; ?>" target="_blank" onclick="window.location.href='p2p_clientes.php'" class="btn-filter" style="background:#25d366; text-decoration:none; display:inline-block;"><i class="fab fa-whatsapp"></i> ENVIAR</a>
                    <button onclick="copyToClipboard('<?php echo str_replace("\n", "\\n", $_SESSION['comprovante']['msg']); ?>')" class="btn-filter" style="margin-left:5px;">COPIAR</button>
                    <a href="p2p_clientes.php" style="margin-left:10px; color:white; text-decoration:none;"><i class="fas fa-times"></i></a>
                </div>
            </div>
            <?php unset($_SESSION['comprovante']); endif; ?>

            <div style="display:flex; justify-content:space-between; margin-bottom:20px; flex-wrap:wrap; gap:10px;">
                <div style="display:flex; gap:5px;">
                    <button class="btn-filter" onclick="openModal('modalAdd')">+ GERAR CÓDIGO</button>
                    <?php if($role === 'admin' || $permitir_teste_revenda == 1): ?>
                    <a href="?create_test=1" class="btn-filter" style="background:var(--warning); color:black; text-decoration:none; display:flex; align-items:center;">+ TESTE (4H)</a>
                    <?php endif; ?>
                </div>
                <form method="GET"><input type="text" name="search" placeholder="Buscar código..." style="padding:10px; background:#1e2227; border:1px solid #3a4149; color:white; border-radius:5px;"></form>
            </div>

            <div class="card-table">
                <table>
                    <thead>
                        <tr>
                            <?php if($role === 'admin'): ?>
                            <th style="width: 30px; text-align: center;"><input type="checkbox" id="selectAllP2P" onclick="toggleAllP2P(this)" style="cursor:pointer; width:16px; height:16px; accent-color: var(--accent);"></th>
                            <?php endif; ?>
                            <th>Código</th><th>Criado por</th><th>Vencimento</th><th>Status</th><th style="text-align:right;">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($usuarios_p2p as $u): 
                            $vencido = ($u['exp_date'] < time());
                            $is_teste = (($u['exp_date'] - time()) < 86400 && ($u['exp_date'] - time()) > 0);
                        ?>
                        <tr>
                            <?php if($role === 'admin'): ?>
                            <td style="text-align: center;">
                                <input type="checkbox" class="p2p-checkbox" value="<?php echo $u['id']; ?>" onchange="toggleBulkBarP2P()" style="cursor:pointer; width:16px; height:16px; accent-color: var(--accent);">
                            </td>
                            <?php endif; ?>
                            <td>
                                <strong style="font-size:16px; color:white; letter-spacing:1px;"><?php echo $u['username']; ?></strong>
                                <?php if($is_teste): ?><br><span style="font-size:10px; color:var(--warning); font-weight:bold;">[TESTE 4H]</span><?php endif; ?>
                            </td>
                            <td><span class="badge" style="background: rgba(0, 123, 255, 0.1); color: var(--accent);"><?php echo htmlspecialchars($u['reseller_name'] ?? 'Admin'); ?></span></td>
                            <td><?php echo date('d/m/Y H:i', $u['exp_date']); ?></td>
                            <td><?php if($u['enabled']==0) echo "<span class='badge' style='background:#000'>Bloqueado</span>"; elseif($vencido) echo "<span class='badge bg-danger'>Vencido</span>"; else echo "<span class='badge bg-success'>Ativo</span>"; ?></td>
                            <td style="text-align:right;">
                                <button class="btn-action" style="background:#007bff;" onclick='viewP2P(<?php echo json_encode($u); ?>)' title="Ver Dados"><i class="fas fa-eye"></i></button>
                                <button class="btn-action" style="background:#6c757d;" onclick='openEditP2P(<?php echo json_encode($u); ?>)' title="Editar Bouquet/WhatsApp"><i class="fas fa-edit"></i></button>
                                <button class="btn-action" style="background:var(--success);" onclick='openRenew(<?php echo json_encode($u); ?>)' title="Renovar/Ativar"><i class="fas fa-sync-alt"></i></button>
                                <a href="?block=<?php echo $u['id']; ?>" class="btn-action" style="background:var(--warning); color:black;"><i class="fas <?php echo $u['enabled']?'fa-lock':'fa-lock-open'; ?>"></i></a>
                                <a href="?delete=<?php echo $u['id']; ?>" class="btn-action" style="background:var(--danger);" onclick="return confirm('Excluir permanentemente?')"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                        <?php endforeach; if(empty($usuarios_p2p)) echo "<tr><td colspan='".($role === 'admin' ? '6' : '5')."' style='text-align:center; padding:20px; color:var(--text-muted)'>Nenhum código P2P gerado.</td></tr>"; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php include 'rodape.php'; ?>
    </div>

    <?php if($role === 'admin'): ?>
    <div id="modalApiP2P" class="modal" style="display:none;"><div class="modal-content">
        <h3 style="margin-top:0;"><i class="fas fa-link" style="color:var(--info);"></i> Conexão P2P Remota</h3>
        <p style="font-size:13px; color:var(--text-muted); margin-top:-5px;">Configure a comunicação automática com seu segundo servidor P2P.</p>
        <form method="POST">
            <input type="hidden" name="action_save_api_p2p" value="1">
            <div class="form-group-modal">
                <label>URL da API Remota (Deixe em branco para desativar)</label>
                <input type="text" name="api_p2p_url" value="<?php echo htmlspecialchars($url_api_p2p); ?>" placeholder="Ex: http://123.45.67.89/api_p2p.php">
            </div>
            <div class="form-group-modal">
                <label>Token Secreto de Segurança</label>
                <input type="text" name="api_p2p_key" value="<?php echo htmlspecialchars($token_p2p); ?>" placeholder="O mesmo token configurado no outro painel">
            </div>
            <button type="submit" class="btn-save-modal" style="background:var(--info);">SALVAR CONEXÃO</button>
            <button type="button" onclick="closeModal('modalApiP2P')" style="width:100%; background:none; border:none; color:gray; margin-top:10px; cursor:pointer;">Cancelar</button>
        </form>
    </div></div>
    <?php endif; ?>

    <div id="modalEditP2P" class="modal" style="display:none;"><div class="modal-content">
        <h3 style="margin-top:0;"><i class="fas fa-edit" style="color:var(--accent);"></i> Editar Cliente P2P</h3>
        <p style="font-size:13px; color:var(--text-muted); margin-top:-5px;">Código: <strong id="edit_code" style="color:white;"></strong></p>
        <form method="POST">
            <input type="hidden" name="action_edit_p2p" value="1">
            <input type="hidden" name="edit_user_id" id="edit_id">
            
            <div class="form-group-modal">
                <label>Bouquet (Pacote)</label>
                <select name="bouquet" id="edit_bouquet">
                    <option value="">-- Sem Bouquet (Acesso Completo) --</option>
                    <?php foreach($bouquets_lista as $b): ?>
                        <option value="<?php echo $b['id']; ?>"><?php echo htmlspecialchars($b['bouquet_name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group-modal">
                <label>WhatsApp (Opcional)</label>
                <input type="text" name="whatsapp" id="edit_whatsapp" placeholder="Ex: 5511...">
            </div>

            <button type="submit" class="btn-save-modal">SALVAR ALTERAÇÕES</button>
            <button type="button" onclick="closeModal('modalEditP2P')" style="width:100%; background:none; border:none; color:gray; margin-top:10px; cursor:pointer;">Cancelar</button>
        </form>
    </div></div>

    <?php if($role === 'admin'): ?>
    <div id="modalBulkP2P" class="modal" style="display:none;"><div class="modal-content">
        <h3 style="margin-top:0;"><i class="fas fa-layer-group" style="color:var(--accent);"></i> Ações em Massa</h3>
        <form method="POST">
            <input type="hidden" name="action_bulk_p2p" value="1">
            <input type="hidden" name="bulk_ids" id="bulk_ids_input">
            
            <div class="form-group-modal">
                <label>Selecione a Ação</label>
                <select name="bulk_action_type" id="bulk_action_type" onchange="changeBulkAction(this.value)" required>
                    <option value="">-- Escolha --</option>
                    <option value="renew">Renovar Vencimento</option>
                    <option value="block">Bloquear / Desbloquear</option>
                    <option value="transfer">Mudar Revendedor</option>
                    <option value="delete">Apagar Permanentemente</option>
                </select>
            </div>

            <div class="form-group-modal" id="bulk_renew_div" style="display:none;">
                <label>Adicionar Meses</label>
                <input type="number" name="bulk_months" value="1" min="1">
            </div>

            <div class="form-group-modal" id="bulk_transfer_div" style="display:none;">
                <label>Selecione o Novo Revendedor</label>
                <select name="bulk_reseller">
                    <?php foreach($lista_revendedores as $rev): ?>
                        <option value="<?php echo $rev['id']; ?>"><?php echo htmlspecialchars($rev['username']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <button type="submit" class="btn-save-modal" onclick="return confirm('Deseja aplicar esta ação para todos os clientes selecionados?')">APLICAR AÇÃO</button>
            <button type="button" onclick="closeModal('modalBulkP2P')" style="width:100%; background:none; border:none; color:gray; margin-top:10px; cursor:pointer;">Cancelar</button>
        </form>
    </div></div>
    <?php endif; ?>

    <div id="modalAdd" class="modal" style="display:none;"><div class="modal-content">
        <h3 style="margin-top:0;"><i class="fas fa-qrcode" style="color:var(--accent);"></i> Gerar Código P2P</h3>
        <form method="POST">
            <input type="hidden" name="action_create_p2p" value="1">
            <div class="form-group-modal">
                <label>Meses</label>
                <select name="meses"><option value="1">1 Mês (1 crédito)</option><option value="3">3 Meses (3 créditos)</option><option value="6">6 Meses (6 créditos)</option><option value="12">1 Ano (12 créditos)</option></select>
            </div>
            <div class="form-group-modal"><label>WhatsApp (Opcional)</label><input type="text" name="whatsapp" placeholder="5511..."></div>
            <button type="submit" class="btn-save-modal">GERAR AGORA</button>
            <button type="button" onclick="closeModal('modalAdd')" style="width:100%; background:none; border:none; color:gray; margin-top:10px; cursor:pointer;">Cancelar</button>
        </form>
    </div></div>

    <div id="modalRenew" class="modal" style="display:none;"><div class="modal-content">
        <h3 style="margin-top:0;"><i class="fas fa-sync-alt" style="color:var(--success);"></i> Renovar P2P</h3>
        <p style="font-size:13px; color:var(--text-muted); margin-top:-5px;">Código: <strong id="renew_code" style="color:white;"></strong></p>
        <form method="POST">
            <input type="hidden" name="action_renew_p2p" value="1">
            <input type="hidden" name="renew_user_id" id="renew_id">
            <div class="form-group-modal"><label>Adicionar meses</label><input type="number" name="renew_months" value="1" min="1" style="font-size:18px; text-align:center; font-weight:bold;"></div>
            <button type="submit" class="btn-save-modal" style="background:var(--success);">CONFIRMAR RENOVAÇÃO</button>
            <button type="button" onclick="closeModal('modalRenew')" style="width:100%; background:none; border:none; color:gray; margin-top:10px; cursor:pointer;">Cancelar</button>
        </form>
    </div></div>

    <div id="modalView" class="modal" style="display:none;"><div class="modal-content">
        <h3 style="margin-top:0;">Dados de Acesso</h3>
        <textarea id="view_text" rows="10" readonly style="width:100%; background:#121519; color:white; border:1px solid var(--border-color); padding:10px; border-radius:5px; resize:none; font-size:12px; margin-bottom:10px;"></textarea>
        <button onclick="copyView()" class="btn-save-modal" style="background:#007bff; margin-bottom:10px;">COPIAR DADOS</button>
        <a id="view_zap" href="#" target="_blank" class="btn-save-modal" style="background:#25d366; display:block; text-align:center; text-decoration:none; box-sizing:border-box;">ENVIAR WHATSAPP</a>
        <button type="button" onclick="closeModal('modalView')" style="width:100%; background:none; border:none; color:gray; margin-top:10px; cursor:pointer;">Fechar</button>
    </div></div>

    <script>
        const lojaLink = "<?php echo $link_loja_p2p; ?>";
        const rawTemplateP2P = <?php echo json_encode($template_p2p); ?>;

        function toggleMenu() { 
            document.getElementById('sidebar').classList.toggle('active'); 
            document.getElementById('overlay').classList.toggle('active'); 
        }

        function toggleSubmenu(id) {
            const sub = document.getElementById(id);
            const arrow = document.getElementById('arrow-' + id);
            if (sub.style.display === "block") { sub.style.display = "none"; if(arrow) arrow.classList.remove('rotate'); } 
            else { sub.style.display = "block"; if(arrow) arrow.classList.add('rotate'); }
        }

        function openModal(id) { document.getElementById(id).style.display = 'flex'; }
        function closeModal(id) { document.getElementById(id).style.display = 'none'; }

        // --- SCRIPTS DE AÇÕES EM MASSA E EDIÇÃO ---
        function openEditP2P(u) {
            document.getElementById('edit_id').value = u.id;
            document.getElementById('edit_code').innerText = u.username;
            document.getElementById('edit_whatsapp').value = u.whatsapp || '';
            
            // Tratamento do Bouquet (que vem em JSON do banco)
            let bq_val = '';
            try {
                if (u.bouquet && u.bouquet !== 'null' && u.bouquet !== '[]') {
                    let parsed = JSON.parse(u.bouquet);
                    if (Array.isArray(parsed) && parsed.length > 0) {
                        bq_val = parsed[0];
                    }
                }
            } catch(e) {}
            document.getElementById('edit_bouquet').value = bq_val;
            
            openModal('modalEditP2P');
        }

        <?php if($role === 'admin'): ?>
        function toggleAllP2P(source) {
            const checkboxes = document.querySelectorAll('.p2p-checkbox');
            checkboxes.forEach(chk => chk.checked = source.checked);
            toggleBulkBarP2P();
        }

        function toggleBulkBarP2P() {
            const checkboxes = document.querySelectorAll('.p2p-checkbox:checked');
            const bar = document.getElementById('bulkBarP2P');
            const countSpan = document.getElementById('countP2P');
            if (bar && countSpan) {
                if (checkboxes.length > 0) {
                    countSpan.innerText = checkboxes.length;
                    bar.style.display = 'flex';
                } else {
                    bar.style.display = 'none';
                    const selectAll = document.getElementById('selectAllP2P');
                    if (selectAll) selectAll.checked = false;
                }
            }
        }

        function openBulkModalP2P() {
            const checkboxes = document.querySelectorAll('.p2p-checkbox:checked');
            let ids = [];
            checkboxes.forEach(chk => ids.push(chk.value));
            document.getElementById('bulk_ids_input').value = ids.join(',');
            
            document.getElementById('bulk_action_type').value = "";
            changeBulkAction("");
            openModal('modalBulkP2P');
        }

        function changeBulkAction(val) {
            document.getElementById('bulk_renew_div').style.display = (val === 'renew') ? 'block' : 'none';
            document.getElementById('bulk_transfer_div').style.display = (val === 'transfer') ? 'block' : 'none';
        }
        <?php endif; ?>

        // APLICA O TEMPLATE HARDCODED P2P NO OLHO
        function viewP2P(u) {
            const date = u.exp_date ? new Date(u.exp_date * 1000).toLocaleString('pt-BR', {day:'2-digit', month:'2-digit', year:'numeric', hour:'2-digit', minute:'2-digit'}) : 'Ilimitado';
            
            let text = rawTemplateP2P;
            text = text.replace(/#username#/g, u.username)
                       .replace(/#password#/g, u.password)
                       .replace(/#exp_date#/g, date)
                       .replace(/#link_loja#/g, lojaLink);
            
            // Se for teste, muda o título
            if ((u.exp_date - (Date.now()/1000)) < 86400 && (u.exp_date - (Date.now()/1000)) > 0) {
                text = text.replace("🚀 *DADOS DE ACESSO P2P*", "🧪 *TESTE P2P (4 HORAS)*");
            }
            
            document.getElementById('view_text').value = text;
            
            const zap = (u.whatsapp || "").replace(/\D/g, '');
            document.getElementById('view_zap').href = `https://wa.me/${zap}?text=${encodeURIComponent(text)}`;
            openModal('modalView');
        }

        function openRenew(u) {
            document.getElementById('renew_id').value = u.id;
            document.getElementById('renew_code').innerText = u.username;
            openModal('modalRenew');
        }

        function copyView() {
            const area = document.getElementById('view_text');
            area.select(); document.execCommand('copy');
            Swal.fire({icon:'success', title:'Copiado!', background:'#272c33', color:'#fff'});
        }

        function copyToClipboard(t) {
            const el = document.createElement('textarea'); el.value = t.replace(/\\n/g, '\n'); document.body.appendChild(el);
            el.select(); document.execCommand('copy'); document.body.removeChild(el);
            Swal.fire({icon:'success', title:'Copiado!', background:'#272c33', color:'#fff'});
        }
    </script>
    <script src="tema.js"></script>
</body>
</html>
