<?php

namespace frontend\models;

use Yii;

/**
 * This is the model class for table "option_values".
 *
 * @property integer $option_value_id
 * @property string $option_key
 * @property string $option_value_text
 * @property integer $option_language_id
 * @property integer $option_value_parent
 * @property integer $option_user
 *
 * @property Language $optionLang
 */
class OptionValues extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'option_values';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['option_key', 'option_value_text'], 'required'],
            [['option_language_id', 'option_value_parent', 'option_user'], 'integer'],
            [['option_key'], 'string', 'max' => 200]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'option_value_id' => Yii::t('app', 'Option Value ID'),
            'option_key' => Yii::t('app', 'Option Key'),
            'option_value_text' => Yii::t('app', 'Option Value Text'),
            'option_language_id' => Yii::t('app', 'Option Lang ID'),
            'option_value_parent' => Yii::t('app', 'Option Value Parent'),
            'option_user' => Yii::t('app', 'Option User'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getOptionLang()
    {
        return $this->hasOne(Language::className(), ['language_id' => 'option_language_id']);
    }
    public function getLanguages() {
        return (new LanguageLang())->find()->orderBy('language_id ASC')->asArray()->all();
    }
    public function getLanguagesCodes() {
        return (new Language())->find()->orderBy('language_id ASC')->asArray()->all();
    }
    public function getDropDownArray() {
        $langs = array();
        foreach($this->getLanguages() as $lang) {
            $langs[$lang['language_id']] = $lang['lang_title'];
        }
        return $langs;
    }
    public function beforeSave($insert) {
        if (parent::beforeSave($insert)) {
            $this->option_user = \Yii::$app->user->getId();
            if($this->option_value_parent == 0) {
                unset($this->option_value_parent);
            }
            return true;
        } else {
            return false;
        }
    }
    public function getUserOptions() {
        return (new OptionValues())->find()->where('option_user=:user')->addParams([':user' => \Yii::$app->user->getID()])->andWhere(['not', ['option_user' => null]])->asArray()->all();
    }
    public function getUserOptionsArray() {
        $options = array('0' => Yii::t('app', 'Default Parent'));
        foreach($this->getUserOptions() as $option) {
            $options[$option['option_value_id']] = $option['option_key'].' - '.$option['option_value_text'];
        }
        return $options;
    }
}
