<?php
    
    namespace frontend\controllers;
    
    use common\models\Customer;
    use common\models\OrdersProducts;
    use common\widgets\Mailer;
    use Yii;
    use yii\base\InvalidConfigException;
    use yii\base\InvalidParamException;
    use yii\helpers\ArrayHelper;
    use yii\web\Controller;
    use common\models\Basket;
    use common\modules\product\models\ProductVariant;
    use common\models\Orders;
    
    class OrderController extends Controller
    {
        
        public function actionMain()
        {
            $basket = \Yii::$app->basket;
            $data = $basket->getData();
            $models = $basket->findModels(array_keys($data));
            return $this->render('index', [
                'models' => $models,
                'basket' => $basket,
            ]);
        }
        
        /**
         * @return string
         */
        public function actionSave()
        {
            $modelOrder = new Orders;
            /**
             * @var $basket Basket
             */
            $basket = \Yii::$app->basket;
            $productV = $basket->getData();
            if(!empty( $productV ) && $modelOrder->load(Yii::$app->request->post()) && $modelOrder->save()) {
                foreach($productV as $index => $row) {
                    $modelOrdersProducts = new OrdersProducts();
                    $mod_id = $index;
                    $product = ProductVariant::findOne($mod_id);
                    /**
                     * Проверяем товар на наличие
                     */
                    if( !$product->price > 0) {
                        /**
                         * Добавляем сообщение об ошибке
                         */
                        \Yii::$app->getSession()
                                  ->setFlash('error', 'К сожалению товара ' . $product->name . ' нет в наличии');
                        $basket->delete($product->product_variant_id);
                        unset( $productV[ $index ] );
                    } else {
                        /**
                         * Удаляем товар с массива и сохраняем в заказ
                         */
                        $modelOrdersProducts->order_id = $modelOrder->id;
                        $modelOrdersProducts->product_name = $product->product->name;
                        $modelOrdersProducts->name = $product->name;
                        $modelOrdersProducts->price = $productV[ $index ][ 'price' ];
                        $modelOrdersProducts->count = $productV[ $index ][ 'count' ];
                        $modelOrdersProducts->sum_cost = $productV[ $index ][ 'price' ] * $productV[ $index ][ 'count' ];
                        $modelOrdersProducts->mod_id = $mod_id;
                        $modelOrdersProducts->sku = $product->sku;
                        $modelOrdersProducts->validate();
                        $modelOrdersProducts->save();
                        $productV[ $index ] = ArrayHelper::toArray($modelOrdersProducts);
                        if(isset($product->image)){
                            $productV[ $index ][ 'img' ] = \common\components\artboximage\ArtboxImageHelper::getImageSrc($product->image->imageUrl, 'list');
                        }

                    }
                }
                /**
                 * Сохраняем заказ
                 */
                if(!Yii::$app->user->id && !empty( $modelOrder->email )) {
                    $modelUser = new Customer();
                    $modelUser->role = 'person';
                    $modelUser->username = $modelOrder->email;
                    $modelUser->name = $modelOrder->name;
                    $modelUser->phone = $modelOrder->phone;
                    $modelUser->password = Yii::$app->getSecurity()
                                                    ->generateRandomString(10);
                    $modelUser->group_id = 2;
                    $modelUser->save();
                }
                $order = clone $modelOrder;
                /**
                 * Чистим сессию корзины
                 */
                $modelOrder->clearBasket();
                Mailer::widget([
                    'type'    => 'order',
                    'subject' => 'Спасибо за Ваш заказ',
                    'email'   => $modelOrder->email,
                    'params'  => [
                        'order'    => $order,
                        'variants' => $productV,
                    ],
                ]);
                //$text = "# zakaz: ". $order->id .". V blijayshee vremya menedjer svyajetsya s Vami. (044) 303 90 15";
                //Yii::$app->sms->send($order->phone, $text);
                Yii::$app->session[ 'order_data' ] = [ 'order'    => $order,
                                                       'variants' => $productV,
                ];
                return $this->redirect([ 'order/success' ]);
            }
            $data = $basket->getData();
            $models = $basket->findModels(array_keys($data));
            return $this->render('index', [
                'models' => $models,
                'basket' => $basket,
            ]);
        }

        
        public function actionQuick()
        {
            $response = \Yii::$app->response;
            $request = \Yii::$app->request;
            $response->format = $response::FORMAT_JSON;
            $product_variant_id = (int) $request->post('product_variant_id');
            $orders = new Orders([
                'scenario' => Orders::SCENARIO_QUICK,
                'name'     => 'Покупка в 1 клик',
            ]);
            if(!empty( $product_variant_id )) {
                /**
                 * @var ProductVariant $product_variant
                 */
                $product_variant = ProductVariant::findOne($product_variant_id);
            } else {
                throw new InvalidParamException('Не указан товар');
            }
            if(!empty( $product_variant ) && $orders->load($request->post()) && $orders->save()) {
                if( $product_variant->price <= 0) {
                    $orders->delete();
                    return [
                        'error' => 'К сожалению товара ' . $product_variant->name . ' нет в наличии',
                    ];
                } else {
                    $order_product = new OrdersProducts([
                        'order_id'     => $orders->id,
                        'product_name' => $product_variant->product->name,
                        'name'         => $product_variant->name,
                        'price'        => $product_variant->price,
                        'count'        => 1,
                        'sum_cost'     => $product_variant->price,
                        'mod_id'       => $product_variant->product_variant_id,
                        'sku'          => $product_variant->sku,
                    ]);
                    $order_product->save();
                    return [
                        'result' => 'Спасибо за заказ! Наши менеджеры свяжутся с Вами в ближайшее время.',
                    ];
                }
            } else {
                throw new InvalidConfigException('Товар не найден или не удалось загрузить данные о покупателе.');
            }
        }


        public function actionSuccess()
        {
            return $this->render('success');
        }


        public function actionQuickBasket()
        {

            $response = \Yii::$app->response;
            $request = \Yii::$app->request;
            $response->format = $response::FORMAT_JSON;
            /**
             * @var array $data
             */
            $data = \Yii::$app->basket->getData();

            $orders = new Orders([
                'scenario' => Orders::SCENARIO_QUICK,
                'name'     => 'Покупка в 1 клик',
            ]);



            if(!empty( $data )) {

                /**
                 * @var ProductVariant[] $product_variants
                 * @var OrdersProducts[] $order_products
                 */
                $product_variants = [];
                $order_products = [];
                foreach($data as $product_variant_id => $item) {

                    $product_variant = ProductVariant::findOne($product_variant_id);
                    if(!empty($product_variant)  && $product_variant->price > 0) {
                        $product_variants[$product_variant_id] = $product_variant;
                        $order_products[$product_variant_id] = new OrdersProducts([
                            'product_name' => $product_variant->product->name,
                            'name'         => $product_variant->name,
                            'price'        => $product_variant->price,
                            'count'        => $item['count'],
                            'sum_cost'     => $item['count'] * $product_variant->price,
                            'mod_id'       => $product_variant->product_variant_id,
                            'sku'          => $product_variant->sku,
                        ]);
                    }
                }

            } else {

                throw new InvalidParamException('Не указан товар');
            }



            if(!empty( $order_products ) && $orders->load($request->post()) && $orders->save()) {

                foreach($order_products as $order_product) {
                    $order_product->order_id = $orders->id;
                    $order_product->save();
                }
                \Yii::$app->basket->clear();
                return [
                    'result' => 'Спасибо за заказ! Наши менеджеры свяжутся с Вами в ближайшее время.',
                ];
            } else {

                throw new InvalidConfigException('Товар не найден или не удалось загрузить данные о покупателе.');
            }
        }
    }
