<?php

namespace Modules\User\Services;

use Illuminate\Http\Request;
use Modules\User\Enums\UserRoleEnum;
use Modules\User\Interfaces\ModuleRepositoryInterface;

class ModuleService
{

    public function __construct(
        private ModuleRepositoryInterface $moduleRepository,
        private UserService $userService
    ){}

    public function get(array $request)
    {
        $builder = $this->moduleRepository->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['dashboard'])
        {
            $builder->where('dashboard','LIKE', '%'.$request['dashboard'].'%');
        }

        if(@$request['sidebar'])
        {
            $builder->where('sidebar_status',true);
        }

        if (@$request['user_id'])
        {
            $user = $this->userService->getItem($request['user_id']);
            // $builder->whereHas('users',function ($query) use ($request){
            //     $query->where('user_id',$request['user_id']);
            // });
            if($user->role != UserRoleEnum::SUPER_ADMIN->value)
            {
                $builder->whereHas('users',function ($query) use ($request){
                    $query->where('user_id',$request['user_id']);
                });
            }
        }
        if (@$request['title'])
        {
            $builder->where('status','LIKE', '%'.$request['title'].'%');
        }

        if (@$request['orderBy'])
        {
            $builder->orderBy($request['orderBy']['key'],$request['orderBy']['value']);
        }
        else
        {
            $builder->orderBy('id','ASC');
        }

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

        return $modules;
    }

    public function checkModuleAccess(array $content , $user_id)
    {
        $module = $this->moduleRepository->getItemByPath($content);
        $role = auth()->user()->role;
        if($role == UserRoleEnum::SUPER_ADMIN->value)
        {
            return true;
        }
        return $this->moduleRepository->checkModuleAccess(($module->id ?? null),$user_id);
    }
}