<?php
/**
 * ============================================================================
 * buyer/complete-profile.php
 * Buyer Profile Completion Form
 * Multi-step form for setting up buyer business profile
 * ============================================================================
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/BuyerSystem.php';

// Check login
if (!isLoggedIn()) {
    header('Location: ' . APP_URL . '/auth/login.php');
    exit();
}

// Check user type
if (getUserType() !== 'buyer') {
    header('Location: ' . APP_URL . '/dashboard/');
    exit();
}

// Initialize
use App\Database;
$database = Database::getInstance();
$db = $database->getConnection();
$currentUserId = getUserId();
$currentUserName = getUserName();
$buyerSystem = new BuyerSystem($database, $currentUserId);

// If profile already complete, redirect to dashboard
if ($buyerSystem->hasCompleteProfile()) {
    header('Location: ' . APP_URL . '/buyer/dashboard.php');
    exit();
}

// Get user info
$sql = "SELECT * FROM users WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->execute([$currentUserId]);
$userInfo = $stmt->fetch(PDO::FETCH_ASSOC);

// Get existing profile if any
$existingProfile = $buyerSystem->getProfile();

// Get districts for location selection
$sql = "SELECT * FROM districts ORDER BY district_name ASC";
$stmt = $db->query($sql);
$districts = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $db->beginTransaction();
        
        // Validate required fields
        $required = ['buyer_type', 'business_name', 'business_phone', 'business_district', 'business_address'];
        $errors = [];
        
        foreach ($required as $field) {
            if (empty($_POST[$field])) {
                $errors[] = ucfirst(str_replace('_', ' ', $field)) . ' is required';
            }
        }
        
        if (!empty($errors)) {
            throw new Exception(implode(', ', $errors));
        }
        
        // Validate buyer type
        $validTypes = ['individual', 'retailer', 'wholesaler', 'processor', 'exporter'];
        if (!in_array($_POST['buyer_type'], $validTypes)) {
            throw new Exception('Invalid buyer type');
        }
        
        // Prepare profile data
        $profileData = [
            'user_id' => $currentUserId,
            'buyer_type' => $_POST['buyer_type'],
            'business_name' => trim($_POST['business_name']),
            'business_registration' => trim($_POST['business_registration'] ?? ''),
            'tax_id' => trim($_POST['tax_id'] ?? ''),
            'business_phone' => trim($_POST['business_phone']),
            'business_email' => trim($_POST['business_email'] ?? $userInfo['email']),
            'business_address' => trim($_POST['business_address']),
            'business_district' => intval($_POST['business_district']),
            'buying_capacity' => $_POST['buying_capacity'] ?? 'small',
            'preferred_payment_method' => $_POST['preferred_payment_method'] ?? 'cash',
            'business_description' => trim($_POST['business_description'] ?? ''),
            'categories_of_interest' => !empty($_POST['categories_of_interest']) ? json_encode($_POST['categories_of_interest']) : null,
            'delivery_preference' => $_POST['delivery_preference'] ?? 'pickup',
            'is_profile_complete' => 1
        ];
        
        // Check if profile exists
        if ($existingProfile) {
            // Update existing profile
            $updateFields = [];
            $updateValues = [];
            
            foreach ($profileData as $key => $value) {
                if ($key !== 'user_id') {
                    $updateFields[] = "$key = ?";
                    $updateValues[] = $value;
                }
            }
            
            $updateValues[] = $currentUserId;
            
            $sql = "UPDATE buyer_profiles SET " . implode(', ', $updateFields) . " WHERE user_id = ?";
            $stmt = $db->prepare($sql);
            $stmt->execute($updateValues);
        } else {
            // Insert new profile
            $fields = array_keys($profileData);
            $placeholders = array_fill(0, count($fields), '?');
            
            $sql = "INSERT INTO buyer_profiles (" . implode(', ', $fields) . ") VALUES (" . implode(', ', $placeholders) . ")";
            $stmt = $db->prepare($sql);
            $stmt->execute(array_values($profileData));
        }
        
        // Update user's full name if provided
        if (!empty($_POST['full_name']) && $_POST['full_name'] !== $userInfo['full_name']) {
            $sql = "UPDATE users SET full_name = ? WHERE id = ?";
            $stmt = $db->prepare($sql);
            $stmt->execute([trim($_POST['full_name']), $currentUserId]);
        }
        
        $db->commit();
        
        // Set success message
        $_SESSION['flash_message'] = 'Profile completed successfully!';
        $_SESSION['flash_type'] = 'success';
        
        // Redirect to verification or dashboard
        $requiresVerification = in_array($_POST['buyer_type'], ['wholesaler', 'processor', 'exporter']);
        
        if ($requiresVerification) {
            header('Location: ' . APP_URL . '/buyer/verification.php');
        } else {
            header('Location: ' . APP_URL . '/buyer/dashboard.php');
        }
        exit();
        
    } catch (Exception $e) {
        $db->rollBack();
        $error = $e->getMessage();
    }
}

$pageTitle = 'Complete Your Buyer Profile';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - AIMS</title>
    
    <!-- Bootstrap 5.3 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
    
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
    
    <style>
        :root {
            --primary-color: #3b82f6;
            --primary-dark: #2563eb;
        }
        
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        
        .profile-container {
            max-width: 800px;
            margin: 40px auto;
            padding: 0 20px;
        }
        
        .profile-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            overflow: hidden;
        }
        
        .profile-header {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
            color: white;
            padding: 2rem;
            text-align: center;
        }
        
        .profile-header h2 {
            font-size: 1.8rem;
            font-weight: bold;
            margin-bottom: 0.5rem;
        }
        
        .profile-header p {
            opacity: 0.9;
            margin-bottom: 0;
        }
        
        .profile-body {
            padding: 2.5rem;
        }
        
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 2rem;
            position: relative;
        }
        
        .step-indicator::before {
            content: '';
            position: absolute;
            top: 15px;
            left: 0;
            right: 0;
            height: 2px;
            background: #e5e7eb;
            z-index: 0;
        }
        
        .step {
            position: relative;
            z-index: 1;
            flex: 1;
            text-align: center;
        }
        
        .step-circle {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: #e5e7eb;
            color: #6b7280;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 0.875rem;
            margin-bottom: 0.5rem;
        }
        
        .step.active .step-circle {
            background: var(--primary-color);
            color: white;
        }
        
        .step.completed .step-circle {
            background: #10b981;
            color: white;
        }
        
        .step-label {
            font-size: 0.75rem;
            color: #6b7280;
            font-weight: 500;
        }
        
        .step.active .step-label {
            color: var(--primary-color);
            font-weight: 600;
        }
        
        .form-section {
            display: none;
        }
        
        .form-section.active {
            display: block;
            animation: fadeIn 0.3s ease;
        }
        
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .section-title {
            font-size: 1.25rem;
            font-weight: bold;
            margin-bottom: 1.5rem;
            color: #1f2937;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .section-title i {
            color: var(--primary-color);
        }
        
        .form-label {
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .form-control, .form-select {
            border-radius: 10px;
            border: 2px solid #e5e7eb;
            padding: 0.75rem 1rem;
            transition: all 0.3s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(59, 130, 246, 0.25);
        }
        
        .buyer-type-card {
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            padding: 1.5rem;
            cursor: pointer;
            transition: all 0.3s ease;
            height: 100%;
        }
        
        .buyer-type-card:hover {
            border-color: var(--primary-color);
            box-shadow: 0 5px 15px rgba(59, 130, 246, 0.2);
            transform: translateY(-3px);
        }
        
        .buyer-type-card.selected {
            border-color: var(--primary-color);
            background: rgba(59, 130, 246, 0.05);
        }
        
        .buyer-type-card .icon {
            font-size: 2.5rem;
            margin-bottom: 1rem;
        }
        
        .buyer-type-card h5 {
            font-size: 1.1rem;
            font-weight: bold;
            margin-bottom: 0.5rem;
        }
        
        .buyer-type-card p {
            font-size: 0.875rem;
            color: #6b7280;
            margin-bottom: 0;
        }
        
        .btn-nav {
            padding: 0.75rem 2rem;
            border-radius: 10px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
            border: none;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(59, 130, 246, 0.3);
        }
        
        .category-checkbox {
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            padding: 0.75rem 1rem;
            transition: all 0.2s ease;
            cursor: pointer;
        }
        
        .category-checkbox:hover {
            border-color: var(--primary-color);
            background: rgba(59, 130, 246, 0.05);
        }
        
        .category-checkbox input:checked + label {
            color: var(--primary-color);
            font-weight: 600;
        }
        
        .info-box {
            background: #eff6ff;
            border-left: 4px solid var(--primary-color);
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .info-box i {
            color: var(--primary-color);
        }
        
        .required-indicator {
            color: #ef4444;
            margin-left: 2px;
        }
    </style>
</head>
<body>
    <div class="profile-container">
        <!-- Header Logo -->
        <div class="text-center mb-4">
            <a href="<?php echo APP_URL; ?>/" class="text-white text-decoration-none">
                <h3 class="fw-bold mb-0"><i class="bi bi-cart-check me-2"></i>AIMS Buyer Portal</h3>
            </a>
        </div>
        
        <div class="profile-card">
            <!-- Header -->
            <div class="profile-header">
                <h2><i class="bi bi-person-badge me-2"></i>Complete Your Buyer Profile</h2>
                <p>Help us understand your business needs better</p>
            </div>
            
            <!-- Body -->
            <div class="profile-body">
                <!-- Error Display -->
                <?php if (isset($error)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="bi bi-exclamation-triangle me-2"></i><?php echo htmlspecialchars($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>
                
                <!-- Step Indicator -->
                <div class="step-indicator">
                    <div class="step active" id="step1Indicator">
                        <div class="step-circle">1</div>
                        <div class="step-label">Buyer Type</div>
                    </div>
                    <div class="step" id="step2Indicator">
                        <div class="step-circle">2</div>
                        <div class="step-label">Business Info</div>
                    </div>
                    <div class="step" id="step3Indicator">
                        <div class="step-circle">3</div>
                        <div class="step-label">Preferences</div>
                    </div>
                </div>
                
                <form method="POST" id="profileForm">
                    <!-- Step 1: Buyer Type -->
                    <div class="form-section active" id="step1">
                        <div class="section-title">
                            <i class="bi bi-briefcase"></i>
                            Select Your Buyer Type
                        </div>
                        
                        <div class="info-box mb-4">
                            <i class="bi bi-info-circle me-2"></i>
                            <small><strong>Choose the option that best describes your business:</strong> Different buyer types unlock different features and capabilities.</small>
                        </div>
                        
                        <div class="row g-3">
                            <div class="col-md-6">
                                <div class="buyer-type-card" data-type="individual">
                                    <div class="icon text-secondary"><i class="bi bi-person"></i></div>
                                    <h5>Individual Buyer</h5>
                                    <p>Personal purchases for home consumption</p>
                                    <small class="text-muted d-block mt-2">
                                        <i class="bi bi-check-circle text-success me-1"></i> Browse & purchase<br>
                                        <i class="bi bi-check-circle text-success me-1"></i> Track orders<br>
                                        <i class="bi bi-check-circle text-success me-1"></i> Save favorites
                                    </small>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="buyer-type-card" data-type="retailer">
                                    <div class="icon text-primary"><i class="bi bi-shop"></i></div>
                                    <h5>Retailer</h5>
                                    <p>Small to medium retail business</p>
                                    <small class="text-muted d-block mt-2">
                                        <i class="bi bi-check-circle text-success me-1"></i> All individual features<br>
                                        <i class="bi bi-check-circle text-success me-1"></i> Request quotes<br>
                                        <i class="bi bi-check-circle text-success me-1"></i> Supplier management
                                    </small>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="buyer-type-card" data-type="wholesaler">
                                    <div class="icon text-success"><i class="bi bi-building"></i></div>
                                    <h5>Wholesaler</h5>
                                    <p>Large volume bulk purchases</p>
                                    <small class="text-muted d-block mt-2">
                                        <i class="bi bi-check-circle text-success me-1"></i> All retailer features<br>
                                        <i class="bi bi-check-circle text-success me-1"></i> Unlimited bulk orders<br>
                                        <i class="bi bi-check-circle text-success me-1"></i> Advanced analytics<br>
                                        <i class="bi bi-patch-check text-warning me-1"></i> Requires verification
                                    </small>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="buyer-type-card" data-type="processor">
                                    <div class="icon text-warning"><i class="bi bi-gear-wide-connected"></i></div>
                                    <h5>Processor/Manufacturer</h5>
                                    <p>Processing raw agricultural products (e.g., Kakira Sugar)</p>
                                    <small class="text-muted d-block mt-2">
                                        <i class="bi bi-check-circle text-success me-1"></i> All wholesaler features<br>
                                        <i class="bi bi-check-circle text-success me-1"></i> Contract farming<br>
                                        <i class="bi bi-check-circle text-success me-1"></i> Quality specifications<br>
                                        <i class="bi bi-patch-check text-warning me-1"></i> Requires verification
                                    </small>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="buyer-type-card" data-type="exporter">
                                    <div class="icon text-danger"><i class="bi bi-globe"></i></div>
                                    <h5>Exporter</h5>
                                    <p>International agricultural export business</p>
                                    <small class="text-muted d-block mt-2">
                                        <i class="bi bi-check-circle text-success me-1"></i> All processor features<br>
                                        <i class="bi bi-check-circle text-success me-1"></i> Export documentation<br>
                                        <i class="bi bi-check-circle text-success me-1"></i> Multi-currency support<br>
                                        <i class="bi bi-patch-check text-warning me-1"></i> Requires verification
                                    </small>
                                </div>
                            </div>
                        </div>
                        
                        <input type="hidden" name="buyer_type" id="buyerTypeInput" required>
                        
                        <div class="d-flex justify-content-end mt-4">
                            <button type="button" class="btn btn-primary btn-nav" id="step1Next">
                                Next: Business Information <i class="bi bi-arrow-right ms-2"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Step 2: Business Information -->
                    <div class="form-section" id="step2">
                        <div class="section-title">
                            <i class="bi bi-building"></i>
                            Business Information
                        </div>
                        
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Full Name <span class="required-indicator">*</span></label>
                                <input type="text" class="form-control" name="full_name" 
                                       value="<?php echo htmlspecialchars($userInfo['full_name']); ?>" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label">Business Name <span class="required-indicator">*</span></label>
                                <input type="text" class="form-control" name="business_name" 
                                       placeholder="e.g., Fresh Produce Ltd" 
                                       value="<?php echo htmlspecialchars($existingProfile['business_name'] ?? ''); ?>" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label">Business Registration Number</label>
                                <input type="text" class="form-control" name="business_registration" 
                                       placeholder="Optional" 
                                       value="<?php echo htmlspecialchars($existingProfile['business_registration'] ?? ''); ?>">
                                <small class="text-muted">Required for wholesalers, processors, and exporters</small>
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label">Tax Identification Number (TIN)</label>
                                <input type="text" class="form-control" name="tax_id" 
                                       placeholder="Optional" 
                                       value="<?php echo htmlspecialchars($existingProfile['tax_id'] ?? ''); ?>">
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label">Business Phone <span class="required-indicator">*</span></label>
                                <input type="tel" class="form-control" name="business_phone" 
                                       placeholder="0700000000" 
                                       value="<?php echo htmlspecialchars($existingProfile['business_phone'] ?? $userInfo['phone_number']); ?>" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label">Business Email</label>
                                <input type="email" class="form-control" name="business_email" 
                                       placeholder="business@example.com" 
                                       value="<?php echo htmlspecialchars($existingProfile['business_email'] ?? $userInfo['email']); ?>">
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label">Business District <span class="required-indicator">*</span></label>
                                <select class="form-select" name="business_district" required>
                                    <option value="">Select District</option>
                                    <?php foreach ($districts as $district): ?>
                                    <option value="<?php echo $district['id']; ?>" 
                                            <?php echo (isset($existingProfile['business_district']) && $existingProfile['business_district'] == $district['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($district['district_name']); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label">Buying Capacity <span class="required-indicator">*</span></label>
                                <select class="form-select" name="buying_capacity" required>
                                    <option value="small" <?php echo (isset($existingProfile['buying_capacity']) && $existingProfile['buying_capacity'] == 'small') ? 'selected' : ''; ?>>Small (< 1M UGX/month)</option>
                                    <option value="medium" <?php echo (isset($existingProfile['buying_capacity']) && $existingProfile['buying_capacity'] == 'medium') ? 'selected' : ''; ?>>Medium (1M - 10M UGX/month)</option>
                                    <option value="large" <?php echo (isset($existingProfile['buying_capacity']) && $existingProfile['buying_capacity'] == 'large') ? 'selected' : ''; ?>>Large (> 10M UGX/month)</option>
                                </select>
                            </div>
                            
                            <div class="col-12">
                                <label class="form-label">Business Address <span class="required-indicator">*</span></label>
                                <textarea class="form-control" name="business_address" rows="3" 
                                          placeholder="Street, Building, Landmark" required><?php echo htmlspecialchars($existingProfile['business_address'] ?? ''); ?></textarea>
                            </div>
                            
                            <div class="col-12">
                                <label class="form-label">Business Description</label>
                                <textarea class="form-control" name="business_description" rows="3" 
                                          placeholder="Brief description of your business activities"><?php echo htmlspecialchars($existingProfile['business_description'] ?? ''); ?></textarea>
                            </div>
                        </div>
                        
                        <div class="d-flex justify-content-between mt-4">
                            <button type="button" class="btn btn-outline-secondary btn-nav" id="step2Prev">
                                <i class="bi bi-arrow-left me-2"></i> Previous
                            </button>
                            <button type="button" class="btn btn-primary btn-nav" id="step2Next">
                                Next: Preferences <i class="bi bi-arrow-right ms-2"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Step 3: Preferences -->
                    <div class="form-section" id="step3">
                        <div class="section-title">
                            <i class="bi bi-sliders"></i>
                            Buying Preferences
                        </div>
                        
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Preferred Payment Method</label>
                                <select class="form-select" name="preferred_payment_method">
                                    <option value="cash">Cash</option>
                                    <option value="mobile_money">Mobile Money</option>
                                    <option value="bank_transfer">Bank Transfer</option>
                                    <option value="credit">Credit/Invoice</option>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label class="form-label">Delivery Preference</label>
                                <select class="form-select" name="delivery_preference">
                                    <option value="pickup">Self Pickup</option>
                                    <option value="delivery">Delivery Needed</option>
                                    <option value="flexible">Flexible</option>
                                </select>
                            </div>
                            
                            <div class="col-12">
                                <label class="form-label">Categories of Interest</label>
                                <small class="text-muted d-block mb-3">Select the product categories you're interested in purchasing</small>
                                
                                <div class="row g-2">
                                    <?php
                                    $categories = [
                                        'Grains & Cereals' => 'bi-basket',
                                        'Fruits' => 'bi-apple',
                                        'Vegetables' => 'bi-flower1',
                                        'Livestock' => 'bi-egg',
                                        'Dairy Products' => 'bi-cup-straw',
                                        'Coffee & Tea' => 'bi-cup-hot',
                                        'Spices' => 'bi-flower2',
                                        'Root Crops' => 'bi-flower3'
                                    ];
                                    
                                    foreach ($categories as $category => $icon):
                                    ?>
                                    <div class="col-md-6">
                                        <div class="category-checkbox">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="categories_of_interest[]" 
                                                       value="<?php echo htmlspecialchars($category); ?>" 
                                                       id="cat_<?php echo str_replace(' ', '_', $category); ?>">
                                                <label class="form-check-label" for="cat_<?php echo str_replace(' ', '_', $category); ?>">
                                                    <i class="<?php echo $icon; ?> me-2"></i><?php echo htmlspecialchars($category); ?>
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="info-box mt-4">
                            <i class="bi bi-lightbulb me-2"></i>
                            <small><strong>What's next?</strong> After completing your profile, you can start browsing products. Wholesalers, processors, and exporters will need to complete verification to unlock all features.</small>
                        </div>
                        
                        <div class="d-flex justify-content-between mt-4">
                            <button type="button" class="btn btn-outline-secondary btn-nav" id="step3Prev">
                                <i class="bi bi-arrow-left me-2"></i> Previous
                            </button>
                            <button type="submit" class="btn btn-primary btn-nav">
                                <i class="bi bi-check-circle me-2"></i> Complete Profile
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Back to Site Link -->
        <div class="text-center mt-3">
            <a href="<?php echo APP_URL; ?>/dashboard/" class="text-white text-decoration-none">
                <i class="bi bi-arrow-left me-2"></i>Back to Main Site
            </a>
        </div>
    </div>
    
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    
    <!-- Bootstrap Bundle -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- Select2 -->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
        $(document).ready(function() {
            let currentStep = 1;
            const totalSteps = 3;
            
            // Initialize Select2
            $('select').select2({
                theme: 'bootstrap-5'
            });
            
            // Buyer Type Selection
            $('.buyer-type-card').click(function() {
                $('.buyer-type-card').removeClass('selected');
                $(this).addClass('selected');
                const type = $(this).data('type');
                $('#buyerTypeInput').val(type);
            });
            
            // Step Navigation
            $('#step1Next').click(function() {
                if (!$('#buyerTypeInput').val()) {
                    alert('Please select a buyer type');
                    return;
                }
                goToStep(2);
            });
            
            $('#step2Prev').click(function() {
                goToStep(1);
            });
            
            $('#step2Next').click(function() {
                // Validate Step 2
                const form = document.getElementById('profileForm');
                const step2Inputs = $('#step2 input[required], #step2 select[required], #step2 textarea[required]');
                let valid = true;
                
                step2Inputs.each(function() {
                    if (!this.value) {
                        valid = false;
                        $(this).addClass('is-invalid');
                    } else {
                        $(this).removeClass('is-invalid');
                    }
                });
                
                if (!valid) {
                    alert('Please fill in all required fields');
                    return;
                }
                
                goToStep(3);
            });
            
            $('#step3Prev').click(function() {
                goToStep(2);
            });
            
            function goToStep(step) {
                // Hide all sections
                $('.form-section').removeClass('active');
                
                // Show target section
                $('#step' + step).addClass('active');
                
                // Update indicators
                $('.step').removeClass('active completed');
                
                for (let i = 1; i <= totalSteps; i++) {
                    if (i < step) {
                        $('#step' + i + 'Indicator').addClass('completed');
                    } else if (i === step) {
                        $('#step' + i + 'Indicator').addClass('active');
                    }
                }
                
                currentStep = step;
                
                // Scroll to top
                window.scrollTo({ top: 0, behavior: 'smooth' });
            }
            
            // Form validation
            $('#profileForm').submit(function(e) {
                const buyerType = $('#buyerTypeInput').val();
                const requiresRegistration = ['wholesaler', 'processor', 'exporter'].includes(buyerType);
                
                if (requiresRegistration && !$('input[name="business_registration"]').val()) {
                    alert('Business registration number is required for ' + buyerType + ' buyers');
                    e.preventDefault();
                    goToStep(2);
                    $('input[name="business_registration"]').focus();
                    return false;
                }
            });
        });
    </script>
</body>
</html>