<?php

namespace frontend\controllers;

use common\models\Customers;
use common\models\OrderItems;
use common\models\Orders;
use common\models\RemoteOrders;
use common\modules\product\models\ProductVariant;
use common\widgets\BasketModal;
use Yii;

use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\data\ArrayDataProvider;
/**
 * OrderController implements the CRUD actions for Order model.
 */
class OrdersController extends Controller
{


    /**
     * @inheritdoc
     */
    public function beforeAction($action)
    {
        if ($action->id == 'buy-items' || $action->id == 'delete') {
            Yii::$app->controller->enableCsrfValidation = false;
        }

        return true;
    }

    public function actionFirst(){

        $array = Yii::$app->session->get('order');

        if(isset($array['order_id']) ) {
            $model = Orders::findOne($array['order_id']);
        }else {
            $model = new Orders();
        }


        if(Yii::$app->request->post() &&  $model->load(Yii::$app->request->post())){

            if($model->save()){

                $array['order_id'] =  $model->order_id;

                Yii::$app->session->set('order', $array );

                return $this->redirect(['orders/second']);
            }

        } else {
            if (!Yii::$app->user->isGuest) {
                $customer = Yii::$app->user->identity;
                $model->name = $customer->name;
                $model->email = $customer->email;
                $model->phone = $customer->phone;
            }
        }


        return $this->render('basket-step-01',[
            'model' => $model
        ]);
    }

    public function actionSecond(){

        $sessionData = \Yii::$app->session->get('order');

        $order_id = $sessionData['order_id'];

        if(!empty($order_id)){
            $order_model = Orders::findOne($order_id);
        } else{
            $this->redirect(['orders/first']);
        }

        unset($sessionData['order_id']);

        $variant = ProductVariant::find()->where(['product_variant_id'=>array_keys($sessionData)])->indexBy('product_variant_id')->all();


        if(Yii::$app->request->post()){

            foreach ($sessionData as $k => $item) {
                $itemModel = OrderItems::find()->where(['order_id'=>$order_id, 'item_id'=> $variant[$k]->product_variant_id])->one();

                $remoteItemModel = RemoteOrders::find()->where(['ID'=>$order_id, 'ID_Product'=> $variant[$k]->product_variant_id])->one();




                if($remoteItemModel instanceof RemoteOrders){
                    $remoteItemModel->ID =  (string)$order_id;
                    $remoteItemModel->ID_Client = (string)$order_model->customer_id;
                    $remoteItemModel->ID_Product =  (string)$variant[$k]->product_variant_id;
                    $remoteItemModel->Quantity = $sessionData[$k]['num'];
                    $remoteItemModel->Price_old = $variant[$k]->price;
                    $remoteItemModel->Date = date("Y-m-d H:i:s");
//                    $remoteItemModel->Rate = '';
                    $remoteItemModel->Sum = $variant[$k]->price * $sessionData[$k]['num'];
                    $remoteItemModel->Payment_type = $order_model->payment;
                    $remoteItemModel->save();
                } else {
                    $remoteItemModel = new RemoteOrders();
                    $remoteItemModel->ID =  (string)$order_id;
                    $remoteItemModel->ID_Client =  (string)$order_model->customer_id;
                    $remoteItemModel->ID_Product =  (string)$variant[$k]->product_variant_id;
                    $remoteItemModel->Quantity = $sessionData[$k]['num'];
                    $remoteItemModel->Price_old = $variant[$k]->price;
                    $remoteItemModel->Date = date("Y-m-d H:i:s");
//                    $remoteItemModel->Rate = '';
                    $remoteItemModel->Sum = $variant[$k]->price * $sessionData[$k]['num'];
                    $remoteItemModel->Payment_type = $order_model->payment;
                    $remoteItemModel->save();

                }

                if($itemModel instanceof OrderItems){
                    $itemModel->order_id = $order_id;
                    $itemModel->item_id = $variant[$k]->product_variant_id;
                    $itemModel->item_count = $sessionData[$k]['num'];
                    $itemModel->price = $variant[$k]->price;
                    $itemModel->save();
                } else {
                    $itemModel = new OrderItems();
                    $itemModel->order_id = $order_id;
                    $itemModel->item_id = $variant[$k]->product_variant_id;
                    $itemModel->item_count = $sessionData[$k]['num'];
                    $itemModel->price = $variant[$k]->price;
                    $itemModel->save();
                }

            }
            Yii::$app->session->set('order', [] );
            return $this->redirect(['orders/third']);

        } else {

            $price = 0;

            $count = count($sessionData);

            foreach ($sessionData as $k => $item) {
                $sessionData[$k]['item'] = $variant[$k];
                $price += $variant[$k]->price * $sessionData[$k]['num'];
            }

        }

        return $this->render('basket-step-02',[
            'items'=>$sessionData,
            'count' => $count,
            'price' => $price,
            'order_id' => $order_id,
            'order_model' => $order_model,
        ]);

    }

    public function actionThird(){
        return $this->render('basket-step-03');
    }


//    /**
//     * Lists all Order models.
//     * @return mixed
//     */
//    public function actionIndex()
//    {
//
//        if (Yii::$app->request->post()) {
//            $item = $items_id = array();
//
//            $i = 0;
//            $order = Yii::$app->request->post();
//
//            $orderData['Order'] = $order['OrderForm'];
//
//            foreach($order['OrderForm']['one_item'] as $k => $v ){
//                $item[$k]['num'] = $v['num'];
//                $items_id[] = $k;
//                $i++;
//            }
//
//            $items = Items::find()->where(['id'=>$items_id])->all();
//
//
//            $orderModel = new Order();
//            $orderModel->load($orderData);
//            $orderModel->save();
//
//
//            foreach($items as $one_item){
//                $ItemOrderModel = new ItemOrder();
//                $ItemOrderModel->order_id = $orderModel->id;
//                $ItemOrderModel->num = $item[$one_item->id]['num'];
//                $ItemOrderModel->item_id = $one_item->id;
//                $ItemOrderModel->price = $one_item->price * $item[$one_item->id]['num'];
//                $ItemOrderModel->item_name = $one_item->name;
//                $ItemOrderModel->save();
//            }
//            Yii::$app->session->set('order', [] );
//            return $this->redirect(['order/complete']);
//        }
//        $total_price = 0;
//
//        $items_id = [];
//
//        $orders = Yii::$app->session->get('order');
//
//        if(!empty($orders)){
//            foreach($orders as $k => $v) {
//                $items_id[] = $k;
//            }
//        }
//
//
//        $items = Items::find()->where(['id'=>$items_id])->all();
//
//        foreach($items as $item) {
//            $total_price += $orders[$item['id']]['num'] * $item['price'];
//        }
//
//
//        $dataProvider = new ArrayDataProvider([
//            'allModels' => $items
//        ]);
//
//        return $this->render('index', [
//            'dataProvider' => $dataProvider,
//            'total_price'=> $total_price,
//            'model' => new OrderForm()
//        ]);
//    }


    public function actionComplete()
    {
        return $this->render('complete', [
        ]);
    }

    public function actionBuyItems(){
        $data = Yii::$app->request->post();
        $sessionData = Yii::$app->session->get('order');
        if(isset($sessionData) && !array_search($data['id'],Yii::$app->session->get('order')) ){
            $array = Yii::$app->session->get('order');
            $array[$data['id']] = $data;
            Yii::$app->session->set('order', $array );
        } else {
            $array[$data['id']] = $data;
            Yii::$app->session->set('order', $array );
        }
        echo BasketModal::widget([]);

    }
    /**
     * Displays a single Order model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Order model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Order();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Order model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Order model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete()
    {
        $data = Yii::$app->request->post();
        $sessionData = Yii::$app->session->get('order');
        unset($sessionData[$data['id']]);
        Yii::$app->session->set('order', $sessionData);
        return count(Yii::$app->session->get('order'));
    }

    /**
     * Finds the Order model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Order the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Order::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
