<?php

namespace app\controllers;

use Yii;
use yii\base\InvalidArgumentException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
//additional
use app\models\Store;
use app\models\ShopifyClient;
use app\models\Configurations;
use app\models\Orders;
use app\models\CartDetails;
//use app\models\Refunds;
//use yii\helpers\Url;
use SquareConnect;

/**
 * Site controller
 */
class CheckoutController extends Controller {

    public function beforeAction($action) {
        $this->enableCsrfValidation = false;
        return parent::beforeAction($action);
    }

    /**
     * Render proxy checkout
     */
    public function actionIndex() {

        $shop = Yii::$app->request->get('shop');
        $shop = $shop == "spensry.com" || $shop == "www.spensry.com" ? 'spensry.myshopify.com' : $shop;
        $model = Configurations::find()->where(['meta_key' => $shop . '_square_detail'])->one();
        $square_app_id = false;
        $square = false;
        $sandbox = false;
        if ($model !== null) {
            $config = unserialize($model->meta_value);
//            echo "<pre>"; print_r($config); die('wait');
            if ((isset($config['sandbox']) && $config['sandbox'] == '1')) {
                $sandbox = true;
                $square = true;
                $square_app_id = $config['sandbox_application_id'];
            } else if (isset($config['enable_square']) && $config['enable_square'] == '1') {
                $square = true;
                $square_app_id = $config['live_application_id'];
            } else {
                $square = false;
            }
        }
        $this->render('index', ['square' => $square, 'square_app_id' => $square_app_id, 'sandbox' => $sandbox]);
    }

    /**
     *  Get Shopify store countries drop-down
     */
    public function actionGetcountries() {

        ob_start();
        $shop = Yii::$app->request->get('store');
        $shop = $shop == "spensry.com" || $shop == "www.spensry.com" ? 'spensry.myshopify.com' : $shop;

        $Store = Store::find()->where(['name' => $shop])->one();
        $token = $Store->token;
        $sc = new ShopifyClient($shop, $token, Yii::$app->params['APP_KEY'], Yii::$app->params['SECRET_KEY']);
        $orderData = $sc->call('GET', '/admin/countries.json');
        $data = json_encode($orderData);
        echo "getcountries(" . $data . ");";
    }

    /**
     *  Get Shopify store province drop-down
     */
    public function actionGetprovinces() {

        ob_start();
        $shop = Yii::$app->request->get('store');
        $shop = $shop == "spensry.com" || $shop == "www.spensry.com" ? 'spensry.myshopify.com' : $shop;
        $url = Yii::$app->request->get('url');
        $Store = Store::find()->where(['name' => $shop])->one();
        $token = $Store->token;
        $sc = new ShopifyClient($shop, $token, Yii::$app->params['APP_KEY'], Yii::$app->params['SECRET_KEY']);
        $orderData = $sc->call('GET', $url);
        $data = json_encode($orderData);
        echo "getprovinces(" . $data . ");";
    }

    /**
     *  Get Shopify billing province dropdown
     */
    public function actionGetbillingprovinces() {
        ob_start();
        $shop = Yii::$app->request->get('store');
        $shop = $shop == "spensry.com" || $shop == "www.spensry.com" ? 'spensry.myshopify.com' : $shop;
        $url = Yii::$app->request->get('url');
        $Store = Store::find()->where(['name' => $shop])->one();
        $token = $Store->token;
        $sc = new ShopifyClient($shop, $token, Yii::$app->params['APP_KEY'], Yii::$app->params['SECRET_KEY']);
        $orderData = $sc->call('GET', $url);
        $data = json_encode($orderData);
        echo "getbillingprovinces(" . $data . ");";
    }

    /**
     *  Apply Coupon Shopify
     */
    public function actionApplycoupon() {

        ob_start();
        $price_rule = array();
        $shop = Yii::$app->request->get('store');
        $shop = $shop == "spensry.com" || $shop == "www.spensry.com" ? 'spensry.myshopify.com' : $shop;
        $url = Yii::$app->request->get('url');
        $coupon_code = Yii::$app->request->get('coupon_code');
        $coupon_url = '/admin/price_rules.json';
        $Store = Store::find()->where(['name' => $shop])->one();
        $token = $Store->token;
        $sc = new ShopifyClient($shop, $token, Yii::$app->params['APP_KEY'], Yii::$app->params['SECRET_KEY']);
        $orderData = $sc->call('GET', $coupon_url);

        if (!isset($orderData)) {
            $final_dic = array(
                'value' => "Invalid",
            );
            $data = json_encode($final_dic);
            echo "applycoupon(" . $data . ");";
            exit;
        }
        $coupon_list = [];
        foreach ($orderData as $key => $val) {
            $price_rule_id = $val['id'];
            $price_rule[$price_rule_id] = $val;
            $coupon_urlm = '/admin/price_rules/' . $price_rule_id . '/discount_codes.json';
            $coupon_list_detail = $sc->call('GET', $coupon_urlm);
            if(!empty($coupon_list_detail)) {
                $coupon_list = array_merge($coupon_list, $coupon_list_detail);
            } else {
                $coupon_list[] = ["code" => ""];
            }
        }

        date_default_timezone_set('America/Los_Angeles');
        $final_Coupon_Array = '';
        $validStart = true;
        $validEnd = true;
        $validUsage = true;
        foreach ($coupon_list as $key => $val) {
            if (strtoupper($val['code']) == strtoupper($coupon_code)) {
                $price_rule_id = $val['price_rule_id'];

                $final_Coupon_Array['coupon_detail'] = $val;
                $final_Coupon_Array['price_rule'] = $price_rule[$price_rule_id];

                // Validate if Start_at and End_at are valid
                if($final_Coupon_Array['price_rule']['starts_at'] != "") {
                    $validStart = strtotime($final_Coupon_Array['price_rule']['starts_at']) < time();
                }
                if($final_Coupon_Array['price_rule']['ends_at'] != "") {
                    $validEnd = strtotime($final_Coupon_Array['price_rule']['ends_at']) > time();
                }
                // Validate if Usage_limit is valid
                if($final_Coupon_Array['price_rule']['usage_limit'] != "") {
                    $validUsage = $final_Coupon_Array['coupon_detail']['usage_count'] < $final_Coupon_Array['price_rule']['usage_limit'];
                }
                break;
            }
        }
        
        if (is_array($final_Coupon_Array) && $validStart && $validEnd && $validUsage) {
            //echo "yes coupon found";

            $value = $final_Coupon_Array['price_rule']['value'];
            $value_type = $final_Coupon_Array['price_rule']['value_type'];
            //$target_type=$final_Coupon_Array['price_rule']['target_type'];
            $entitled_product_ids = $final_Coupon_Array['price_rule']['entitled_product_ids'];
            $final_dic = array(
                'value' => $value,
                'value_type' => $value_type,
                'entitled_product_ids' => $entitled_product_ids,
                'coupon_type' => $final_Coupon_Array['price_rule']['target_type']
            );
            $data = json_encode($final_dic);
            echo "applycoupon(" . $data . ");";
        } else {
            //echo "invalid coupon";
            $final_dic = array(
                'value' => "Invalid Coupon",
            );
            $data = json_encode($final_dic);
            echo "applycoupon(" . $data . ");";
        }
    }
    
    /*
     * Validate email address
     */
    public function actionValidateemail() {

        $email = Yii::$app->request->get('email');
        $record = 'MX';
        list($user, $domain) = explode('@', $email);
        if (checkdnsrr($domain, $record)) {
            $result = array("validation" => "true");
            $res = json_encode($result);
            echo "myJsonMethod(" . $res . ")";
            exit;
        } else {
            $result = array("validation" => "false");
            $res = json_encode($result);
            echo "myJsonMethod(" . $res . ")";
            exit;
        }
    }

    /*
     * Checkout Ajax
     */
    public function actionCheckoutajax() {

        ob_start();
        $response = '';
        $shop = Yii::$app->request->get('store');
        $shop = $shop == "spensry.com" || $shop == "www.spensry.com" ? 'spensry.myshopify.com' : $shop;
        $Store = Store::find()->where(['name' => $shop])->one();
        $logs = fopen("logs.txt", "a") or die("Unable to open file!");
        fwrite($logs, "\n [".date("Y-m-d H:i:s A")."] Checkout: ". json_encode($_GET)."\n");
        if($Store == null) {
            fwrite($logs, "Invalid request");
            echo "docheckout('Invalid request);";
            exit;
        }
        $token = $Store->token;
        $sc = new ShopifyClient($shop, $token, Yii::$app->params['APP_KEY'], Yii::$app->params['SECRET_KEY']);
        $email = Yii::$app->request->get('email');
        $cart_item = Yii::$app->request->get('cart_item');
        $currency = Yii::$app->request->get('currency');
        $shipping_amount = 0;
        $shipping_title = '';
        $shipping_rates = Yii::$app->request->get('shipping_rates');
        if (isset($shipping_rates)) {
            $shipping_title = $shipping_rates['title'];
            $shipping_amount = $shipping_rates['amount'];
        }
        $total_price = (float)Yii::$app->request->get('total_price');
        $amount = $total_price*100;
        $billing = Yii::$app->request->get('billing_address');
        $billing_address = array(
            "first_name" => $billing["first_name"],
            "last_name" => $billing["last_name"],
            "address1" => $billing['address'],
            "address2" => $billing['apartment'],
            "city" => $billing['city'],
            "phone" => $billing['phone'],
            "company" => $billing['company'],
            "province" => $billing['state'],
            "country" => $billing['country'],
            "zip" => $billing['postal']
        );
        $shipping = Yii::$app->request->get('shipping_address');
        $shipping_address = array(
            "first_name" => $shipping['first_name'],
            "last_name" => $shipping['last_name'],
            "address1" => $shipping['address'],
            "address2" => $shipping['apartment'],
            "city" => $shipping['city'],
            "phone" => $shipping['phone'],
            "company" => $shipping['company'],
            "province" => $shipping['state'],
            "country" => $shipping['country'],
            "zip" => $shipping['postal']
        );
        $line_item = array();
        foreach ($cart_item['items'] as $key => $val) {
            $items = array(
//                "title" => $val['title'],
//                'product_id' => $val['product_id'],
                'variant_id' => $val['variant_id'],
                'quantity' => $val['quantity'],
                'price' => $val['price'] / 100
            );
            $line_item[] = $items;
        }
        $nonce = Yii::$app->request->get('nonce');
        $cart_token = Yii::$app->request->get('token');
        $gateway = Yii::$app->request->get('gateway');
        $name = $billing["first_name"]." ".$billing["last_name"];
        $payment_status = "";
        $customer_id = "";
        if ($gateway == 'SQUARE') {  // Sequare Gateway selected

            // check sandbox or live.
            $config = Configurations::find()->where(['meta_key' => $shop . '_square_detail'])->one();
            $square_config = unserialize($config->meta_value);
            if (isset($square_config['sandbox']) && $square_config['sandbox'] == '1') {
                $sandbox = TRUE;
            } else {
                $sandbox = FALSE;
            }

            // Set Square API credentials.
            $host = $sandbox ? 'https://connect.squareupsandbox.com' : 'https://connect.squareup.com';
            $access_token = $sandbox ? $square_config['sandbox_access_token'] : $square_config['live_access_token'];
            $location_id = $sandbox ? $square_config['sandbox_location_id'] : $square_config['live_location_id'];
            
            fwrite($logs, "sandbox: sandbox");

            # setup authorization
            $api_config = new \SquareConnect\Configuration();
            $api_config->setHost($host);
            $api_config->setAccessToken($access_token);
            $api_client = new \SquareConnect\ApiClient($api_config);
            fwrite($logs, "1");

            $billingAddress = new \SquareConnect\Model\Address();            
            $billingAddress->setAddressLine1($billing['address']);
            $billingAddress->setAddressLine2($billing['apartment']);
            $billingAddress->setLocality($billing['city']);
            $billingAddress->setAdministrativeDistrictLevel1($billing['state']);
            $billingAddress->setPostalCode($billing['postal']);
            $billingAddress->setCountry($billing['country']);
            $billingAddress->setFirstName($billing["first_name"]);
            $billingAddress->setLastName($billing["last_name"]);
            $billingAddress->setOrganization($billing['company']);

            fwrite($logs, "2");
            $shippingAddress = new \SquareConnect\Model\Address();            
            $shippingAddress->setAddressLine1($shipping['address']);
            $shippingAddress->setAddressLine2($shipping['apartment']);
            $shippingAddress->setLocality($shipping['city']);
            $shippingAddress->setAdministrativeDistrictLevel1($shipping['state']);
            $shippingAddress->setPostalCode($shipping['postal']);
            $shippingAddress->setCountry($shipping['country']);
            $shippingAddress->setFirstName($shipping["first_name"]);
            $shippingAddress->setLastName($shipping["last_name"]);
            $shippingAddress->setOrganization($shipping['company']);

            fwrite($logs, "3");
            $squareCustomer = Orders::find()->where(['email' => $email])->andWhere(['!=', 'square_customer_id', 'null'])->one();
            if($squareCustomer !== null) {
                fwrite($logs, "4 --". $squareCustomer->square_customer_id.'--');
                $customer_id = $squareCustomer->square_customer_id;
            } else {
                // Create new customer with address
                $apiInstance = new SquareConnect\Api\CustomersApi($api_client);
                $customer = new \SquareConnect\Model\CreateCustomerRequest();

                $customer->setIdempotencyKey(uniqid());
                $customer->setGivenName($name);
                $customer->setCompanyName($billing['company']);
                $customer->setEmailAddress($email);
                $customer->setAddress($billingAddress);
                $customer->setPhoneNumber($billing['phone']);

                fwrite($logs, "5");
                try {
                    $customer_response = $apiInstance->createCustomer($customer);
                    $customer_id = $customer_response->getCustomer()->getId();
                    fwrite($logs, "6");
                } catch (\SquareConnect\ApiException $e) {
                    
                    fwrite($logs, "Customer error: " . $e->getResponseBody()->errors[0]->category." ".$e->getResponseBody()->errors[0]->detail);
                    $error['status'] = 'fail';
                    $error['message'] = $e->getResponseBody()->errors[0]->category." ".$e->getResponseBody()->errors[0]->detail;
                    $response = json_encode($error);
                    echo "docheckout(" . $response . ");";
                    exit;
                }
            }
            fwrite($logs, "7");

            # create an instance of the Payments API class
            $payments_api = new \SquareConnect\Api\PaymentsApi($api_client);
            $body = new \SquareConnect\Model\CreatePaymentRequest();
            $amountMoney = new \SquareConnect\Model\Money();

            # Monetary amounts are specified in the smallest unit of the applicable currency.
            # This amount is in cents. It's also hard-coded for $1.00, which isn't very useful.
            $amountMoney->setAmount($amount);
            $amountMoney->setCurrency($currency);

            fwrite($logs, "8");
            $body->setSourceId($nonce);
            $body->setAmountMoney($amountMoney);
            $body->setLocationId($location_id);
            
            // Set billing and shipping address with Square payment
            $body->setBillingAddress($billingAddress);
            $body->setShippingAddress($shippingAddress);

            // Attach customer_id with Square payment
            if($customer_id !== "") {
                $body->setCustomerId($customer_id);
            }

            fwrite($logs, "9");
            # Every payment you process with the SDK must have a unique idempotency key.
            $body->setIdempotencyKey(uniqid());

            try {
                fwrite($logs, "10");
                $result = $payments_api->createPayment($body);
                // Parse the Payment gateway response
                $response_array = $result->getPayment();
            } catch (\SquareConnect\ApiException $e) {
             
                fwrite($logs, "Payment failed: " . $e->getResponseBody()->errors[0]->category." ".$e->getResponseBody()->errors[0]->detail);
                $error['status'] = 'fail';
                $error['message'] = $e->getResponseBody()->errors[0]->category." ".$e->getResponseBody()->errors[0]->detail;
                $response = json_encode($error);
                echo "docheckout(" . $response . ");";
                exit;
            }
            
            //Error Handling
            if ($result->getErrors()) {
                
                fwrite($logs, "Error Handling: " . json_encode($result->getErrors()));
                $response = json_encode($result->getErrors());
                echo "docheckout(" . $response . ");";
                exit;
            } else {
                $payment_status = "Success";
            }

            if ($payment_status == "Success") {
                fwrite($logs, " Payment Success");
                $orderDatanew = array('order' => array(
                        'email' => $email,
                        //'send_fulfillment_receipt'=> true,
                        'send_receipt' => true,
                        'line_items' => $line_item,
                        //'customer' =>$customer,
                        'billing_address' => $billing_address,
                        'taxes_included' => false,
                        'shipping_address' => $shipping_address,
                        'financial_status' => "paid",
                        'fulfillment_status' => "unfulfilled",
                        'checkout_token' => $cart_token
                    )
                );
                fwrite($logs, '11');
                if (Yii::$app->request->get('customer') != '') {
                    $customer = array(
                        "id" => Yii::$app->request->get('customer'),
                    );
                    $orderDatanew['order']['customer'] = $customer;
                } else {
                    $orderDatanew['order']['buyer_accepts_marketing'] = true;
                }
                fwrite($logs, '12');
                $coupon = Yii::$app->request->get('coupon_detail');
                if ($coupon['coupon_type'] != '') {
                    $discount_code = array(
                        "code" => strtoupper($coupon['coupon_name']),
                        "amount" => abs($coupon['coupon_amount_rate']),
                        "type" => $coupon['coupon_type']
                    );
                    $discount_codes[] = $discount_code;
                    $orderDatanew['order']['discount_codes'] = $discount_codes;
                }
                fwrite($logs, '13');
                if ($shipping_rates['amount'] != '') {
                    $ship = array(
                        'title' => $shipping_rates['title'],
                        'price' => $shipping_rates['amount']
                    );
                    $shippinglines[] = $ship;
                    $orderDatanew['order']['shipping_lines'] = $shippinglines;
                }
                fwrite($logs, "14 Order array: ". json_encode($orderDatanew));
                $tax = Yii::$app->request->get('tax_detail');
                if ($tax['tax_price'] != '') {
                    $tax_amt = $tax['tax_price'];
                    $tax = array(
                        "title" => $tax['tax_name'],
                        "price" => $tax_amt,
                        "rate" => $tax['tax_rate'],
                    );
                    $taxlines[] = $tax;
                    $orderDatanew['order']['tax_lines'] = $taxlines;
                    $orderDatanew['order']['total_tax'] = $tax_amt;
                }
                if ($currency == 'EUR') {
                    $orderDatanew['order']['taxes_included'] = true;
                }
                $txn = array(
                    "kind" => "sale",
                    "status" => "success",
                    "amount" => $total_price,
                    "gateway" => "Credit Card"
                );
                fwrite($logs, json_encode($txn));
                $transacrtion[] = $txn;
                $orderDatanew['order']['transactions'] = $transacrtion;
                fwrite($logs, "\n Complete Order array: ".json_encode($orderDatanew));
                $orderData = $sc->call('POST', "/admin/orders.json", $orderDatanew);
                fwrite($logs, json_encode($orderData));
                
                if (!empty($orderData['errors'])) {
                    fwrite($logs, "New Order error ".json_encode($orderData));
                    $err_response['status'] = 'fail';
                    $err_response['message'] = 'something went wrong';

                    if (!empty($orderData['errors']['customer'])) {
                        $err_response['message'] = $orderData['errors']['customer'][0];
                    }
                    $response = json_encode($err_response);
                    echo "docheckout(" . $response . ");";
                    exit;
                }
                $orderid = $orderData['id'];
                if ($orderData['id']) {
                    fwrite($logs, "New Order placed $orderid \n\n");
                    $store_id = $Store->id;
                    $payment_mode = "Card";

                    $order_name = $orderData['name'];
                    $this->actionSavetransactiondetail($store_id, $orderid, $order_name, $response_array, $payment_mode, $name, $email, $billing['postal'], $billing['country'], $gateway, $amount, $currency, $customer_id);

                    $model = new CartDetails();
                    $model->order_id = $orderid;
                    $model->cart_token = $cart_token;
                    $model->save();

                    $dd = array('status_message' => "payment has been created successfully.");
                    $new_url = str_replace('checkout.shopify.com', $shop, $orderData['order_status_url']);
                    $dd['response'] = $new_url;
                    $dd['order_id'] = $orderid;
                    $response = json_encode($dd);
                    echo "docheckout(" . $response . ");";
                }
            }
        }
    }

    public function actionSavetransactiondetail($store_id, $orderid, $order_name, $response, $payment_mode, $name, $email, $postal, $country, $gateway, $amount, $currency, $customer_id) {
        $Ordersave = new Orders();
        $Ordersave->store_id = $store_id;
        $Ordersave->order_id = $orderid;
        $Ordersave->order_name = $order_name;
        $Ordersave->customer_name = $name;
        $Ordersave->email = $email;
        $Ordersave->pin = $postal;
        $Ordersave->country = $country;

        if ($gateway == "SQUARE") {
            $card = $response->getCardDetails()->getCard();
            $Ordersave->sequare_payment_id = $response->getId();
            $Ordersave->square_customer_id = $customer_id;
            $Ordersave->amount = $amount;
            $Ordersave->currency = $currency;
            $Ordersave->card_status = $response->getCardDetails()->getStatus();
            $Ordersave->card_brand = $card->getCardBrand();
            $Ordersave->last_4 = $card->getLast4();
            $Ordersave->expiry = $card->getExpMonth().' '.$card->getExpYear();
            $Ordersave->location_id = $response->getLocationId();
            $Ordersave->square_order_id = $response->getOrderId();
            $Ordersave->status = $response->getStatus();
        }

        $Ordersave->payment_mode = $payment_mode;
        $Ordersave->save(false);
    }

    /*
     * Checkout with total $0
     */
    public function actionProcessCheckout() {

        ob_start();
        $response = '';
        $shop = Yii::$app->request->get('store');
        $shop = $shop == "spensry.com" || $shop == "www.spensry.com" ? 'spensry.myshopify.com' : $shop;
        $Store = Store::find()->where(['name' => $shop])->one();
        if($Store == null) {
            echo "docheckout('Invalid request);";
            exit;
        }
        $token = $Store->token;
        $sc = new ShopifyClient($shop, $token, Yii::$app->params['APP_KEY'], Yii::$app->params['SECRET_KEY']);
        $email = Yii::$app->request->get('email');
        $cart_item = Yii::$app->request->get('cart_item');
        $currency = Yii::$app->request->get('currency');
        $shipping_amount = 0;
        $shipping_title = '';
        $shipping_rates = Yii::$app->request->get('shipping_rates');
        if (isset($shipping_rates)) {
            $shipping_title = $shipping_rates['title'];
            $shipping_amount = $shipping_rates['amount'];
        }
        $total_price = (float)Yii::$app->request->get('total_price');
        $billing = Yii::$app->request->get('billing_address');
        $billing_address = array(
            "first_name" => $billing["first_name"],
            "last_name" => $billing["last_name"],
            "address1" => $billing['address'],
            "address2" => $billing['apartment'],
            "city" => $billing['city'],
            "phone" => $billing['phone'],
            "company" => $billing['company'],
            "province" => $billing['state'],
            "country" => $billing['country'],
            "zip" => $billing['postal']
        );
        $shipping = Yii::$app->request->get('shipping_address');
        $shipping_address = array(
            "first_name" => $shipping['first_name'],
            "last_name" => $shipping['last_name'],
            "address1" => $shipping['address'],
            "address2" => $shipping['apartment'],
            "city" => $shipping['city'],
            "phone" => $shipping['phone'],
            "company" => $shipping['company'],
            "province" => $shipping['state'],
            "country" => $shipping['country'],
            "zip" => $shipping['postal']
        );
        $line_item = array();
        foreach ($cart_item['items'] as $key => $val) {
            $items = array(
                'variant_id' => $val['variant_id'],
                'quantity' => $val['quantity'],
                'price' => $val['price'] / 100
            );
            $line_item[] = $items;
        }
        $nonce = Yii::$app->request->get('nonce');
        $cart_token = Yii::$app->request->get('token');
        if ($nonce == '0') {  // Sequare Gateway selected

            $orderDatanew = array('order' => array(
                    'email' => $email,
                    //'send_fulfillment_receipt'=> true,
                    'send_receipt' => true,
                    'line_items' => $line_item,
                    //'customer' =>$customer,
                    'billing_address' => $billing_address,
                    'taxes_included' => false,
                    'shipping_address' => $shipping_address,
                    'financial_status' => "paid",
                    'fulfillment_status' => "unfulfilled",
                    'checkout_token' => $cart_token
                )
            );
            if (Yii::$app->request->get('customer') != '') {
                $customer = array(
                    "id" => Yii::$app->request->get('customer'),
                );
                $orderDatanew['order']['customer'] = $customer;
            } else {
                $orderDatanew['order']['buyer_accepts_marketing'] = true;
            }
            $coupon = Yii::$app->request->get('coupon_detail');
            if ($coupon['coupon_type'] != '') {
                $discount_code = array(
                    "code" => strtoupper($coupon['coupon_name']),
                    "amount" => abs($coupon['coupon_amount_rate']),
                    "type" => $coupon['coupon_type']
                );
                $discount_codes[] = $discount_code;
                $orderDatanew['order']['discount_codes'] = $discount_codes;
            }
            if ($shipping_rates['amount'] != '') {
                $ship = array(
                    'title' => $shipping_rates['title'],
                    'price' => 0
                );
                $shippinglines[] = $ship;
                $orderDatanew['order']['shipping_lines'] = $shippinglines;
            }
            $tax = Yii::$app->request->get('tax_detail');
            if ($tax['tax_price'] != '') {
                $tax_amt = $tax['tax_price'];
                $tax = array(
                    "title" => $tax['tax_name'],
                    "price" => $tax_amt,
                    "rate" => $tax['tax_rate'],
                );
                $taxlines[] = $tax;
                $orderDatanew['order']['tax_lines'] = $taxlines;
                $orderDatanew['order']['total_tax'] = $tax_amt;
            }
            if ($currency == 'EUR') {
                $orderDatanew['order']['taxes_included'] = true;
            }
            $orderData = $sc->call('POST', "/admin/orders.json", $orderDatanew);
            if (!empty($orderData['errors'])) {

                $err_response['status'] = 'fail';
                $err_response['message'] = 'something went wrong';

                if (!empty($orderData['errors']['customer'])) {
                    $err_response['message'] = $orderData['errors']['customer'][0];
                }
                $response = json_encode($err_response);
                echo "docheckout(" . $response . ");";
                exit;
            }
            if ($orderData['id']) {
                $model = new CartDetails();
                $model->order_id = $orderData['id'];
                $model->cart_token = $cart_token;
                $model->save();
                $dd = array('status_message' => "Order has been created successfully.");
                $new_url = str_replace('checkout.shopify.com', $shop, $orderData['order_status_url']);
                $dd['response'] = $new_url;
                $response = json_encode($dd);
                echo "docheckout(" . $response . ");";
            }
        }
    }
}
