<?php

namespace app\models;

use Yii;
use yii\db\ActiveRecord;

class Question extends ActiveRecord
{
    const TYPE_TEXT = 'text';
    const TYPE_SCALE = 'scale';
    const TYPE_SINGLE_CHOICE = 'single_choice';

    public static function tableName()
    {
        return '{{%question}}';
    }

    public function rules()
    {
        return [
            [['survey_id', 'question_text', 'type'], 'required'],
            ['survey_id', 'integer'],
            ['question_text', 'string'],
            ['type', 'in', 'range' => [self::TYPE_TEXT, self::TYPE_SCALE, self::TYPE_SINGLE_CHOICE]],
            ['order', 'integer', 'min' => 0],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'survey_id' => 'Опрос',
            'question_text' => 'Текст вопроса',
            'type' => 'Тип вопроса',
            'order' => 'Порядок',
            'created_at' => 'Создан',
        ];
    }

    public function getTypeName()
    {
        $types = [
            self::TYPE_TEXT => 'Текстовый ответ',
            self::TYPE_SCALE => 'Оценка по шкале (1-5)',
            self::TYPE_SINGLE_CHOICE => 'Выбор одного варианта',
        ];
        
        return $types[$this->type] ?? 'Неизвестный тип';
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            
            if (empty($this->order)) {
                $maxOrder = self::find()
                    ->where(['survey_id' => $this->survey_id])
                    ->max('`order`');
                $this->order = $maxOrder ? $maxOrder + 1 : 1;
            }
            return true;
        }
        return false;
    }

    // Relations
    public function getSurvey()
    {
        return $this->hasOne(Survey::class, ['id' => 'survey_id']);
    }
}