<?php
/**
 * REGISTRATION PAGE
 * File: auth/register.php
 * Handles new user registration with AJAX
 */

require_once '../app/Core/init.php';

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax'])) {
    header('Content-Type: application/json');
    
    try {
        // Validate CSRF token
        $token = $_POST['csrf_token'] ?? '';
        if (!Security::validateToken($token)) {
            echo json_encode(['success' => false, 'message' => 'Invalid security token. Please refresh and try again.']);
            exit;
        }
        
        $user_type = $_POST['user_type'] ?? 'customer';
        
        if ($user_type === 'customer') {
            $result = registerCustomer($_POST);
        } else {
            $result = registerVendor($_POST);
        }
        
        echo json_encode($result);
    } catch (Exception $e) {
        log_message('Registration AJAX error: ' . $e->getMessage(), 'error');
        echo json_encode(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
    }
    exit;
}

// Redirect if already logged in
if (Auth::check()) {
    $user_type = $_SESSION['user_type'];
    if ($user_type === 'admin') {
        redirect('/admin/index.php');
    } elseif ($user_type === 'vendor') {
        redirect('/vendor/index.php');
    } elseif ($user_type === 'customer') {
        redirect('../index.php');
    }
}

/**
 * Register Customer
 */
function registerCustomer($data) {
    $errors = [];
    
    $first_name = trim($data['first_name'] ?? '');
    $last_name = trim($data['last_name'] ?? '');
    $email = trim($data['email'] ?? '');
    $phone = trim($data['phone'] ?? '');
    $password = $data['password'] ?? '';
    $confirm_password = $data['confirm_password'] ?? '';
    $agree_terms = isset($data['agree_terms']);
    
    // Validation
    if (empty($first_name)) {
        $errors['first_name'] = 'First name is required';
    } elseif (strlen($first_name) < 2) {
        $errors['first_name'] = 'First name must be at least 2 characters';
    }
    
    if (empty($last_name)) {
        $errors['last_name'] = 'Last name is required';
    } elseif (strlen($last_name) < 2) {
        $errors['last_name'] = 'Last name must be at least 2 characters';
    }
    
    if (empty($email)) {
        $errors['email'] = 'Email is required';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = 'Invalid email format';
    }
    
    if (empty($phone)) {
        $errors['phone'] = 'Phone number is required';
    } elseif (!preg_match('/^[0-9+\-\s()]{10,20}$/', $phone)) {
        $errors['phone'] = 'Invalid phone number format';
    }
    
    if (empty($password)) {
        $errors['password'] = 'Password is required';
    } elseif (strlen($password) < 8) {
        $errors['password'] = 'Password must be at least 8 characters';
    } elseif (!preg_match('/[A-Z]/', $password)) {
        $errors['password'] = 'Password must contain at least one uppercase letter';
    } elseif (!preg_match('/[a-z]/', $password)) {
        $errors['password'] = 'Password must contain at least one lowercase letter';
    } elseif (!preg_match('/[0-9]/', $password)) {
        $errors['password'] = 'Password must contain at least one number';
    }
    
    if ($password !== $confirm_password) {
        $errors['confirm_password'] = 'Passwords do not match';
    }
    
    if (!$agree_terms) {
        $errors['agree_terms'] = 'You must agree to the terms and conditions';
    }
    
    $userModel = new User();
    if ($userModel->emailExists($email)) {
        $errors['email'] = 'Email already registered';
    }
    
    if (!empty($errors)) {
        return ['success' => false, 'errors' => $errors];
    }
    
    $db = Database::getInstance();
    $db->beginTransaction();
    
    try {
        $user_id = $userModel->create([
            'email' => $email,
            'password' => password_hash($password, PASSWORD_BCRYPT),
            'user_type' => 'customer',
            'email_verified' => 0
        ]);
        
        if (!$user_id) {
            throw new Exception('Failed to create user account');
        }
        
        $customerModel = new Customer();
        $customer_id = $customerModel->create([
            'user_id' => $user_id,
            'first_name' => $first_name,
            'last_name' => $last_name,
            'phone' => $phone
        ]);
        
        if (!$customer_id) {
            throw new Exception('Failed to create customer profile');
        }
        
        $walletModel = new Wallet();
        $walletModel->create($user_id);
        
        $mailer = new Mailer();
        $token = bin2hex(random_bytes(32));
        $userModel->setVerificationToken($user_id, $token);
        $mailer->sendVerificationEmail($email, $first_name, $token, 'customer');
        
        $db->commit();
        
        return [
            'success' => true,
            'message' => 'Registration successful! Please check your email to verify your account.',
            'redirect' => 'login.php'
        ];
        
    } catch (Exception $e) {
        $db->rollBack();
        log_message('Registration error: ' . $e->getMessage(), 'error');
        return ['success' => false, 'message' => 'Registration failed. Please try again.'];
    }
}

/**
 * Register Vendor
 */
function registerVendor($data) {
    $errors = [];
    
    $business_name = trim($data['business_name'] ?? '');
    $business_type = trim($data['business_type'] ?? '');
    $business_registration_type = trim($data['business_registration_type'] ?? '');
    $email = trim($data['email'] ?? '');
    $phone = trim($data['phone'] ?? '');
    $address = trim($data['address'] ?? '');
    $city = trim($data['city'] ?? '');
    $state = trim($data['state'] ?? '');
    $business_description = trim($data['business_description'] ?? '');
    $password = $data['password'] ?? '';
    $confirm_password = $data['confirm_password'] ?? '';
    $agree_terms = isset($data['agree_terms']);
    
    // Validation
    if (empty($business_name)) {
        $errors['business_name'] = 'Business name is required';
    } elseif (strlen($business_name) < 3) {
        $errors['business_name'] = 'Business name must be at least 3 characters';
    }
    
    if (empty($business_type)) {
        $errors['business_type'] = 'Business type is required';
    }
    
    if (empty($business_registration_type)) {
        $errors['business_registration_type'] = 'Business registration type is required';
    }
    
    if (empty($email)) {
        $errors['email'] = 'Email is required';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = 'Invalid email format';
    }
    
    if (empty($phone)) {
        $errors['phone'] = 'Phone number is required';
    } elseif (!preg_match('/^[0-9+\-\s()]{10,20}$/', $phone)) {
        $errors['phone'] = 'Invalid phone number format';
    }
    
    if (empty($address)) {
        $errors['address'] = 'Business address is required';
    }
    
    if (empty($city)) {
        $errors['city'] = 'City is required';
    }
    
    if (empty($state)) {
        $errors['state'] = 'State is required';
    }
    
    if (empty($password)) {
        $errors['password'] = 'Password is required';
    } elseif (strlen($password) < 8) {
        $errors['password'] = 'Password must be at least 8 characters';
    } elseif (!preg_match('/[A-Z]/', $password)) {
        $errors['password'] = 'Password must contain at least one uppercase letter';
    } elseif (!preg_match('/[a-z]/', $password)) {
        $errors['password'] = 'Password must contain at least one lowercase letter';
    } elseif (!preg_match('/[0-9]/', $password)) {
        $errors['password'] = 'Password must contain at least one number';
    }
    
    if ($password !== $confirm_password) {
        $errors['confirm_password'] = 'Passwords do not match';
    }
    
    if (!$agree_terms) {
        $errors['agree_terms'] = 'You must agree to the terms and conditions';
    }
    
    $userModel = new User();
    if ($userModel->emailExists($email)) {
        $errors['email'] = 'Email already registered';
    }
    
    if (!empty($errors)) {
        return ['success' => false, 'errors' => $errors];
    }
    
    $db = Database::getInstance();
    $db->beginTransaction();
    
    try {
        $user_id = $userModel->create([
            'email' => $email,
            'password' => password_hash($password, PASSWORD_BCRYPT),
            'user_type' => 'vendor',
            'email_verified' => 0
        ]);
        
        if (!$user_id) {
            throw new Exception('Failed to create user account');
        }
        
        $vendorModel = new Vendor();
        $vendor_id = $vendorModel->create([
            'user_id' => $user_id,
            'business_name' => $business_name,
            'business_type' => $business_type,
            'business_registration_type' => $business_registration_type,
            'phone' => $phone,
            'address' => $address,
            'city' => $city,
            'state' => $state,
            'business_description' => $business_description,
            'approval_status' => 'pending'
        ]);
        
        if (!$vendor_id) {
            throw new Exception('Failed to create vendor profile');
        }
        
        $walletModel = new Wallet();
        $walletModel->create($user_id);
        
        $mailer = new Mailer();
        $token = bin2hex(random_bytes(32));
        $userModel->setVerificationToken($user_id, $token);
        $mailer->sendVerificationEmail($email, $business_name, $token, 'vendor');
        
        $db->commit();
        
        return [
            'success' => true,
            'message' => 'Vendor registration successful! Your account is pending approval. Please check your email to verify your account.',
            'redirect' => 'login.php'
        ];
        
    } catch (Exception $e) {
        $db->rollBack();
        log_message('Vendor registration error: ' . $e->getMessage(), 'error');
        return ['success' => false, 'message' => 'Registration failed. Please try again.'];
    }
}

$page_title = 'Register - ' . APP_NAME;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= $page_title ?></title>
    <link rel="stylesheet" href="../assets/plugins/fontawesome/css/all.min.css">
    <link rel="stylesheet" href="../assets/plugins/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="../assets/css/style.css">
    <style>
        .tab-buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 30px;
        }
        .tab-btn {
            flex: 1;
            padding: 15px;
            border: 2px solid #e0e0e0;
            background: white;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 600;
        }
        .tab-btn:hover {
            border-color: #05472A;
            background: #f8f9fa;
        }
        .tab-btn.active {
            border-color: #05472A;
            background: #05472A;
            color: white;
        }
        .tab-content-wrapper {
            display: none;
        }
        .tab-content-wrapper.active {
            display: block;
            animation: fadeIn 0.3s;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        #loading-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 9999;
            align-items: center;
            justify-content: center;
        }
        #loading-overlay.show {
            display: flex;
        }
        .spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid #0d6efd;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <!-- Header -->
    <?php include '../templates/layouts/frontend/header.php'; ?>
    
    <!-- Loading Overlay -->
    <div id="loading-overlay">
        <div class="spinner"></div>
    </div>
    
    <div class="container-fluid p-0">
        <div class="row g-0">
            <div class="col-xl-5">
                <div class="account-page-area p-4 p-md-5">
                    <div class="mb-4">
                        <h2 class="fw-semibold mb-2">Create Account</h2>
                        <p class="text-muted">Join <?= APP_NAME ?> today</p>
                    </div>
                    
                    <!-- Alert Messages -->
                    <div id="alert-container"></div>
                    
                    <!-- Tab Buttons -->
                    <div class="tab-buttons">
                        <button type="button" class="tab-btn active" onclick="switchTab('customer')">
                            <i class="fas fa-shopping-cart me-2"></i>Customer
                        </button>
                        <button type="button" class="tab-btn" onclick="switchTab('vendor')">
                            <i class="fas fa-store me-2"></i>Vendor
                        </button>
                    </div>
                    
                    <!-- Customer Form -->
                    <div id="customer-form" class="tab-content-wrapper active">
                        <form id="customerRegistrationForm" class="register-form" method="POST" action="">
                            <input type="hidden" name="ajax" value="1">
                            <?= Security::csrfField() ?>
                            <input type="hidden" name="user_type" value="customer">
                            <input type="hidden" name="ajax" value="1">
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">First Name <span class="text-danger">*</span></label>
                                    <input type="text" name="first_name" class="form-control" placeholder="Enter first name" required>
                                    <div class="invalid-feedback"></div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Last Name <span class="text-danger">*</span></label>
                                    <input type="text" name="last_name" class="form-control" placeholder="Enter last name" required>
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Email Address <span class="text-danger">*</span></label>
                                <input type="email" name="email" class="form-control" placeholder="your@email.com" required>
                                <div class="invalid-feedback"></div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Phone Number <span class="text-danger">*</span></label>
                                <input type="tel" name="phone" class="form-control" placeholder="+234 xxx xxx xxxx" required>
                                <div class="invalid-feedback"></div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Password <span class="text-danger">*</span></label>
                                <div class="position-relative">
                                    <input id="password" type="password" name="password" class="form-control" placeholder="Create password" required>
                                    <i data-bs-toggle="#password" class="fa-regular fa-eye-slash toggle-password"></i>
                                </div>
                                <div class="invalid-feedback"></div>
                                <small class="text-muted">Must be 8+ characters with uppercase, lowercase, and number</small>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Confirm Password <span class="text-danger">*</span></label>
                                <div class="position-relative">
                                    <input id="confirmPassword" type="password" name="confirm_password" class="form-control" placeholder="Confirm password" required>
                                    <i data-bs-toggle="#confirmPassword" class="fa-regular fa-eye-slash toggle-password"></i>
                                </div>
                                <div class="invalid-feedback"></div>
                            </div>
                            
                            <div class="form-check mb-4 text-start">
                                <input class="form-check-input" type="checkbox" name="agree_terms" value="1" id="agreeTermsCustomer" required>
                                <label class="form-check-label" for="agreeTermsCustomer">
                                    I agree to the <a href="../terms-conditions.php" target="_blank">Terms of Service</a> 
                                    and <a href="../privacy-policy.php" target="_blank">Privacy Policy</a>
                                </label>
                                <div class="invalid-feedback"></div>
                            </div>
                            
                            <button type="submit" class="btn btn-primary btn-lg w-100">Create Customer Account</button>
                        </form>
                    </div>
                    
                    <!-- Vendor Form -->
                    <div id="vendor-form" class="tab-content-wrapper">
                        <form id="vendorRegistrationForm" class="register-form" method="POST" action="">
                            <input type="hidden" name="ajax" value="1">
                            <?= Security::csrfField() ?>
                            <input type="hidden" name="user_type" value="vendor">
                            <input type="hidden" name="ajax" value="1">
                            
                            <div class="mb-3">
                                <label class="form-label">Business Name <span class="text-danger">*</span></label>
                                <input type="text" name="business_name" class="form-control" placeholder="Enter business name" required>
                                <div class="invalid-feedback"></div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Business Type <span class="text-danger">*</span></label>
                                <select name="business_type" class="form-control" required>
                                    <option value="">Select business type</option>
                                    <option value="Technology Equipment Rental">Technology Equipment Rental</option>
                                    <option value="Event Planning & Equipment">Event Planning & Equipment</option>
                                    <option value="Photography Equipment Rental">Photography Equipment Rental</option>
                                    <option value="Audio & Sound Equipment">Audio & Sound Equipment</option>
                                    <option value="Tools & Construction Equipment">Tools & Construction Equipment</option>
                                    <option value="Party Supplies & Equipment">Party Supplies & Equipment</option>
                                    <option value="Furniture Rental">Furniture Rental</option>
                                    <option value="Vehicle Rental">Vehicle Rental</option>
                                    <option value="Other">Other</option>
                                </select>
                                <div class="invalid-feedback"></div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Business Registration Type <span class="text-danger">*</span></label>
                                <select name="business_registration_type" class="form-control" required>
                                    <option value="">Select registration type</option>
                                    <option value="Not Registered">Not Registered</option>
                                    <option value="Sole Proprietorship">Sole Proprietorship</option>
                                    <option value="Limited Liability">Limited Liability</option>
                                    <option value="Unlimited Liability">Unlimited Liability</option>
                                    <option value="Association/Club">Association/Club</option>
                                    <option value="Others">Others</option>
                                </select>
                                <div class="invalid-feedback"></div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Business Email <span class="text-danger">*</span></label>
                                <input type="email" name="email" class="form-control" placeholder="business@email.com" required>
                                <div class="invalid-feedback"></div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Business Phone <span class="text-danger">*</span></label>
                                <input type="tel" name="phone" class="form-control" placeholder="+234 xxx xxx xxxx" required>
                                <div class="invalid-feedback"></div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Business Address <span class="text-danger">*</span></label>
                                <input type="text" name="address" class="form-control" placeholder="Street address" required>
                                <div class="invalid-feedback"></div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">City <span class="text-danger">*</span></label>
                                    <input type="text" name="city" class="form-control" placeholder="City" required>
                                    <div class="invalid-feedback"></div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">State <span class="text-danger">*</span></label>
                                    <input type="text" name="state" class="form-control" placeholder="State" required>
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Business Description</label>
                                <textarea name="business_description" class="form-control" rows="3" placeholder="Tell us about your business"></textarea>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Password <span class="text-danger">*</span></label>
                                <div class="position-relative">
                                    <input id="passwordVendor" type="password" name="password" class="form-control" placeholder="Create password" required>
                                    <i data-bs-toggle="#passwordVendor" class="fa-regular fa-eye-slash toggle-password"></i>
                                </div>
                                <div class="invalid-feedback"></div>
                                <small class="text-muted">Must be 8+ characters with uppercase, lowercase, and number</small>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Confirm Password <span class="text-danger">*</span></label>
                                <div class="position-relative">
                                    <input id="confirmPasswordVendor" type="password" name="confirm_password" class="form-control" placeholder="Confirm password" required>
                                    <i data-bs-toggle="#confirmPasswordVendor" class="fa-regular fa-eye-slash toggle-password"></i>
                                </div>
                                <div class="invalid-feedback"></div>
                            </div>
                            
                            <div class="form-check mb-4 text-start">
                                <input class="form-check-input" type="checkbox" name="agree_terms" value="1" id="agreeTermsVendor" required>
                                <label class="form-check-label" for="agreeTermsVendor">
                                    I agree to the <a href="../terms-conditions.php" target="_blank">Terms of Service</a> 
                                    and <a href="../privacy-policy.php" target="_blank">Privacy Policy</a>
                                </label>
                                <div class="invalid-feedback"></div>
                            </div>
                            
                            <button type="submit" class="btn btn-primary btn-lg w-100">Create Vendor Account</button>
                        </form>
                    </div>
                    
                    <div class="bottom-text text-center mt-4">
                        Already have an account? <a href="login.php" class="fw-medium text-decoration-underline">Sign In</a>
                    </div>
                </div>
            </div>
            <div class="col-xl-7 d-none d-xl-block">
                <div class="background-image bg-light d-flex flex-column h-100 justify-content-center p-5 rounded-4" data-image-src="../assets/images/lines.svg">
                    <div class="py-5 text-center">
                        <div class="mb-5">
                            <h2 class="fw-semibold">Welcome to <?= APP_NAME ?></h2>
                            <p>Start renting or listing items today with our easy-to-use platform.</p>
                        </div>
                        <img src="../assets/images/png-img/real-time-analytics.png" alt="" class="img-fluid">
                    </div>
                </div>
            </div>
        </div>
    </div>
    

<script>
// Tab switching function
function switchTab(type) {
    // Remove active from all buttons
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
    // Add active to clicked button
    event.target.classList.add('active');
    
    // Hide all form tabs
    document.querySelectorAll('.tab-content-wrapper').forEach(content => {
        content.classList.remove('active');
        content.style.display = 'none';
    });
    
    // Show selected form tab
    const selectedTab = document.getElementById(type + '-form');
    selectedTab.classList.add('active');
    selectedTab.style.display = 'block';
}

// Toggle password visibility
document.querySelectorAll('.toggle-password').forEach(icon => {
    icon.addEventListener('click', function() {
        const targetSelector = this.getAttribute('data-bs-toggle');
        const input = document.querySelector(targetSelector);
        
        if (input.type === 'password') {
            input.type = 'text';
            this.classList.remove('fa-eye-slash');
            this.classList.add('fa-eye');
        } else {
            input.type = 'password';
            this.classList.remove('fa-eye');
            this.classList.add('fa-eye-slash');
        }
    });
});

// Handle form submissions
function handleFormSubmit(formId, userType) {
    const form = document.getElementById(formId);
    
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        
        // Clear previous errors
        form.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid'));
        form.querySelectorAll('.invalid-feedback').forEach(el => el.textContent = '');
        document.getElementById('alert-container').innerHTML = '';
        
        // Show loading
        document.getElementById('loading-overlay').classList.add('show');
        
        // Get form data
        const formData = new FormData(form);
        formData.append('ajax', '1');
        formData.append('user_type', userType);
        
        // Submit via AJAX
        fetch('register.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            // Hide loading
            document.getElementById('loading-overlay').classList.remove('show');
            
            if (data.success) {
                // Show success message
                document.getElementById('alert-container').innerHTML = 
                    `<div class="alert alert-success alert-dismissible fade show">
                        <i class="fas fa-check-circle me-2"></i>
                        <strong>Success!</strong> ${data.message}
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>`;
                
                // Clear form
                form.reset();
                
                // Scroll to top
                window.scrollTo({ top: 0, behavior: 'smooth' });
                
                // Redirect after 3 seconds
                setTimeout(() => {
                    window.location.href = data.redirect;
                }, 6000);
                
            } else {
                // Show error messages
                if (data.errors) {
                    let errorHtml = '<div class="alert alert-danger alert-dismissible fade show"><i class="fas fa-exclamation-circle me-2"></i><strong>Please fix the following errors:</strong><ul class="mb-0 mt-2">';
                    
                    Object.keys(data.errors).forEach(field => {
                        const error = data.errors[field];
                        errorHtml += `<li>${error}</li>`;
                        
                        // Mark field as invalid
                        const input = form.querySelector(`[name="${field}"]`);
                        if (input) {
                            input.classList.add('is-invalid');
                            const feedback = input.parentElement.querySelector('.invalid-feedback');
                            if (feedback) {
                                feedback.textContent = error;
                                feedback.style.display = 'block';
                            }
                        }
                    });
                    
                    errorHtml += '</ul><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>';
                    document.getElementById('alert-container').innerHTML = errorHtml;
                    
                } else if (data.message) {
                    document.getElementById('alert-container').innerHTML = 
                        `<div class="alert alert-danger alert-dismissible fade show">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            ${data.message}
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>`;
                }
                
                // Scroll to top to show errors
                window.scrollTo({ top: 0, behavior: 'smooth' });
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('loading-overlay').classList.remove('show');
            
            document.getElementById('alert-container').innerHTML = 
                `<div class="alert alert-danger alert-dismissible fade show">
                    <i class="fas fa-exclamation-circle me-2"></i>
                    <strong>Error!</strong> An error occurred. Please try again.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>`;
            
            window.scrollTo({ top: 0, behavior: 'smooth' });
        });
    });
}

// Initialize both forms
handleFormSubmit('customerRegistrationForm', 'customer');
handleFormSubmit('vendorRegistrationForm', 'vendor');

// Ensure vendor form is hidden on load
document.getElementById('vendor-form').style.display = 'none';
</script>




    <!-- Footer -->
    <?php include '../templates/layouts/frontend/footer.php'; ?>
    
    <!-- Scripts -->
    <script src="../assets/plugins/jQuery/jquery.min.js"></script>
    <script src="../assets/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../assets/js/script.js"></script>
    
</body>
</html>