<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Filament\Models\Contracts\FilamentUser;
use Filament\Models\Contracts\HasName;
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, HasName
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * Indicates if the model's ID is auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = true;

    /**
     * The data type of the primary key ID.
     *
     * @var string
     */
    protected $keyType = 'int';

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'id',
        'user_id',
        'username',     // 手机号作为登录名（必填）
        'email',        // 邮箱（可选）
        'phone',        // 手机号（备用）
        'password',
        'password_hash',
        'full_name',
        'role',
        'department',
        'is_active',
        'remember_token',
        'last_login',
        'login_count',
        'deleted_at',
    ];

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

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'is_active' => 'boolean',
        ];
    }

    public function canAccessPanel(?Panel $panel): bool
    {
        // 只有激活的用户才能访问面板
        return $this->is_active === true;
    }

    /**
     * Get the password for authentication.
     */
    public function getAuthPassword(): string
    {
        return (string) $this->password_hash;
    }

    /**
     * Get the username for authentication.
     */
    public function getAuthIdentifierName(): string
    {
        return 'username';
    }

    /**
     * Retrieve the unique identifier for the user.
     */
    public function getAuthIdentifier(): mixed
    {
        return $this->username;
    }

    /**
     * Get the password attribute (for compatibility).
     */
    public function getPasswordAttribute(): string
    {
        return $this->password_hash;
    }

    /**
     * Set the password attribute (for compatibility).
     */
    public function setPasswordAttribute(string $value): void
    {
        $this->attributes['password_hash'] = $value;
    }

    /**
     * Get the name to display for the user in Filament.
     * This fixes the TypeError where getUserName() expected string but got null.
     */
    public function getFilamentName(): string
    {
        return $this->full_name ?: $this->username ?: $this->email ?: 'Unknown User';
    }

    /**
     * Retrieve a user by their credentials.
     * Override this to use username instead of email for authentication.
     */
    public function retrieveByCredentials(array $credentials)
    {
        if (empty($credentials)) {
            return null;
        }

        // Check if the credentials array has 'username' key
        if (isset($credentials['username'])) {
            return static::where('username', $credentials['username'])->first();
        }

        // Fallback to default behavior for other credentials
        foreach ($credentials as $key => $value) {
            if (in_array($key, ['password', 'remember_token'])) {
                continue;
            }

            if (method_exists(static::class, $key)) {
                if ($this->{$key}() instanceof \Illuminate\Database\Eloquent\Relations\BelongsTo) {
                    if ($this->{$key}()->getRelated()->where($key, $value)->exists()) {
                        return $this;
                    }
                } else {
                    if (static::where($key, $value)->exists()) {
                        return static::where($key, $value)->first();
                    }
                }
            }
        }

        return null;
    }

    /**
     * 获取用户的老师信息（如果当前用户是老师）
     */
    public function teacher(): \Illuminate\Database\Eloquent\Relations\HasOne
    {
        return $this->hasOne(Teacher::class, 'user_id', 'id');
    }

    /**
     * 检查当前用户是否是老师
     */
    public function isTeacher(): bool
    {
        return $this->teacher()->exists();
    }

    /**
     * 获取当前登录用户的teacher_id（如果没有则返回null）
     */
    public static function getCurrentTeacherId(): ?int
    {
        $user = auth()->user();
        if (!$user) {
            return null;
        }

        $teacher = $user->teacher;
        return $teacher?->teacher_id;
    }
}
