<?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 [
                [
                    [
                        'phone',
                    ],
                    'required',
                ],
                [
                    [ 'comment' ],
                    'safe',
                ],
                [
                    [ 'email' ],
                    'email',
                ],
                [
                    [ 'phone' ],
                    'match',
                    'pattern' => '/^\+38\(\d{3}\)\d{3}-\d{2}-\d{2}$/',
                    'on' => self::SCENARIO_QUICK,
                ],
                [
                    [
                        'name',
                        'phone2',
                        'numbercard',
                        'body',
                        'declaration',
                        'stock',
                        'consignment',
                        'payment',
                        'insurance',
                        'amount_imposed',
                        'shipping_by',
                        'city',
                        'adress',
                        'total',
                        'status',
                    ],
                    'string',
                    'max' => 255,
                ],
            ];
        }
        
        public function attributeLabels()
        {
            return [
                'name'    => Yii::t('app', 'order_name'),
                'phone'   => Yii::t('app', 'order_phone'),
                'email'   => Yii::t('app', 'order_email'),
                'comment' => Yii::t('app', 'order_comment'),
                'id'             => Yii::t('app', 'orders_id'),
                'phone2'         => Yii::t('app', 'orders_phone2'),
                'adress'         => Yii::t('app', 'orders_adress'),
                'body'           => Yii::t('app', 'orders_body'),
                'reserve'        => Yii::t('app', 'orders_reserve'),
                'status'         => Yii::t('app', 'orders_status'),
                'total'          => Yii::t('app', 'orders_total'),
                'labels'         => Yii::t('app', 'orders_labels'),
                'label'          => Yii::t('app', 'orders_label'),
                'date_dedline'   => Yii::t('app', 'orders_date_dedline'),
                'numbercard'     => Yii::t('app', 'orders_numbercard'),
                'delivery'       => Yii::t('app', 'orders_delivery'),
                'declaration'    => Yii::t('app', 'orders_declaration'),
                'stock'          => Yii::t('app', 'orders_stock'),
                'consignment'    => Yii::t('app', 'orders_consignment'),
                'payment'        => Yii::t('app', 'orders_payment'),
                'insurance'      => Yii::t('app', 'orders_insurance'),
                'amount_imposed' => Yii::t('app', 'orders_amount_imposed'),
                'shipping_by'    => Yii::t('app', 'orders_shipping_by'),
                'city'           => Yii::t('app', 'orders_city'),
                'date_time'      => Yii::t('app', 'orders_datetime'),
            ];
        }
        
        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' ]);
        }
    }