<?php
    
    namespace frontend\controllers;
    
    use common\behaviors\AjaxFilter;
    use common\models\Basket;
    use common\models\Orders;
    use common\models\OrdersProducts;
    use common\modules\product\models\ProductVariant;
    use yii\filters\VerbFilter;
    use yii\web\BadRequestHttpException;
    
    class OrderController extends \yii\web\Controller
    {
        
        public $enableCsrfValidation = false;
        
        public function behaviors()
        {
            return [
                'verbs' => [
                    'class'   => VerbFilter::className(),
                    'actions' => [
                        'make' => [ 'post' ],
                    ],
                ],
                'ajax'  => [
                    'class' => AjaxFilter::className(),
                ],
            ];
        }
        
        public function actionMake()
        {
            $respone = \Yii::$app->response;
            $respone->format = $respone::FORMAT_JSON;
            $post = \Yii::$app->request->post();
            /**
             * @var Basket $basket
             */
            $basket = \Yii::$app->basket;
            $basket_items = array_keys($basket->getData());
            $order = new Orders();
            if($order->load($post) && $order->save()) {
                if(!empty( $basket_items )) {
                    foreach($basket_items as $basket_item) {
                        $product = ProductVariant::find()
                                                 ->where([ 'product_variant.product_variant_id' => $basket_item ])
                                                 ->joinWith('lang', true, 'INNER JOIN')
                                                 ->joinWith('product.lang', true, 'INNER JOIN')
                                                 ->one();
                        if(!empty( $product )) {
                            $orderProduct = new OrdersProducts([
                                'order_id'     => $order->id,
                                'product_name' => $product->product->lang->name,
                                'mod_id'       => $product->product_variant_id,
                                'name'         => $product->lang->name,
                                'sku'          => $product->sku,
                                'count'        => 1,
                            ]);
                            $orderProduct->save();
                        }
                    }
                    $basket->clear();
                }
                return [
                    'message' => $this->renderPartial('success', [
                        'order' => $order,
                    ]),
                ];
            } else {
                throw new BadRequestHttpException('Что то пошло не так');
            }
        }
    }
