<?php

declare(strict_types=1);

namespace App\Models;

use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements FilamentUser
{
    use HasFactory, Notifiable;

    public const ROLE_ADMIN = 'admin';
    public const ROLE_STAFF = 'staff';

    /**
     * Default attributes.
     * New users default to 'staff' unless set otherwise.
     */
    protected $attributes = [
        'role' => self::ROLE_STAFF,
    ];

    /**
     * Mass-assignable attributes.
     * If you prefer stricter control, replace with: protected $guarded = ['id'];
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'role',
    ];

    /**
     * Hidden attributes for arrays / JSON.
     *
     * @var list<string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Attribute casts.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'role'              => 'string',
        ];
    }

    /**
     * Handy role checks.
     */
    public function isAdmin(): bool
    {
        return $this->role === self::ROLE_ADMIN;
    }

    public function isStaff(): bool
    {
        return $this->role === self::ROLE_STAFF;
    }

    public function hasRole(string $role): bool
    {
        return $this->role === $role;
    }

    /**
     * Control access to the Filament admin panel.
     * - Allow users with role admin or staff.
     * - Keep an explicit email allowlist as an override (optional).
     */
    public function canAccessPanel(Panel $panel): bool
    {
        // Optional hard allowlist (kept from your snippet)
        $allowlistedEmails = [
            'adam@dori.co.nz',
        ];
        if (in_array($this->email, $allowlistedEmails, true)) {
            return true;
        }

        // Role-based access (two roles: admin, staff)
        return in_array($this->role, [self::ROLE_ADMIN, self::ROLE_STAFF], true);
    }
}
