<?php

use yii\db\Migration;

/**
 * Handles the creation of table `{{%user}}`.
 */
class m260206_162657_create_user_table extends Migration
{
    /**
     * {@inheritdoc}
     */
     public function safeUp()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('{{%user}}', [
            'id' => $this->primaryKey(),
            'full_name' => $this->string(255)->notNull(),
            'email' => $this->string(100)->notNull()->unique(),
            'phone' => $this->string(20)->notNull(),
            'password_hash' => $this->string(255)->notNull(),
            'auth_key' => $this->string(32),
            'password_reset_token' => $this->string(255)->unique(),
            'status' => $this->smallInteger()->notNull()->defaultValue(10),
            'role' => $this->string(20)->notNull()->defaultValue('employee'),
            'created_at' => $this->integer()->notNull(),
            'updated_at' => $this->integer()->notNull(),
        ], $tableOptions);

        // Индексы для оптимизации
        $this->createIndex('idx-user-email', '{{%user}}', 'email');
        $this->createIndex('idx-user-status', '{{%user}}', 'status');
        $this->createIndex('idx-user-role', '{{%user}}', 'role');

        // Добавляем администратора по умолчанию
        $this->insert('{{%user}}', [
            'full_name' => 'Администратор',
            'email' => 'admin@mail.ru',
            'phone' => '+7(999)999-99-99',
            'password_hash' => Yii::$app->security->generatePasswordHash('adminka'),
            'auth_key' => Yii::$app->security->generateRandomString(),
            'role' => 'admin',
            'status' => 10,
            'created_at' => time(),
            'updated_at' => time(),
        ]);

        // Добавляем тестового сотрудника
        $this->insert('{{%user}}', [
            'full_name' => 'Иванов Иван Иванович',
            'email' => 'test@mail.ru',
            'phone' => '+7(123)456-78-90',
            'password_hash' => Yii::$app->security->generatePasswordHash('password123'),
            'auth_key' => Yii::$app->security->generateRandomString(),
            'role' => 'employee',
            'status' => 10,
            'created_at' => time(),
            'updated_at' => time(),
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        $this->dropTable('{{%user}}');
    }
}
