<?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 Laravel\Sanctum\HasApiTokens;
use App\Models\Scopes\TenantScope;
Use DB;


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

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

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

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
        'permissions' => 'array',
        'is_active' => 'boolean'
    ];

    public function tenant()
{
    return $this->belongsTo(Tenant::class);
}

protected static function booted()
{
    static::addGlobalScope(new TenantScope);

    static::creating(function ($model) {
        if (app()->bound('currentTenant') && empty($model->tenant_id)) {
            $model->tenant_id = app('currentTenant')->id;
        }
    });
}

    public function servedQueues()
    {
        return $this->hasMany(WaitingQueue::class, 'served_by');
    }

    public function createdAppointments()
    {
        return $this->hasMany(Appointment::class, 'created_by');
    }

    public function activityLogs()
    {
        return $this->hasMany(ActivityLog::class);
    }

    public function isAdmin()
    {
        return $this->role === 'administrateur';
    }

    public function isAssistant()
    {
        return $this->role === 'assistant';
    }

    public function hasPermission_old($permission)
    {
        if ($this->isAdmin()) {
            return true;
        }

        return in_array($permission, $this->permissions ?? []);
    }


    public function roles()
{
    return $this->belongsToMany(Role::class, 'role_user')
        ->withPivot('tenant_id')
        ->withTimestamps();
}
/*
public function hasPermission($permissionId)
{
    return $this->permissions()->where('permissions.id', $permissionId)->exists();
}
*/
/*
public function hasPermission($permissionName)
{

    return \DB::table('permissions')
        ->join('permission_role', 'permissions.id', '=', 'permission_role.permission_id')
        ->join('roles', 'permission_role.role_id', '=', 'roles.id')
        ->join('role_user', 'roles.id', '=', 'role_user.role_id')
        ->where('role_user.user_id', $this->id)
        ->where('permissions.name', $permissionName)
        ->exists();

    return \DB::table('permissions')
        ->join('permission_role', 'permission_role.permission_id', '=', 'permissions.id')
        ->join('role_user', 'role_user.id', '=', 'permission_role.role_id')
        ->join('roles', 'roles.id', '=', 'role_user.role_id')
        ->where('role_user.user_id', 21)
        ->where('permissions.name', 'add_customer')
        ->exists();
}
*/
public function roleUser()
{
    return $this->hasOne(RoleUser::class, 'user_id');
}

public function permissions()
{
    return $this->hasManyThrough(
        Permission::class,
        RoleUser::class,
        'user_id', // Foreign key on role_user table
        'id',      // Foreign key on permissions table
        'id',      // Local key on users table
        'id'       // Local key on role_user table (role_id in permission_role refers to this)
    )->join('permission_role', 'role_user.id', '=', 'permission_role.role_id');
}

}
