<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\FoodOrder;
use App\Models\FoodOrderItem;
use App\Models\MenuItem;
use App\Models\Restaurant;
use App\Models\User;
use Carbon\Carbon;

class FoodOrderSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // التأكد من وجود مطاعم وعملاء
        $restaurants = Restaurant::all();
        $customers = User::where('user_type', 'passenger')->get();
        
        if ($restaurants->isEmpty() || $customers->isEmpty()) {
            $this->command->info('⚠️  يجب إنشاء مطاعم وعملاء أولاً');
            return;
        }

        $this->command->info('🌱 بدء إنشاء بيانات الطلبات الافتراضية...');

        // إنشاء طلبات معلقة (pending)
        $this->createPendingOrders($restaurants, $customers);
        
        // إنشاء طلبات مؤكدة (confirmed)
        $this->createConfirmedOrders($restaurants, $customers);
        
        // إنشاء طلبات قيد التحضير (preparing)
        $this->createPreparingOrders($restaurants, $customers);
        
        // إنشاء طلبات جاهزة (ready)
        $this->createReadyOrders($restaurants, $customers);
        
        // إنشاء طلبات مكتملة (completed)
        $this->createCompletedOrders($restaurants, $customers);
        
        // إنشاء طلبات مرفوضة (rejected)
        $this->createRejectedOrders($restaurants, $customers);

        $this->command->info('✅ تم إنشاء بيانات الطلبات بنجاح!');
    }

    private function createPendingOrders($restaurants, $customers)
    {
        for ($i = 0; $i < 5; $i++) {
            $restaurant = $restaurants->random();
            $customer = $customers->random();
            $menuItems = MenuItem::where('restaurant_id', $restaurant->id)->get();
            
            if ($menuItems->isEmpty()) continue;

            $order = FoodOrder::create([
                'restaurant_id' => $restaurant->id,
                'customer_id' => $customer->id,
                'order_number' => 'ORD-' . str_pad(rand(1000, 9999), 4, '0', STR_PAD_LEFT),
                'subtotal' => 0,
                'delivery_fee' => 2000,
                'tax' => 0,
                'total' => 0,
                'delivery_address' => $this->getRandomAddress(),
                'delivery_latitude' => 33.3152 + (rand(-100, 100) / 10000),
                'delivery_longitude' => 44.3661 + (rand(-100, 100) / 10000),
                'status' => 'pending',
                'payment_method' => $this->getRandomPaymentMethod(),
                'payment_status' => 'pending',
                'special_instructions' => $this->getRandomInstructions(),
                'created_at' => Carbon::now()->subMinutes(rand(5, 60)),
            ]);

            $this->createOrderItems($order, $menuItems);
            $this->updateOrderTotal($order);
        }
    }

    private function createConfirmedOrders($restaurants, $customers)
    {
        for ($i = 0; $i < 3; $i++) {
            $restaurant = $restaurants->random();
            $customer = $customers->random();
            $menuItems = MenuItem::where('restaurant_id', $restaurant->id)->get();
            
            if ($menuItems->isEmpty()) continue;

            $order = FoodOrder::create([
                'restaurant_id' => $restaurant->id,
                'customer_id' => $customer->id,
                'order_number' => 'ORD-' . str_pad(rand(1000, 9999), 4, '0', STR_PAD_LEFT),
                'subtotal' => 0,
                'delivery_fee' => 2000,
                'tax' => 0,
                'total' => 0,
                'delivery_address' => $this->getRandomAddress(),
                'delivery_latitude' => 33.3152 + (rand(-100, 100) / 10000),
                'delivery_longitude' => 44.3661 + (rand(-100, 100) / 10000),
                'status' => 'confirmed',
                'payment_method' => $this->getRandomPaymentMethod(),
                'payment_status' => 'paid',
                'special_instructions' => $this->getRandomInstructions(),
                'created_at' => Carbon::now()->subMinutes(rand(30, 120)),
            ]);

            $this->createOrderItems($order, $menuItems);
            $this->updateOrderTotal($order);
        }
    }

    private function createPreparingOrders($restaurants, $customers)
    {
        for ($i = 0; $i < 2; $i++) {
            $restaurant = $restaurants->random();
            $customer = $customers->random();
            $menuItems = MenuItem::where('restaurant_id', $restaurant->id)->get();
            
            if ($menuItems->isEmpty()) continue;

            $order = FoodOrder::create([
                'restaurant_id' => $restaurant->id,
                'customer_id' => $customer->id,
                'order_number' => 'ORD-' . str_pad(rand(1000, 9999), 4, '0', STR_PAD_LEFT),
                'subtotal' => 0,
                'delivery_fee' => 2000,
                'tax' => 0,
                'total' => 0,
                'delivery_address' => $this->getRandomAddress(),
                'delivery_latitude' => 33.3152 + (rand(-100, 100) / 10000),
                'delivery_longitude' => 44.3661 + (rand(-100, 100) / 10000),
                'status' => 'preparing',
                'payment_method' => $this->getRandomPaymentMethod(),
                'payment_status' => 'paid',
                'special_instructions' => $this->getRandomInstructions(),
                'created_at' => Carbon::now()->subMinutes(rand(60, 180)),
            ]);

            $this->createOrderItems($order, $menuItems);
            $this->updateOrderTotal($order);
        }
    }

    private function createReadyOrders($restaurants, $customers)
    {
        for ($i = 0; $i < 2; $i++) {
            $restaurant = $restaurants->random();
            $customer = $customers->random();
            $menuItems = MenuItem::where('restaurant_id', $restaurant->id)->get();
            
            if ($menuItems->isEmpty()) continue;

            $order = FoodOrder::create([
                'restaurant_id' => $restaurant->id,
                'customer_id' => $customer->id,
                'order_number' => 'ORD-' . str_pad(rand(1000, 9999), 4, '0', STR_PAD_LEFT),
                'subtotal' => 0,
                'delivery_fee' => 2000,
                'tax' => 0,
                'total' => 0,
                'delivery_address' => $this->getRandomAddress(),
                'delivery_latitude' => 33.3152 + (rand(-100, 100) / 10000),
                'delivery_longitude' => 44.3661 + (rand(-100, 100) / 10000),
                'status' => 'ready',
                'payment_method' => $this->getRandomPaymentMethod(),
                'payment_status' => 'paid',
                'special_instructions' => $this->getRandomInstructions(),
                'created_at' => Carbon::now()->subMinutes(rand(120, 240)),
            ]);

            $this->createOrderItems($order, $menuItems);
            $this->updateOrderTotal($order);
        }
    }

    private function createCompletedOrders($restaurants, $customers)
    {
        for ($i = 0; $i < 8; $i++) {
            $restaurant = $restaurants->random();
            $customer = $customers->random();
            $menuItems = MenuItem::where('restaurant_id', $restaurant->id)->get();
            
            if ($menuItems->isEmpty()) continue;

            $order = FoodOrder::create([
                'restaurant_id' => $restaurant->id,
                'customer_id' => $customer->id,
                'order_number' => 'ORD-' . str_pad(rand(1000, 9999), 4, '0', STR_PAD_LEFT),
                'subtotal' => 0,
                'delivery_fee' => 2000,
                'tax' => 0,
                'total' => 0,
                'delivery_address' => $this->getRandomAddress(),
                'delivery_latitude' => 33.3152 + (rand(-100, 100) / 10000),
                'delivery_longitude' => 44.3661 + (rand(-100, 100) / 10000),
                'status' => 'completed',
                'payment_method' => $this->getRandomPaymentMethod(),
                'payment_status' => 'paid',
                'special_instructions' => $this->getRandomInstructions(),
                'actual_delivery_time' => Carbon::now()->subHours(rand(1, 24)),
                'customer_rating' => rand(3, 5),
                'customer_feedback' => $this->getRandomFeedback(),
                'created_at' => Carbon::now()->subHours(rand(2, 48)),
            ]);

            $this->createOrderItems($order, $menuItems);
            $this->updateOrderTotal($order);
        }
    }

    private function createRejectedOrders($restaurants, $customers)
    {
        for ($i = 0; $i < 2; $i++) {
            $restaurant = $restaurants->random();
            $customer = $customers->random();
            $menuItems = MenuItem::where('restaurant_id', $restaurant->id)->get();
            
            if ($menuItems->isEmpty()) continue;

            $order = FoodOrder::create([
                'restaurant_id' => $restaurant->id,
                'customer_id' => $customer->id,
                'order_number' => 'ORD-' . str_pad(rand(1000, 9999), 4, '0', STR_PAD_LEFT),
                'subtotal' => 0,
                'delivery_fee' => 2000,
                'tax' => 0,
                'total' => 0,
                'delivery_address' => $this->getRandomAddress(),
                'delivery_latitude' => 33.3152 + (rand(-100, 100) / 10000),
                'delivery_longitude' => 44.3661 + (rand(-100, 100) / 10000),
                'status' => 'rejected',
                'payment_method' => $this->getRandomPaymentMethod(),
                'payment_status' => 'refunded',
                'special_instructions' => $this->getRandomInstructions(),
                'created_at' => Carbon::now()->subHours(rand(1, 12)),
            ]);

            $this->createOrderItems($order, $menuItems);
            $this->updateOrderTotal($order);
        }
    }

    private function createOrderItems($order, $menuItems)
    {
        $itemCount = rand(1, 4);
        $selectedItems = $menuItems->random(min($itemCount, $menuItems->count()));
        
        foreach ($selectedItems as $menuItem) {
            FoodOrderItem::create([
                'food_order_id' => $order->id,
                'menu_item_id' => $menuItem->id,
                'quantity' => rand(1, 3),
                'unit_price' => $menuItem->price,
                'total_price' => $menuItem->price * rand(1, 3),
            ]);
        }
    }

    private function updateOrderTotal($order)
    {
        $subtotal = $order->orderItems->sum('total_price');
        $tax = $subtotal * 0.1; // 10% ضريبة
        $total = $subtotal + $order->delivery_fee + $tax;

        $order->update([
            'subtotal' => $subtotal,
            'tax' => $tax,
            'total' => $total,
        ]);
    }

    private function getRandomAddress()
    {
        $addresses = [
            'شارع الرشيد، بغداد',
            'الكرادة، بغداد',
            'الجادرية، بغداد',
            'المنصور، بغداد',
            'البياع، بغداد',
            'الزعفرانية، بغداد',
            'الحرية، بغداد',
            'الكرخ، بغداد',
        ];
        
        return $addresses[array_rand($addresses)];
    }

    private function getRandomPaymentMethod()
    {
        $methods = ['cash', 'card', 'online'];
        return $methods[array_rand($methods)];
    }

    private function getRandomInstructions()
    {
        $instructions = [
            'يرجى عدم إضافة ملح كثير',
            'يرجى تسليم الطلب للبواب',
            'يرجى الاتصال عند الوصول',
            'الطابق الثالث، الشقة 15',
            'يرجى إضافة صلصة حارة',
            'يرجى عدم إضافة بصل',
            null,
            null,
        ];
        
        return $instructions[array_rand($instructions)];
    }

    private function getRandomFeedback()
    {
        $feedbacks = [
            'الطعام كان لذيذ جداً، شكراً لكم',
            'التوصيل كان سريع والطعام ساخن',
            'خدمة ممتازة، سأطلب مرة أخرى',
            'الطعام جيد لكن التوصيل تأخر قليلاً',
            'ممتاز، أنصح الجميع بهذا المطعم',
            'الطعام لذيذ والتوصيل سريع',
            'خدمة جيدة، شكراً لكم',
            'الطعام كان ساخن ولذيذ',
        ];
        
        return $feedbacks[array_rand($feedbacks)];
    }
}
