<?php

namespace App\Models;

use App\Models\SM\Fnction;
use App\Models\SM\FnctionPermission;
use App\Models\SM\Permission;
use App\Models\SM\Role;
use App\Models\SM\RoleFnction;
use App\Models\SM\UserRole;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use stdClass;

class User extends Authenticatable
{
    use HasFactory, Notifiable, HasApiTokens, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'created_at' => 'date:d/m/Y',
            'password' => 'hashed',
        ];
    }

    public function roles()
    {
        return $this->belongsToMany(Role::class, UserRole::class, 'user_id', 'role_id');
    }

    public function permissions()
    {
        $permission_id = [];
        foreach ($this->roles as $role) {
            array_push($permission_id, ...$role->fncPermissions->pluck('id')->toArray());
        }
        return FnctionPermission::with('permission')->whereIn('id', $permission_id)->get();
    }

    public function fnctions()
    {
        $fnc_id = [];
        foreach($this->roles as $role){
            array_push($fnc_id,...$role->fnctions->pluck('id')->toArray());
        }
        return Fnction::with('permissions')->whereIn('id',$fnc_id)->get()->map(function($item){
            $fnc = new stdClass;
            $fnc->code = $item->code;
            $permissions = $this->permissions()->whereIn('id',$item->permissions->pluck('pivot.id')->toArray())->pluck('permission.name')->toArray();
            $fnc->permissions = $permissions;
            return $fnc;
        });
    }

    public function hasPermission($fnction)
    {
        $fnction  = explode('.', $fnction);
        $permissions = explode(',', $fnction[1]);
        foreach ($this->fnctions() as $fnc) {
            if ($fnction[0] === $fnc->code && count(array_intersect($permissions, $fnc->permissions))) {
                return true;
            }
        }
        return false;
    }
}
