<?php

namespace App\Services;

use App\Models\Module;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use Report;

class ModuleService
{
    public function getAll($conditions)
    {
        return Module::where($conditions)->with('children', function ($child) use ($conditions) {
            return $child->where(['is_active' => true]);
        })->get();
    }

    public function getAllWithResources($conditions)
    {
        return Module::where($conditions)->with('children', function (Builder $child) use ($conditions) {
            return $child
                ->where(['is_active' => true])
                ->with('resources', fn ($resource) => $resource->where('access_control_type', 'Private'));
        })
            ->with('resources', fn ($resource) => $resource->where('access_control_type', 'Private'))
            ->get();
    }

    public function checkModuleOnlyActiveInChildren($parent, $module)
    {
        return Module::where('name', $parent)->where('is_active', 1)->whereHas('children', function ($q) use ($module) {
            return $q->where('name', '!=', $module)->where('is_active', false);
        })->exists();
    }

    public function checkCurrentUserGroupCanCreateModule($module)
    {
        $ids = [];
        $modules = $this->getAllModuleWithChildren($module)->get();
        foreach ($modules as $group) {
            $ids[] = $group->module_permissions->pluck('group_ID')->toArray();

            $ids = array_merge(...$ids);

            if (isset($module->children)) {
                foreach ($module->children as $childGroups) {
                    $ids[] = $childGroups->module_permissions->pluck('group_ID')->toArray();
                    $ids = array_merge(...$ids);

                }
            }
        }
        return in_array(auth()->user()->group_id, $ids);
    }



    public function getAllModuleWithChildren($module)
    {
        return Module::where('name', $module)->where('is_active', true)->with('children', function ($q) {
            return $q->where('is_active', true);
        })->whereHas('module_permissions');
    }

    public function getModuleByName($module)
    {
        return Module::where('name', $module)->where('is_active', true)->first();

    }
}
