<?php
// Bloqueio de user agents suspeitos
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$bloqueados = ['Python', 'aiohttp', 'curl', 'requests', 'scrapy'];
foreach ($bloqueados as $bot) {
    if (stripos($userAgent, $bot) !== false) {
        $logData = '['  . date('Y-m-d H:i:s') . "] BLOQUEADO\n"
            . "  Bot: $bot\n"
            . "  IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown') . "\n"
            . "  Forwarded: " . ($_SERVER['HTTP_X_FORWARDED_FOR'] ?? '-') . "\n"
            . "  User-Agent: $userAgent\n"
            . "  URI: " . ($_SERVER['REQUEST_URI'] ?? '-') . "\n"
            . "  Method: " . ($_SERVER['REQUEST_METHOD'] ?? '-') . "\n"
            . "  Referer: " . ($_SERVER['HTTP_REFERER'] ?? '-') . "\n"
            . "  Host: " . ($_SERVER['HTTP_HOST'] ?? '-') . "\n"
            . "  Query: " . ($_SERVER['QUERY_STRING'] ?? '-') . "\n"
            . str_repeat('-', 60) . "\n";
        file_put_contents(__DIR__ . '/log.txt', $logData, FILE_APPEND | LOCK_EX);
        http_response_code(403);
        exit('Access denied.');
    }
}

session_start();

// Se já estiver logado, redirecionar para dashboard
if (isset($_SESSION['auth_token'])) {
    require_once __DIR__ . '/backend/classes/Session.php';
    $session = new Session();
    $user_data = $session->validateSession($_SESSION['auth_token']);
    
    if ($user_data) {
        header("Location: /dashboard");
        exit();
    }
}

// Buscar configurações do sistema
require_once __DIR__ . '/backend/classes/ConfigSistema.php';
$configSistema = new ConfigSistema();
$config = $configSistema->getConfig();
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" type="image/png" href="assets/icone.png">
    <title><?php echo htmlspecialchars($config['nome_sistema']); ?> - Criar Conta</title>
    <link rel="stylesheet" href="css/register.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        /* Fallback logo styles for server compatibility */
        .logo-image {
            max-width: 200px !important;
            max-height: 80px !important;
            width: auto !important;
            height: auto !important;
            object-fit: contain !important;
        }
    </style>
</head>
<body>
    <div class="register-container">
        <div class="register-content">
            <!-- Logo -->
            <div class="left-side">
                <!-- <div class="logo-text">Onyxpag</div> -->
                <div class="logo-container">
                    <div class="logo-main">
                     <!--   <img src="/assets/wbiotld9mfqgsju0kiohpzghw.png" alt="Onyxpag" class="logo-icon"> -->
                    </div>
                </div>
            </div>

            <!-- Register Form -->
            <div class="right-side">
                <div class="register-form-container">
                <!-- Top Icons -->
              <!--  <div class="top-icons">
                    <div class="icon-item">
                        <div class="icon-circle"><?php echo htmlspecialchars($config['icone']); ?></div>
                    </div>
                    <div class="icon-item">
                        <div class="icon-circle"><?php echo htmlspecialchars($config['icone']); ?></div>
                        <span class="icon-label"><?php echo strtolower(htmlspecialchars($config['nome_sistema'])); ?></span>
                    </div>
                </div> -->

                <!-- Welcome Text -->
                <div class="welcome-section">
                    <h1>Aventura começa aqui</h1>
                    <p>Torne o gerenciamento de seus aplicativos fácil e divertido!</p>
                </div>

                <!-- Alert Messages -->
                <div id="alert-container"></div>

                <!-- Register Form -->
                <form class="register-form" id="register-form">
                    <!-- Tipo de Pessoa Toggle -->
                    <div class="form-group">
                        <label>Tipo de Cadastro</label>
                        <div class="tipo-pessoa-toggle">
                            <button type="button" class="tipo-btn active" data-tipo="juridica" id="btn-juridica">
                                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                    <path d="m2 7 4.41-4.41A2 2 0 0 1 7.83 2h8.34a2 2 0 0 1 1.42.59L22 7"></path>
                                    <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"></path>
                                    <path d="M15 22v-4a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v4"></path>
                                    <path d="M2 7h20"></path>
                                </svg>
                                Pessoa Jurídica
                            </button>
                            <button type="button" class="tipo-btn" data-tipo="fisica" id="btn-fisica">
                                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                    <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                                    <circle cx="12" cy="7" r="4"></circle>
                                </svg>
                                Pessoa Física
                            </button>
                        </div>
                    </div>

                    <input type="hidden" id="tipo_pessoa" name="tipo_pessoa" value="juridica">

                    <!-- Nome (dinâmico) -->
                    <div class="form-group">
                        <label for="nome_empresa" id="label-nome">Nome da Empresa</label>
                        <div class="input-wrapper">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="input-icon" id="icon-nome">
                                <path d="m2 7 4.41-4.41A2 2 0 0 1 7.83 2h8.34a2 2 0 0 1 1.42.59L22 7"></path>
                                <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"></path>
                                <path d="M15 22v-4a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v4"></path>
                                <path d="M2 7h20"></path>
                            </svg>
                            <input type="text" id="nome_empresa" name="nome_empresa" placeholder="Digite o nome da empresa" required>
                        </div>
                    </div>

                    <!-- CNPJ (para pessoa jurídica) -->
                    <div class="form-group" id="group-cnpj">
                        <label for="cnpj">CNPJ</label>
                        <div class="input-wrapper">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="input-icon">
                                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
                                <polyline points="14,2 14,8 20,8"></polyline>
                                <line x1="16" x2="8" y1="13" y2="13"></line>
                                <line x1="16" x2="8" y1="17" y2="17"></line>
                                <polyline points="10,9 9,9 8,9"></polyline>
                            </svg>
                            <input type="text" id="cnpj" name="cnpj" placeholder="00.000.000/0001-00">
                        </div>
                    </div>

                    <!-- CPF (para pessoa física) -->
                    <div class="form-group" id="group-cpf" style="display: none;">
                        <label for="cpf">CPF</label>
                        <div class="input-wrapper">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="input-icon">
                                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
                                <polyline points="14,2 14,8 20,8"></polyline>
                                <line x1="16" x2="8" y1="13" y2="13"></line>
                                <line x1="16" x2="8" y1="17" y2="17"></line>
                                <polyline points="10,9 9,9 8,9"></polyline>
                            </svg>
                            <input type="text" id="cpf" name="cpf" placeholder="000.000.000-00">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="responsavel_nome">Nome do Responsável</label>
                        <div class="input-wrapper">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="input-icon lucide-user">
                                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                                <circle cx="12" cy="7" r="4"></circle>
                            </svg>
                            <input type="text" id="responsavel_nome" name="responsavel_nome" placeholder="Nome completo do responsável" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="email">Email</label>
                        <div class="input-wrapper">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="input-icon lucide-mail">
                                <path d="m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"></path>
                                <rect x="2" y="4" width="20" height="16" rx="2"></rect>
                            </svg>
                            <input type="email" id="email" name="email" placeholder="Digite seu email" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="telefone">Whatsapp</label>
                        <div class="input-wrapper">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="input-icon">
                                <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path>
                            </svg>
                            <input type="tel" id="telefone" name="telefone" placeholder="(00) 00000-0000" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="password">Senha</label>
                        <div class="input-wrapper">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="input-icon lucide-lock">
                                <rect width="18" height="11" x="3" y="11" rx="2" ry="2"></rect>
                                <path d="m7 11V7a5 5 0 0 1 10 0v4"></path>
                            </svg>
                            <input type="password" id="password" name="password" placeholder="Digite sua senha" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="confirm-password">Confirme sua senha</label>
                        <div class="input-wrapper">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="input-icon lucide-key">
                                <path d="m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"></path>
                                <path d="m21 2-9.6 9.6"></path>
                                <circle cx="7.5" cy="15.5" r="5.5"></circle>
                            </svg>
                            <input type="password" id="confirm-password" name="confirm_password" placeholder="Digite novamente sua senha" required>
                        </div>
                    </div>

                    <div class="form-options">
                        <label class="terms-checkbox">
                            <input type="checkbox" id="terms" name="terms" required>
                            <span class="checkmark"></span>
                            Concordo com os <a href="#" class="terms-link">Termos de Uso</a>
                        </label>
                    </div>

                    <button type="submit" class="register-btn" id="register-btn">
                        <span class="btn-text">Criar Conta</span>
                        <div class="btn-loading" style="display: none;">
                            <div class="spinner"></div>
                        </div>
                    </button>
                </form>

                <!-- Footer -->
                <div class="register-footer">
                    <p>Já possui uma conta? <a href="/" class="login-link">Faça seu login</a></p>
                </div>
            </div>
        </div>
    </div>

    <script>
    // Toggle entre Pessoa Física e Jurídica
    const btnJuridica = document.getElementById('btn-juridica');
    const btnFisica = document.getElementById('btn-fisica');
    const tipoPessoaInput = document.getElementById('tipo_pessoa');
    const groupCnpj = document.getElementById('group-cnpj');
    const groupCpf = document.getElementById('group-cpf');
    const labelNome = document.getElementById('label-nome');
    const inputNome = document.getElementById('nome_empresa');
    const cnpjInput = document.getElementById('cnpj');
    const cpfInput = document.getElementById('cpf');
    const iconNome = document.getElementById('icon-nome');

    btnJuridica.addEventListener('click', function() {
        btnJuridica.classList.add('active');
        btnFisica.classList.remove('active');
        tipoPessoaInput.value = 'juridica';
        groupCnpj.style.display = 'block';
        groupCpf.style.display = 'none';
        labelNome.textContent = 'Nome da Empresa';
        inputNome.placeholder = 'Digite o nome da empresa';
        cnpjInput.required = true;
        cpfInput.required = false;
        cpfInput.value = '';
        
        // Trocar ícone para empresa
        iconNome.innerHTML = `
            <path d="m2 7 4.41-4.41A2 2 0 0 1 7.83 2h8.34a2 2 0 0 1 1.42.59L22 7"></path>
            <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"></path>
            <path d="M15 22v-4a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v4"></path>
            <path d="M2 7h20"></path>
        `;
    });

    btnFisica.addEventListener('click', function() {
        btnFisica.classList.add('active');
        btnJuridica.classList.remove('active');
        tipoPessoaInput.value = 'fisica';
        groupCnpj.style.display = 'none';
        groupCpf.style.display = 'block';
        labelNome.textContent = 'Nome Completo';
        inputNome.placeholder = 'Digite seu nome completo';
        cpfInput.required = true;
        cnpjInput.required = false;
        cnpjInput.value = '';
        
        // Trocar ícone para pessoa
        iconNome.innerHTML = `
            <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
            <circle cx="12" cy="7" r="4"></circle>
        `;
    });

    // Máscara para CNPJ (limita a 14 dígitos)
    document.getElementById('cnpj').addEventListener('input', function(e) {
        let value = e.target.value.replace(/\D/g, '');
        
        // Limitar a 14 dígitos
        if (value.length > 14) {
            value = value.substring(0, 14);
        }
        
        value = value.replace(/^(\d{2})(\d)/, '$1.$2');
        value = value.replace(/^(\d{2})\.(\d{3})(\d)/, '$1.$2.$3');
        value = value.replace(/\.(\d{3})(\d)/, '.$1/$2');
        value = value.replace(/(\d{4})(\d)/, '$1-$2');
        e.target.value = value;
    });

    // Máscara para CPF (limita a 11 dígitos)
    document.getElementById('cpf').addEventListener('input', function(e) {
        let value = e.target.value.replace(/\D/g, '');
        
        // Limitar a 11 dígitos
        if (value.length > 11) {
            value = value.substring(0, 11);
        }
        
        value = value.replace(/^(\d{3})(\d)/, '$1.$2');
        value = value.replace(/^(\d{3})\.(\d{3})(\d)/, '$1.$2.$3');
        value = value.replace(/\.(\d{3})(\d)/, '.$1-$2');
        e.target.value = value;
    });

    // Máscara para Telefone (suporta celular e fixo)
    document.getElementById('telefone').addEventListener('input', function(e) {
        let value = e.target.value.replace(/\D/g, '');
        
        // Limitar a 11 dígitos (celular) ou 10 (fixo)
        if (value.length > 11) {
            value = value.substring(0, 11);
        }
        
        // Aplicar máscara
        if (value.length <= 10) {
            // Telefone fixo: (00) 0000-0000
            value = value.replace(/^(\d{2})(\d)/, '($1) $2');
            value = value.replace(/(\d{4})(\d)/, '$1-$2');
        } else {
            // Celular: (00) 00000-0000
            value = value.replace(/^(\d{2})(\d)/, '($1) $2');
            value = value.replace(/(\d{5})(\d)/, '$1-$2');
        }
        
        e.target.value = value;
    });

    document.getElementById('register-form').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const btn = document.getElementById('register-btn');
        const btnText = btn.querySelector('.btn-text');
        const btnLoading = btn.querySelector('.btn-loading');
        
        // Validar senhas
        const password = document.getElementById('password').value;
        const confirmPassword = document.getElementById('confirm-password').value;
        
        if (password !== confirmPassword) {
            showAlert('error', 'As senhas não coincidem');
            return;
        }
        
        if (password.length < 6) {
            showAlert('error', 'A senha deve ter pelo menos 6 caracteres');
            return;
        }
        
        // Validar termos
        const termsCheckbox = document.getElementById('terms');
        if (!termsCheckbox.checked) {
            showAlert('error', 'Por favor, aceite os Termos de Uso para continuar');
            // Adicionar destaque visual no checkbox
            const termsLabel = termsCheckbox.closest('.terms-checkbox');
            termsLabel.style.border = '2px solid #dc3545';
            termsLabel.style.padding = '8px';
            termsLabel.style.borderRadius = '5px';
            termsLabel.style.backgroundColor = '#fff5f5';
            
            // Remover destaque após 3 segundos
            setTimeout(() => {
                termsLabel.style.border = '';
                termsLabel.style.padding = '';
                termsLabel.style.backgroundColor = '';
            }, 3000);
            
            return;
        }
        
        // Mostrar loading
        btn.disabled = true;
        btnText.style.display = 'none';
        btnLoading.style.display = 'block';
        
        const tipoPessoa = document.getElementById('tipo_pessoa').value;
        const formData = {
            tipo_pessoa: tipoPessoa,
            nome_empresa: document.getElementById('nome_empresa').value,
            responsavel_nome: document.getElementById('responsavel_nome').value,
            email: document.getElementById('email').value,
            telefone: document.getElementById('telefone').value,
            senha: password,
            // Dados do dispositivo para rastreamento
            platform: navigator.platform || null,
            screen_resolution: `${screen.width}x${screen.height}`,
            timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || null
        };
        
        // Adicionar CNPJ ou CPF dependendo do tipo
        if (tipoPessoa === 'juridica') {
            formData.cnpj = document.getElementById('cnpj').value;
        } else {
            formData.cpf = document.getElementById('cpf').value;
        }
        
        try {
            const response = await fetch('backend/api/register.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(formData)
            });
            
            const data = await response.json();
            
            if (data.success) {
                showAlert('success', data.message + ' Redirecionando...');
                setTimeout(() => {
                    window.location.href = data.redirect;
                }, 2000);
            } else {
                showAlert('error', data.message);
            }
        } catch (error) {
            showAlert('error', 'Erro ao conectar com o servidor');
        } finally {
            // Esconder loading
            btn.disabled = false;
            btnText.style.display = 'block';
            btnLoading.style.display = 'none';
        }
    });
    
    function showAlert(type, message) {
        const container = document.getElementById('alert-container');
        const alert = document.createElement('div');
        alert.className = `alert alert-${type}`;
        alert.innerHTML = `
            <div class="alert-content">
                <span>${message}</span>
                <button onclick="this.parentElement.parentElement.remove()" class="alert-close">&times;</button>
            </div>
        `;
        
        container.innerHTML = '';
        container.appendChild(alert);
        
        // Auto remove after 5 seconds
        setTimeout(() => {
            if (alert.parentElement) {
                alert.remove();
            }
        }, 5000);
    }
    </script>
    
    <style>
    /* Estilos para alerts */
    .alert {
        margin: 15px 0;
        padding: 12px 15px;
        border-radius: 8px;
        font-size: 14px;
        animation: slideIn 0.3s ease-out;
    }
    
    .alert-success {
        background-color: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }
    
    .alert-error {
        background-color: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }
    
    .alert-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .alert-close {
        background: none;
        border: none;
        font-size: 18px;
        cursor: pointer;
        color: inherit;
        opacity: 0.7;
    }
    
    .alert-close:hover {
        opacity: 1;
    }
    
    /* Loading spinner */
    .spinner {
        width: 18px;
        height: 18px;
        border: 2px solid #ffffff;
        border-top: 2px solid transparent;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    @keyframes slideIn {
        from {
            opacity: 0;
            transform: translateY(-10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    .terms-checkbox {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
        color: #666;
        transition: all 0.3s ease;
    }
    
    .terms-link {
        color: #118d43;
        text-decoration: none;
    }
    
    .terms-link:hover {
        color: #0d7535;
        text-decoration: underline;
    }
    
    /* Tipo de Pessoa Toggle */
    .tipo-pessoa-toggle {
        display: flex;
        gap: 10px;
        margin-top: 8px;
    }
    
    .tipo-btn {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        padding: 12px 16px;
        border: 2px solid #e0e0e0;
        background: #fff;
        border-radius: 8px;
        cursor: pointer;
        font-size: 14px;
        font-weight: 500;
        color: #666;
        transition: all 0.3s ease;
    }
    
    .tipo-btn:hover {
        border-color: #118d43;
        color: #118d43;
    }
    
    .tipo-btn.active {
        border-color: #118d43;
        background: #118d43;
        color: #fff;
    }
    
    .tipo-btn svg {
        width: 18px;
        height: 18px;
    }
    </style>
</body>
</html>
