<?php
/**
 * Painel Externo para Inserção de Listas - Sem Login
 * Versão 2.0 - Com arquivo de configuração separado
 */

// Incluir configurações
require_once 'config.php';

// Função para normalizar endereço MAC (mesma do sistema original)
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);
}

// Inicializar variáveis
$message = '';
$message_type = '';
$form_data = [];

// Processar formulário quando enviado
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    try {
        $pdo = getDbConnection();
        
        // Validar campos obrigatórios
        $required_fields = ['dns_id', 'mac_address', 'username', 'password', 'pin'];
        $errors = [];
        
        foreach ($required_fields as $field) {
            if (empty($_POST[$field])) {
                $errors[] = "Campo '$field' é obrigatório";
            }
        }
        
        if (!empty($errors)) {
            throw new Exception(implode(', ', $errors));
        }
        
        // Normalizar endereço MAC
        $mac_address = normalise_mac($_POST['mac_address']);
        if (empty($mac_address)) {
            throw new Exception('Endereço MAC inválido');
        }
        
        // Verificar se MAC já existe
        $check_stmt = $pdo->prepare("SELECT id FROM " . USERS_TABLE . " WHERE mac_address = :mac");
        $check_stmt->execute([':mac' => $mac_address]);
        if ($check_stmt->fetch()) {
            throw new Exception('Este endereço MAC já está cadastrado');
        }
        
        // 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 " . USERS_TABLE . " (dns_id, mac_address, username, password, pin, link, device_key, created_at) 
                VALUES (:dns_id, :mac_address, :username, :password, :pin, :link, :device_key, NOW())";
        
        $stmt = $pdo->prepare($sql);
        $result = $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
        ]);
        
        if ($result) {
            $message = 'Usuário adicionado com sucesso! Device Key: ' . $device_key;
            $message_type = 'success';
            
            // Log da atividade
            logActivity('user_added', [
                'mac_address' => $mac_address,
                'username' => $_POST['username'],
                'dns_id' => $_POST['dns_id']
            ]);
            
            // Limpar formulário após sucesso
            $form_data = [];
        } else {
            throw new Exception('Erro ao inserir dados no banco');
        }
        
    } catch(Exception $e) {
        $message = 'Erro: ' . $e->getMessage();
        $message_type = 'error';
        
        // Manter dados do formulário em caso de erro
        $form_data = $_POST;
        
        // Log do erro
        logActivity('user_add_error', [
            'error' => $e->getMessage(),
            'form_data' => $_POST
        ]);
    }
}

// Buscar lista de DNS disponíveis
try {
    $pdo = getDbConnection();
    $dns_stmt = $pdo->query("SELECT id, title, url FROM " . DNS_TABLE . " ORDER BY title");
    $dns_list = $dns_stmt->fetchAll();
} catch(Exception $e) {
    $dns_list = [];
    if (empty($message)) {
        $message = 'Erro ao carregar lista de DNS: ' . $e->getMessage();
        $message_type = 'error';
    }
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= PANEL_TITLE ?></title>
    <style>
        :root {
            --primary-blue: #003366;
            --dark-blue: #001a33;
            --light-blue: #00AEEF;
            --gold: #FFD166;
            --success-green: #28a745;
            --danger-red: #dc3545;
            --text-light: #f8f9fa;
            --warning-orange: #fd7e14;
        }

        * {
            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: 650px;
            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);
        }

        .form-control.error {
            border-color: var(--danger-red);
        }

        .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;
            font-size: 14px;
        }

        .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;
        }

        .info-box {
            background: rgba(0, 174, 239, 0.1);
            border: 1px solid rgba(0, 174, 239, 0.3);
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }

        .info-box h3 {
            color: var(--light-blue);
            margin-bottom: 10px;
            font-size: 1rem;
        }

        .info-box ul {
            list-style: none;
            padding-left: 0;
        }

        .info-box li {
            margin-bottom: 5px;
            padding-left: 20px;
            position: relative;
        }

        .info-box li:before {
            content: "✓";
            position: absolute;
            left: 0;
            color: var(--success-green);
            font-weight: bold;
        }

        @media (max-width: 768px) {
            .container {
                margin: 10px;
            }
            
            .content {
                padding: 20px;
            }
            
            .header h1 {
                font-size: 1.5rem;
            }

            .input-group {
                flex-direction: column;
            }
        }
    </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 - Versão 2.0</div>
        </div>
        
        <div class="content">
            <?php if ($message): ?>
                <div class="alert alert-<?= $message_type === 'success' ? 'success' : 'error' ?>">
                    <?= htmlspecialchars($message) ?>
                </div>
            <?php endif; ?>

            <div class="info-box">
                <h3><span class="emoji">ℹ️</span>Instruções de Uso</h3>
                <ul>
                    <li>Preencha todos os campos obrigatórios</li>
                    <li>Use a função "Extrair" para preencher automaticamente a partir de uma URL M3U</li>
                    <li>O endereço MAC será formatado automaticamente</li>
                    <li>Um Device Key será gerado automaticamente se não fornecido</li>
                </ul>
            </div>

            <form method="POST" action="" id="userForm">
                <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()">
                            <span class="emoji">🔍</span>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']) ?>"
                                    <?= (isset($form_data['dns_id']) && $form_data['dns_id'] == $dns['id']) ? 'selected' : '' ?>>
                                <?= 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($form_data['mac_address'] ?? '') ?>"
                        required
                        maxlength="17"
                    >
                    <div class="help-text">Será formatado automaticamente (ex: A1:B2:C3:D4:E5:F6)</div>
                </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($form_data['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($form_data['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($form_data['pin'] ?? '0000') ?>"
                        required
                        maxlength="4"
                        pattern="[0-9]{4}"
                    >
                    <div class="help-text">4 dígitos numéricos</div>
                </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="url" 
                        placeholder="Link (opcional)" 
                        value="<?= htmlspecialchars($form_data['link'] ?? '') ?>"
                    >
                </div>

                <div class="form-group">
                    <label class="form-label" for="device_key">
                        <span class="emoji">🔐</span>Device Key (opcional)
                    </label>
                    <input 
                        class="form-control" 
                        id="device_key" 
                        name="device_key" 
                        type="text" 
                        placeholder="Será gerado automaticamente se vazio" 
                        value="<?= htmlspecialchars($form_data['device_key'] ?? '') ?>"
                        maxlength="8"
                    >
                    <div class="help-text">8 dígitos numéricos (gerado automaticamente se não fornecido)</div>
                </div>

                <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() {
            let value = this.value.toUpperCase().replace(/[^\dA-F]/g, '');
            let formatted = value.replace(/(.{2})/g, '$1:').slice(0, -1);
            if (formatted.length > 17) {
                formatted = formatted.substring(0, 17);
            }
            this.value = formatted;
        });

        // Validação do PIN (apenas números)
        document.getElementById('pin').addEventListener('input', function() {
            this.value = this.value.replace(/[^\d]/g, '').substring(0, 4);
        });

        // Validação do Device Key (apenas números)
        document.getElementById('device_key').addEventListener('input', function() {
            this.value = this.value.replace(/[^\d]/g, '').substring(0, 8);
        });

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

        // Validação do formulário antes do envio
        document.getElementById('userForm').addEventListener('submit', function(e) {
            const macAddress = document.getElementById('mac_address').value;
            const pin = document.getElementById('pin').value;
            
            // Validar MAC address
            if (macAddress.length < 17) {
                alert('Endereço MAC deve ter 6 pares de caracteres (ex: A1:B2:C3:D4:E5:F6)');
                e.preventDefault();
                return;
            }
            
            // Validar PIN
            if (pin.length !== 4 || !/^\d{4}$/.test(pin)) {
                alert('PIN deve ter exatamente 4 dígitos numéricos');
                e.preventDefault();
                return;
            }
        });
    </script>
</body>
</html>

