<?php

namespace frontend\models;

use Yii;

/**
 * This is the model class for table "option".
 *
 * @property integer $option_id
 * @property string $model
 * @property integer $model_id
 * @property string $name
 * @property string $template
 * @property integer $parent_id
 */
class Option extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'option';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['model', 'model_id', 'name', 'template'], 'required'],
            [['model_id', 'option_pid'], 'integer'],
            [['model', 'name', 'template'], 'string', 'max' => 200]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'option_id' => Yii::t('app', 'Option ID'),
            'model' => Yii::t('app', 'Model'),
            'model_id' => Yii::t('app', 'Model ID'),
            'name' => Yii::t('app', 'Name'),
            'template' => Yii::t('app', 'Template'),
            'option_pid' => Yii::t('app', 'Parent ID'),
            'date_add' => Yii::t('app', 'Date created'),
            'translate' => Yii::t('app', 'Translatable'),
        ];
    }
    
    public function getLangs() {
        return (new Language())->find()->where(['>', 'language_id', 0])->andWhere(['status' => 1])->asArray()->all();
    }
    
    public static function change($id, $post, $modeldb, $model_id) {
        $models[$id] = Option::findOne($id);
        $modellang[$id] = array();
        $langs = OptionLang::findAll(['option_language_id' => $id]);
        foreach($langs as $lang) {
            $modellang[$id][$lang->language_id] = $lang;
        }
        $children = (new Option())->find()->where(['option_pid' => $id])->all();
        foreach($children as $child) {
            $models[$child->option_id] = $child;
            $modellang[$child->option_id] = array();
            $langs = OptionLang::findAll(['option_id' =>$child->option_id]);
            foreach($langs as $lang) {
                $modellang[$child->option_id][$lang->language_id] = $lang;
            }
        }
        $ok = 1;
        if(!empty($post)) {
            foreach($post['Option'] as $key => $option) {
                if(in_array($key, array('model', 'model_id'))) { continue; }
                if(empty($option['value'][$models[$key]->name]) && !empty($option['lang'])) {
                    foreach($option['lang'] as $language_id => $lang) {
                        if(!empty($lang)) {
                            $option['value'][$models[$key]->name] = $lang;
                            break;
                        }
                    }
                }
                $modellang[$key][0]->value = $option['value'][$models[$key]->name];
                if(empty($modellang[$key][0]->value) || !$modellang[$key][0]->save()) {
                    $ok = 0;
                    $models[$key]->addError('value', 'Value must be set');
                    $modellang[$key][0]->addError('value', 'Value must be set');
                }
                if(!empty($option['lang'])) {
                    foreach($option['lang'] as $language_id => $lang) {
                        if(empty($modellang[$key][$language_id])) {
                            $modellang[$key][$language_id] = new OptionLang();
                            $modellang[$key][$language_id]->option_id = $models[$key]->option_id;
                            $modellang[$key][$language_id]->language_id = $language_id;
                            $modellang[$key][$language_id]->value = $lang;
                        } else {
                            $modellang[$key][$language_id]->value = $lang;
                        }
                        if(!$modellang[$key][$language_id]->save()) {
                            $ok = 0;
                        }
                    }
                }
            }
            if($ok) {
                return array('id' => $id, 'models' => $models, 'modelslang' => $modelslang, 'success' => true);
            } else {
                return array(
                    'models' => $models,
                    'modellang' => $modellang,
                    'modeldb' => $modeldb,
                    'model_id' => $model_id,
                    'success' => false
                );
            }
        }
        return array(
            'models' => $models,
            'modellang' => $modellang,
            'modeldb' => $modeldb,
            'model_id' => $model_id,
            'success' => false
        );
    }

    public static function create($post, $modeldb, $model_id, $fields, $multiple) {
    	$multiple = boolval($multiple);
        $model = new Option();
        $modellang = new OptionLang();
        if(!empty($post['Option'])) {
            $ok = 1;
            $parentid = null;
            $models = array();
            foreach($post['Option'] as $index => $option) {
                if(in_array($index, array('model', 'model_id')) && $index !== 0) { continue; }
                $first = 1;
                foreach($option['value'] as $key => $value) {
                    $models[$index][$key] = new Option();
                    $models[$index][$key]->model = $post['Option']['model'];
                    $models[$index][$key]->model_id = $post['Option']['model_id'];
                    $models[$index][$key]->template = $option[$key]['template'];
                    $models[$index][$key]->translate = $option[$key]['translate']?1:0;
                    $models[$index][$key]->name = $key;
                    if(!$first) {
                        $models[$index][$key]->option_pid = $parentid;
                    }
                    $modelslang[$index][$key][0] = new OptionLang();
                    if(!empty($option['lang'][$key])) {
                        foreach($option['lang'][$key] as $code => $lang) {
                            if(!empty($lang)) {
                                $value = $lang;
                                break;
                            }
                        }
                    }
                    if(!empty($value) && $models[$index][$key]->save()) {
                        if($first) {
                            $parentid = $models[$index][$key]->option_id;
                        }
                        $modelslang[$index][$key][0]->option_id = $models[$index][$key]->option_id;
                        $modelslang[$index][$key][0]->language_id = 0;
                        $modelslang[$index][$key][0]->value = $value;
                        if($modelslang[$index][$key][0]->save()) {
                            if(!empty($option['lang'][$key])) {
                                foreach($option['lang'][$key] as $code => $lang) {
                                    if(!empty($lang)) {
                                        $modelslang[$index][$key][$code] = new OptionLang();
                                        $modelslang[$index][$key][$code]->option_id = $models[$index][$key]->option_id;
                                        $modelslang[$index][$key][$code]->language_id = $code;
                                        $modelslang[$index][$key][$code]->value = $lang;
                                        if(!$modelslang[$index][$key][$code]->save()) {
                                            $ok = 0;
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        $models[$index][$key]->validate();
                        $modelslang[$index][$key][0]->validate();
                        $modelslang[$index][$key][0]->addError('value', 'Value must be set');
                        if(!empty($option['lang'][$key])) {
                            foreach($option['lang'][$key] as $code => $lang) {
                                if(!empty($lang)) {
                                    $modelslang[$index][$key][$code] = new OptionLang();
                                    $modelslang[$index][$key][$code]->option_id = $models[$index][$key]->option_id;
                                    $modelslang[$index][$key][$code]->language_id = $code;
                                    $modelslang[$index][$key][$code]->value = $lang;
                                }
                            }
                        }
                        $ok = 0;
                    }
                    $first = 0;
                }
            }
            if($ok) {
            	if($modeldb == 'Feedback') {
            		$newflag = new Option();
            		$newflag->model = $modeldb;
            		$newflag->model_id = $model_id;
            		$newflag->name = 'is_new';
            		$newflag->template = 'checkbox';
            		$newflag->option_pid = $parentid;
            		$newflag->translate = 0;
            		if($newflag->save()) {
            			$newflaglang = new OptionLang();
            			$newflaglang->option_id = $newflag->option_id;
            			$newflaglang->language_id = 0;
            			$newflaglang->value = '1';
            			if(!$newflaglang->save()) {
            				$newflag->delete();
            			}
            		}
            	}
                return array('models' => $models, 'modelslang' => $modelslang, 'success' => true);
            } else {
                return array(
                    'models' => $models,
                    'modellang' => $modelslang,
                    'modeldb' => $modeldb,
                    'model_id' => $model_id,
                    'fields' => $fields,
                    'success' => false,
                	'multiple' => $multiple
                );
            }
        } else {
            return array(
                'model' => $model,
                'modeldb' => $modeldb,
                'model_id' => $model_id,
                'fields' => $fields,
                'success' => false,
            	'multiple' => $multiple
            );
        }
    }
    
    public function getOptions() {
    	return $this->hasMany(Option::className(), ['option_pid' => 'option_id'])->indexBy('name');
    }
    
    public function getOption() {
    	return $this->hasOne(Option::className(), ['option_id' => 'option_pid']);
    }
    
    public function getOptionLangs() {
    	return $this->hasMany(OptionLang::className(), ['option_id' => 'option_id']);
    }
    
    public function getOptionDefaultLang($array = false) {
    	$query = $this->getOptionLangs()->where(['language_id' => 0]);
    	if($array) {
    		$query->asArray();
    	}
    	return $query->one();
    }
    
    public static function markOld($id) {
    	$model = Option::findOne($id);
    	$is_new = $model->getOptions()->where(['name' => 'is_new'])->one();
    	if(empty($is_new)) return false;
    	$is_newlang = $is_new->getOptionDefaultLang();
    	$is_newlang->value = '0';
    	if($is_newlang->save()) {
    		return true;
    	} else {
    		return false;
    	}
    }
    
}
