<?php

namespace Modules\Order\Repositories;

use Illuminate\Http\Request;
use Modules\Order\Models\Cart;
use Modules\Order\Interfaces\CartRepositoryInterface;

class CartRepository implements CartRepositoryInterface
{

    public function get($request)
    {
        $query = Cart::orderBy('id', 'DESC');

        if ($request->user_id)
        {
            $query->where('user_id',$request->user_id);
        }

        if ($request->status)
        {
            $query->where('status',$request->status);
        }

        if ($request->date_from) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }


        if ($request->paginate ?? null) {
            $carts = $query->paginate(50);
        } else {
            $carts = $query->cursor();
        }

        return $carts;
    }


    public function getItem(Cart $cart)
    {
        return $cart;
    }

    public function getCart(Request $request)
    {
        $cart = Cart::query()
            ->where('status',$request->status)
            ->where('user_id',$request->user_id)
            ->where('product_id',$request->product_id)
            ->where('main_attribute_id',$request->main_attribute_id)
            ->where('sub_attribute_id',$request->sub_attribute_id)
            ->first();
        return $cart;
    }

    public function store(Request $request): Cart
    {
        $data = $request->all();
        unset($data['id']);// for security reasons
        $cart = Cart::create($data);
        return $cart;
    }

    public function update(Request $request,$cart): Cart
    {
        $data = $request->all();
        unset($data['id']);// for security reasons
        $cart->update($data);
        return $cart;
    }


    /**
     * Remove the specified client from storage.
     * @param Request $request
     * @param int $id
     * @return array
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :array
    {
        $cart = Cart::find($id);
        if ($cart)
        {
            $cart->delete();
            return [ ['message'=> __('dashboard.deletedDone')]];
        }
        return [ ['message'=> __('dashboard.noResult')], 400];
    }

    public function destroyAll(Request $request)
    {
        $carts = $this->get($request);
        foreach ($carts as $row)
        {
            $row->delete();
        }
    }

}
