<?php
// Painel Externo para Inserção de Listas - Sem Login
// Este arquivo permite adicionar novos usuários sem necessidade de autenticação

// Configurações de conexão com banco de dados
// IMPORTANTE: Ajuste estas configurações conforme seu ambiente
$db_host = 'localhost';
$db_name = 'seu_banco_de_dados';
$db_user = 'seu_usuario';
$db_pass = 'sua_senha';

try {
    $pdo = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", $db_user, $db_pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Erro de conexão: " . $e->getMessage());
}

// Função para normalizar endereço MAC
function normalise_mac(string $raw): string {
    $dec = base64_decode($raw, true);
    if ($dec !== false) $raw = $dec;
    $raw = strtolower(trim($raw));
    if (strpos($raw, '00:') === 0) $raw = substr($raw, 3);
    $hex = preg_replace('/[^0-9a-f]/', '', $raw);
    $pairs = array_filter(str_split($hex, 2), static fn($p) => strlen($p) === 2);
    return implode(':', $pairs);
}

// Processar formulário quando enviado
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    try {
        // Normalizar endereço MAC
        $mac_address = normalise_mac($_POST['mac_address']);
        
        // Gerar device_key se não fornecido
        $device_key = !empty($_POST['device_key']) ? $_POST['device_key'] : '';
        if (empty($device_key)) {
            $chars = '1234567890';
            $device_key = '';
            for ($i = 0; $i < 8; $i++) {
                $device_key .= $chars[random_int(0, strlen($chars) - 1)];
            }
        }
        
        // Preparar dados para inserção
        $sql = "INSERT INTO playlist (dns_id, mac_address, username, password, pin, link, device_key) 
                VALUES (:dns_id, :mac_address, :username, :password, :pin, :link, :device_key)";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':dns_id' => $_POST['dns_id'],
            ':mac_address' => $mac_address,
            ':username' => $_POST['username'],
            ':password' => $_POST['password'],
            ':pin' => $_POST['pin'],
            ':link' => $_POST['link'],
            ':device_key' => $device_key
        ]);
        
        $message = 'Usuário adicionado com sucesso!';
        $message_type = 'success';
        
        // Limpar formulário após sucesso
        $_POST = [];
        
    } catch(PDOException $e) {
        $message = 'Erro ao adicionar usuário: ' . $e->getMessage();
        $message_type = 'error';
    }
}

// Buscar lista de DNS disponíveis
try {
    $dns_stmt = $pdo->query("SELECT id, title, url FROM dns ORDER BY title");
    $dns_list = $dns_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    $dns_list = [];
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Painel Externo - Adicionar Lista</title>
    <style>
        :root {
            --primary-blue: #003366;
            --dark-blue: #001a33;
            --light-blue: #00AEEF;
            --gold: #FFD166;
            --success-green: #28a745;
            --danger-red: #dc3545;
            --text-light: #f8f9fa;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            background: linear-gradient(135deg, var(--dark-blue), var(--primary-blue));
            background-attachment: fixed;
            color: var(--text-light);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .container {
            background: rgba(0, 0, 0, 0.7);
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 174, 239, 0.2);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(0, 174, 239, 0.25);
            width: 100%;
            max-width: 600px;
            overflow: hidden;
        }

        .header {
            background: linear-gradient(90deg, var(--dark-blue), var(--primary-blue));
            padding: 25px;
            text-align: center;
            border-bottom: 2px solid var(--light-blue);
        }

        .header h1 {
            color: var(--gold);
            font-size: 1.8rem;
            font-weight: 700;
            text-shadow: 0 0 6px rgba(0,0,0,0.6);
        }

        .header .subtitle {
            color: var(--text-light);
            font-size: 0.9rem;
            margin-top: 5px;
            opacity: 0.8;
        }

        .content {
            padding: 30px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: var(--gold);
        }

        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid rgba(0, 174, 239, 0.3);
            border-radius: 8px;
            background: rgba(0, 0, 0, 0.5);
            color: var(--text-light);
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--light-blue);
            box-shadow: 0 0 10px rgba(0, 174, 239, 0.3);
        }

        .form-control::placeholder {
            color: rgba(248, 249, 250, 0.5);
        }

        .input-group {
            display: flex;
            gap: 10px;
            align-items: stretch;
        }

        .input-group .form-control {
            flex: 1;
        }

        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }

        .btn-primary {
            background: linear-gradient(45deg, var(--dark-blue), var(--primary-blue));
            color: white;
            box-shadow: 0 4px 15px rgba(0, 174, 239, 0.25);
        }

        .btn-primary:hover {
            background: linear-gradient(45deg, var(--primary-blue), var(--light-blue));
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 174, 239, 0.35);
        }

        .btn-secondary {
            background: linear-gradient(45deg, #6c757d, #495057);
            color: white;
        }

        .btn-secondary:hover {
            background: linear-gradient(45deg, #495057, #343a40);
            transform: translateY(-2px);
        }

        .btn-block {
            width: 100%;
        }

        .alert {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            text-align: center;
            font-weight: 500;
        }

        .alert-success {
            background-color: rgba(40, 167, 69, 0.2);
            border: 1px solid rgba(40, 167, 69, 0.3);
            color: #d4edda;
        }

        .alert-error {
            background-color: rgba(220, 53, 69, 0.2);
            border: 1px solid rgba(220, 53, 69, 0.3);
            color: #f8d7da;
        }

        .help-text {
            font-size: 0.85rem;
            color: rgba(248, 249, 250, 0.7);
            margin-top: 5px;
        }

        .emoji {
            font-size: 1.2em;
            margin-right: 8px;
        }

        @media (max-width: 768px) {
            .container {
                margin: 10px;
            }
            
            .content {
                padding: 20px;
            }
            
            .header h1 {
                font-size: 1.5rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><span class="emoji">📋</span>Painel Externo</h1>
            <div class="subtitle">Adicionar Nova Lista de Usuário</div>
        </div>
        
        <div class="content">
            <?php if ($message): ?>
                <div class="alert alert-<?= $message_type === 'success' ? 'success' : 'error' ?>">
                    <?= htmlspecialchars($message) ?>
                </div>
            <?php endif; ?>

            <form method="POST" action="">
                <div class="form-group">
                    <label class="form-label" for="m3u_url">
                        <span class="emoji">📄</span>Lista M3U / URL Xtream (opcional)
                    </label>
                    <div class="input-group">
                        <input 
                            class="form-control" 
                            id="m3u_url" 
                            type="text" 
                            placeholder="Cole aqui a URL (ex.: http://host:porta/get.php?username=USER&password=PASS&type=m3u)"
                        >
                        <button type="button" class="btn btn-secondary" onclick="extractFromUrl()">
                            Extrair
                        </button>
                    </div>
                    <div class="help-text">
                        Ao clicar em "Extrair", os campos usuário e senha serão preenchidos automaticamente.
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label" for="dns_id">
                        <span class="emoji">🌐</span>DNS
                    </label>
                    <select class="form-control" name="dns_id" id="dns_id" required>
                        <option value="">Selecione uma opção</option>
                        <?php foreach($dns_list as $dns): ?>
                            <option value="<?= $dns['id'] ?>" data-url="<?= htmlspecialchars($dns['url']) ?>">
                                <?= htmlspecialchars($dns['title']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="form-group">
                    <label class="form-label" for="mac_address">
                        <span class="emoji">📟</span>Endereço MAC
                    </label>
                    <input 
                        class="form-control" 
                        id="mac_address" 
                        name="mac_address" 
                        type="text" 
                        placeholder="Ex: A1B2C3D4E5F6" 
                        value="<?= htmlspecialchars($_POST['mac_address'] ?? '') ?>"
                        required
                    >
                </div>

                <div class="form-group">
                    <label class="form-label" for="username">
                        <span class="emoji">👤</span>Nome de Usuário
                    </label>
                    <input 
                        class="form-control" 
                        id="username" 
                        name="username" 
                        type="text" 
                        placeholder="Nome de usuário" 
                        value="<?= htmlspecialchars($_POST['username'] ?? '') ?>"
                        required
                    >
                </div>

                <div class="form-group">
                    <label class="form-label" for="password">
                        <span class="emoji">🔑</span>Senha
                    </label>
                    <input 
                        class="form-control" 
                        id="password" 
                        name="password" 
                        type="text" 
                        placeholder="Senha" 
                        value="<?= htmlspecialchars($_POST['password'] ?? '') ?>"
                        required
                    >
                </div>

                <div class="form-group">
                    <label class="form-label" for="pin">
                        <span class="emoji">🔒</span>PIN Parental
                    </label>
                    <input 
                        class="form-control" 
                        id="pin" 
                        name="pin" 
                        type="text" 
                        placeholder="PIN parental" 
                        value="<?= htmlspecialchars($_POST['pin'] ?? '0000') ?>"
                        required
                    >
                </div>

                <div class="form-group">
                    <label class="form-label" for="link">
                        <span class="emoji">🔗</span>Link
                    </label>
                    <input 
                        class="form-control" 
                        id="link" 
                        name="link" 
                        type="text" 
                        placeholder="Link (opcional)" 
                        value="<?= htmlspecialchars($_POST['link'] ?? '') ?>"
                    >
                </div>

                <input type="hidden" name="device_key" value="">

                <div class="form-group">
                    <button type="submit" name="submit" class="btn btn-primary btn-block">
                        <span class="emoji">💾</span>Adicionar Lista
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Formatação automática do MAC address
        document.getElementById('mac_address').addEventListener('input', function() {
            this.value = this.value.toUpperCase().replace(/[^\dA-F]/g, '').replace(/(.{2})/g, '$1:').slice(0, -1);
        });

        // Função para extrair dados da URL M3U
        function extractFromUrl() {
            const url = document.getElementById('m3u_url').value.trim();
            if (!url) {
                alert('Por favor, insira uma URL primeiro.');
                return;
            }

            try {
                const urlObj = new URL(url);
                const params = new URLSearchParams(urlObj.search);
                
                // Extrair username e password
                const username = params.get('username');
                const password = params.get('password');
                
                if (username) {
                    document.getElementById('username').value = username;
                }
                
                if (password) {
                    document.getElementById('password').value = password;
                }

                // Tentar encontrar DNS correspondente
                const hostname = urlObj.hostname;
                const dnsSelect = document.getElementById('dns_id');
                
                for (let option of dnsSelect.options) {
                    if (option.dataset.url && option.dataset.url.includes(hostname)) {
                        dnsSelect.value = option.value;
                        break;
                    }
                }

                // Preencher link se não estiver preenchido
                if (!document.getElementById('link').value) {
                    document.getElementById('link').value = url;
                }

                alert('Dados extraídos com sucesso!');
                
            } catch (e) {
                alert('URL inválida. Verifique o formato e tente novamente.');
            }
        }
    </script>
</body>
</html>

