<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/middleware.php';
require_once __DIR__ . '/includes/auth.php';

if (!isset($pdo)) {
    $pdo = require_once __DIR__ . '/config/database.php';
}

require_guest();

$errors = [];
if (is_post()) {
    ensure_csrf();
    $full_name = sanitize_str($_POST['full_name'] ?? '');
    $email = sanitize_str($_POST['email'] ?? '');
    $phone = sanitize_str($_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $business_type = sanitize_str($_POST['business_type'] ?? '');
    
    // Enhanced validation
    if (empty($full_name)) {
        $errors[] = 'Full name is required';
    } elseif (strlen($full_name) < 3) {
        $errors[] = 'Full name must be at least 3 characters';
    }
    
    if (empty($email)) {
        $errors[] = 'Email is required';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please enter a valid email address';
    }
    
    if (empty($phone)) {
        $errors[] = 'Phone number is required';
    } elseif (!preg_match('/^(\+234|0)?[789][01]\d{8}$/', $phone)) {
        $errors[] = 'Please enter a valid Nigerian phone number';
    }
    
    if (empty($password)) {
        $errors[] = 'Password is required';
    } elseif (strlen($password) < 8) {
        $errors[] = 'Password must be at least 8 characters';
    } elseif (!preg_match('/[A-Z]/', $password)) {
        $errors[] = 'Password must contain at least one uppercase letter';
    } elseif (!preg_match('/[a-z]/', $password)) {
        $errors[] = 'Password must contain at least one lowercase letter';
    } elseif (!preg_match('/[0-9]/', $password)) {
        $errors[] = 'Password must contain at least one number';
    }
    
    if ($password !== $confirm_password) {
        $errors[] = 'Passwords do not match';
    }
    
    if (empty($business_type)) {
        $errors[] = 'Please select your business type';
    }
    
    if (empty($errors)) {
        $errors = register_customer($pdo, $full_name, $email, $phone, $password);
        if (empty($errors)) {
            // Store business type for later use
            $stmt = $pdo->prepare("UPDATE users SET business_type=? WHERE email=?");
            $stmt->execute([$business_type, $email]);
            
            $verifyEnabled = get_setting($pdo, 'email_verification_enabled', false);
            if ($verifyEnabled) {
                set_flash('success', 'Registration successful! Please check your email to verify your account.');
                redirect(url('login.php'));
            } else {
                // Auto-login
                attempt_login($pdo, $email, $password);
                set_flash('success', 'Welcome to Go Legal! Your account has been created.');
                
                $redirect = $_POST['redirect'] ?? $_GET['redirect'] ?? 'customer/dashboard.php';
                redirect(url($redirect));
            }
        }
    }
}

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

<style>
.register-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 40px 20px;
}

.register-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 40px;
    align-items: start;
}

.register-card {
    background: #fff;
    border: 1px solid var(--border);
    border-radius: 20px;
    padding: 40px;
    box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1);
}

.register-header {
    margin-bottom: 32px;
}

.register-title {
    font-size: 32px;
    font-weight: 800;
    color: var(--text);
    margin: 0 0 8px;
}

.register-subtitle {
    font-size: 16px;
    color: var(--muted);
    margin: 0;
    line-height: 1.6;
}

.form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-bottom: 20px;
}

.form-group {
    display: flex;
    flex-direction: column;
    margin-bottom: 20px;
}

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

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

.form-input {
    padding: 14px 16px;
    border: 1px solid var(--border);
    border-radius: 10px;
    font-size: 15px;
    transition: all 0.2s;
}

.form-input:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
}

.form-select {
    padding: 14px 16px;
    border: 1px solid var(--border);
    border-radius: 10px;
    font-size: 15px;
    background: #fff;
    cursor: pointer;
    transition: all 0.2s;
}

.form-select:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
}

.password-requirements {
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 10px;
    padding: 16px;
    margin-top: 8px;
}

.requirement-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.requirement-item {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 6px;
    font-size: 13px;
    color: #6b7280;
}

.requirement-item.met {
    color: #16a34a;
}

.requirement-icon {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 10px;
    font-weight: bold;
}

.requirement-item.met .requirement-icon {
    background: #dcfce7;
    color: #16a34a;
}

.requirement-item:not(.met) .requirement-icon {
    background: #f3f4f6;
    color: #9ca3af;
}

.btn-register {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
    border: none;
    padding: 16px 24px;
    border-radius: 10px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    width: 100%;
}

.btn-register:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 20px -5px rgba(16, 185, 129, 0.3);
}

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

.benefits-section {
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border-radius: 20px;
    padding: 40px;
}

.benefits-title {
    font-size: 24px;
    font-weight: 700;
    color: var(--text);
    margin: 0 0 24px;
}

.benefit-item {
    display: flex;
    align-items: start;
    gap: 16px;
    margin-bottom: 24px;
}

.benefit-icon {
    width: 48px;
    height: 48px;
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 20px;
    flex-shrink: 0;
}

.benefit-content h3 {
    margin: 0 0 8px;
    font-size: 18px;
    font-weight: 600;
    color: var(--text);
}

.benefit-content p {
    margin: 0;
    font-size: 14px;
    color: var(--muted);
    line-height: 1.6;
}

.trust-badges {
    display: flex;
    gap: 16px;
    margin-top: 32px;
    padding-top: 24px;
    border-top: 1px solid var(--border);
}

.trust-badge {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 13px;
    color: var(--muted);
}

.trust-badge-icon {
    color: #10b981;
}

@media (max-width: 768px) {
    .register-grid {
        grid-template-columns: 1fr;
        gap: 30px;
    }
    
    .form-grid {
        grid-template-columns: 1fr;
    }
    
    .register-card,
    .benefits-section {
        padding: 30px 20px;
    }
    
    .register-title {
        font-size: 28px;
    }
}
</style>

<div class="register-container">
    <div class="register-grid">
        <!-- Registration Form -->
        <div class="register-card">
            <div class="register-header">
                <h1 class="register-title">Start Your Journey</h1>
                <p class="register-subtitle">You're one step away from making your business official. Join over 200+ founders who chose the stress-free path to CAC registration.</p>
            </div>
            
            <?php if (!empty($errors)): ?>
                <div class="alert alert-error" style="margin-bottom: 24px;">
                    <?php foreach ($errors as $error): ?>
                        <div style="margin-bottom: 8px;"><?=e($error)?></div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            
            <form method="post" action="<?=url('register.php') . (isset($_GET['redirect']) ? '?redirect=' . urlencode($_GET['redirect']) : '')?>" id="registerForm">
                <?=csrf_field()?>
                <?php if (isset($_GET['redirect'])): ?>
                    <input type="hidden" name="redirect" value="<?=e($_GET['redirect'])?>">
                <?php endif; ?>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label for="full_name" class="form-label">Full Legal Name *</label>
                        <input 
                            type="text" 
                            id="full_name" 
                            name="full_name" 
                            class="form-input" 
                            placeholder="Enter your full legal name"
                            required
                            minlength="3"
                        >
                    </div>
                    
                    <div class="form-group">
                        <label for="business_type" class="form-label">Business Type *</label>
                        <select id="business_type" name="business_type" class="form-select" required>
                            <option value="">Select business type</option>
                            <option value="startup">Startup / Tech Company</option>
                            <option value="small_business">Small Business</option>
                            <option value="enterprise">Enterprise / Corporation</option>
                            <option value="ngo">Non-Profit / NGO</option>
                            <option value="freelance">Freelancer / Consultant</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="email" class="form-label">Email Address *</label>
                        <input 
                            type="email" 
                            id="email" 
                            name="email" 
                            class="form-input" 
                            placeholder="your@email.com"
                            required
                        >
                    </div>
                    
                    <div class="form-group">
                        <label for="phone" class="form-label">Phone Number *</label>
                        <input 
                            type="tel" 
                            id="phone" 
                            name="phone" 
                            class="form-input" 
                            placeholder="+234XXXXXXXXXX or 0XXXXXXXXXX"
                            required
                            pattern="(\+234|0)?[789][01]\d{8}"
                        >
                    </div>
                    
                    <div class="form-group">
                        <label for="password" class="form-label">Password *</label>
                        <input 
                            type="password" 
                            id="password" 
                            name="password" 
                            class="form-input" 
                            placeholder="Create a strong password"
                            required
                            minlength="8"
                        >
                        <div class="password-requirements">
                            <ul class="requirement-list">
                                <li class="requirement-item" id="req-length">
                                    <span class="requirement-icon">○</span>
                                    At least 8 characters
                                </li>
                                <li class="requirement-item" id="req-uppercase">
                                    <span class="requirement-icon">○</span>
                                    One uppercase letter
                                </li>
                                <li class="requirement-item" id="req-lowercase">
                                    <span class="requirement-icon">○</span>
                                    One lowercase letter
                                </li>
                                <li class="requirement-item" id="req-number">
                                    <span class="requirement-icon">○</span>
                                    One number
                                </li>
                                <li class="requirement-item" id="req-match">
                                    <span class="requirement-icon">○</span>
                                    Passwords match
                                </li>
                            </ul>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="confirm_password" class="form-label">Confirm Password *</label>
                        <input 
                            type="password" 
                            id="confirm_password" 
                            name="confirm_password" 
                            class="form-input" 
                            placeholder="Re-enter your password"
                            required
                            minlength="8"
                        >
                    </div>
                </div>
                
                <button type="submit" class="btn-register">
                    Create Account
                </button>
                
                <div style="text-align: center; margin-top: 20px;">
                    <span style="color: var(--muted); font-size: 14px;">Already have an account?</span>
                    <a href="<?=url('login.php')?>" style="color: var(--primary); text-decoration: none; font-weight: 600; margin-left: 4px;">Sign In</a>
                </div>
            </form>
        </div>
        
        <!-- Benefits Section -->
        <div class="benefits-section">
            <h2 class="benefits-title">Why entrepreneurs love Go Legal</h2>
            
            <div class="benefit-item">
                <div class="benefit-icon"><?=ui_icon('start',20)?></div>
                <div class="benefit-content">
                    <h3>Fast & Efficient</h3>
                    <p>We've optimized every step to ensure your CAC registration moves as quickly as possible. No delays, no excuses.</p>
                </div>
            </div>
            
            <div class="benefit-item">
                <div class="benefit-icon"><?=ui_icon('approved',20)?></div>
                <div class="benefit-content">
                    <h3>Accuracy Guaranteed</h3>
                    <p>Our experts review your application before filing to prevent rejections and save you from unnecessary extra costs.</p>
                </div>
            </div>
            
            <div class="benefit-item">
                <div class="benefit-icon"><?=ui_icon('processing',20)?></div>
                <div class="benefit-content">
                    <h3>Total Transparency</h3>
                    <p>Track your application status in real-time. You'll never have to guess where your documents are or what happens next.</p>
                </div>
            </div>
            
            <div class="benefit-item">
                <div class="benefit-icon"><?=ui_icon('users',20)?></div>
                <div class="benefit-content">
                    <h3>Expert Support</h3>
                    <p>Got questions? Our team of compliance experts is here to guide you through the entire process, start to finish.</p>
                </div>
            </div>
            
            <div class="trust-badges">
                <div class="trust-badge">
                    <span class="trust-badge-icon">✓</span>
                    <span>200+ Businesses</span>
                </div>
                <div class="trust-badge">
                    <span class="trust-badge-icon">✓</span>
                    <span>No Hidden Fees</span>
                </div>
                <div class="trust-badge">
                    <span class="trust-badge-icon">✓</span>
                    <span>Expert Filing</span>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const passwordInput = document.getElementById('password');
    const confirmPasswordInput = document.getElementById('confirm_password');
    
    // Password requirements
    const requirements = {
        length: document.getElementById('req-length'),
        uppercase: document.getElementById('req-uppercase'),
        lowercase: document.getElementById('req-lowercase'),
        number: document.getElementById('req-number'),
        match: document.getElementById('req-match')
    };
    
    function updateRequirements(password, confirmPassword) {
        // Length
        if (password.length >= 8) {
            requirements.length.classList.add('met');
            requirements.length.querySelector('.requirement-icon').textContent = '✓';
        } else {
            requirements.length.classList.remove('met');
            requirements.length.querySelector('.requirement-icon').textContent = '○';
        }
        
        // Uppercase
        if (/[A-Z]/.test(password)) {
            requirements.uppercase.classList.add('met');
            requirements.uppercase.querySelector('.requirement-icon').textContent = '✓';
        } else {
            requirements.uppercase.classList.remove('met');
            requirements.uppercase.querySelector('.requirement-icon').textContent = '○';
        }
        
        // Lowercase
        if (/[a-z]/.test(password)) {
            requirements.lowercase.classList.add('met');
            requirements.lowercase.querySelector('.requirement-icon').textContent = '✓';
        } else {
            requirements.lowercase.classList.remove('met');
            requirements.lowercase.querySelector('.requirement-icon').textContent = '○';
        }
        
        // Number
        if (/[0-9]/.test(password)) {
            requirements.number.classList.add('met');
            requirements.number.querySelector('.requirement-icon').textContent = '✓';
        } else {
            requirements.number.classList.remove('met');
            requirements.number.querySelector('.requirement-icon').textContent = '○';
        }
        
        // Match
        if (password && confirmPassword && password === confirmPassword) {
            requirements.match.classList.add('met');
            requirements.match.querySelector('.requirement-icon').textContent = '✓';
        } else {
            requirements.match.classList.remove('met');
            requirements.match.querySelector('.requirement-icon').textContent = '○';
        }
    }
    
    passwordInput.addEventListener('input', function() {
        updateRequirements(this.value, confirmPasswordInput.value);
    });
    
    confirmPasswordInput.addEventListener('input', function() {
        updateRequirements(passwordInput.value, this.value);
    });
    
    // Phone number formatting
    const phoneInput = document.getElementById('phone');
    phoneInput.addEventListener('input', function() {
        let value = this.value.replace(/\D/g, '');
        
        // Format Nigerian phone numbers
        if (value.length === 11 && value.startsWith('0')) {
            this.value = value;
        } else if (value.length === 10 && !value.startsWith('0')) {
            this.value = '0' + value;
        } else if (value.length === 13 && value.startsWith('234')) {
            this.value = '+' + value;
        }
    });
});
</script>

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