<?php
/**
 * Pagina de Registro - BarberFlow SaaS
 * Cadastro de novas lojas/barbearias com subdominio personalizado
 */
require_once __DIR__ . '/../includes/config.php';

$pdo = getDB();
$error = '';
$success = '';
$baseDomain = 'duolead.com.br';

// Buscar plano selecionado
$planId = isset($_GET['plan']) ? $_GET['plan'] : 'free';
$plan = $pdo->prepare("SELECT * FROM plans WHERE id = ? AND is_active = 1");
$plan->execute([$planId]);
$selectedPlan = $plan->fetch(PDO::FETCH_ASSOC);

if (!$selectedPlan) {
    $planId = 'free';
    $plan->execute(['free']);
    $selectedPlan = $plan->fetch(PDO::FETCH_ASSOC);
}

// Buscar todos os planos para exibir
$allPlans = $pdo->query("SELECT * FROM plans WHERE is_active = 1 ORDER BY sort_order ASC")->fetchAll(PDO::FETCH_ASSOC);

// AJAX: Verificar disponibilidade do subdominio
if (isset($_GET['check_subdomain'])) {
    header('Content-Type: application/json');
    $subdomain = trim($_GET['check_subdomain']);
    $subdomain = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $subdomain));
    
    if (strlen($subdomain) < 3) {
        echo json_encode(['available' => false, 'message' => 'Minimo 3 caracteres']);
        exit;
    }
    
    if (strlen($subdomain) > 30) {
        echo json_encode(['available' => false, 'message' => 'Maximo 30 caracteres']);
        exit;
    }
    
    // Palavras reservadas
    $reserved = ['www', 'app', 'admin', 'api', 'mail', 'ftp', 'cpanel', 'webmail', 'painel', 'sistema', 'login', 'register', 'dashboard'];
    if (in_array($subdomain, $reserved)) {
        echo json_encode(['available' => false, 'message' => 'Este nome esta reservado']);
        exit;
    }
    
    $check = $pdo->prepare("SELECT id FROM stores WHERE subdomain = ?");
    $check->execute([$subdomain]);
    
    if ($check->fetch()) {
        echo json_encode(['available' => false, 'message' => 'Subdominio ja em uso']);
    } else {
        echo json_encode(['available' => true, 'message' => 'Disponivel!', 'url' => $subdomain . '.' . $baseDomain]);
    }
    exit;
}

// Processar formulario
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $storeName = trim($_POST['store_name'] ?? '');
    $storeType = $_POST['store_type'] ?? 'barbershop';
    $businessType = $_POST['business_type'] ?? 'service'; // service ou retail
    $subdomain = trim($_POST['subdomain'] ?? '');
    $ownerName = trim($_POST['owner_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    $selectedPlanId = $_POST['plan_id'] ?? 'free';
    
    // Limpar subdominio
    $subdomain = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $subdomain));

    // Validacoes
    if (empty($storeName) || empty($ownerName) || empty($email) || empty($password) || empty($subdomain)) {
        $error = 'Preencha todos os campos obrigatorios.';
    } elseif (strlen($subdomain) < 3) {
        $error = 'O subdominio deve ter no minimo 3 caracteres.';
    } elseif (strlen($subdomain) > 30) {
        $error = 'O subdominio deve ter no maximo 30 caracteres.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'E-mail invalido.';
    } elseif (strlen($password) < 6) {
        $error = 'A senha deve ter no minimo 6 caracteres.';
    } elseif ($password !== $confirmPassword) {
        $error = 'As senhas nao conferem.';
    } else {
        // Verificar subdominio reservado
        $reserved = ['www', 'app', 'admin', 'api', 'mail', 'ftp', 'cpanel', 'webmail', 'painel', 'sistema', 'login', 'register', 'dashboard'];
        if (in_array($subdomain, $reserved)) {
            $error = 'Este subdominio esta reservado. Escolha outro.';
        } else {
            // Verificar se subdominio ja existe
            $checkSubdomain = $pdo->prepare("SELECT id FROM stores WHERE subdomain = ?");
            $checkSubdomain->execute([$subdomain]);
            if ($checkSubdomain->fetch()) {
                $error = 'Este subdominio ja esta em uso.';
            } else {
                // Verificar se email ja existe
                $checkEmail = $pdo->prepare("SELECT id FROM users WHERE email = ?");
                $checkEmail->execute([$email]);
                if ($checkEmail->fetch()) {
                    $error = 'Este e-mail ja esta cadastrado.';
                } else {
                    // Gerar slug unico para a loja
                    $slug = $subdomain;

                    try {
                        $pdo->beginTransaction();

                        // Criar a loja
                        $insertStore = $pdo->prepare("
                            INSERT INTO stores (name, type, business_type, slug, subdomain, whatsapp_number, email, plan_id, status, trial_ends_at, created_at)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'trial', DATE_ADD(NOW(), INTERVAL 14 DAY), NOW())
                        ");
                        $insertStore->execute([
                            $storeName,
                            $storeType,
                            $businessType,
                            $slug,
                            $subdomain,
                            $phone,
                            $email,
                            $selectedPlanId
                        ]);
                        $storeId = $pdo->lastInsertId();

                        // Criar usuario owner
                        $passwordHash = password_hash($password, PASSWORD_DEFAULT);
                        $insertUser = $pdo->prepare("
                            INSERT INTO users (store_id, name, email, password_hash, phone, role, is_active, created_at)
                            VALUES (?, ?, ?, ?, ?, 'owner', 1, NOW())
                        ");
                        $insertUser->execute([
                            $storeId,
                            $ownerName,
                            $email,
                            $passwordHash,
                            $phone
                        ]);
                        $userId = $pdo->lastInsertId();

                        // Atualizar owner_user_id na loja
                        $updateStore = $pdo->prepare("UPDATE stores SET owner_user_id = ? WHERE id = ?");
                        $updateStore->execute([$userId, $storeId]);

                        $pdo->commit();

                        $storeUrl = 'https://' . $subdomain . '.' . $baseDomain;
                        $success = 'Conta criada com sucesso! Sua loja esta disponivel em: ' . $storeUrl;
                        header("Refresh: 4; url=/pages/login.php?registered=1&email=" . urlencode($email));

                    } catch (Exception $e) {
                        $pdo->rollBack();
                        $error = 'Erro ao criar conta. Tente novamente.';
                    }
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Criar Conta - BarberFlow</title>
<meta name="description" content="Crie sua conta no BarberFlow e comece a gerenciar sua barbearia hoje mesmo.">
<meta name="robots" content="noindex, nofollow">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/iconify-icon@1.0.7/dist/iconify-icon.min.js"></script>
<style>
:root{--gold:#CCA43B;--gold-light:#FFD700;--bg-dark:#0A0A0A;--bg-darker:#050505;--bg-card:#151515;--bg-input:#1A1A1A;--text-primary:#FFF;--text-secondary:#B0B0B0;--text-muted:#707070;--success:#22C55E;--error:#EF4444;--border:rgba(255,255,255,0.1);--gradient-gold:linear-gradient(135deg,#CCA43B 0%,#FFD700 50%,#CCA43B 100%)}
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Inter',sans-serif;background:var(--bg-dark);color:var(--text-primary);line-height:1.6;min-height:100vh}
.register-container{display:flex;min-height:100vh}
.register-left{flex:1;display:flex;flex-direction:column;justify-content:center;padding:3rem;background:linear-gradient(135deg,rgba(204,164,59,0.1) 0%,transparent 50%),var(--bg-darker)}
.register-right{flex:1;display:flex;flex-direction:column;justify-content:center;align-items:center;padding:3rem;background:var(--bg-dark)}
.logo{display:flex;align-items:center;gap:.75rem;font-size:1.75rem;font-weight:800;color:var(--text-primary);text-decoration:none;margin-bottom:2rem}
.logo iconify-icon{color:var(--gold);font-size:2rem}
.register-title{font-size:2.5rem;font-weight:800;margin-bottom:1rem}
.register-title span{background:var(--gradient-gold);-webkit-background-clip:text;-webkit-text-fill-color:transparent}
.register-subtitle{font-size:1.1rem;color:var(--text-secondary);margin-bottom:2rem;max-width:400px}
.features-list{list-style:none}
.features-list li{display:flex;align-items:center;gap:1rem;padding:.75rem 0;color:var(--text-secondary)}
.features-list iconify-icon{color:var(--success);font-size:1.5rem}
.register-form{width:100%;max-width:480px}
.form-header{text-align:center;margin-bottom:2rem}
.form-header h2{font-size:1.75rem;margin-bottom:.5rem}
.form-header p{color:var(--text-muted)}
.plan-selector{display:grid;grid-template-columns:repeat(2,1fr);gap:1rem;margin-bottom:2rem}
.plan-option{background:var(--bg-card);border:2px solid var(--border);border-radius:12px;padding:1rem;cursor:pointer;transition:all .3s;text-align:center}
.plan-option:hover{border-color:rgba(204,164,59,0.5)}
.plan-option.selected{border-color:var(--gold);background:rgba(204,164,59,0.1)}
.plan-option input{display:none}
.plan-name{font-weight:700;margin-bottom:.25rem}
.plan-price{color:var(--gold);font-size:1.25rem;font-weight:800}
.plan-price small{font-size:.75rem;color:var(--text-muted);font-weight:400}
.form-group{margin-bottom:1.25rem}
.form-row{display:grid;grid-template-columns:1fr 1fr;gap:1rem}
.form-label{display:block;margin-bottom:.5rem;font-weight:500;font-size:.9rem}
.form-label span{color:var(--error)}
.form-input{width:100%;padding:.875rem 1rem;background:var(--bg-input);border:1px solid var(--border);border-radius:8px;color:var(--text-primary);font-size:1rem;transition:border-color .2s}
.form-input:focus{outline:none;border-color:var(--gold)}
.form-input::placeholder{color:var(--text-muted)}
.form-select{width:100%;padding:.875rem 1rem;background:var(--bg-input);border:1px solid var(--border);border-radius:8px;color:var(--text-primary);font-size:1rem;cursor:pointer}
.form-select option{background:var(--bg-card);color:var(--text-primary)}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:.5rem;width:100%;padding:1rem;border-radius:8px;font-weight:600;text-decoration:none;transition:all .3s;cursor:pointer;border:none;font-size:1rem}
.btn-primary{background:var(--gradient-gold);color:#000}
.btn-primary:hover{transform:translateY(-2px);box-shadow:0 10px 40px rgba(204,164,59,0.3)}
.btn-primary:disabled{opacity:0.6;cursor:not-allowed;transform:none}
.alert{padding:1rem;border-radius:8px;margin-bottom:1.5rem;display:flex;align-items:center;gap:.75rem}
.alert-error{background:rgba(239,68,68,0.15);border:1px solid rgba(239,68,68,0.3);color:#FCA5A5}
.alert-success{background:rgba(34,197,94,0.15);border:1px solid rgba(34,197,94,0.3);color:#86EFAC}
.form-footer{text-align:center;margin-top:1.5rem;color:var(--text-muted)}
.form-footer a{color:var(--gold);text-decoration:none;font-weight:500}
.form-footer a:hover{text-decoration:underline}
.terms{font-size:.85rem;color:var(--text-muted);text-align:center;margin-top:1rem}
.terms a{color:var(--gold)}

/* Subdomain Input */
.subdomain-wrapper{display:flex;align-items:center;background:var(--bg-input);border:1px solid var(--border);border-radius:8px;overflow:hidden;transition:border-color .2s}
.subdomain-wrapper:focus-within{border-color:var(--gold)}
.subdomain-wrapper input{flex:1;padding:.875rem 1rem;background:transparent;border:none;color:var(--text-primary);font-size:1rem;min-width:0}
.subdomain-wrapper input:focus{outline:none}
.subdomain-suffix{padding:.875rem 1rem;background:var(--bg-card);color:var(--text-muted);font-size:.9rem;white-space:nowrap;border-left:1px solid var(--border)}
.subdomain-status{display:flex;align-items:center;gap:.5rem;margin-top:.5rem;font-size:.85rem;min-height:1.5rem}
.subdomain-status.checking{color:var(--text-muted)}
.subdomain-status.available{color:var(--success)}
.subdomain-status.unavailable{color:var(--error)}
.subdomain-status iconify-icon{font-size:1rem}

/* Business Type Radio Cards */
.business-type-selector{display:grid;grid-template-columns:1fr 1fr;gap:1rem;margin-bottom:1.5rem}
.business-card{background:var(--bg-card);border:2px solid var(--border);border-radius:16px;padding:1.5rem;cursor:pointer;transition:all .3s;text-align:center;position:relative}
.business-card:hover{border-color:rgba(204,164,59,0.5);transform:translateY(-2px)}
.business-card.selected{border-color:var(--gold);background:rgba(204,164,59,0.1)}
.business-card.selected::after{content:'';position:absolute;top:10px;right:10px;width:20px;height:20px;background:var(--gold);border-radius:50%;display:flex;align-items:center;justify-content:center}
.business-card.selected::before{content:'?';position:absolute;top:10px;right:10px;width:20px;height:20px;color:#000;font-size:12px;font-weight:bold;z-index:1;display:flex;align-items:center;justify-content:center}
.business-card input{display:none}
.business-card-icon{width:60px;height:60px;background:var(--bg-input);border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 1rem;font-size:1.75rem;color:var(--gold)}
.business-card.selected .business-card-icon{background:var(--gold);color:#000}
.business-card-title{font-weight:700;font-size:1.1rem;margin-bottom:.5rem}
.business-card-desc{font-size:.85rem;color:var(--text-muted);line-height:1.4}
.business-card-features{margin-top:1rem;text-align:left;font-size:.8rem;color:var(--text-secondary)}
.business-card-features li{display:flex;align-items:center;gap:.5rem;margin:.25rem 0}
.business-card-features iconify-icon{color:var(--success);font-size:.9rem}

@media(max-width:968px){.register-container{flex-direction:column}.register-left{padding:2rem;order:2}.register-right{padding:2rem}.plan-selector{grid-template-columns:1fr}.form-row{grid-template-columns:1fr}}
</style>
</head>
<body>
<div class="register-container">
<div class="register-left">
<a href="/pages/landing.php" class="logo"><iconify-icon icon="solar:scissors-bold"></iconify-icon>BarberFlow</a>
<h1 class="register-title">Comece sua jornada de <span>sucesso</span></h1>
<p class="register-subtitle">Junte-se a mais de 500 barbearias que ja transformaram seus negocios com o BarberFlow.</p>
<ul class="features-list">
<li><iconify-icon icon="solar:check-circle-bold"></iconify-icon>14 dias de teste gratis</li>
<li><iconify-icon icon="solar:check-circle-bold"></iconify-icon>Subdominio personalizado exclusivo</li>
<li><iconify-icon icon="solar:check-circle-bold"></iconify-icon>Configuracao em menos de 5 minutos</li>
<li><iconify-icon icon="solar:check-circle-bold"></iconify-icon>Suporte via WhatsApp</li>
<li><iconify-icon icon="solar:check-circle-bold"></iconify-icon>Cancele quando quiser</li>
</ul>
</div>
<div class="register-right">
<form class="register-form" method="POST" action="" id="registerForm">
<div class="form-header">
<h2>Criar sua conta</h2>
<p>Preencha os dados abaixo para comecar</p>
</div>

<?php if ($error): ?>
<div class="alert alert-error">
<iconify-icon icon="solar:danger-triangle-bold"></iconify-icon>
<?php echo htmlspecialchars($error); ?>
</div>
<?php endif; ?>

<?php if ($success): ?>
<div class="alert alert-success">
<iconify-icon icon="solar:check-circle-bold"></iconify-icon>
<?php echo htmlspecialchars($success); ?>
</div>
<?php endif; ?>

<div class="form-group">
<label class="form-label">Escolha seu plano</label>
<div class="plan-selector">
<?php foreach ($allPlans as $p): ?>
<label class="plan-option <?php echo $p['id'] === $planId ? 'selected' : ''; ?>">
<input type="radio" name="plan_id" value="<?php echo $p['id']; ?>" <?php echo $p['id'] === $planId ? 'checked' : ''; ?>>
<div class="plan-name"><?php echo htmlspecialchars($p['name']); ?></div>
<div class="plan-price">
R$ <?php echo number_format($p['price_monthly'], 0, ',', '.'); ?>
<small>/mes</small>
</div>
</label>
<?php endforeach; ?>
</div>
</div>

<div class="form-group">
<label class="form-label">Qual e o seu tipo de negocio? <span>*</span></label>
<div class="business-type-selector">
<label class="business-card selected" data-type="service">
<input type="radio" name="business_type" value="service" checked>
<input type="hidden" name="store_type" value="barbershop" class="store-type-input">
<div class="business-card-icon">
<iconify-icon icon="solar:scissors-bold"></iconify-icon>
</div>
<div class="business-card-title">Barbearia / Salao</div>
<div class="business-card-desc">Foco em agendamentos e servicos</div>
<ul class="business-card-features">
<li><iconify-icon icon="solar:check-circle-bold"></iconify-icon> Agenda online</li>
<li><iconify-icon icon="solar:check-circle-bold"></iconify-icon> Gestao de profissionais</li>
<li><iconify-icon icon="solar:check-circle-bold"></iconify-icon> Servicos e precos</li>
</ul>
</label>
<label class="business-card" data-type="retail">
<input type="radio" name="business_type" value="retail">
<input type="hidden" name="store_type" value="clothing_store" class="store-type-input">
<div class="business-card-icon">
<iconify-icon icon="solar:bag-bold"></iconify-icon>
</div>
<div class="business-card-title">Loja / Varejo</div>
<div class="business-card-desc">Foco em produtos e catalogo</div>
<ul class="business-card-features">
<li><iconify-icon icon="solar:check-circle-bold"></iconify-icon> Catalogo de produtos</li>
<li><iconify-icon icon="solar:check-circle-bold"></iconify-icon> Controle de estoque</li>
<li><iconify-icon icon="solar:check-circle-bold"></iconify-icon> Gestao de pedidos</li>
</ul>
</label>
</div>
</div>

<div class="form-group">
<label class="form-label">Nome do seu negocio <span>*</span></label>
<input type="text" name="store_name" id="storeName" class="form-input" placeholder="Ex: Barbearia do Joao" required value="<?php echo htmlspecialchars($_POST['store_name'] ?? ''); ?>">
</div>

<div class="form-group">
<label class="form-label">Escolha seu subdominio <span>*</span></label>
<div class="subdomain-wrapper">
<input type="text" name="subdomain" id="subdomain" placeholder="suabarbearia" required maxlength="30" value="<?php echo htmlspecialchars($_POST['subdomain'] ?? ''); ?>">
<span class="subdomain-suffix">.<?php echo $baseDomain; ?></span>
</div>
<div class="subdomain-status" id="subdomainStatus"></div>
</div>

<div class="form-row">
<div class="form-group">
<label class="form-label">Seu nome <span>*</span></label>
<input type="text" name="owner_name" class="form-input" placeholder="Nome completo" required value="<?php echo htmlspecialchars($_POST['owner_name'] ?? ''); ?>">
</div>
<div class="form-group">
<label class="form-label">WhatsApp</label>
<input type="tel" name="phone" class="form-input" placeholder="(00) 00000-0000" value="<?php echo htmlspecialchars($_POST['phone'] ?? ''); ?>">
</div>
</div>

<div class="form-group">
<label class="form-label">E-mail <span>*</span></label>
<input type="email" name="email" class="form-input" placeholder="seu@email.com" required value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
</div>

<div class="form-row">
<div class="form-group">
<label class="form-label">Senha <span>*</span></label>
<input type="password" name="password" class="form-input" placeholder="Minimo 6 caracteres" required minlength="6">
</div>
<div class="form-group">
<label class="form-label">Confirmar senha <span>*</span></label>
<input type="password" name="confirm_password" class="form-input" placeholder="Repita a senha" required>
</div>
</div>

<button type="submit" class="btn btn-primary" id="submitBtn">
<iconify-icon icon="solar:rocket-bold"></iconify-icon>
Criar minha conta gratis
</button>

<p class="terms">Ao criar sua conta, voce concorda com nossos <a href="#">Termos de Uso</a> e <a href="#">Politica de Privacidade</a>.</p>

<p class="form-footer">Ja tem uma conta? <a href="/pages/login.php">Fazer login</a></p>
</form>
</div>
</div>
<script>
// Business Type Cards
document.querySelectorAll('.business-card').forEach(card => {
    card.addEventListener('click', function() {
        document.querySelectorAll('.business-card').forEach(c => c.classList.remove('selected'));
        this.classList.add('selected');
        this.querySelector('input[type="radio"]').checked = true;
    });
});

document.querySelectorAll('.plan-option').forEach(option => {
    option.addEventListener('click', function() {
        document.querySelectorAll('.plan-option').forEach(o => o.classList.remove('selected'));
        this.classList.add('selected');
    });
});

// Subdomain handling
const subdomainInput = document.getElementById('subdomain');
const storeNameInput = document.getElementById('storeName');
const statusEl = document.getElementById('subdomainStatus');
const submitBtn = document.getElementById('submitBtn');
let checkTimeout;
let subdomainValid = false;

function sanitizeSubdomain(text) {
    return text.toLowerCase()
        .normalize('NFD').replace(/[\u0300-\u036f]/g, '')
        .replace(/[^a-z0-9]/g, '')
        .substring(0, 30);
}

function checkSubdomain(subdomain) {
    if (subdomain.length < 3) {
        statusEl.className = 'subdomain-status unavailable';
        statusEl.innerHTML = '<iconify-icon icon="solar:close-circle-bold"></iconify-icon> Minimo 3 caracteres';
        subdomainValid = false;
        return;
    }
    
    statusEl.className = 'subdomain-status checking';
    statusEl.innerHTML = '<iconify-icon icon="solar:refresh-bold"></iconify-icon> Verificando...';
    
    fetch('?check_subdomain=' + encodeURIComponent(subdomain))
        .then(r => r.json())
        .then(data => {
            if (data.available) {
                statusEl.className = 'subdomain-status available';
                statusEl.innerHTML = '<iconify-icon icon="solar:check-circle-bold"></iconify-icon> ' + data.message + ' - ' + data.url;
                subdomainValid = true;
            } else {
                statusEl.className = 'subdomain-status unavailable';
                statusEl.innerHTML = '<iconify-icon icon="solar:close-circle-bold"></iconify-icon> ' + data.message;
                subdomainValid = false;
            }
        })
        .catch(() => {
            statusEl.className = 'subdomain-status';
            statusEl.innerHTML = '';
            subdomainValid = true;
        });
}

subdomainInput.addEventListener('input', function() {
    this.value = sanitizeSubdomain(this.value);
    clearTimeout(checkTimeout);
    checkTimeout = setTimeout(() => checkSubdomain(this.value), 500);
});

// Auto-generate subdomain from store name
storeNameInput.addEventListener('input', function() {
    if (!subdomainInput.dataset.userEdited) {
        const suggested = sanitizeSubdomain(this.value);
        if (suggested.length >= 3) {
            subdomainInput.value = suggested;
            clearTimeout(checkTimeout);
            checkTimeout = setTimeout(() => checkSubdomain(suggested), 500);
        }
    }
});

subdomainInput.addEventListener('focus', function() {
    this.dataset.userEdited = 'true';
});

document.getElementById('registerForm').addEventListener('submit', function(e) {
    if (!subdomainValid && subdomainInput.value.length >= 3) {
        e.preventDefault();
        alert('Aguarde a verificacao do subdominio ou escolha outro.');
    }
});
</script>
</body>
</html>
