<?php

namespace App\Repositories\Ecommerce\Order;

use App\Events\Ecommerce\Product\Order\OrderCreated;
use App\Models\Ecommerce\Product\Order\Order;
use App\Models\Ecommerce\Product\Order\Shipping\OrderShipping;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

class OrderRepository
{
    /**
     * Order repo
     */
    public function __construct(
        protected array $data = [],
    ) {}

    /**
     * Create new order
     */
    public function create()
    {
        $order = Order::create(Arr::except($this->data, ['product_ids']));

        if (isset($this->data['product_ids'])) {
            foreach ($this->data['product_ids'] as $product_id) {
                $cartItems = auth()->user()->carts()->where('product_id', $product_id)->get();
                foreach ($cartItems as $cartItem) {
                    DB::table('order_items')->insert([
                        'product_name' => $cartItem->product->name,
                        'product_id' => $cartItem->product_id,
                        'order_id' => $order->id,
                        'channel_id' => $cartItem->product->channels->first()?->id ?? tmpostChannel()->id,
                        'quantity' => $cartItem->product_quantity,
                        'unit_price_amount' => $cartItem->product->price_amount,
                        'unit_cost_amount' => $cartItem->product->cost_amount,
                    ]);
                }
                $cartItems->each(function ($cartItem) {
                    $cartItem->delete();
                });
            }
        } else {
            auth()->user()->carts()->with(['product' => [
                'media',
                'channels',
            ]])->get()->each(function ($cart) use ($order) {
                DB::table('order_items')->insert([
                    'product_name' => $cart->product->name,
                    'product_id' => $cart->product_id,
                    'order_id' => $order->id,
                    'channel_id' => $cart->product->channels->first()?->id ?? tmpostChannel()->id,
                    'quantity' => $cart->product_quantity,
                    'unit_price_amount' => $cart->product->price_amount,
                    'unit_cost_amount' => $cart->product->cost_amount,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);

                $cart->product->update([
                    'stock' => $cart->product->stock - $cart->product_quantity,
                ]);
            });

            auth()->user()->carts()->delete();
        }

        OrderCreated::dispatch($order);

        return $order;
    }

    /**
     * Available times
     */
    public static function availableTimes(): array
    {
        $today = now()->format('d.m.Y');
        $tomorrow = now()->addHour(24)->format('d.m.Y');
        $times = [
            'today' => [],
            'tomorrow' => [],
        ];

        if (strtotime('now') <= strtotime('09:00')) {
            $times['today'][] = [
                'date' => $today,
                'hour' => OrderShipping::MORNING,
            ];
        }

        if (strtotime('now') <= strtotime('13:00')) {
            $times['today'][] = [
                'date' => $today,
                'hour' => OrderShipping::EVENING,
            ];
        }

        $times['tomorrow'] = [
            [
                'date' => $tomorrow,
                'hour' => OrderShipping::MORNING,
            ],
            [
                'date' => $tomorrow,
                'hour' => OrderShipping::EVENING,
            ],
        ];

        return [
            'dates' => [
                'today' => $today,
                'tomorrow' => $tomorrow,
            ],
            'hours' => $times,
        ];
    }
}
