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

$pdo = getConexaoAtiva(); // Banco Principal
$pdo_int = getConexaoInterna(); // Banco Local (Onde ficam os Web Players)

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

// --- PROTEÇÃO GERAL (Admin e Revenda) ---
if (!isset($_SESSION['user_id'])) {
    die("Acesso negado. Por favor, faça login no painel.");
}

$id_usuario = $_SESSION['user_id'];
$nome_usuario = $_SESSION['username'] ?? 'Usuário';
$role = $_SESSION['user_role'] ?? 'revenda';
$is_admin = ($role === 'admin'); 

// ====================================================================
// 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_revendedores = ($modo_ativo === 'xui') ? '`users`' : '`reg_users`';

// --- INÍCIO: BUSCA DE PERSONALIZAÇÃO DINÂMICA (No Banco Interno) ---
$nome_painel = 'TOP IPTV';
$logo_url = '';
$cor_primaria = '#007bff';

try {
    $tabela_existe = $pdo_int->query("SHOW TABLES LIKE 'painel_config'")->rowCount() > 0;
    if ($tabela_existe) {
        $config_painel = $pdo_int->query("SELECT * FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        if ($config_painel) {
            $nome_painel = !empty($config_painel['nome_painel']) ? $config_painel['nome_painel'] : $nome_painel;
            $logo_url = !empty($config_painel['logo_url']) ? $config_painel['logo_url'] : $logo_url;
            $cor_primaria = !empty($config_painel['cor_primaria']) ? $config_painel['cor_primaria'] : $cor_primaria;
        }
    }
} catch (Exception $e) { }

// Busca saldo
try {
    $user_credits = $pdo->query("SELECT credits FROM $tabela_revendedores WHERE id = " . intval($id_usuario))->fetchColumn() ?: 0;
} catch (Exception $e) { $user_credits = 0; }

// =========================================================================
// BANCO DE DADOS: TABELA DE PLAYERS E TABELA DE LIMITES (NO BANCO INTERNO)
// =========================================================================
try {
    // Tabela dos Players
    $pdo_int->exec("CREATE TABLE IF NOT EXISTS `revenda_players` (
        `id` int(11) AUTO_INCREMENT PRIMARY KEY,
        `member_id` int(11) NOT NULL,
        `slug` varchar(50) NOT NULL UNIQUE,
        `nome_marca` varchar(100) DEFAULT 'Meu Player',
        `logo_url` varchar(255) DEFAULT '',
        `cor_fundo` varchar(20) DEFAULT '#121519',
        `cor_botao` varchar(20) DEFAULT '#007bff',
        `data_criacao` timestamp DEFAULT CURRENT_TIMESTAMP
    )");
    
    // Tabela de Limites por Revenda
    $pdo_int->exec("CREATE TABLE IF NOT EXISTS `revenda_limites` (
        `member_id` int(11) PRIMARY KEY,
        `limite_players` int(11) DEFAULT 1
    )");
} catch (Exception $e) {}

$protocolo = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https://" : "http://";
$dominio = $_SERVER['HTTP_HOST'];
$base_path = rtrim(dirname($_SERVER['PHP_SELF']), '/');

$mensagem_alerta = "";

// --- AÇÃO: ATUALIZAR LIMITE DA REVENDA (SÓ ADMIN) ---
if ($is_admin && $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action_update_limit'])) {
    $m_id = intval($_POST['limit_member_id']);
    $new_limit = intval($_POST['new_limit']);
    try {
        $stmtLimit = $pdo_int->prepare("INSERT INTO revenda_limites (member_id, limite_players) VALUES (?, ?) ON DUPLICATE KEY UPDATE limite_players = ?");
        $stmtLimit->execute([$m_id, $new_limit, $new_limit]);
        $mensagem_alerta = "<div class='alert success'><i class='fas fa-check-circle'></i> Limite atualizado com sucesso!</div>";
    } catch (Exception $e) {
        $mensagem_alerta = "<div class='alert danger'><i class='fas fa-exclamation-triangle'></i> Erro ao atualizar limite.</div>";
    }
}

// --- BUSCA O LIMITE E A QUANTIDADE ATUAL DA REVENDA ---
$limite_atual = 1; // Padrão é 1
$total_criados = 0;

if (!$is_admin) {
    // Quantos ele pode criar
    $stmtLim = $pdo_int->prepare("SELECT limite_players FROM revenda_limites WHERE member_id = ?");
    $stmtLim->execute([$id_usuario]);
    $resLim = $stmtLim->fetch(PDO::FETCH_ASSOC);
    if ($resLim) { $limite_atual = $resLim['limite_players']; }
    
    // Quantos ele já criou
    $stmtCount = $pdo_int->prepare("SELECT COUNT(*) FROM revenda_players WHERE member_id = ?");
    $stmtCount->execute([$id_usuario]);
    $total_criados = $stmtCount->fetchColumn();
}

$atingiu_limite = (!$is_admin && $total_criados >= $limite_atual);


// --- AÇÃO: SALVAR OU EDITAR PLAYER ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action_save_player'])) {
    $id_player = $_POST['player_id'] ?? '';
    
    $member_id_save = $is_admin ? intval($_POST['member_id']) : $id_usuario;
    $nome_marca = trim($_POST['nome_marca']);
    $cor_fundo = trim($_POST['cor_fundo']);
    $cor_botao = trim($_POST['cor_botao']);
    
    $logo_final = trim($_POST['logo_url_texto']);
    
    if (isset($_FILES['logo_file']) && $_FILES['logo_file']['error'] === UPLOAD_ERR_OK) {
        $pasta_upload = 'uploads_logos/';
        if (!is_dir($pasta_upload)) { mkdir($pasta_upload, 0755, true); }
        
        $extensao = strtolower(pathinfo($_FILES['logo_file']['name'], PATHINFO_EXTENSION));
        $extensoes_permitidas = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        
        if (in_array($extensao, $extensoes_permitidas)) {
            $novo_nome = 'logo_' . uniqid() . '.' . $extensao;
            $caminho_completo = $pasta_upload . $novo_nome;
            
            if (move_uploaded_file($_FILES['logo_file']['tmp_name'], $caminho_completo)) {
                $logo_final = $protocolo . $dominio . $base_path . '/' . $caminho_completo;
            } else {
                $mensagem_alerta = "<div class='alert danger'>Erro ao salvar a imagem no servidor.</div>";
            }
        } else {
            $mensagem_alerta = "<div class='alert danger'>Formato não permitido. Use PNG, JPG ou WEBP.</div>";
        }
    }

    if (empty($mensagem_alerta)) {
        try {
            if (!empty($id_player)) {
                // MODO EDIÇÃO
                if (!$is_admin) {
                    $check_dono = $pdo_int->prepare("SELECT id FROM revenda_players WHERE id = ? AND member_id = ?");
                    $check_dono->execute([$id_player, $id_usuario]);
                    if (!$check_dono->fetch()) { die("Erro: Você não tem permissão para editar este player."); }
                }
                $stmt = $pdo_int->prepare("UPDATE revenda_players SET member_id = ?, nome_marca = ?, logo_url = ?, cor_fundo = ?, cor_botao = ? WHERE id = ?");
                $stmt->execute([$member_id_save, $nome_marca, $logo_final, $cor_fundo, $cor_botao, $id_player]);
                $mensagem_alerta = "<div class='alert success'><i class='fas fa-check-circle'></i> Player atualizado com sucesso!</div>";
            } else {
                // MODO CRIAÇÃO (VERIFICA O LIMITE AQUI)
                if ($atingiu_limite) {
                    throw new Exception("Você atingiu o limite de {$limite_atual} Web Player(s). Contate o Administrador.");
                }

                $slug = bin2hex(random_bytes(6)); 
                $check = $pdo_int->prepare("SELECT id FROM revenda_players WHERE slug = ?");
                $check->execute([$slug]);
                if($check->fetch()) { $slug = bin2hex(random_bytes(8)); }

                $stmt = $pdo_int->prepare("INSERT INTO revenda_players (member_id, slug, nome_marca, logo_url, cor_fundo, cor_botao) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->execute([$member_id_save, $slug, $nome_marca, $logo_final, $cor_fundo, $cor_botao]);
                $mensagem_alerta = "<div class='alert success'><i class='fas fa-check-circle'></i> Novo Player criado! Já pode copiar o link anônimo.</div>";
                
                // Atualiza a contagem da revenda na tela
                if(!$is_admin) { $total_criados++; $atingiu_limite = ($total_criados >= $limite_atual); }
            }
        } catch (Exception $e) {
            $mensagem_alerta = "<div class='alert danger'><i class='fas fa-exclamation-triangle'></i> Erro: " . $e->getMessage() . "</div>";
        }
    }
}

// AÇÃO: EXCLUIR PLAYER
if (isset($_GET['delete'])) {
    $id_del = intval($_GET['delete']);
    if ($is_admin) {
        $pdo_int->prepare("DELETE FROM revenda_players WHERE id = ?")->execute([$id_del]);
    } else {
        $pdo_int->prepare("DELETE FROM revenda_players WHERE id = ? AND member_id = ?")->execute([$id_del, $id_usuario]);
    }
    header("Location: admin_player_revenda.php");
    exit;
}

// BUSCA LISTA DE REVENDEDORES E CRIA O MAPA DE NOMES
$revendedores = [];
$mapa_nomes = [];
$mapa_limites = [];
if ($is_admin) {
    try {
        // Usa a tabela dinâmica de revendedores
        $revendedores = $pdo->query("SELECT id, username FROM $tabela_revendedores WHERE member_group_id != 1 ORDER BY username ASC")->fetchAll(PDO::FETCH_ASSOC);
        $todos = $pdo->query("SELECT id, username FROM $tabela_revendedores")->fetchAll(PDO::FETCH_ASSOC);
        foreach($todos as $t) { $mapa_nomes[$t['id']] = $t['username']; }
        
        $limites_db = $pdo_int->query("SELECT member_id, limite_players FROM revenda_limites")->fetchAll(PDO::FETCH_ASSOC);
        foreach($limites_db as $ld) { $mapa_limites[$ld['member_id']] = $ld['limite_players']; }
    } catch(Exception $e){}
}

// BUSCA OS PLAYERS CRIADOS (No Banco Interno)
if ($is_admin) {
    $players = $pdo_int->query("SELECT * FROM revenda_players ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
} else {
    $stmtPlay = $pdo_int->prepare("SELECT * FROM revenda_players WHERE member_id = ? ORDER BY id DESC");
    $stmtPlay->execute([$id_usuario]);
    $players = $stmtPlay->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>Web Player White Label - <?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">
    <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; }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background-color: var(--bg-dark); color: var(--text-main); display: flex; height: 100vh; overflow: hidden; }
        
        /* USANDO A SIDEBAR.PHP */
        .sidebar { width: 260px; background-color: var(--bg-sidebar); display: flex; flex-direction: column; transition: 0.3s; border-right: 1px solid var(--border-color); 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; padding-bottom: 20px;}
        .menu-list::-webkit-scrollbar { width: 6px; }
        .menu-list::-webkit-scrollbar-thumb { background: #3a4149; border-radius: 3px; }

        .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); }
        .menu-category { padding: 20px 20px 5px; font-size: 11px; font-weight: bold; color: var(--text-muted); text-transform: uppercase; letter-spacing: 1px;}
        .logout-btn { padding: 15px; background-color: var(--danger); color: white; text-align: center; text-decoration: none; font-weight: bold; }

        .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: transform 0.3s ease; font-size: 11px; }
        
        .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 25px; background-color: var(--bg-sidebar); border-bottom: 1px solid var(--border-color); gap: 15px;}
        .menu-toggle { display: none; background: none; border: none; color: white; font-size: 22px; cursor: pointer; padding: 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; }
        .mode-badge { padding: 6px 15px; background: rgba(0, 123, 255, 0.15); color: var(--accent); border-radius: 20px; font-size: 12px; font-weight: bold; border: 1px solid var(--accent); white-space: nowrap; display: inline-block; }
        
        .content-area { padding: 30px; flex: 1; max-width: 1200px; margin: 0 auto; width: 100%; box-sizing: border-box; }
        .card { background: var(--bg-card); border-radius: 12px; border: 1px solid var(--border-color); padding: 25px; margin-bottom: 25px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); }
        .card h3 { margin-top: 0; color: white; border-bottom: 1px solid var(--border-color); padding-bottom: 15px; display: flex; align-items: center; gap: 10px;}
        
        .form-group { margin-bottom: 20px; }
        label { display: block; margin-bottom: 8px; font-size: 13px; font-weight: bold; color: var(--text-muted); }
        
        input[type="text"], input[type="number"], input[type="color"], select { width: 100%; padding: 12px; background: #121519; border: 1px solid var(--border-color); color: white; border-radius: 8px; box-sizing: border-box; font-size: 14px;}
        
        input[type="file"] { width: 100%; padding: 9px; background: #121519; border: 1px dashed var(--border-color); color: white; border-radius: 8px; box-sizing: border-box; font-size: 13px; cursor: pointer; }
        input[type="file"]::file-selector-button { background: var(--border-color); color: white; border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer; font-weight: bold; margin-right: 15px; transition: 0.2s;}
        input[type="file"]::file-selector-button:hover { background: #4a525b; }
        
        input[type="text"]:focus, input[type="number"]:focus, select:focus { border-color: var(--accent); outline: none; }
        input[type="color"] { padding: 5px; height: 45px; cursor: pointer; }
        
        .btn-save { background: var(--accent); color: white; border: none; padding: 15px; border-radius: 8px; cursor: pointer; font-weight: bold; width: 100%; margin-top: 10px; font-size: 15px; transition: 0.2s;}
        .btn-save:hover { filter: brightness(1.1); box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .btn-save:disabled { background: #444 !important; cursor: not-allowed !important; color: #888 !important; box-shadow: none !important; }
        
        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-weight: bold; display: flex; align-items: center; gap: 10px;}
        .alert.success { background: rgba(40, 167, 69, 0.15); border: 1px solid var(--success); color: var(--success); }
        .alert.danger { background: rgba(220, 53, 69, 0.15); border: 1px solid var(--danger); color: var(--danger); }
        .alert.warning { background: rgba(243, 156, 18, 0.15); border: 1px solid var(--warning); color: var(--warning); }
        
        .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }

        .table-responsive { overflow-x: auto; width: 100%; }
        table { width: 100%; border-collapse: collapse; margin-top: 15px; font-size: 13px; min-width: 800px;}
        th, td { text-align: left; padding: 15px; border-bottom: 1px solid var(--border-color); }
        th { color: var(--text-muted); text-transform: uppercase; font-size: 11px; font-weight: bold; background: #16191d;}
        td { color: var(--text-main); vertical-align: middle; }
        
        .btn-action { background: #3a4149; color: white; border: none; padding: 8px 12px; border-radius: 6px; cursor: pointer; font-weight: bold; transition: 0.2s; display: inline-flex; align-items: center; gap: 5px; text-decoration: none; font-size: 12px;}
        .btn-action:hover { filter: brightness(1.2); }
        .btn-copy { background: #28a745; }
        .btn-delete { background: #dc3545; }

        .player-logo-preview { max-width: 100px; max-height: 40px; object-fit: contain; background: rgba(0,0,0,0.5); padding: 5px; border-radius: 4px; border: 1px dashed var(--border-color);}
        .color-dot { display: inline-block; width: 15px; height: 15px; border-radius: 50%; border: 1px solid white; vertical-align: middle; margin-right: 5px;}

        @media (max-width: 768px) {
            .menu-toggle { display: block; margin-right: 15px; }
            .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; }
            .content-area { padding: 15px; }
            .grid-2 { grid-template-columns: 1fr; gap: 0;}
            .topbar { padding: 15px 20px; justify-content: flex-start;}
            .topbar-right { margin-left: auto; }
        }
    </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;"><i class="fas fa-play-circle" style="color:var(--accent);"></i> Gerador de Web Player</h2>
            </div>
            <div class="topbar-right">
                <span class="mode-badge"><i class="fas fa-database"></i> MODO: <?php echo defined('MODO_SISTEMA') ? strtoupper(MODO_SISTEMA) : strtoupper($modo_ativo); ?></span>
            </div>
        </header>

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

            <?php if ($is_admin): ?>
            <div class="card" style="border-top: 4px solid var(--warning);">
                <h3><i class="fas fa-sliders-h" style="color: var(--warning);"></i> Limites de Revendedores</h3>
                <p style="font-size: 12px; color: var(--text-muted); margin-top:-5px; margin-bottom: 15px;">Aumente o limite de Web Players que uma revenda específica pode criar (O padrão é 1 para todos).</p>
                <form method="POST">
                    <input type="hidden" name="action_update_limit" value="1">
                    <div class="grid-2">
                        <div class="form-group">
                            <label>Selecione a Revenda</label>
                            <select name="limit_member_id" id="sel_limite_revenda" required onchange="atualizarCampoLimite()">
                                <option value="" disabled selected>Escolha um revendedor...</option>
                                <?php foreach($revendedores as $r): 
                                    $limitAtual = $mapa_limites[$r['id']] ?? 1;
                                ?>
                                    <option value="<?php echo $r['id']; ?>" data-limit="<?php echo $limitAtual; ?>"><?php echo htmlspecialchars($r['username']); ?> (Atual: <?php echo $limitAtual; ?>)</option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Quantidade Permitida</label>
                            <input type="number" name="new_limit" id="val_new_limit" min="1" value="1" required>
                        </div>
                    </div>
                    <button type="submit" class="btn-save" style="background: #28a745; width: auto;"><i class="fas fa-check"></i> ATUALIZAR LIMITE</button>
                </form>
            </div>
            <?php endif; ?>

            <div class="card" style="border-top: 4px solid var(--accent);">
                <h3 id="formTitle"><i class="fas fa-magic" style="color:var(--accent);"></i> <?php echo $is_admin ? 'Gerar Player para Revenda' : 'Configurar Meu Player'; ?></h3>
                
                <?php if (!$is_admin): ?>
                    <p style="font-size: 13px; color: var(--text-muted);">Você possui <strong><?php echo $total_criados; ?></strong> de <strong><?php echo $limite_atual; ?></strong> player(s) criados.</p>
                <?php endif; ?>
                
                <form method="POST" id="formPlayer" enctype="multipart/form-data">
                    <input type="hidden" name="action_save_player" value="1">
                    <input type="hidden" name="player_id" id="f_player_id" value="">
                    
                    <div class="grid-2">
                        <?php if($is_admin): ?>
                            <div class="form-group">
                                <label>Dono do Player (Revendedor)</label>
                                <select name="member_id" id="f_member_id" required>
                                    <option value="<?php echo $id_usuario; ?>">Eu mesmo (Painel Oficial)</option>
                                    <?php foreach($revendedores as $r): ?>
                                        <option value="<?php echo $r['id']; ?>"><?php echo htmlspecialchars($r['username']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        <?php else: ?>
                            <input type="hidden" name="member_id" id="f_member_id" value="<?php echo $id_usuario; ?>">
                        <?php endif; ?>

                        <div class="form-group">
                            <label>Nome da sua Marca (Ex: João TV)</label>
                            <input type="text" name="nome_marca" id="f_nome_marca" placeholder="Nome que vai aparecer no site" required>
                        </div>
                    </div>

                    <div class="grid-2">
                        <div class="form-group">
                            <label>Colar Link da Logo</label>
                            <input type="text" name="logo_url_texto" id="f_logo_url_texto" placeholder="Ex: https://imgur.com/logo.png">
                        </div>
                        <div class="form-group">
                            <label style="color:var(--success);"><i class="fas fa-upload"></i> OU Fazer Upload do Computador</label>
                            <input type="file" name="logo_file" id="f_logo_file" accept="image/png, image/jpeg, image/webp, image/gif">
                        </div>
                    </div>
                    <small style="color:var(--text-muted); display:block; margin-top:-10px; margin-bottom:20px;">Se você selecionar um arquivo do computador, o link colado será ignorado.</small>

                    <div class="grid-2">
                        <div class="form-group">
                            <label>Cor de Fundo</label>
                            <div style="display:flex; gap:10px;">
                                <input type="color" name="cor_fundo" id="f_cor_fundo" value="#121519" style="width: 60px;">
                                <input type="text" value="#121519" id="f_cor_fundo_txt" readonly style="color: var(--text-muted);">
                            </div>
                        </div>

                        <div class="form-group">
                            <label>Cor do Botão</label>
                            <div style="display:flex; gap:10px;">
                                <input type="color" name="cor_botao" id="f_cor_botao" value="#007bff" style="width: 60px;">
                                <input type="text" value="#007bff" id="f_cor_botao_txt" readonly style="color: var(--text-muted);">
                            </div>
                        </div>
                    </div>
                    
                    <div style="display:flex; gap:10px;">
                        <button type="submit" id="btnSaveForm" class="btn-save"><i class="fas fa-save"></i> SALVAR E GERAR LINK SECRETO</button>
                        <button type="button" onclick="resetForm()" class="btn-action" style="margin-top:10px; padding: 15px; font-size:15px; display:none;" id="btnCancel">Cancelar Edição</button>
                    </div>
                </form>
            </div>

            <div class="card">
                <h3><i class="fas fa-link" style="color: #f39c12;"></i> Links Prontos para Uso</h3>
                <div class="table-responsive">
                    <table>
                        <thead>
                            <tr>
                                <th>Marca</th>
                                <th>Cores</th>
                                <th>Seu Link Oficial</th>
                                <th>Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(empty($players)): ?>
                                <tr><td colspan="4" style="text-align:center; color: var(--text-muted); padding: 30px 0;">Você ainda não criou nenhum Web Player.</td></tr>
                            <?php else: foreach($players as $p): 
                                
                                $link_player = $protocolo . $dominio . "/webplayer/index.php?id=" . $p['slug'];
                            ?>
                                <tr>
                                    <td>
                                        <div style="display:flex; align-items:center; gap:10px;">
                                            <?php if(!empty($p['logo_url'])): ?>
                                                <img src="<?php echo htmlspecialchars($p['logo_url']); ?>" class="player-logo-preview">
                                            <?php endif; ?>
                                            <div>
                                                <strong><?php echo htmlspecialchars($p['nome_marca']); ?></strong>
                                                <?php if($is_admin): 
                                                    $dono_nome = $mapa_nomes[$p['member_id']] ?? 'ID: ' . $p['member_id'];
                                                    if ($p['member_id'] == $id_usuario) $dono_nome = 'Eu mesmo (Admin)';
                                                ?>
                                                    <div style="font-size:11px; color:#8b5cf6; margin-top:3px;"><i class="fas fa-user-tie"></i> Revenda: <?php echo htmlspecialchars($dono_nome); ?></div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <div style="margin-bottom:4px;"><span class="color-dot" style="background:<?php echo htmlspecialchars($p['cor_fundo']); ?>;"></span> Fundo</div>
                                        <div><span class="color-dot" style="background:<?php echo htmlspecialchars($p['cor_botao']); ?>;"></span> Botão</div>
                                    </td>
                                    <td>
                                        <input type="text" value="<?php echo $link_player; ?>" id="link_<?php echo $p['id']; ?>" readonly style="background:transparent; border:1px dashed var(--border-color); padding:8px; color:var(--success); font-weight:bold; font-size:12px; width:100%; max-width:300px; border-radius:4px;">
                                    </td>
                                    <td>
                                        <button class="btn-action btn-copy" onclick="copiarLink('link_<?php echo $p['id']; ?>')" title="Copiar Link para mandar pro Cliente"><i class="fas fa-copy"></i> Copiar</button>
                                        
                                        <button class="btn-action" onclick='editarPlayer(<?php echo json_encode($p); ?>)' title="Editar Cores/Logo"><i class="fas fa-edit"></i></button>
                                        
                                        <a href="?delete=<?php echo $p['id']; ?>" class="btn-action btn-delete" onclick="return confirm('Tem certeza? O link atual vai parar de funcionar para os clientes.')" title="Apagar"><i class="fas fa-trash"></i></a>
                                    </td>
                                </tr>
                            <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php include 'rodape.php'; ?>
    </div>

    <script>
        // Verificação do limite no Javascript para travar o botão visualmente
        const atingiuLimite = <?php echo $atingiu_limite ? 'true' : 'false'; ?>;

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

        function toggleSubmenu(id) {
            var submenu = document.getElementById(id);
            var arrow = document.getElementById('arrow-' + id);
            
            if (submenu.style.display === "block") {
                submenu.style.display = "none";
                if(arrow) arrow.style.transform = "rotate(0deg)";
            } else {
                submenu.style.display = "block";
                if(arrow) arrow.style.transform = "rotate(180deg)";
            }
        }

        function copiarLink(id) {
            var copyText = document.getElementById(id);
            copyText.select();
            copyText.setSelectionRange(0, 99999);
            navigator.clipboard.writeText(copyText.value).then(() => {
                alert("Link Anônimo do Player copiado! Envie com segurança para seus clientes.");
            }).catch(err => {
                document.execCommand("copy");
                alert("Link copiado!");
            });
        }

        document.getElementById('f_cor_fundo').addEventListener('input', function() { document.getElementById('f_cor_fundo_txt').value = this.value; });
        document.getElementById('f_cor_botao').addEventListener('input', function() { document.getElementById('f_cor_botao_txt').value = this.value; });

        function editarPlayer(dados) {
            document.getElementById('formTitle').innerHTML = '<i class="fas fa-edit" style="color:var(--warning);"></i> Editar Meu Player';
            document.getElementById('f_player_id').value = dados.id;
            
            if(document.getElementById('f_member_id').tagName === 'SELECT') {
                document.getElementById('f_member_id').value = dados.member_id;
            } else {
                document.getElementById('f_member_id').value = dados.member_id;
            }
            
            document.getElementById('f_nome_marca').value = dados.nome_marca;
            document.getElementById('f_logo_url_texto').value = dados.logo_url;
            document.getElementById('f_logo_file').value = ''; 
            document.getElementById('f_cor_fundo').value = dados.cor_fundo;
            document.getElementById('f_cor_fundo_txt').value = dados.cor_fundo;
            document.getElementById('f_cor_botao').value = dados.cor_botao;
            document.getElementById('f_cor_botao_txt').value = dados.cor_botao;
            
            // Se ele for editar, liberamos o botão de salvar mesmo que ele esteja no limite
            document.getElementById('btnSaveForm').disabled = false;
            document.getElementById('btnSaveForm').innerHTML = '<i class="fas fa-save"></i> SALVAR EDIÇÃO';
            
            document.getElementById('btnCancel').style.display = 'block';
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }

        function resetForm() {
            document.getElementById('formTitle').innerHTML = '<i class="fas fa-magic" style="color:var(--accent);"></i> Configurar Meu Player';
            document.getElementById('formPlayer').reset();
            document.getElementById('f_player_id').value = '';
            document.getElementById('f_cor_fundo_txt').value = '#121519';
            document.getElementById('f_cor_botao_txt').value = '#007bff';
            document.getElementById('btnCancel').style.display = 'none';
            
            // Se for criar um novo e ele estiver no limite, travamos de novo
            if(atingiuLimite) {
                document.getElementById('btnSaveForm').disabled = true;
                document.getElementById('btnSaveForm').innerHTML = '<i class="fas fa-lock"></i> LIMITE DE PLAYERS ATINGIDO';
            } else {
                document.getElementById('btnSaveForm').disabled = false;
                document.getElementById('btnSaveForm').innerHTML = '<i class="fas fa-save"></i> SALVAR E GERAR LINK SECRETO';
            }
        }
        
        // Puxa a quantidade certa quando o admin for alterar no select
        function atualizarCampoLimite() {
            var sel = document.getElementById('sel_limite_revenda');
            var opt = sel.options[sel.selectedIndex];
            document.getElementById('val_new_limit').value = opt.getAttribute('data-limit');
        }
        
        // Trava o botão ao carregar a página se o limite já estourou
        window.onload = function() {
            if(atingiuLimite && document.getElementById('f_player_id').value === '') {
                document.getElementById('btnSaveForm').disabled = true;
                document.getElementById('btnSaveForm').innerHTML = '<i class="fas fa-lock"></i> LIMITE DE PLAYERS ATINGIDO';
            }
        };
        
        setTimeout(function() { 
            try { 
                var alerts = document.querySelectorAll('.alert'); 
                for(var i=0; i<alerts.length; i++) { alerts[i].style.opacity='0'; } 
                setTimeout(function(){ 
                    for(var j=0; j<alerts.length; j++) { alerts[j].style.display='none'; } 
                }, 500); 
            } catch(e) {} 
        }, 4000);
    </script>
    <script src="tema.js"></script>
</body>
</html>