<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Relations\HasMany;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'Username',
        'email',
        'password',
        "UserCode",
        "National_ID",
        "FullName", 
        "Phone",
        "Address",
        "Role_ID",
    ];

    /**
     * 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',
            'password' => 'hashed',
        ];
    }

    protected $table = "users";

    static public function getUsers(){

        return User::select('users.*', 'roles_2.name as role_name')->join('roles_2','roles_2.id', '=', 'users.Role_ID')->get();
    }

    static public function getRecords(){
        return RoleModel::get();
    }
    static public function getUser($id){
        return User::find($id);
    }
    static public function getRecord($id){
        return RoleModel::find($id);
    }
    public function userPermissions(): HasMany
{
    return $this->hasMany(UserPermission::class, 'user_id');
}

public function hasPermission($slug): bool
{
    // Check if a user-specific permission exists
    $userPermission = $this->userPermissions()
        ->join('permissions_1', 'permissions_1.id', '=', 'user_permissions.permission_id')
        ->where('permissions_1.slug', $slug)
        ->first();

    if ($userPermission) {
        return (bool) $userPermission->has_permission;
    }

    // If no user-specific override, fallback to role permissions
    return PermissionRolesModel::getPermission($slug, $this->Role_ID) > 0;
}


}
