<?php
namespace common\components\activeRecordBehaviors;
use yii;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use \common\models\MetaTags;

class MetaTagBehavior 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)
    {
        $meta = \Yii::$app->request->post('MetaTags');
        if ($meta)
        {
            foreach ($meta as $lang_id => $attributes) 
            {
                $meta_tag = MetaTags::find()->where([
                    'object_id' => $this->owner->id,
                    'model_id'  => get_class($this->owner),
                    'lang_id' => $lang_id,
                ])->one();

                if (!$meta_tag)
                {
                    $meta_tag = new MetaTags;
                }

                $attributes['object_id'] = $this->owner->id;
                $attributes['model_id']  = get_class($this->owner);
                $attributes['lang_id'] = $lang_id;

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

        return true;
    }

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

                $attributes['object_id'] = $this->owner->id;
                $attributes['model_id']  = get_class($this->owner);
                $attributes['lang_id'] = $lang_id;

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

        return true;
    }

    public function Delete($event)
    {
        if($this->owner->metaTags)
        {
            foreach ($this->owner->metaTags as $meta) 
            {
                $meta->delete();
            }
        }
        
        return true;
    }
}
