<?php
namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Mtc\Shop\Order;
use Mtc\Shop\Order\Item as OrderItem;
use DeliveryMethod;
use Mtc\Modules\Members\Models\Member;

class OrderFactory extends Factory
{
    protected $model = Order::class;

    public function definition(): array
    {
        $delivery = DeliveryMethod::inRandomOrder()->first();

        return [
            'paid'                  => 1,
            'date'                  => now(),
            'delivery_method_id'    => $delivery->id,
            'delivery_name'         => $delivery->name,
            'delivery_cost'         => $delivery->cost,
            'cost_total'            => 0,
            'cost_total_exvat'      => 0,
            'status'                => fake()->randomElement([0,1]),
            // … all your other columns …
            'member'                => Member::factory(),
            'admin_id'              => 1,
        ];
    }

    public function configure()
    {
        return $this->afterCreating(function(Order $order){
            $items = OrderItem::factory()
                ->count(rand(1,3))
                ->for($order, 'order')
                ->create();

            $sumExVat = $items->sum('price_paid_exvat');
            $sumInVat = $items->sum('price_paid');

            $order->update([
                'cost_total_exvat' => $sumExVat,
                'cost_total'       => $sumInVat + $order->delivery_cost,
            ]);
        });
    }
}