<?php

namespace App\Models;

use App\Models\Concerns\HasPublicId;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

final class User extends Authenticatable
{
    use HasApiTokens, HasPublicId, Notifiable;

    protected $fillable = ['public_id','company_id','branch_id','name','email','password','is_active','last_login_at'];
    protected $hidden = ['password','remember_token'];

    protected function casts(): array
    {
        return ['email_verified_at'=>'datetime','password'=>'hashed','is_active'=>'boolean','last_login_at'=>'datetime'];
    }

    public function company(): BelongsTo { return $this->belongsTo(Company::class); }
    public function branch(): BelongsTo { return $this->belongsTo(Branch::class); }
    public function roles(): BelongsToMany { return $this->belongsToMany(Role::class); }

    public function hasPermission(string $slug): bool
    {
        if (! $this->is_active) {
            return false;
        }

        return $this->roles()->whereHas('permissions', fn ($query) => $query->where('slug', $slug))->exists();
    }

    public function isSuperAdministrator(): bool
    {
        return $this->roles()->where('slug', 'super-administrator')->exists();
    }
}
