<?php
    
    namespace frontend\controllers;

    use artbox\catalog\models\Product;
    use artbox\catalog\models\Variant;
    use artbox\order\models\Delivery;
    use artbox\order\models\OrderProduct;
    use artbox\order\models\Payment;
    use frontend\models\Order;
    use yii\web\Controller;

    /**
     * Class CheckoutController
     *
     * @package frontend\controllers
     */
    class CheckoutController extends Controller
    {
        public function actionIndex()
        {
            /**
             * @var \artbox\order\models\Basket $basket
             */
            $basket = \Yii::$app->get('basket');
            $data = $basket->getData();
            $variants = [];
            if (!empty($data)) {
                $variants = $basket->findModels(array_keys($data));
            }
            $topItems = Product::find()
                               ->with('lang', 'image', 'variants')
                               ->is('mask', 1)
                               ->limit(20)
                               ->all();
            return $this->render(
                'index',
                [
                    'basket'   => $basket,
                    'variants' => $variants,
                    'topItems' => $topItems,
                ]
            );
        }
    
        public function actionInfo()
        {
            $model = new Order(
                [
                    'scenario' => Order::SCENARIO_INFO,
                ]
            );
            if (!\Yii::$app->user->isGuest) {
                /**
                 * @var \artbox\order\models\Customer $user
                 */
                $user = \Yii::$app->user->identity;
                $model->name = $user->name;
                $model->email = $user->email;
                $model->phone = $user->phone;
                $model->city = $user->city;
                $model->address = $user->address;
            }
            $model->loadActive();
            if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
                $model->saveActive();
                return $this->redirect([ 'delivery' ]);
            }
            return $this->render(
                'info',
                [
                    'model' => $model,
                ]
            );
        }
    
        public function actionDelivery()
        {
            $model = new Order(
                [
                    'scenario' => Order::SCENARIO_INFO,
                ]
            );
            if (!empty($order = \Yii::$app->session->get('order')) && $model->load($order, '') && $model->validate()) {
                $model->scenario = Order::SCENARIO_DELIVERY;
                $model->loadActive();
                if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
                    $model->saveActive();
                    return $this->redirect([ 'payment' ]);
                }
            } else {
                return $this->redirect([ 'info' ]);
            }
            $deliveries = Delivery::find()
                                  ->with('lang')
                                  ->where([ 'status' => true ])
                                  ->orderBy([ 'sort' => SORT_ASC ])
                                  ->all();
            return $this->render(
                'delivery',
                [
                    'model'      => $model,
                    'deliveries' => $deliveries,
                ]
            );
        }
    
        public function actionPayment()
        {
            $model = new Order(
                [
                    'scenario' => Order::SCENARIO_INFO,
                ]
            );
            $order = \Yii::$app->session->get('order');
            if (!empty($model)) {
                if ($model->load($order, '') && $model->validate()) {
                    $model->scenario = Order::SCENARIO_DELIVERY;
                    if ($model->load($order, '') && $model->validate()) {
                        $model->scenario = Order::SCENARIO_PAYMENT;
                        $model->loadActive();
                        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
                            $model->saveActive();
                            return $this->redirect('confirm');
                        } else {
                            $payments = Payment::find()
                                               ->with('lang')
                                               ->where([ 'status' => true ])
                                               ->orderBy([ 'sort' => SORT_ASC ])
                                               ->all();
                            return $this->render(
                                'payment',
                                [
                                    'model'    => $model,
                                    'payments' => $payments,
                                ]
                            );
                        }
                    }
                }
            }
            return $this->redirect(
                'delivery'
            );
        }
    
        public function actionConfirm()
        {
            $model = new Order();
            $order = \Yii::$app->session->get('order');
            $model->load($order, '');
            if (!$model->validate()) {
                return $this->redirect([ 'payment' ]);
            }
            if (\Yii::$app->request->isPost) {
                $model->label_id = 1;
                $model->save(false);
                /**
                 * @var \artbox\order\models\Basket $basket
                 */
                $basket = \Yii::$app->get('basket');
                foreach ($basket->findModels(array_keys($basket->getData())) as $variant) {
                    $orderProduct = new OrderProduct(
                        [
                            'order_id'   => $model->id,
                            'variant_id' => $variant->id,
                            'sku'        => $variant->sku,
                            'price'      => $variant->price,
                            'count'      => $basket->getItem($variant->id)[ 'count' ],
                        ]
                    );
                    $orderProduct->save();
                }
                \Yii::$app->session->remove('order');
                $basket->clear();
                \Yii::$app->session->setFlash(
                    'success',
                    \Yii::t(
                        'app',
                        'Заказ успешно оформлен. Ваш номер заказ: ' . $model->id . '.'
                    )
                );
                return $this->redirect([ 'site/index' ]);
            }
            return $this->render(
                'confirm',
                [
                    'model' => $model,
                ]
            );
        }
    
        public function actionFast()
        {
            $this->enableCsrfValidation = false;
            $model = new Order(
                [
                    'scenario' => Order::SCENARIO_FAST,
                ]
            );
            if ($model->load(\Yii::$app->request->post())) {
                $model->label_id = 1;
                $model->delivery_id = 5;
                $model->payment_id = 3;
                if ($model->save()) {
                    /**
                     * @var Variant $variant
                     */
                    $variant = Variant::find()
                                      ->where([ 'id' => $model->variantId ])
                                      ->one();
                    ( new OrderProduct(
                        [
                            'order_id'   => $model->id,
                            'variant_id' => $model->variantId,
                            'sku'        => $variant->sku,
                            'price'      => $variant->price,
                            'count'      => 1,
                        ]
                    ) )->save(false);
                    \Yii::$app->session->setFlash(
                        'success',
                        \Yii::t(
                            'app',
                            'Заказ успешно оформлен. Ваш номер заказ: ' . $model->id . '.'
                        )
                    );
                    return $this->redirect($model->returnUrl ? : [ 'site/index' ]);
                }
            }
            $response = \Yii::$app->response;
            $response->format = $response::FORMAT_JSON;
            return $model->getErrors();
        }
    
        public function beforeAction($action)
        {
            /**
             * @var \artbox\order\models\Basket $basket
             */
            $basket = \Yii::$app->get('basket');
            if ($action->id !== 'index' && $action->id !== 'fast' && empty($basket->getData())) {
                return $this->redirect([ 'site/index' ]);
            }
            return parent::beforeAction($action);
        }
    }
    