<?php

namespace App\Services;

use App\Models\Group;
use App\Models\Resource;
use App\Models\ModulePermission;
use App\Models\ResourcePermission;
use Illuminate\Support\Facades\DB;

class ResourceService
{
    public $reportService;
    public function __construct(ReportService $reportService)
    {
        $this->reportService = $reportService;
    }

    public function getAllResources()
    {
        return $this->reportService->getAllReports();
    }

    public function getAllResourceByModuleId($moduleId)
    {
        $prefix = config("srm_config.installer.table_prefix", "srm_");
        if(auth()->user()->isAdminOrOwner()) {
            return Resource::where(function ($q) use ($prefix, $moduleId) {
                $q->where(function ($q) use ($moduleId) {
                    $q->whereHas('module', function ($q) use ($moduleId) {
                        return $q->where('id', $moduleId);
                    })->orWhereHas('module.parent', function ($q) use ($moduleId) {
                        return $q->where('id', $moduleId);
                    });
                });
            })
            ->orderByDesc('created_at');

        }
        return Resource::where(function ($q) use ($prefix, $moduleId) {
            $q->where(function ($q) use ($moduleId) {
                $q->whereHas('module', function ($q) use ($moduleId) {
                    return $q->where('id', $moduleId);
                })->orWhereHas('module.parent', function ($q) use ($moduleId) {
                    return $q->where('id', $moduleId);
                });
            })->where(function ($q) use ($prefix, $moduleId) {
                $q->whereHas('resource_permissions', function ($q) use ($prefix, $moduleId) {
                    return $q->where($prefix . 'resource_permissions.group_id', auth()->user()->group_id);
                })->orWhere(function ($q) {
                    $q->where('access_control_type', 'Public');
                })->orWhere('resource_creator', auth()->id());
            });
        })
        ->orderByDesc('created_at');

    }

}
