<?php

namespace Modules\Category\Services;

use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Category\Interfaces\CategoryRepositoryInterface;
use Modules\Category\Models\Category;
use Modules\MainService\Views\ViewFactory;
use Modules\User\Enums\UserRoleEnum;

class CategoryService
{
    public function __construct(
        private CategoryRepositoryInterface $categoryRepository,
        private ViewFactory $viewFactory
    ){}

    public function renderView($request = [])
    {
        $request['categories'] = $this->get($request);
        return $this->render($request);
    }

    public function render($request = [])
    {
        return $this->viewFactory
            ->render($request['view'])
            ->renderView($request);
    }

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

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

        if (@$request['start_price'])
        {
            $builder->where('categories.start_price', $request['start_price']);
        }

        if (@$request['end_price'])
        {
            $builder->where('categories.end_price', $request['end_price']);
        }

        if(@$request['employeeFilter'])
        {
            if($request['employeeFilter']->role == UserRoleEnum::Head_Department->value)
            {
                $builder->where(function ($q) use ($request) {
                    $q->where('added_by', $request['employeeFilter']->id)
                        ->orWhereHas('added', function ($query) use ($request) {
                            $query->where('manager_id', $request['employeeFilter']->id);
                        });
                });
            }
            else
            {
                $builder->where('added_by',$request['employeeFilter']->id);
            }
        }

        if (@$request['domain'])
        {
            $builder->where('categories.domain','LIKE', '%'.$request['domain'].'%');
        }

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

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

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

        if (@$request['orderBy'])
        {
            if($request['orderBy']['key'] == 'employee')
            {
                $builder
                    ->join('company_descriptions AS cd', 'contact_lists.company_id', 'cd.company_id')
                    ->where('local', LaravelLocalization::getCurrentLocale())
                    ->addSelect('cd.title as company_name',)
                    ->orderBy('company_name', $request['orderBy']['value']);
            }
            else
            {
                $builder->orderBy($request['orderBy']['key'],$request['orderBy']['value']);
            }
        }
        else
        {
            $builder->orderBy('id','DESC');
        }

        if (@$request['paginate']) {
            $categories= $builder->paginate(50);
        }
        elseif (@$request['groupSector'])
        {
            $categories = $builder->get()->groupBy(function($item) {
                return $item->sector->currentDescription->title;
            });

        }
        else
        {
            $categories=$builder->get();
        }
        return $categories;
    }

    public function getCategoryByBudget($budget)
    {
        $category = $this->categoryRepository->getCategoryByBudget($budget);
        return $category;
    }

    public function checkItem($id)
    {
        $category = $this->categoryRepository->checkItem($id);
        return $category;
    }

    public function getItem($id)
    {
        $category = $this->categoryRepository->getItem($id);

        return $category;
    }

    public function getItemTrashed($id)
    {
        $category = $this->categoryRepository->getItemTrashed($id);
        return $category;
    }

    public function create(array $request): Category
    {
        $category = $this->categoryRepository->create($request);
        $this->categoryRepository->saveData($request,$category->id);
        return $category;
    }
    public function update(array $request,int $id): Category
    {
        $category = $this->checkItem($id);
        $category = $this->categoryRepository->update($request,$category);
        if(@$request['title_en'])
        {
            $this->categoryRepository->saveData($request,$category->id);
        }
        return $category;
    }

    public function updateLock($id)
    {
        $category = $this->checkItem($id);
        $this->update(['lock'=>($category->lock?0:1)],$id);
    }

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