<?php
    
    namespace common\modules\language\behaviors;
    
    use yii\base\Behavior;
    use yii\db\ActiveRecord;
    use yii\db\Transaction;

    /**
     * Class Save Image Behavior
     * @property ActiveRecord $owner
     * @package common\behaviors
     */
    class TransactionBehavior extends Behavior
    {
    
        /**
         * @var Transaction $_transaction
         */
        private $_transaction;
    
        /**
         * @var bool $_transaction_status
         */
        private $_transaction_status = false;
    
        /**
         * @var ActiveRecord[] $model_langs
         */
        public $model_langs = [];
        
        public function events()
        {
            return [
                ActiveRecord::EVENT_BEFORE_INSERT => 'beforeSave',
                ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeSave',
                ActiveRecord::EVENT_AFTER_INSERT => 'afterSave',
                ActiveRecord::EVENT_AFTER_UPDATE => 'afterSave',
            ];
        }
        
        public function beforeSave($event) {
            /**
             * @var ActiveRecord $owner
             */
            $owner = $this->owner;
            $db = $owner::getDb();
            $this->_transaction = $db->beginTransaction();
        }
        
        public function afterSave($event) {
            /**
             * @var ActiveRecord $owner
             */
            $owner = $this->owner;
            if(!empty($this->model_langs) && $owner->getBehavior('language')) {
                if($owner->linkLangs($this->model_langs) && $owner->saveLangs($this->model_langs)) {
                    $this->_transaction->commit();
                    $this->_transaction_status = true;
                } else {
                    $this->_transaction->rollBack();
                    $this->_transaction_status = false;
                }
            } else {
                $this->_transaction->commit();
                $this->_transaction_status = true;
            }
        }
    
        /**
         * @return bool
         */
        public function getTransactionStatus():bool {
            return $this->_transaction_status;
        }
        
    }