<?php
    namespace common\models;
    
    use Yii;
    use yii\web\Session;
    use common\modules\product\models\ProductVariant;
    
    class Orders extends \yii\db\ActiveRecord
    {
        
        const SCENARIO_QUICK = 'quick';
        
        private $data;
        
        public static function tableName()
        {
            return 'orders';
        }
        
        public function scenarios()
        {
            $scenarios = array_merge(parent::scenarios(), [
                self::SCENARIO_QUICK => [ 'phone' ],
            ]);
            return $scenarios;
        }
        
        public function rules()
        {
            return [
                [
                    [
                        'name',
                        'phone',
                    ],
                    'required',
                ],
                [
                    [ 'comment' ],
                    'safe',
                ],
                [
                    [ 'email' ],
                    'email',
                ],
                [
                    [ 'phone' ],
                    'match',
                    'pattern' => '/^\+38\(\d{3}\)\d{3}-\d{2}-\d{2}$/',
                    'on' => self::SCENARIO_QUICK,
                ],
            ];
        }
        
        public function attributeLabels()
        {
            return [
                'name'    => 'Ф.И.О',
                'phone'   => 'Контактный телефон',
                'email'   => 'email',
                'comment' => 'Комментарии',
            ];
        }
        
        public function beforeSave($insert)
        {
            $this->user_id = Yii::$app->user->id;
            $this->date_time = new \yii\db\Expression('NOW()');
            return parent::beforeSave($insert);
        }
        
        public function beforeDelete()
        {
            return parent::beforeDelete();
        }
        
        public function addBasket($mod_id, $count)
        {
            $session = new Session;
            $session->open();
            $data = $session[ 'basket' ];
            $i = 0;
            if(isset( $session[ 'basket' ] )) {
                foreach($session[ 'basket' ] as $key => $basket) {
                    if($mod_id == $basket[ 'id' ]) {
                        $data[ $key ][ 'count' ] += $count;
                        $session[ 'basket' ] = $data;
                        $i++;
                    }
                }
            }
            if($i == 0) {
                $data[] = [
                    'id'    => $mod_id,
                    'count' => $count,
                ];
                $session[ 'basket' ] = $data;
            }
        }
        
        public function rowBasket()
        {
            $session = new Session;
            $session->open();
            $cost = 0;
            $count = 0;
            if(isset( $session[ 'basket' ] ) && count($session[ 'basket' ])) {
                foreach($session[ 'basket' ] as $product) {
                    $count += $product[ 'count' ];
                }
            }
            
            return (object) [
                'cost'  => $cost,
                'count' => $count,
            ];
        }
        
        public function deleteBasketMod($id)
        {
            $session = new Session;
            $session->open();
            $basket = $session[ 'basket' ];
            foreach($basket as $key => $product) {
                if($id == $product[ 'id' ]) {
                    unset( $basket[ $key ] );
                }
            }
            $session[ 'basket' ] = $basket;
        }
        
        public function updateBasket($row)
        {
            $session = new Session;
            $session->open();
            //$data = array();
            if($row[ 'count' ] > 0) {
                $this->data[] = [
                    'id'    => $row[ 'id' ],
                    'count' => $row[ 'count' ],
                ];
            }
            $session[ 'basket' ] = $this->data;
        }
        
        public function getBasketMods()
        {
            $session = new Session;
            $session->open();
            $products = [];
            if(empty( $session[ 'basket' ] )) {
                return [];
            }
            foreach($session[ 'basket' ] as $product) {
                $row = ProductVariant::find()
                                     ->select([
                                         'product_variant.*',
                                         'product.name as product_name',
                                         'product.alias',
                                     ])
                                     ->where([ 'product_variant.product_variant_id' => $product[ 'id' ] ])
                                     ->leftJoin('product', 'product.product_id = product_variant.product_id')
                                     ->one();
                $row->count = $product[ 'count' ];
                $row->sum_cost = $product[ 'count' ] * $row->price;
                $products[] = $row;
            }
            
            return $products;
        }
        
        public function getSumCost()
        {
            $session = new Session;
            $session->open();
            $cost = 0;
            if(empty( $session[ 'basket' ] )) {
                return false;
            }
            foreach($session[ 'basket' ] as $product) {
                $cost += ( $this->getModCost($product[ 'id' ]) * $product[ 'count' ] );
            }
            
            return $cost;
        }
        
        private function getModCost($mod_id)
        {
            $mod = ProductVariant::find()
                                 ->where([ 'product_variant_id' => $mod_id ])
                                 ->one();
            
            return $mod->price;
        }
        
        public function clearBasket()
        {
            $session = new Session;
            $session->open();
            $session[ 'basket' ] = NULL;
        }
        
        public function getUser()
        {
            return $this->hasOne(User::className(), [ 'id' => 'user_id' ]);
        }
        
        public function getProducts()
        {
            return $this->hasMany(OrdersProducts::className(), [ 'order_id' => 'id' ]);
        }
    }