<?php

namespace app\models;

use Yii;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "user".
 *
 * @property int $id
 * @property string $name
 * @property string $username
 * @property string $password
 * @property string|null $phone
 * @property string|null $email
 * @property string $position
 * @property string|null $auth_key
 */
class User extends ActiveRecord implements IdentityInterface
{
    public static function tableName()
    {
        return 'user';
    }

    /**
     * Rules define which fields are "safe" to be loaded and validated.
     */
    public function rules()
    {
        return [
            [['username', 'name', 'email', 'position'], 'required'],
            [['username', 'email'], 'unique'],
            [['email'], 'email'],
            [['username', 'password', 'name', 'phone', 'email', 'position', 'auth_key'], 'string', 'max' => 255],
            // Password is only required on "create" scenario usually, 
            // but we handle the logic in the controller for simplicity.
            [['password'], 'safe'], 
        ];
    }

    /**
     * Labels for form fields (optional)
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'name' => 'Full Name',
            'phone' => 'Phone Number',
            'email' => 'Email Address',
            'position' => 'Position',
        ];
    }

    // --- IdentityInterface Methods (Keep these as they were) ---

    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        return null; 
    }

    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username]);
    }

    public function getId()
    {
        return $this->id;
    }

    public function getAuthKey()
    {
        return $this->auth_key;
    }

    public function validateAuthKey($auth_key)
    {
        return $this->getAuthKey() === $auth_key;
    }

    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password);
    }
}