<?php

namespace Modules\ChipOrder\Services;

use DB;
use Modules\Address\Services\AddressService;
use Modules\Chip\Services\ChipService;
use Modules\ChipOrder\Enums\StatusEnum;
use Modules\ChipOrder\Interfaces\ChipOrderRepositoryInterface;
use Modules\ChipOrder\Models\ChipOrder;

class ChipOrderService
{
    private ChipOrderRepositoryInterface $chipOrderRepositoryInterface;

    public function __construct(
        ChipOrderRepositoryInterface $chipOrderRepositoryInterface,
        private AddressService $addressService,
        private ChipService $productService,
    ) {
        $this->chipOrderRepositoryInterface = $chipOrderRepositoryInterface;
    }

    public function get(array $request = [])
    {
        $builder = $this->chipOrderRepositoryInterface->get($request);

        if (@$request['total']) {
            $builder->where('total', $request['total']);
        }
        if (@$request['id']) {
            $builder->where('id', $request['id']);
        }
        if (@$request['user_id']) {
            $builder->where('user_id', $request['user_id']);
        }

        if (@$request['phone']) {
            $builder->whereHas('user', function ($query) use ($request) {
                $query->where('phone', $request['phone']);
            });
        }

        if (@$request['city_id']) {
            $builder->whereHas('address', function ($query) use ($request) {
                $query->where('city_id', $request['city_id']);
            });
        }

        if (isset($request['typeStatus'])) {
            $builder->where('status', $request['typeStatus']);
        }

        if (@$request['user']) {
            $builder->whereHas('user', function ($query) use ($request) {
                $query->where('name', 'LIKE', '%' . $request['user'] . '%');
            });
        }


        if (@$request['date_from']) {
            $builder->whereDate('chip_orders.created_at', '>=', $request['date_from']);
        }

        if (@$request['date_to']) {
            $builder->whereDate('chip_orders.created_at', '<=', $request['date_to']);
        }

        if (isset($request['status'])) {
            if (@$request['status'] == 0) {
                $builder->onlyTrashed();
            }
        }

        if (@$request['orderBy']) {
            $builder->orderBy($request['orderBy']['key'], $request['orderBy']['value']);
        } else {
            $builder->orderBy('updated_at', 'DESC');
        }

        if (@$request['paginate']) {
            $orders = $builder->paginate(50);
        } elseif (@$request['api']) {
            $orders = $builder;
        } else {
            $orders = $builder->cursor();
        }
        return $orders;
    }


    public function checkItem($id)
    {
        $order = $this->chipOrderRepositoryInterface->checkItem($id);
        return $order;
    }

    public function getItem($id)
    {
        $order = $this->checkItem($id);

        return $order;
    }

    public function getItemTrashed($id)
    {
        $order = $this->chipOrderRepositoryInterface->getItemTrashed($id);
        return $order;
    }
    public function getTotal(array $request)
    {
        return DB::transaction(function () use ($request) {
            $data = [];
            // Calculate total order values
            $total = 0;

            foreach ($request['products'] as $item) {
                $product = $this->productService->getItem($item['chip_id']) ?? null;
                if (!$product) {
                    continue; // Skip if product not found
                }
                $total += $product->cost * $item['count']; // Assuming price field exists in Product;
            }
            $data['shipping_cost'] = $address->city->shipping_price ?? 0;
            $data['tax_cost'] = settings('tax_valid') == "1" ? $total * (settings('tax_value') / 100) : 0;
            $total = $data['shipping_cost'] + $data['tax_cost'] + $total;


            return $total;
        });
    }
    public function create(array $request): ChipOrder
    {
        return DB::transaction(function () use ($request) {
            $data = [];
            // Calculate total order values
            $total = 0;

            foreach ($request['products'] as $item) {
                $product = $this->productService->getItem($item['chip_id']) ?? null;
                if (!$product) {
                    continue; // Skip if product not found
                }
                $total += $product->cost * $item['count']; // Assuming price field exists in Product;
            }
            $address = $this->addressService->getItem($request['address_id']);
            $data['address_id'] = $request['address_id'];
            $data['shipping_cost'] = $address->city->shipping_price ?? 0;
            $data['user_id'] = $request['user_id'] ?? auth()->user()->id;
            $data['tax_cost'] = settings('tax_valid') == "1" ? $total * (settings('tax_value') / 100) : 0;
            $data['total'] = $data['shipping_cost'] + $data['tax_cost'] + $total;
            $data['status'] = StatusEnum::PREPARING->value;

            // Create the order
            $order = $this->chipOrderRepositoryInterface->create($data);



            // Attach products to order
            foreach ($request['products'] as $item) {
                $product = $this->productService->getItem($item['chip_id']) ?? null;
                $this->chipOrderRepositoryInterface->createOrderProduct([
                    'chip_order_id' => $order->id,
                    'chip_id' => $item['chip_id'],
                    'count' => $item['count'],
                    'price' => $product->cost,
                ]);
                $this->productService->updateMain(['count' => $product->count - $item['count']], $item['chip_id']);

            }

            return $order;
        });
    }
    public function update(array $request, int $id): ChipOrder
    {
        $order = $this->checkItem($id);
        $order = $this->chipOrderRepositoryInterface->update($request, $order);
        return $order;
    }
    public function destroy(int $id): void
    {
        $order = $this->checkItem($id);
        if ($order) {
            $this->chipOrderRepositoryInterface->destroy($order);
        } else {
            $order = $this->getItemTrashed($id);
            $this->chipOrderRepositoryInterface->restore($order);
        }
    }
    public function destroyAll(array $request): void
    {
        if ($request['status'] == 1) {
            $this->chipOrderRepositoryInterface->destroyAll($request['ids']);
        } else {
            $this->chipOrderRepositoryInterface->restoreAll($request['ids']);
        }
    }
}
