<?php
require_once 'config/database.php';
require_once 'utils/helpers.php';

echo "Seeding test orders...\n";

try {
    // Get some users
    $stmt = $pdo->query("SELECT id, email FROM users LIMIT 3");
    $users = $stmt->fetchAll();
    
    if (count($users) === 0) {
        echo "No users found. Please create users first.\n";
        exit;
    }

    $orderStatuses = ['completed', 'processing', 'pending', 'cancelled'];
    $paymentStatuses = ['paid', 'unpaid', 'refunded'];
    $plans = [
        ['name' => 'Basic Plan', 'price' => 9.99, 'tier' => 'basic'],
        ['name' => 'Pro Plan', 'price' => 29.99, 'tier' => 'pro'],
        ['name' => 'Enterprise Plan', 'price' => 99.99, 'tier' => 'enterprise']
    ];

    for ($i = 1; $i <= 10; $i++) {
        $user = $users[array_rand($users)];
        $plan = $plans[array_rand($plans)];
        $orderId = generateUUID();
        $orderNumber = "ORD-" . date('Ymd') . "-" . str_pad($i, 4, '0', STR_PAD_LEFT);
        $status = $orderStatuses[array_rand($orderStatuses)];
        $paymentStatus = ($status === 'completed') ? 'paid' : $paymentStatuses[array_rand($paymentStatuses)];
        
        $stmt = $pdo->prepare("
            INSERT INTO orders (id, user_id, order_number, status, payment_status, total_amount, customer_email, customer_name, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, datetime('now', '-" . rand(1, 30) . " days'))
        ");
        
        $stmt->execute([
            $orderId,
            $user['id'],
            $orderNumber,
            $status,
            $paymentStatus,
            $plan['price'],
            $user['email'],
            explode('@', $user['email'])[0]
        ]);
        
        // Add order item
        $itemId = generateUUID();
        $itemStmt = $pdo->prepare("
            INSERT INTO order_items (id, order_id, product_type, product_name, quantity, unit_price, total_price, metadata)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");
        
        $itemStmt->execute([
            $itemId,
            $orderId,
            'subscription',
            $plan['name'],
            1,
            $plan['price'],
            $plan['price'],
            json_encode(['tier' => $plan['tier']])
        ]);
        
        echo "Created order: $orderNumber for {$user['email']}\n";
    }

    echo "\n✅ Orders seeding completed successfully!\n";
} catch (Exception $e) {
    echo "❌ Error seeding orders: " . $e->getMessage() . "\n";
}
?>
