<?php

namespace Modules\Order\Services;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Modules\Coupon\Services\CouponService;
use Modules\Order\Interfaces\CartRepositoryInterface;
use Modules\Order\Models\Cart;
use Modules\Product\Models\ProductAttribute;
use Modules\Product\Services\ProductService;
use Modules\Setting\Enums\SettingOnHandCostValidEnum;
use Modules\Setting\Enums\SettingTaxValidEnum;
use Modules\Shipping\Interfaces\ShippingRepositoryInterface;
use Modules\Shipping\Models\ShippingCity;
use Modules\Shipping\Services\ShippingService;
use Modules\ShippingWay\Services\ShippingWayService;

class CartService
{
    public function __construct(
        private CartRepositoryInterface $cartRepository,
        private CouponService $couponService,
        private ProductService $productService,
    ){}

    public function get(array $request)
    {
        $builder = $this->cartRepository->get($request);

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

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

        $carts = $builder->get();
        return $carts;
    }

    public function getByBrand($request)
    {
        $carts = $this->get($request);
        $products = $carts->groupBy(function ($cart) {
            return $cart->product->brand_id;
        });
        return $products;
    }

    public function getItem(int $id)
    {
        $cart = $this->cartRepository->getItem($id);
        return $cart;
    }

    public function getCart(array $request)
    {
        return $this->cartRepository->getCart($request);
    }

    public function store(array $request): Cart
    {
        $cart = $this->getCart($request);
        if ($cart)
        {
            $data =
            [
                'count' => $cart->count + $request['count']
            ];
            $cart = $this->cartRepository->update($data,$cart);
        }
        else
        {
            $cart = $this->cartRepository->store($request);
        }

        return $cart;
    }
    public function update(array $request, int $id): Cart
    {
        $cart = $this->getItem($id);
        $cart = $this->cartRepository->update($request,$cart);
        return $cart;
    }
    public function destroy(int $id): array
    {
        $cart = $this->getItem($id);
        $response = $this->cartRepository->destroy($cart);
        return $response;
    }


    public function calculate(array $request)
    {
        $response = [];
        $carts = [];
        $total_tax = 0;
        $total_products = 0;
        $total_products_tax = 0;
        $shipping_cost = 0;
        $on_hand_cost = 0;
        $discount = 0;
        $discount_offer = 0;
        $cart_products = $this->get($request);
        $product_costs = 0;
        $product_cost = 0;
        foreach ($cart_products as $key=>$row)
        {
            $carts[$key]['id'] = $row->id;
            $carts[$key]['product'] = $row->product;
            $carts[$key]['count'] = $row->count;
            $product_cost_arr = $row->product->cost;
            $product_price_arr = $row->product->price;
            $product_cost = $product_cost_arr['cost'] * $row->count;
            $product_costs += $product_cost;
            $total_products += getAmountDetails($product_cost_arr['cost'])['amount'] * $row->count;
            $total_tax += getAmountDetails($product_cost_arr['cost'])['tax'] * $row->count;
            if ($product_price_arr['offer_discount'] != 0)
            {
                $discount_offer += $product_price_arr['offer_discount'];
            }
        }

        $total = $product_costs;

        if (isset($request['coupon']))
        {
            $discount = $this->couponService->discount([
                'total'=>$total,
                'coupon'=>$request['coupon']
            ]);
            $product_cost -= $discount;
            $total -= $discount;
        }

        //Sale
        $total -= $discount_offer;


        if ($total < 0)
        {
            $total = 0;
        }

        $shipping_cost = $request['user']->address->city->shipping_cost;
        $total += $shipping_cost;
        $on_hand_cost_valid = settings('on_hand_cost_valid');
        if (isset($request['payment_way_id']))
        {

            if ($request['payment_way_id'] == 1 && $on_hand_cost_valid == SettingOnHandCostValidEnum::TRUE->value)
            {
                $on_hand_cost = settings('on_hand_cost');
                $total += $on_hand_cost;
            }
        }

        $response['products_count'] = $cart_products->sum('count');
        $response['carts'] = $carts;
        $response['total_products'] = number_format($total_products,2);
        $response['total_tax'] = number_format($total_tax,2);
        $response['product_costs'] = number_format($product_costs,2);
        $response['shipping_cost'] = number_format($shipping_cost,2);
        $response['on_hand_cost'] = number_format($on_hand_cost,2);
        $response['discount_offer'] = number_format($discount_offer,2);
        $response['discount'] = number_format($discount,2);
        $response['total_products_tax'] = number_format($total_products_tax,2);
        $response['total'] = number_format($total ,2);

        return $response;
    }

    public function changeCart($visitor , $user)
    {
        $carts = $this->get([
            'user_status'=>$visitor['status'],
            'user_id'=>$visitor['user']->id
        ]);
        foreach ($carts as $cart)
        {
            $this->update([
               'user_status'=>$user['status'],
               'user_id'=>$user['user']->id
            ],$cart->id);
        }
    }
    public function emptyCart(array $request)
    {
        $carts = $this->get([
            'user_status'=>$request['user_status'],
            'user_id'=>$request['user_id']
        ]);
        foreach ($carts as $cart)
        {
            $this->destroy($cart->id);
        }
    }

}
