<?php
/**
 * ============================================================================
 * buyer/index.php
 * Buyer Portal Entry Point - Smart Routing
 * Routes buyers based on profile completion and verification status
 * ============================================================================
 */

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 buyer system
use App\Database;
$database = Database::getInstance();
$db = $database->getConnection();
$currentUserId = getUserId();
$buyerSystem = new BuyerSystem($database, $currentUserId);

// Smart routing logic
// Priority: Profile Completion -> Verification Status -> Dashboard

// 1. Check if buyer has completed their profile
if (!$buyerSystem->hasCompleteProfile()) {
    // Redirect to profile completion page
    header('Location: ' . APP_URL . '/buyer/complete-profile.php');
    exit();
}

// 2. Check if buyer needs verification (for premium buyer types)
$buyerType = $buyerSystem->getBuyerType();
$requiresVerification = in_array($buyerType, ['wholesaler', 'processor', 'exporter']);

if ($requiresVerification && !$buyerSystem->isVerified()) {
    // Check if verification is pending
    $profile = $buyerSystem->getProfile();
    
    if ($profile['verification_status'] === 'pending') {
        // Show verification pending page
        header('Location: ' . APP_URL . '/buyer/verification-pending.php');
        exit();
    } else {
        // Redirect to verification page
        header('Location: ' . APP_URL . '/buyer/verification.php');
        exit();
    }
}

// 3. All checks passed - show dashboard
header('Location: ' . APP_URL . '/buyer/dashboard.php');
exit();
?>