<?php

namespace App\Models;

use App\Models\Resource;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;

class Module extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $primaryKey = 'id';
    protected $connection = 'mysql';

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $prefix = config('srm_config.installer.table_prefix', 'srm_');
        $this->table = "{$prefix}modules";
    }


    public function children()
    {
        return $this->hasMany(Module::class, 'parent_id'); // you may use self::class instead of Category::class
    }

    public function parent()
    {
        return $this->belongsTo(Module::class, 'parent_id'); // you may use self::class instead of Category::class
    }

    public function resources()
    {
        return $this->hasMany(Resource::class, 'module_id'); // you may use self::class instead of Category::class

    }

    public function module_permissions()
    {
        $prefix = config("srm_config.installer.table_prefix", "srm_");

        return $this->belongsToMany(Group::class, $prefix . 'modules_premissions', 'module_id', 'group_id');
    }

    public function checkWhoCanAccessModule()
    {
        foreach ($this->module_permissions as $group) {
            if (isset($group->pivot) && $group->pivot->group_id == auth()->user()->group_id) {
                return true;
            }
        }
        if($this->parent) {
            foreach ($this->parent->module_permissions as $group) {
                if (isset($group->pivot) && $group->pivot->group_id == auth()->user()->group_id) {
                    return true;
                }
            }

        }

        return false;
    }

    public static function getBlankReportModule()
    {
        return static::where('name', 'Blank Reports')->first();
    }

    public static function getChartModule()
    {
        return static::where('name', 'Charts')->first();
    }
    public static function getMetricModule()
    {
        return static::where('name', 'KPIs / Metrics')->first();
    }

}
