<?php

namespace Modules\User\Services;

use Modules\User\Enums\UserRoleEnum;
use Modules\User\Interfaces\CanteenModuleRepositoryInterface;

class CanteenModuleService
{

    private CanteenModuleRepositoryInterface $canteenModuleRepository ;

    public function __construct(CanteenModuleRepositoryInterface $canteenModuleRepository)
    {
        $this->canteenModuleRepository = $canteenModuleRepository;
    }

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

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

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

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

        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','ASC');
        }

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

        return $modules;
    }

    public function checkModuleAccess($path , $user_id)
    {
        if (auth()->user()->role == UserRoleEnum::CANTEEN->value)
        {
            return true;
        }
        $module = $this->canteenModuleRepository->getItemByPath($path);
        return $this->canteenModuleRepository->checkModuleAccess($module->id,$user_id);
    }
}
