<?php

namespace App\Models;

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

class Admin extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $table = 'admins';

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

    /**
     * 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 = [
        'last_login' => 'datetime',
        'password' => 'hashed',
        'is_active' => 'boolean',
        'password_updated_at' => 'datetime',
    ];

    public function passwordHistory(): HasMany
    {
        return $this->hasMany(AdminPasswordHistory::class);
    }

    public function isPasswordExpired(): bool
    {
        if (! $this->password_updated_at) {
            return true;
        }

        $expiryDays = config('auth.password_expiry_days', 90);

        return $this->password_updated_at->addDays($expiryDays)->isPast();
    }

    public function isLocked(): bool
    {
        return ! $this->is_active;
    }

    public function isSuperAdmin(): bool
    {
        return $this->role === 'super_admin';
    }

    public function canAccessAdminPanel(): bool
    {
        return $this->is_active && in_array($this->role, ['super_admin', 'admin']);
    }
}
