<?php

namespace frontend\controllers;

use Yii;
use yii\filters\VerbFilter;
use yii\web\Controller;
use common\models\Cart;
use common\models\Mail;
use frontend\helpers\Helper;

/**
 * Cart Controller
 */
class CartController extends Controller
{

    private $cart;

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'order' => ['POST'],
                ],
            ],
        ];
    }

    public function init()
    {
        $this->cart = Yii::$app->session->get('cart');
        parent::init();
    }

    /**
     * Renders the cart
     */
    public function actionIndex()
    {
        $model = new Cart();

        return $this->render('index', ['cart' => $this->cart, 'model' => $model]);
    }

    /**
     * Add an item to the cart
     *
     * @param $id int
     * @param $qty int
     */
    public function actionAdd($id, $qty)
    {
        $this->cart->addItem($id, $qty);
        return $this->asJson(['items' => $this->cart->getItems()]);
    }

    /**
     * Add an item to the cart
     *
     * @param $id int
     * @param $qty int
     */
    public function actionSet($id, $qty)
    {
        $this->cart->setItem($id, $qty);
        return $this->asJson(['items' => $this->cart->getItems()]);
    }

    /**
     * Empties the cart
     */
    public function actionEmpty()
    {
        $this->cart->empty();
        return $this->redirect(['cart/index']);
    }

    public function actionItems()
    {
        return $this->asJson(['items' => $this->cart->getItems()]);
    }

    /**
     *  Saves SessionCart in DB and notify dolibarr, mp-technic and the client
     */
    public function actionOrder()
    {
        $model = new Cart();

        // form post ?
        if ($model->load(Yii::$app->request->post())) {

            $model->status = Cart::STATUS_NEW;
            $model->session_id = Yii::$app->session->id;
            $model->items = json_encode($this->cart->getItems());
            $model->created_at = date('Y-m-d H:i:s');

            // if not a user, would've filled the form
            if (USER_ID) {
                $user = Yii::$app->user->identity;
                $model->user_name = $user->username;
                $model->user_phone = 'NC';
                $model->user_email = $user->email;
                $model->user_id = USER_ID;
            }


            if ($model->save()) {

                $model->refresh();

                $mailParams = [
                    'cartId' => $model->id,
                    'userName' => $model->user_name,
                    'items' => $this->cart->getItems(),
                ];

                // send mail to admin
                Mail::compose(null, Yii::$app->params['cartEmail'], '[SiteWeb] Nouveau panier rempli', 'cart-submitted', $mailParams);
                // send mail and to client
                Mail::compose(null, $model->user_email, '[MP-Technic] Demande de devis bien reçue', 'cart-submitted-client', $mailParams);

                // empty cart
                $this->cart->empty();

                // send post request to dolibarr (send all new carts)
                $this->notifyDolibarr();

                return $this->redirect('/cart/success');
            } else {
                return $this->render('index', ['cart' => $this->cart, 'model' => $model]);
            }
        }

        die('todo ' . __FILE__);
    }


    /**
     * Send new carts to dolibarr
     */
    public function notifyDolibarr()
    {
        $dolUrl = Yii::$app->params['dolibarr_url'] . '/custom/front/fromovh_new_cart.php';

        $carts = Cart::find()->where(['status' => Cart::STATUS_NEW])->all();
        
        if (!count($carts)) return;

        $json = [];
        foreach($carts as $c) {
            $json[] = $c->attributes;
        }

        // send json post request to dolibarr
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $dolUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2); // limit to two seconds not to hinder the UX
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            Yii::warning('Curl error: ' . curl_error($ch), __METHOD__);
            Helper::emailError(curl_error($ch), [], 'Could not send Cart to dolibarr');
        }

        $json = json_decode($response, true);

        if (!empty($json) &&  $json['success']) {
            foreach($json['insertedIds'] as $id) {
                $cart = Cart::findOne($id);
                $cart->status = Cart::STATUS_SENT;
                $cart->save(false, ['status']);
            }
        }

        curl_close($ch);
    }

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