<?php
namespace common\modules\content\components;

use Yii;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use common\modules\content\models\CoBlocksLang;

class CoBlocksLangBehavior extends Behavior
{
    public function events()
    {
        return [
            ActiveRecord::EVENT_AFTER_UPDATE => 'Save',
            ActiveRecord::EVENT_AFTER_INSERT => 'Insert',
            ActiveRecord::EVENT_BEFORE_DELETE => 'Delete',
        ];
    }

    public function Save($event)
    {
        $langs = Yii::$app->request->post('CoBlocksLang');
        if ($langs)
        {
            foreach ($langs as $lang_id => $attributes) 
            {
                $lang = CoBlocksLang::find()->where([
                    'block_id' => $this->owner->id,
                    'lang_id' => $lang_id,
                ])->one();

                if (!$lang)
                {
                    $lang = new CoBlocksLang;
                }

                $attributes['block_id'] = $this->owner->id;
                $attributes['lang_id'] = $lang_id;

                $lang->setAttributes( $attributes );
                if(!$lang->save()) die(print_r($lang->errors));
            }
        }

        return true;
    }

    public function Insert($event)
    {
        $langs = Yii::$app->request->post('CoBlocksLang');
        if ($langs)
        {
            foreach ($langs as $lang_id => $attributes) 
            {
                $meta_tag = new CoBlocksLang;

                $attributes['block_id'] = $this->owner->id;
                $attributes['lang_id'] = $lang_id;

                $meta_tag->setAttributes($attributes);
                $meta_tag->save(false);
            }
        }

        return true;
    }

    public function Delete($event)
    {
        if($this->owner->langs)
        {
            foreach ($this->owner->langs as $lang) 
            {
                $lang->delete();
            }
        }

        return true;
    }
}
