<?php
/**
 * Página de Registro - MontaLoja
 * Formulário de cadastro de novos clientes
 */

// Carregar configurações da loja (inclui $store, $pdo, $headerSettings, $menuItems, etc.)
require_once __DIR__ . '/includes/store-config.php';

// Verificar se já está logado
if (isCustomerLoggedIn()) {
    header("Location: " . storeUrl());
    exit;
}

$error = '';
$success = '';

// Processar registro
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'register') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    
    // Validações
    if (empty($name) || empty($email) || empty($password)) {
        $error = 'Preencha todos os campos obrigatórios.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Email inválido.';
    } elseif (strlen($password) < 6) {
        $error = 'A senha deve ter pelo menos 6 caracteres.';
    } elseif ($password !== $confirmPassword) {
        $error = 'As senhas não coincidem.';
    } else {
        try {
            // Verificar se email já existe para esta loja
            $checkStmt = $pdo->prepare("SELECT id FROM customers WHERE store_id = ? AND email = ?");
            $checkStmt->execute([$currentStoreId, $email]);
            
            if ($checkStmt->fetch()) {
                $error = 'Este email já está cadastrado. <a href="' . storeUrl('entrar') . '">Fazer login</a>';
            } else {
                // Criar novo cliente
                $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                $insertStmt = $pdo->prepare("INSERT INTO customers (store_id, name, email, phone, password, is_active, created_at) VALUES (?, ?, ?, ?, ?, 1, NOW())");
                $insertStmt->execute([$currentStoreId, $name, $email, $phone ?: '', $hashedPassword]);
                
                // Login automático após registro
                $customerId = $pdo->lastInsertId();
                
                $_SESSION['customer_id'] = $customerId;
                $_SESSION['customer_name'] = $name;
                $_SESSION['customer_email'] = $email;
                $_SESSION['customer_store_id'] = $currentStoreId;
                
                // Redirecionar para a loja com mensagem de sucesso
                header("Location: " . storeUrl() . "?registered=1");
                exit;
            }
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
                $error = 'Este email já está cadastrado.';
            } else {
                $error = 'Erro ao criar conta. Tente novamente.';
                // Log error in production
                error_log("Customer registration error: " . $e->getMessage());
            }
        }
    }
}
?>
<!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 - <?php echo htmlspecialchars($storeName); ?></title>
<meta name="description" content="Crie sua conta em <?php echo htmlspecialchars($storeName); ?>">
<meta name="theme-color" content="#ffffff">
<?php if (!empty($faviconUrl)): ?>
<link rel="icon" type="image/x-icon" href="<?php echo htmlspecialchars($faviconUrl); ?>">
<link rel="shortcut icon" href="<?php echo htmlspecialchars($faviconUrl); ?>">
<?php endif; ?>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans: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>
<link rel="stylesheet" href="/pages/storefront/templates/retail/modern/includes/styles.css?v=1.0.4">
<?php include __DIR__ . "/includes/dynamic-styles.php"; ?>
<style>
/* Dynamic Color Variables from Store Settings */
:root {
    --primary: <?php echo htmlspecialchars($primaryColor ?? '#2563EB'); ?>;
    --primary-soft: <?php echo htmlspecialchars($primaryColor ?? '#2563EB'); ?>14;
    --primary-hover: <?php echo htmlspecialchars($customSettings['colors']['secondary'] ?? $primaryColor ?? '#1D4ED8'); ?>;
    --accent: <?php echo htmlspecialchars($accentColor ?? '#10B981'); ?>;
    --accent-soft: <?php echo htmlspecialchars($accentColor ?? '#10B981'); ?>1A;
    --bg: <?php echo htmlspecialchars($bgColor ?? '#FAFBFC'); ?>;
    --bg-white: <?php echo htmlspecialchars($cardColor ?? '#FFFFFF'); ?>;
    --surface: <?php echo htmlspecialchars($cardColor ?? '#FFFFFF'); ?>;
    --text: <?php echo htmlspecialchars($textColor ?? '#111827'); ?>;
    --text-secondary: <?php echo htmlspecialchars($textSecondary ?? '#6B7280'); ?>;
}

/* Estilos específicos da página de registro */
.main-content {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top: 24px;
    padding-bottom: 40px;
}

.auth-container {
    width: 100%;
    max-width: 480px;
}

.auth-card {
    background: var(--surface);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border);
    padding: 40px;
    box-shadow: var(--shadow);
}

.auth-header {
    text-align: center;
    margin-bottom: 32px;
}

.auth-icon {
    width: 64px;
    height: 64px;
    border-radius: 50%;
    background: var(--accent-soft);
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 16px;
    color: var(--accent);
}

.auth-title {
    font-size: 1.75rem;
    font-weight: 800;
    color: var(--text);
    margin-bottom: 8px;
}

.auth-subtitle {
    color: var(--text-secondary);
    font-size: 0.95rem;
}

/* Form Styles */
.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
}

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

.form-group.full-width {
    grid-column: 1 / -1;
}

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

.form-label .optional {
    color: var(--muted);
    font-weight: 400;
    font-size: 0.85rem;
}

.form-input {
    width: 100%;
    height: 52px;
    padding: 0 16px;
    border: 1px solid var(--border);
    border-radius: var(--radius);
    background: var(--bg);
    font-size: 1rem;
    color: var(--text);
    transition: all 0.2s;
    font-family: inherit;
    box-sizing: border-box;
}

.form-input:focus {
    outline: none;
    border-color: var(--primary);
    background: var(--surface);
    box-shadow: 0 0 0 3px var(--primary-soft);
}

.form-input::placeholder {
    color: var(--muted);
}

.input-wrapper {
    position: relative;
}

.input-wrapper .input-icon {
    position: absolute;
    left: 16px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--muted);
    font-size: 1.2rem;
}

.input-wrapper .form-input {
    padding-left: 48px;
}

.input-wrapper .toggle-password {
    position: absolute;
    right: 16px;
    top: 50%;
    transform: translateY(-50%);
    background: none;
    border: none;
    color: var(--muted);
    cursor: pointer;
    padding: 4px;
}

.input-wrapper .toggle-password:hover {
    color: var(--text);
}

/* Password Strength */
.password-strength {
    margin-top: 8px;
}

.strength-bar {
    height: 4px;
    background: var(--border);
    border-radius: 2px;
    overflow: hidden;
    margin-bottom: 6px;
}

.strength-bar-fill {
    height: 100%;
    width: 0%;
    transition: all 0.3s;
    border-radius: 2px;
}

.strength-bar-fill.weak { width: 25%; background: var(--danger); }
.strength-bar-fill.fair { width: 50%; background: #F59E0B; }
.strength-bar-fill.good { width: 75%; background: #10B981; }
.strength-bar-fill.strong { width: 100%; background: #059669; }

.strength-text {
    font-size: 0.8rem;
    color: var(--muted);
}

/* Terms */
.terms-wrapper {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    margin-bottom: 24px;
}

.terms-wrapper input {
    width: 18px;
    height: 18px;
    accent-color: var(--primary);
    margin-top: 2px;
    flex-shrink: 0;
}

.terms-wrapper label {
    font-size: 0.9rem;
    color: var(--text-secondary);
    line-height: 1.5;
}

.terms-wrapper a {
    color: var(--primary);
    text-decoration: none;
}

.terms-wrapper a:hover {
    text-decoration: underline;
}

.btn-submit {
    width: 100%;
    height: 52px;
    background: var(--accent);
    color: white;
    border: none;
    border-radius: var(--radius);
    font-weight: 700;
    font-size: 1rem;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    font-family: inherit;
}

.btn-submit:hover {
    background: #059669;
    transform: translateY(-2px);
    box-shadow: var(--shadow-lg);
}

.btn-submit:active {
    transform: translateY(0);
}

.btn-submit:disabled {
    opacity: 0.7;
    cursor: not-allowed;
    transform: none;
}

/* Divider */
.divider {
    display: flex;
    align-items: center;
    gap: 16px;
    margin: 28px 0;
}

.divider::before,
.divider::after {
    content: '';
    flex: 1;
    height: 1px;
    background: var(--border);
}

.divider span {
    color: var(--muted);
    font-size: 0.85rem;
}

/* Social Login */
.social-buttons {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.btn-social {
    width: 100%;
    height: 52px;
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    font-weight: 600;
    font-size: 0.95rem;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    font-family: inherit;
    color: var(--text);
    text-decoration: none;
}

.btn-social:hover {
    background: var(--surface-hover);
    border-color: var(--primary);
}

.btn-social iconify-icon {
    font-size: 1.3rem;
}

/* Login link */
.login-link {
    text-align: center;
    margin-top: 28px;
    color: var(--text-secondary);
    font-size: 0.95rem;
}

.login-link a {
    color: var(--primary);
    text-decoration: none;
    font-weight: 600;
}

.login-link a:hover {
    text-decoration: underline;
}

/* Alert Messages */
.alert {
    padding: 14px 16px;
    border-radius: var(--radius);
    margin-bottom: 24px;
    font-size: 0.9rem;
    display: flex;
    align-items: center;
    gap: 10px;
}

.alert a {
    color: inherit;
    font-weight: 600;
}

.alert-error {
    background: var(--danger-soft);
    color: var(--danger);
    border: 1px solid rgba(239, 68, 68, 0.2);
}

.alert-success {
    background: var(--accent-soft);
    color: var(--accent);
    border: 1px solid rgba(16, 185, 129, 0.2);
}

/* Benefits */
.benefits {
    display: flex;
    flex-direction: column;
    gap: 12px;
    margin-top: 32px;
    padding-top: 24px;
    border-top: 1px solid var(--border);
}

.benefits-title {
    font-weight: 700;
    font-size: 0.9rem;
    color: var(--text);
    margin-bottom: 4px;
}

.benefit-item {
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 0.9rem;
    color: var(--text-secondary);
}

.benefit-item iconify-icon {
    color: var(--accent);
    font-size: 1.2rem;
    flex-shrink: 0;
}

/* Back to store */
.back-link {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 24px;
    color: var(--text-secondary);
    text-decoration: none;
    font-size: 0.9rem;
    transition: color 0.2s;
}

.back-link:hover {
    color: var(--primary);
}

/* Responsive */
@media (max-width: 768px) {
    .auth-card {
        padding: 28px 20px;
    }
    
    .auth-title {
        font-size: 1.5rem;
    }
    
    .form-row {
        grid-template-columns: 1fr;
    }
}
</style>
</head>
<body>

<?php include __DIR__ . '/../../../includes/cart.php'; ?>

<?php include __DIR__ . '/includes/header.php'; ?>

<!-- Main Content -->
<main class="main-content">
    <div class="auth-container">
        <a href="<?php echo storeUrl(); ?>" class="back-link">
            <iconify-icon icon="solar:arrow-left-linear" width="20"></iconify-icon>
            Voltar para a loja
        </a>
        
        <div class="auth-card">
            <div class="auth-header">
                <div class="auth-icon">
                    <iconify-icon icon="solar:user-plus-bold" width="32"></iconify-icon>
                </div>
                <h1 class="auth-title">Criar sua conta</h1>
                <p class="auth-subtitle">Cadastre-se para uma experiência personalizada</p>
            </div>
            
            <?php if ($error): ?>
            <div class="alert alert-error">
                <iconify-icon icon="solar:danger-triangle-bold" width="20"></iconify-icon>
                <span><?php echo $error; ?></span>
            </div>
            <?php endif; ?>
            
            <?php if ($success): ?>
            <div class="alert alert-success">
                <iconify-icon icon="solar:check-circle-bold" width="20"></iconify-icon>
                <?php echo htmlspecialchars($success); ?>
            </div>
            <?php endif; ?>
            
            <form method="POST" action="" id="registerForm">
                <input type="hidden" name="action" value="register">
                
                <div class="form-group">
                    <label class="form-label">Nome completo</label>
                    <div class="input-wrapper">
                        <iconify-icon icon="solar:user-bold" class="input-icon"></iconify-icon>
                        <input type="text" name="name" class="form-input" placeholder="Seu nome" required 
                               value="<?php echo htmlspecialchars($_POST['name'] ?? ''); ?>">
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Email</label>
                    <div class="input-wrapper">
                        <iconify-icon icon="solar:letter-bold" class="input-icon"></iconify-icon>
                        <input type="email" name="email" class="form-input" placeholder="seu@email.com" required
                               value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Telefone <span class="optional">(opcional)</span></label>
                    <div class="input-wrapper">
                        <iconify-icon icon="solar:phone-bold" class="input-icon"></iconify-icon>
                        <input type="tel" name="phone" class="form-input" placeholder="(00) 00000-0000" id="phoneInput"
                               value="<?php echo htmlspecialchars($_POST['phone'] ?? ''); ?>">
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Senha</label>
                    <div class="input-wrapper">
                        <iconify-icon icon="solar:lock-bold" class="input-icon"></iconify-icon>
                        <input type="password" name="password" id="password" class="form-input" placeholder="Mínimo 6 caracteres" required minlength="6">
                        <button type="button" class="toggle-password" onclick="togglePassword('password', 'eye-icon-1')">
                            <iconify-icon icon="solar:eye-bold" id="eye-icon-1" width="20"></iconify-icon>
                        </button>
                    </div>
                    <div class="password-strength">
                        <div class="strength-bar">
                            <div class="strength-bar-fill" id="strengthBar"></div>
                        </div>
                        <span class="strength-text" id="strengthText"></span>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Confirmar senha</label>
                    <div class="input-wrapper">
                        <iconify-icon icon="solar:lock-bold" class="input-icon"></iconify-icon>
                        <input type="password" name="confirm_password" id="confirmPassword" class="form-input" placeholder="Digite a senha novamente" required>
                        <button type="button" class="toggle-password" onclick="togglePassword('confirmPassword', 'eye-icon-2')">
                            <iconify-icon icon="solar:eye-bold" id="eye-icon-2" width="20"></iconify-icon>
                        </button>
                    </div>
                    <div id="passwordMatch" style="font-size: 0.8rem; margin-top: 6px;"></div>
                </div>
                
                <div class="terms-wrapper">
                    <input type="checkbox" id="terms" name="terms" required>
                    <label for="terms">
                        Concordo com os <a href="#">Termos de Uso</a> e a <a href="#">Política de Privacidade</a>
                    </label>
                </div>
                
                <button type="submit" class="btn-submit" id="submitBtn">
                    <iconify-icon icon="solar:user-plus-bold" width="22"></iconify-icon>
                    Criar minha conta
                </button>
            </form>
            
            <div class="divider">
                <span>ou cadastre-se com</span>
            </div>
            
            <div class="social-buttons">
                <button type="button" class="btn-social" onclick="registerWithGoogle()">
                    <iconify-icon icon="logos:google-icon"></iconify-icon>
                    Google
                </button>
            </div>
            
            <p class="login-link">
                Já tem uma conta? <a href="<?php echo storeUrl('entrar'); ?>">Fazer login</a>
            </p>
            
            <div class="benefits">
                <span class="benefits-title">Benefícios de ter uma conta:</span>
                <div class="benefit-item">
                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                    Acompanhe seus pedidos
                </div>
                <div class="benefit-item">
                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                    Salve seus produtos favoritos
                </div>
                <div class="benefit-item">
                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                    Checkout mais rápido
                </div>
                <div class="benefit-item">
                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                    Ofertas exclusivas
                </div>
            </div>
        </div>
    </div>
</main>

<?php include __DIR__ . '/includes/footer.php'; ?>

<script>
function togglePassword(inputId, iconId) {
    const passwordInput = document.getElementById(inputId);
    const eyeIcon = document.getElementById(iconId);
    
    if (passwordInput.type === 'password') {
        passwordInput.type = 'text';
        eyeIcon.setAttribute('icon', 'solar:eye-closed-bold');
    } else {
        passwordInput.type = 'password';
        eyeIcon.setAttribute('icon', 'solar:eye-bold');
    }
}

// Password strength checker
document.getElementById('password').addEventListener('input', function(e) {
    const password = e.target.value;
    const strengthBar = document.getElementById('strengthBar');
    const strengthText = document.getElementById('strengthText');
    
    let strength = 0;
    let text = '';
    
    if (password.length >= 6) strength++;
    if (password.length >= 8) strength++;
    if (/[A-Z]/.test(password)) strength++;
    if (/[0-9]/.test(password)) strength++;
    if (/[^A-Za-z0-9]/.test(password)) strength++;
    
    strengthBar.className = 'strength-bar-fill';
    
    if (password.length === 0) {
        strengthText.textContent = '';
    } else if (strength <= 1) {
        strengthBar.classList.add('weak');
        text = 'Fraca';
    } else if (strength <= 2) {
        strengthBar.classList.add('fair');
        text = 'Regular';
    } else if (strength <= 3) {
        strengthBar.classList.add('good');
        text = 'Boa';
    } else {
        strengthBar.classList.add('strong');
        text = 'Forte';
    }
    
    strengthText.textContent = text;
    checkPasswordMatch();
});

// Password match checker
document.getElementById('confirmPassword').addEventListener('input', checkPasswordMatch);

function checkPasswordMatch() {
    const password = document.getElementById('password').value;
    const confirm = document.getElementById('confirmPassword').value;
    const matchDiv = document.getElementById('passwordMatch');
    
    if (confirm.length === 0) {
        matchDiv.textContent = '';
        matchDiv.style.color = '';
    } else if (password === confirm) {
        matchDiv.textContent = '✓ Senhas coincidem';
        matchDiv.style.color = '#10B981';
    } else {
        matchDiv.textContent = '✗ Senhas não coincidem';
        matchDiv.style.color = '#EF4444';
    }
}

// Phone mask
document.getElementById('phoneInput').addEventListener('input', function(e) {
    let value = e.target.value.replace(/\D/g, '');
    
    if (value.length <= 11) {
        if (value.length > 6) {
            value = `(${value.slice(0,2)}) ${value.slice(2,7)}-${value.slice(7)}`;
        } else if (value.length > 2) {
            value = `(${value.slice(0,2)}) ${value.slice(2)}`;
        } else if (value.length > 0) {
            value = `(${value}`;
        }
    }
    
    e.target.value = value;
});

// Form validation
document.getElementById('registerForm').addEventListener('submit', function(e) {
    const password = document.getElementById('password').value;
    const confirm = document.getElementById('confirmPassword').value;
    
    if (password !== confirm) {
        e.preventDefault();
        alert('As senhas não coincidem!');
        return false;
    }
    
    // Disable button to prevent double submit
    document.getElementById('submitBtn').disabled = true;
    document.getElementById('submitBtn').innerHTML = '<iconify-icon icon="solar:refresh-bold" width="22" class="spin"></iconify-icon> Criando conta...';
});

function registerWithGoogle() {
    // Implementar OAuth do Google
    alert('Cadastro com Google em breve!');
}
</script>

<style>
.spin {
    animation: spin 1s linear infinite;
}
@keyframes spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}
</style>

</body>
</html>
