<?php

namespace Database\Seeders;

use App\Models\OrderManagement\Order;
use App\Models\OrderManagement\BillingDesk;
use App\Models\ProductManagement\Product;
use App\Models\OrderManagement\ShippingCompany;
use App\Models\SettingManagement\Status;
use App\Models\StockManagement\Warehouse;
use App\Models\UserManagement\Customer;
use App\Models\UserManagement\User;
use App\Services\OrderService;
use Faker\Factory;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;


class OrderSeeder extends Seeder{

    public function run(){

        /*
         * Create fake order for each user (customers)
         */
        $count = 0;
        Customer::active()->get()->each(function ($customer)
        use(&$count)
         {

            foreach([1,rand(1,5)] as $index) {
                $shippingCompanies = ShippingCompany::get();
                $pointOfSales = BillingDesk::get();
                $warehouses = Warehouse::pointOfSales()->get();

                $products = Product::active()
                                    ->activeCategory()
                                    ->take(rand(1,5))
                                    ->get();
                $subTotalValue = 0;

                // Create Order Products
                $items = $products->map(function ($product) use (&$subTotalValue){
                                    $price = $product->price;
                                    $quantity = rand(1,5);

                                    $subTotalValue += $price * $quantity;
                                    return [
                                        "product_id" => $product->id,
                                        "quantity" => $quantity,
                                        "price" => $price,
                                    ];
                                })->toArray();

                //$subTotalValue = $products->sum('price');
                $discountValue = $subTotalValue / 2;
                $shippingValue = rand(5,100);
                $taxValue = ($subTotalValue - $discountValue) * round($shippingValue / 100 , 2);
                $totalValue = $subTotalValue - $discountValue + $shippingValue + $taxValue;

//                $year = date('Y');
//              //  $startDate = "$year-01-01";  // '-7 months'
//                $endDate = "$year-12-31"; //  'now'

//                $created_at = fake()->dateTimeBetween($startDate, $endDate);
//                $updated_at = fake()->dateTimeBetween($startDate, $endDate);

//                $created_at = fake()->dateTimeThisYear($endDate);
//                $updated_at = fake()->dateTimeThisYear($endDate);

//                $period = format_date($created_at,'Y-m');

              // $orderId =  Order::newId($created_at,$period);

                $orderDatas = [
                    "items" => $items,
                    "order" => [
                        //'ref_id' => $orderId,
                        "customer_id" => $customer->id,
                        'shipping_company_id' => (filled($shippingCompanies)) ? $shippingCompanies->random()->id : null,
                        'point_of_sale_id' =>  (filled($pointOfSales)) ? $pointOfSales->random()->id : null,
                        'warehouse_id' =>  (filled($warehouses)) ? $warehouses->random()->id : null,
                        'payment_method_id' => null,
                        'subtotal' => $subTotalValue,
                        'discount_code' => fake()->slug(1,false),
                        'discount' => $discountValue,
                        'shipping' => $shippingValue,
                        'tax' => $taxValue,
                        'total' => $totalValue,
                        'currency' => getSettingsOf("currency"),
//                        'status_code' => fake()->randomElement($statusesId),
//                        'created_at' => $created_at,
//                        'updated_at' => $updated_at,
                    ],
                ];

                $options = [
                    "ckeck-stock" => filled($orderDatas['order']['warehouse_id']),
                    "use-payment" => ($customer->balance >= $totalValue),
                    "generate-invoice" => rand(1,0),
                ];

//                var_dump($options);

              $result =   (new OrderService)->saveOrder($orderDatas,$customer,$options);

              if ($result['success']){
                  $count++;
                  echo ($result["message"]."\n");

                  $order = Order::find($result['order']['id']);
                  $statuses = [
                      Status::UNDER_PROCESS,
                      Status::DELIVERED,
                      Status::REFUNDED_REQUEST,
                      Status::RETURNED_ORDER,
                      Status::REFUNDED_ORDER,
                      Status::REJECTED,
                  ];
                  $order->setStatusTo(fake()->randomElement($statuses));
              }
              echo ($result["message"]."\n");
            }

        });

        echo __(":count Orders created\n",['count' => format_amount($count)]);
    }
}
