<?php

namespace Modules\Brand\Services;

use Illuminate\Http\Request;
use Modules\Brand\Interfaces\BrandRepositoryInterface;
use Modules\Brand\Models\Brand;
use Modules\Product\Models\ProductWarehouse;

class BrandService
{
    private BrandRepositoryInterface $brandRepository ;

    public function __construct(BrandRepositoryInterface $brandRepository)
    {
        $this->brandRepository = $brandRepository;
    }

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

        if (@$request['title'])
        {
            $builder->where('sd.title', 'LIKE', '%'.$request['title'].'%');
        }
        if (@$request['date_from'])
        {
            $builder->whereDate('brands.created_at', '>=', $request['date_from']);
        }

        if (@$request['date_to'])
        {
            $builder->whereDate('brands.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('id','DESC');
        }

        if (@$request['paginate']) {
            $brands= $builder->paginate(50);
        }else{
            $brands=$builder->cursor();
        }
        return $brands;
    }
    public function checkItem($id)
    {
        $brand = $this->brandRepository->checkItem($id);
        return $brand;
    }

    public function getItem($id)
    {
        $brand = $this->brandRepository->getItem($id);

        return $brand;
    }


    public function getItemTrashed($id)
    {
        $brand = $this->brandRepository->getItemTrashed($id);
        return $brand;
    }

    public function create(array $request): Brand
    {
        $brand = $this->brandRepository->create($request);
        $this->brandRepository->saveData($request,$brand->id);
        return $brand;
    }
    public function update(array $request,int $id): Brand
    {
        $brand = $this->checkItem($id);


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