<?php
/**
 * order_admin.php
 *
 * Order management
 *
 * @author     Makai Lajos
 * @copyright  2015
 * @license    License.txt
 * @version    1.0
 * @link       http://opencart-api.com/product/opencart-rest-admin-api/
 * @see        http://webshop.opencart-api.com/rest-admin-api/
 */
require_once(DIR_SYSTEM . 'engine/restadmincontroller.php');

/*if(strpos(VERSION, '2.2.') !== false || strpos(VERSION, '2.3.') !== false) {
    require_once(DIR_SYSTEM . 'library/cart/cart.php');
    require_once(DIR_SYSTEM . 'library/cart/tax.php');
}*/

class ControllerRestOrderAdmin extends RestAdminController
{

    public function addOrder($post)
    {

        $json = array('success' => false);
        $error = array();

        // Validate if payment address has been set.
        if (!isset($post['payment_address'])) {
            $error[] = "Payment address is empty";
        }

        // Validate if payment method has been set.
        if (!isset($post['payment_method'])) {
            $error[] = "Payment method is empty";
        }

        $products = $post['products'];

        // Validate cart has products and has stock.
        if ((!count($products) && empty($post['vouchers']))) {
            $error[] = "Product is required";
        }

        if (empty($error)) {
            $order_data = array();

            $order_data['totals'] = array();

            if (isset($post['totals']) && !empty($post['totals'])) {
                $order_data['totals'] = $post['totals'];
            }

            $sort_order = array();

            foreach ($order_data['totals'] as $key => $value) {
                $sort_order[$key] = $value['sort_order'];
            }

            array_multisort($sort_order, SORT_ASC, $order_data['totals']);

            $this->load->language('checkout/checkout');

            $order_data['invoice_prefix'] = $this->config->get('config_invoice_prefix');
            $order_data['store_id'] = $this->config->get('config_store_id');
            $order_data['store_name'] = $this->config->get('config_name');

            if ($order_data['store_id']) {
                $order_data['store_url'] = $this->config->get('config_url');
            } else {
                $order_data['store_url'] = HTTP_SERVER;
            }


            $customer_info = $post["customer"];

            $order_data['customer_id'] = $customer_info['customer_id'];
            $order_data['customer_group_id'] = $customer_info['customer_group_id'];
            $order_data['firstname'] = $customer_info['firstname'];
            $order_data['lastname'] = $customer_info['lastname'];
            $order_data['email'] = $customer_info['email'];
            $order_data['telephone'] = $customer_info['telephone'];
            $order_data['fax'] = $customer_info['fax'];

            $custom_field = array();
            if (isset($customer_info['custom_field']) && !empty($customer_info['custom_field'])) {
                if (strpos(VERSION, '2.1.') === false && strpos(VERSION, '2.2.') === false && strpos(VERSION, '2.3.') === false) {
                    $custom_field = unserialize($customer_info['custom_field']);
                } else {
                    $custom_field = json_decode($customer_info['custom_field'], true);
                }
            }

            $order_data['custom_field'] = $custom_field;

            $order_data['payment_firstname'] = $post['payment_address']['firstname'];
            $order_data['payment_lastname'] = $post['payment_address']['lastname'];
            $order_data['payment_company'] = $post['payment_address']['company'];
            $order_data['payment_address_1'] = $post['payment_address']['address_1'];
            $order_data['payment_address_2'] = $post['payment_address']['address_2'];
            $order_data['payment_city'] = $post['payment_address']['city'];
            $order_data['payment_postcode'] = $post['payment_address']['postcode'];
            $order_data['payment_zone'] = $post['payment_address']['zone'];
            $order_data['payment_zone_id'] = $post['payment_address']['zone_id'];
            $order_data['payment_country'] = $post['payment_address']['country'];
            $order_data['payment_country_id'] = $post['payment_address']['country_id'];
            //$order_data['payment_address_format'] = $post['payment_address']['address_format'];
            $order_data['payment_address_format'] = "";
            $order_data['payment_custom_field'] = (isset($post['payment_address']['custom_field']) ? $post['payment_address']['custom_field'] : array());

            if (isset($post['payment_method']['title'])) {
                $order_data['payment_method'] = $post['payment_method']['title'];
            } else {
                $order_data['payment_method'] = '';
            }

            if (isset($post['payment_method']['code'])) {
                $order_data['payment_code'] = $post['payment_method']['code'];
            } else {
                $order_data['payment_code'] = '';
            }

            if ($post['shipping_address']) {
                $order_data['shipping_firstname'] = $post['shipping_address']['firstname'];
                $order_data['shipping_lastname'] = $post['shipping_address']['lastname'];
                $order_data['shipping_company'] = $post['shipping_address']['company'];
                $order_data['shipping_address_1'] = $post['shipping_address']['address_1'];
                $order_data['shipping_address_2'] = $post['shipping_address']['address_2'];
                $order_data['shipping_city'] = $post['shipping_address']['city'];
                $order_data['shipping_postcode'] = $post['shipping_address']['postcode'];
                $order_data['shipping_zone'] = $post['shipping_address']['zone'];
                $order_data['shipping_zone_id'] = $post['shipping_address']['zone_id'];
                $order_data['shipping_country'] = $post['shipping_address']['country'];
                $order_data['shipping_country_id'] = $post['shipping_address']['country_id'];
                //$order_data['shipping_address_format'] = $post['shipping_address']['address_format'];
                $order_data['shipping_address_format'] = "";
                $order_data['shipping_custom_field'] = (isset($post['shipping_address']['custom_field']) ? $post['shipping_address']['custom_field'] : array());

                if (isset($post['shipping_method']['title'])) {
                    $order_data['shipping_method'] = $post['shipping_method']['title'];
                } else {
                    $order_data['shipping_method'] = '';
                }

                if (isset($post['shipping_method']['code'])) {
                    $order_data['shipping_code'] = $post['shipping_method']['code'];
                } else {
                    $order_data['shipping_code'] = '';
                }
            } else {
                $order_data['shipping_firstname'] = '';
                $order_data['shipping_lastname'] = '';
                $order_data['shipping_company'] = '';
                $order_data['shipping_address_1'] = '';
                $order_data['shipping_address_2'] = '';
                $order_data['shipping_city'] = '';
                $order_data['shipping_postcode'] = '';
                $order_data['shipping_zone'] = '';
                $order_data['shipping_zone_id'] = '';
                $order_data['shipping_country'] = '';
                $order_data['shipping_country_id'] = '';
                $order_data['shipping_address_format'] = '';
                $order_data['shipping_custom_field'] = array();
                $order_data['shipping_method'] = '';
                $order_data['shipping_code'] = '';
            }

            $order_data['products'] = array();

            foreach ($products as $product) {
                $option_data = array();

                foreach ($product['option'] as $option) {
                    $option_data[] = array(
                        'product_option_id' => $option['product_option_id'],
                        'product_option_value_id' => $option['product_option_value_id'],
                        'option_id' => $option['option_id'],
                        'option_value_id' => $option['option_value_id'],
                        'name' => $option['name'],
                        'value' => $option['value'],
                        'type' => $option['type']
                    );
                }

                $order_data['products'][] = array(
                    'product_id' => $product['product_id'],
                    'name' => $product['name'],
                    'model' => $product['model'],
                    'option' => $option_data,
                    'download' => (isset($product['download']) && !empty($product['download'])) ? $product['download'] : array(),
                    'quantity' => $product['quantity'],
                    'subtract' => $product['subtract'],
                    'price' => $product['price'],
                    'total' => $product['total'],
                    'tax' => $this->tax->getTax($product['price'], $product['tax_class_id']),
                    'reward' => $product['reward']
                );
            }

            $order_data['vouchers'] = array();

            // Gift Voucher
            /*$order_data['vouchers'] = array();

            if (!empty($post['vouchers'])) {
                foreach ($post['vouchers'] as $voucher) {
                    $order_data['vouchers'][] = array(
                        'description'      => $voucher['description'],
                        'code'             => substr(md5(mt_rand()), 0, 10),
                        'to_name'          => $voucher['to_name'],
                        'to_email'         => $voucher['to_email'],
                        'from_name'        => $voucher['from_name'],
                        'from_email'       => $voucher['from_email'],
                        'voucher_theme_id' => $voucher['voucher_theme_id'],
                        'message'          => $voucher['message'],
                        'amount'           => $voucher['amount']
                    );
                }
            }*/

            $order_data['comment'] = $post['comment'];
            $order_data['total'] = $post['total'];


            $order_data['affiliate_id'] = (isset($post['affiliate_id']) ? $post['affiliate_id'] : 0);
            $order_data['commission'] = (isset($post['commission']) ? $post['commission'] : 0);
            $order_data['marketing_id'] = (isset($post['marketing_id']) ? $post['marketing_id'] : 0);
            $order_data['tracking'] = (isset($post['tracking']) ? $post['tracking'] : '');


            $order_data['language_id'] = $this->config->get('config_language_id');

            if (strpos(VERSION, '2.2.') === false && strpos(VERSION, '2.3.') === false) {
                $order_data['currency_id'] = $this->currency->getId();
                $order_data['currency_code'] = $this->currency->getCode();
                $order_data['currency_value'] = $this->currency->getValue($this->currency->getCode());
            } else {
                $order_data['currency_id'] = $this->currency->getId($this->config->get('config_currency'));
                $order_data['currency_code'] = $this->config->get('config_currency');
                $order_data['currency_value'] = $this->currency->getValue($this->config->get('config_currency'));

            }

            $order_data['ip'] = $this->request->server['REMOTE_ADDR'];

            if (!empty($this->request->server['HTTP_X_FORWARDED_FOR'])) {
                $order_data['forwarded_ip'] = $this->request->server['HTTP_X_FORWARDED_FOR'];
            } elseif (!empty($this->request->server['HTTP_CLIENT_IP'])) {
                $order_data['forwarded_ip'] = $this->request->server['HTTP_CLIENT_IP'];
            } else {
                $order_data['forwarded_ip'] = '';
            }

            if (isset($this->request->server['HTTP_USER_AGENT'])) {
                $order_data['user_agent'] = $this->request->server['HTTP_USER_AGENT'];
            } else {
                $order_data['user_agent'] = '';
            }

            if (isset($this->request->server['HTTP_ACCEPT_LANGUAGE'])) {
                $order_data['accept_language'] = $this->request->server['HTTP_ACCEPT_LANGUAGE'];
            } else {
                $order_data['accept_language'] = '';
            }

            $this->load->model('checkout/order');

            $data['order_id'] = $this->model_checkout_order->addOrder($order_data);

            $this->model_checkout_order->addOrderHistory($data['order_id'], $this->config->get('cod_order_status_id'), $order_data['comment']);

            $json["success"] = true;
            $json["data"] = array("id" => $data['order_id']);

            $this->sendResponse($json);

        } else {
            $json["error"] = $error;
            $this->sendResponse($json);
        }
    }


    /*
    * ORDER ADMIN FUNCTIONS
    * index.php?route=rest/order_admin/order
    */
    public function order()
    {

        $this->checkPlugin();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $requestjson = file_get_contents('php://input');
            $requestjson = json_decode($requestjson, true);

            if (!empty($requestjson)) {
                $this->addOrder($requestjson);
            } else {
                $this->sendResponse(array('success' => false));
            }
        }
    }


    /*
    * ORDER FUNCTIONS
    */
    public function orders()
    {


        $this->add_data(array('helelejej'));
        $this->checkPlugin();

        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            //get order details
            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                $this->getOrder($this->request->get['id']);
            } else {
                //get orders list
                $this->listOrders();
            }
        } else if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
            //update order data
            $requestjson = file_get_contents('php://input');

            $requestjson = json_decode($requestjson, true);

            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])
                && !empty($requestjson)) {
                $this->updateOrder($this->request->get['id'], $requestjson);
            } else {
                $this->sendResponse(array('success' => false));
            }


        } else if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
            //delete order
            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                $this->deleteOrder($this->request->get['id']);
            } else {
                $this->sendResponse(array('success' => false));
            }
        }
    }

    /*
    * List orders
    */
    public function listOrders()
    {

        $json = array('success' => true);

        $this->load->model('rest/restadmin');

        /*check offset parameter*/
        if (isset($this->request->get['offset']) && $this->request->get['offset'] != "" && ctype_digit($this->request->get['offset'])) {
            $offset = $this->request->get['offset'];
        } else {
            $offset = 0;
        }

        /*check limit parameter*/
        if (isset($this->request->get['limit']) && $this->request->get['limit'] != "" && ctype_digit($this->request->get['limit'])) {
            $limit = $this->request->get['limit'];
        } else {
            $limit = 10000;
        }

        /*get all orders of user*/
        $results = $this->model_rest_restadmin->getAllOrders($offset, $limit);

        $orders = array();

        if (count($results)) {
            foreach ($results as $result) {

                $product_total = $this->model_rest_restadmin->getTotalOrderProductsByOrderId($result['order_id']);
                $voucher_total = $this->model_rest_restadmin->getTotalOrderVouchersByOrderId($result['order_id']);

                $orders[] = array(
                    'order_id' => $result['order_id'],
                    'name' => $result['firstname'] . ' ' . $result['lastname'],
                    'status' => $result['status'],
                    'date_added' => $result['date_added'],
                    'products' => ($product_total + $voucher_total),
                    'total' => $result['total'],
                    'currency_code' => $result['currency_code'],
                    'currency_value' => $result['currency_value'],
                );
            }

            if (count($orders) == 0) {
                $json['success'] = false;
                $json['error'] = "No orders found";
            } else {
                $json['data'] = $orders;
            }

        } else {
            $json['error'] = "No orders found";
            $json['success'] = false;
        }

        $this->sendResponse($json);
    }

    /*
    * List orders whith details
    */
    public function listorderswithdetails()
    {


        $this->checkPlugin();
        $_SERVER['HTTP_X_OC_RESTADMIN_ID']="34df4346782dfr534aa567";
        $api_secret = $_SERVER['HTTP_X_OC_RESTADMIN_ID'];


        if ($api_secret) {
            $user_id = $this->db->query("SELECT * FROM `oc_user` where bifatura='" . $api_secret . "'")->row['user_id'];

        } else {
            $user_id = 0;
        }


        if ($_SERVER['REQUEST_METHOD'] === 'GET') {

            $json = array('success' => true);


            $this->load->model('rest/restadmin');

            /*check limit parameter*/
            if (isset($this->request->get['limit']) && $this->request->get['limit'] != "" && ctype_digit($this->request->get['limit'])) {
                $limit = $this->request->get['limit'];
            } else {
                $limit = 100000;
            }
            $log = new \Log('birfatura.log');


            $log->write($this->request->get);
            $filter_date_added_from = null;

            if (isset($this->request->get['filter_date_added_from'])) {
                $date_added_from = date('Y-m-d H:i:s', strtotime($this->request->get['filter_date_added_from']));
                if ($this->validateDate($date_added_from)) {
                    $filter_date_added_from = $date_added_from;
                }
            }

            $filter_date_added_on = null;

            if (isset($this->request->get['filter_date_added_on'])) {
                $date_added_on = date('Y-m-d', strtotime($this->request->get['filter_date_added_on']));
                if ($this->validateDate($date_added_on, 'Y-m-d')) {
                    $filter_date_added_on = $date_added_on;
                }
            }

            $filter_date_added_to = null;
            if (isset($this->request->get['filter_date_added_to'])) {
                $date_added_to = date('Y-m-d H:i:s', strtotime($this->request->get['filter_date_added_to']));
                if ($this->validateDate($date_added_to)) {
                    $filter_date_added_to = $date_added_to;
                }
            }

            $filter_date_modified_on = null;

            if (isset($this->request->get['filter_date_modified_on'])) {
                $date_modified_on = date('Y-m-d', strtotime($this->request->get['filter_date_modified_on']));
                if ($this->validateDate($date_modified_on, 'Y-m-d')) {
                    $filter_date_modified_on = $date_modified_on;
                }
            }

            $filter_date_modified_from = null;

            if (isset($this->request->get['filter_date_modified_from'])) {
                $date_modified_from = date('Y-m-d H:i:s', strtotime($this->request->get['filter_date_modified_from']));
                if ($this->validateDate($date_modified_from)) {
                    $filter_date_modified_from = $date_modified_from;
                }
            }

            $filter_date_modified_to = null;
            if (isset($this->request->get['filter_date_modified_to'])) {
                $date_modified_to = date('Y-m-d H:i:s', strtotime($this->request->get['filter_date_modified_to']));
                if ($this->validateDate($date_modified_to)) {
                    $filter_date_modified_to = $date_modified_to;
                }
            }

            if (isset($this->request->get['page'])) {
                $page = $this->request->get['page'];
            } else {
                $page = 1;
            }

            if (isset($this->request->get['filter_order_status_id'])) {
                $filter_order_status_id = $this->request->get['filter_order_status_id'];
            } else {
                $filter_order_status_id = null;
            }

            /*check filter_id_lower_than parameter*/
            if (isset($this->request->get['filter_id_lower_than']) && ctype_digit($this->request->get['filter_id_lower_than'])) {
                $filter_id_lower_than = $this->request->get['filter_id_lower_than'];
            } else {
                $filter_id_lower_than = null;
            }

            /*check filter_id_larger_than parameter*/
            if (isset($this->request->get['filter_id_larger_than']) && ctype_digit($this->request->get['filter_id_larger_than'])) {
                $filter_id_larger_than = $this->request->get['filter_id_larger_than'];
            } else {
                $filter_id_larger_than = null;
            }

            $data = array(
                'filter_date_added_on' => $filter_date_added_on,
                'filter_date_added_from' => $filter_date_added_from,
                'filter_date_added_to' => $filter_date_added_to,
                'filter_date_modified_on' => $filter_date_modified_on,
                'filter_date_modified_from' => $filter_date_modified_from,
                'filter_date_modified_to' => $filter_date_modified_to,
                'filter_order_status_id' => $filter_order_status_id,
                'filter_id_lower_than' => $filter_id_lower_than,
                'filter_id_larger_than' => $filter_id_larger_than,
                'filter_user_id' => $user_id,
                'start' => ($page - 1) * $limit,
                'limit' => $limit
            );


            if ($user_id) {
                $results = $this->model_rest_restadmin->getOrdersByFilter($data);

            } else {
                $results = array();

            }
            /*get all orders*/
            //$results = $this->model_account_order->getAllOrders($offset, $limit);
            $orders = array();

            if (count($results)) {

                foreach ($results as $result) {

                    $orderData = $this->getOrderDetailsToOrder($result);


                    if (!empty($orderData)) {
                        $orders[] = $orderData;
                    }
                }

                if (count($orders) == 0) {
                    $json['success'] = false;
                    $json['error'] = "No orders found";
                } else {
                    $json['data'] = $orders;
                }

            } else {
                $json['error'] = "No orders found";
                $json['success'] = false;
            }
        } else {
            $json['success'] = false;
        }

        $this->sendResponse($json);
    }

    /*Get order details*/
    public function getOrder($order_id)
    {

        $this->load->model('checkout/order');
        $this->load->model('account/order');

        $json = array('success' => true);

        if (ctype_digit($order_id)) {
            $order_info = $this->model_checkout_order->getOrder($order_id);

            if (!empty($order_info)) {
                $json['success'] = true;
                $json['data'] = $this->getOrderDetailsToOrder($order_info);

            } else {
                $json['success'] = false;
                $json['error'] = "The specified order does not exist.";

            }
        } else {
            $json['success'] = false;
            $json['error'] = "Invalid order id";

        }

        $this->sendResponse($json);
    }

    /*Get all orders of user */
    public function userorders()
    {

        $result = $this->checkPlugin();
        $this->add_data($this->request->get);

        if ($_SERVER['REQUEST_METHOD'] === 'GET') {

            $json = array('success' => true);

            $user = null;


            /*check user parameter*/
            if (isset($this->request->get['user'])) {
                $user = $this->request->get['user'];
            } else {
                $json['success'] = false;
            }


            if ($json['success'] == true) {
                $orderData['orders'] = array();

                $this->load->model('rest/restadmin');

                /*get all orders of user*/
                $results = $this->model_rest_restadmin->getOrdersByUser($user);


                $orders = array();

                foreach ($results as $result) {

                    $product_total = $this->model_rest_restadmin->getTotalOrderProductsByOrderId($result['order_id']);


                    // $voucher_total = $this->model_rest_restadmin->getTotalOrderVouchersByOrderId($result['order_id']);

                    $orders[] = array(
                        'order_id' => $result['order_id'],
                        'name' => $result['first_name'] . ' ' . $result['last_name'],
                        'status' => $result['status'],
                        'date_added' => $result['date_added'],
                        'products' => ($product_total),
                        'total' => $result['total'],
                        'currency_code' => 'TRY',
                        'currency_value' => 1,
                    );
                }

                if (count($orders) == 0) {
                    $json['success'] = false;
                    $json['error'] = "No orders found";
                } else {
                    $json['data'] = $orders;
                }
            } else {
                $json['success'] = false;
            }
        }

        $this->sendResponse($json);
    }

    private function getOrderDetailsToOrder($order_info)
    {

        $this->load->model('entegrasyon/order');
        $this->load->model('rest/restadmin');
        $this->load->model('account/order');

        $orderData = array();

        if (!empty($order_info)) {
            foreach ($order_info as $key => $value) {
                $orderData[$key] = $value;
            }

            $orderData['products'] = array();

            $products = $this->model_entegrasyon_order->getOrderProducts($orderData['order_id']);


            $item_total_exclude_tax = 0;
            $item_total_tax = 0;


            foreach ($products as $product) {
                $option_data = array();


                //$origProduct = $this->model_catalog_product->getProduct($product['product_id']);

                $total_formated=number_format($product['price'],2);
                $orderData['products'][] = array(
                    'order_product_id' => $product['order_product_id'],
                    'product_id' => rand(000000,999999),
                    'name' => $product['name'],
                    'model' => $product['model'],
                    'image' => 'https://floimages.mncdn.com/media/catalog/product/22-08/18/100445028_m1.JPG',
                    'sku' => $product['model'].'5u',
                    'option' => $option_data,
                    'quantity' => $product['quantity'],
                    'currency_code' => 'TRY',
                    'currency_value' => 1,
                    'price_formated' => number_format(($product['price']+$product['kdv']),2).'TL',
                    'price' => (float)$product['price']+$product['kdv'],
                    'price_exclude_tax' => number_format($product['list_price'],2),
                    'tax' => (float)$product['kdv'],
                    'total_formated' => number_format(($product['price']+$product['kdv']),2)  .'TL',
                    'total' => (float)$product['quantity'] * $product['list_price'],
                    'total_exclude_tax' => number_format(($product['quantity'] * $product['list_price']),2),
                    'total_tax' => (float)$product['kdv']
                );
                $item_total_exclude_tax += $product['price'];
                $item_total_tax += ($product['kdv'] * $product['quantity']);
            }
        }



                $orderData['histories'] = array();

/*
                $totals = $this->model_rest_restadmin->getOrderTotals($orderData['order_id']);

                foreach ($totals as $total) {
                    $orderData['totals'][] = array(
                        'title' => $total['title'],
                        'text'  => $this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value']),
                        'value'  => $total['value']
                    );
                }

*/
                unset($total);

             /*   $shippingCode = explode(".", $orderData['shipping_code']);
                $shippingTaxClassId = $this->config->get($shippingCode[0].'_tax_class_id');

                $shipping_total = $this->model_rest_restadmin->getOrderSubValue($orderData['order_id'], 'shipping');
*/
                $orderData['shipping_exclude_tax'] = 0;
                $orderData['shipping_tax']    = 0;
               /* if(!empty($shippingTaxClassId)) {
                    $shipping_lines = $this->model_rest_restadmin->getOrderTotalSubTaxes($shippingTaxClassId, 'shipping');

                    foreach($shipping_lines as $line){
                        $rate = (float)$line['rate'];
                        if($line['type'] == "P"){
                            $tax = array(
                                'name' =>$line['name'],
                                'price' =>$shipping_total,
                                'tax'=> ($shipping_total/100)*$rate
                            );
                            $orderData['shipping_exclude_tax']+=$shipping_total;
                            $orderData['shipping_tax']+=($shipping_total/100)*$rate;
                        }else {
                            $tax = array(
                                'name' =>$line['name'],
                                'price' => 0,
                                'tax'=> $rate
                            );

                            $orderData['shipping_exclude_tax']+=0;
                            $orderData['shipping_tax']+=$rate;

                        }
                        $orderData['shipping_lines'][] = $tax;
                    }
                } else {
                    $orderData['shipping_total'] = $shipping_total;
                }
               */
               $orderData['shipping_total'] =0;
                $orderData['item_total_tax'] = $item_total_tax;
                $orderData['item_total_exclude_tax'] = $item_total_exclude_tax;

              //  $subtotal = $this->model_rest_restadmin->getOrderSubValue($orderData['order_id'], 'sub_total');
                $orderData['subtotal'] =$item_total_tax + $item_total_exclude_tax;

               // $couponInfo = $this->model_rest_restadmin->getOrderCoupon($orderData['order_id']);

                $orderData['coupons'] = array();
                $orderData['totals'] = array();

              /*  if(!empty($couponInfo)){
                    foreach($couponInfo as $couponItem){
                        $orderData['coupons'][] = array('code'=>$couponItem['code'], 'amount'=>abs($couponItem['amount']));
                    }
                }*/

                //$voucherInfo = $this->model_rest_restadmin->getOrderVoucher($orderData['order_id']);
                $orderData['discounts'] = array();
           /*     if(!empty($voucherInfo)){
                    foreach($voucherInfo as $voucherItem){
                        $orderData['discounts'][] = array('code'=>$voucherItem['code'], 'amount'=>abs($voucherItem['amount']));
                    }
                }*/

        return $orderData;
    }

    /*
        Update order status

    */
    public function updateOrder($id, $data)
    {


        $json = array('success' => false);

        $this->load->model('checkout/order');

        if (ctype_digit($id)) {

            if (isset($data['status']) && ctype_digit($data['status'])) {

                $result = $this->model_checkout_order->getOrder($id);
                if (!empty($result)) {
                    $json['success'] = true;
                    $this->model_checkout_order->addOrderHistory($id, $data['status']);
                } else {
                    $json['success'] = false;
                    $json['error'] = "The specified order does not exist.";
                }

            } else {
                $json['success'] = false;
            }
        } else {
            $json['success'] = false;
        }

        $this->sendResponse($json);
    }

    /*Delete order*/
    public function deleteOrder($id)
    {

        $json['success'] = false;

        $this->load->model('checkout/order');

        if (ctype_digit($id)) {
            $result = $this->model_checkout_order->getOrder($id);

            if (!empty($result)) {
                $json['success'] = true;
                // Void the order first
                $this->model_checkout_order->addOrderHistory($id, 0);

                $this->model_checkout_order->deleteOrder($id);
                // Gift Voucher
                $this->load->model('checkout/voucher');

                $this->model_checkout_voucher->disableVoucher($id);
            } else {
                $json['success'] = false;
                $json['error'] = "The specified order does not exist.";
            }

        } else {
            $json['success'] = false;
        }

        $this->sendResponse($json);
    }


    /*
    * Update order status by status name
    */
    public function orderstatus()
    {


        $this->checkPlugin();
        if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])
            ) {
                $requestjson = file_get_contents('php://input');

                $requestjson = json_decode($requestjson, true);

                $this->updateOrderStatusByName($this->request->get['id'], $requestjson);
            } else {
                $json['success'] = false;
                $json['error'] = "Invalid request, please set order id and order status";

                $this->sendResponse($json);
            }
        }
    }

    /*
     *   Update order status by status name
    */
    public function updateOrderStatusByName($id, $data)
    {

        $json = array('success' => false);

        $this->load->model('checkout/order');

        if (ctype_digit($id)) {
            if (isset($data['status']) && ($data['status']) != "") {

                $status = $this->findStatusByName($data['status']);

                if ($status) {
                    $result = $this->model_checkout_order->getOrder($id);
                    if (!empty($result)) {
                        $json['success'] = true;
                        $this->model_checkout_order->addOrderHistory($id, $status);
                    } else {
                        $json['success'] = false;
                        $json['error'] = "The specified order does not exist.";
                    }
                } else {
                    $json['success'] = false;
                    $json['error'] = "The specified status does not exist.";
                }
            } else {
                $json['success'] = false;
                $json['error'] = "Invalid status id";
            }
        } else {
            $json['success'] = false;
            $json['error'] = "Invalid order id";
        }

        $this->sendResponse($json);

    }

    private function findStatusByName($status_name)
    {
        $this->load->model('rest/restadmin');

        $status_id = $this->model_rest_restadmin->getOrderStatusByName($status_name);
        return ((count($status_id) > 0 && $status_id[0]['order_status_id']) ? $status_id[0]['order_status_id'] : false);
    }

    /*
    * ADD ORDER HISTORY
    */
    public function orderhistory()
    {

        $this->checkPlugin();

        if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
            $requestjson = file_get_contents('php://input');

            $requestjson = json_decode($requestjson, true);

            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])
                && !empty($requestjson)) {
                $this->addOrderHistory($this->request->get['id'], $requestjson);
            } else {
                $this->sendResponse(array('success' => false));
            }
        }
    }

    private function addOrderHistory($id, $data)
    {

        $json = array('success' => true);

        $this->load->model('checkout/order');

        $order_info = $this->model_checkout_order->getOrder($id);

        if ($order_info) {
            $this->model_checkout_order->addOrderHistory($id, $data['order_status_id'], $data['comment'], $data['notify']);
        } else {
            $json["success"] = false;
            $json["error"] = "Order not found";
        }

        $this->sendResponse($json);
    }

    //date format validator
    private function validateDate($date, $format = 'Y-m-d H:i:s')
    {
        $d = DateTime::createFromFormat($format, $date);
        return $d && $d->format($format) == $date;
    }

    /*
    * ORDER ADMIN FUNCTIONS V2
    * index.php?route=rest/order_admin/orderv2
    */
    public function orderv2()
    {

        $this->checkPlugin();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $requestjson = file_get_contents('php://input');
            $requestjson = json_decode($requestjson, true);

            if (!empty($requestjson)) {
                $this->addOrderV2($requestjson);
            } else {
                $this->sendResponse(array('success' => false));
            }
        }
    }


    /*CREATE ORDER*/
    public function addOrderV2($post)
    {

        $json = array('success' => false);
        $error = array();

        unset($this->session->data['shipping_method']);
        unset($this->session->data['shipping_methods']);
        unset($this->session->data['payment_address']);
        unset($this->session->data['payment_methods']);
        unset($this->session->data['payment_method']);
        unset($this->session->data['customer']);
        $this->cart->clear();

        // Validate if payment address has been set.
        if (!isset($post['payment_address'])) {
            $error[] = "Payment address is empty";
        }

        // Validate if payment method has been set.
        if (!isset($post['payment_method'])) {
            $error[] = "Payment method is empty";
        }

        $products = $post['products'];

        // Validate cart has products and has stock.
        if ((!count($products))) {
            $error[] = "Product is required";
        }

        //Add items to cart
        $this->load->model('catalog/product');

        $cartResult = true;

        foreach ($products as $product) {
            $cartResult = $this->addItemCart($product);
            if ($cartResult["success"] == false) {
                break;
            }
        }

        if ($cartResult["success"] == false) {
            return $this->sendResponse($cartResult);
        }

        $this->load->model('rest/restadmin');

        if (empty($error)) {
            $order_data = array();

            $this->load->language('checkout/checkout');

            $order_data['invoice_prefix'] = $this->config->get('config_invoice_prefix');
            $order_data['store_id'] = $this->config->get('config_store_id');
            $order_data['store_name'] = $this->config->get('config_name');

            if ($order_data['store_id']) {
                $order_data['store_url'] = $this->config->get('config_url');
            } else {
                $order_data['store_url'] = HTTP_SERVER;
            }


            $customer_info = $post["customer"];

            $order_data['customer_id'] = $customer_info['customer_id'];
            $order_data['customer_group_id'] = $customer_info['customer_group_id'];
            $order_data['firstname'] = $customer_info['firstname'];
            $order_data['lastname'] = $customer_info['lastname'];
            $order_data['email'] = $customer_info['email'];
            $order_data['telephone'] = $customer_info['telephone'];
            $order_data['fax'] = $customer_info['fax'];

            $custom_field = array();
            if (isset($customer_info['custom_field']) && !empty($customer_info['custom_field'])) {
                if (strpos(VERSION, '2.1.') === false && strpos(VERSION, '2.2.') === false && strpos(VERSION, '2.3.') === false) {
                    $custom_field = unserialize($customer_info['custom_field']);
                } else {
                    $custom_field = json_decode($customer_info['custom_field'], true);
                }
            }
            $order_data['custom_field'] = $custom_field;

            $order_data['payment_firstname'] = $post['payment_address']['firstname'];
            $order_data['payment_lastname'] = $post['payment_address']['lastname'];
            $order_data['payment_company'] = $post['payment_address']['company'];
            $order_data['payment_address_1'] = $post['payment_address']['address_1'];
            $order_data['payment_address_2'] = $post['payment_address']['address_2'];
            $order_data['payment_city'] = $post['payment_address']['city'];
            $order_data['payment_postcode'] = $post['payment_address']['postcode'];
            $order_data['payment_zone'] = $post['payment_address']['zone'];
            $order_data['payment_zone_id'] = $post['payment_address']['zone_id'];
            $order_data['payment_country'] = $post['payment_address']['country'];
            $order_data['payment_country_id'] = $post['payment_address']['country_id'];
            //$order_data['payment_address_format'] = $post['payment_address']['address_format'];
            $order_data['payment_address_format'] = "";
            $order_data['payment_custom_field'] = (isset($post['payment_address']['custom_field']) ? $post['payment_address']['custom_field'] : array());

            if (isset($post['payment_method']['title'])) {
                $order_data['payment_method'] = $post['payment_method']['title'];
            } else {
                $order_data['payment_method'] = '';
            }

            if (isset($post['payment_method']['code'])) {
                $order_data['payment_code'] = $post['payment_method']['code'];
            } else {
                $order_data['payment_code'] = '';
            }


            // Customer Group
            if ($order_data['customer_group_id'] != "") {
                $this->config->set('config_customer_group_id', $order_data['customer_group_id']);
                //$order_data['customer_group_id'] = $order_data['customer_group_id'];
            } else {
                $order_data['customer_group_id'] = $this->config->get('config_customer_group_id');
            }
            // Customer Details
            $this->session->data['customer']['customer_id'] = $order_data['customer_id'];
            $this->session->data['customer']['customer_group_id'] = $order_data['customer_group_id'];
            $this->session->data['customer']['firstname'] = $order_data['firstname'];
            $this->session->data['customer']['lastname'] = $order_data['lastname'];
            $this->session->data['customer']['email'] = $order_data['email'];
            $this->session->data['customer']['telephone'] = $order_data['telephone'];
            $this->session->data['customer']['fax'] = $order_data['fax'];
            $this->session->data['customer']['custom_field'] = $order_data['custom_field'];

            $this->session->data['payment_address']['firstname'] = $order_data['payment_firstname'];
            $this->session->data['payment_address']['lastname'] = $order_data['payment_lastname'];
            $this->session->data['payment_address']['company'] = $order_data['payment_company'];
            $this->session->data['payment_address']['address_1'] = $order_data['payment_address_1'];
            $this->session->data['payment_address']['address_2'] = $order_data['payment_address_2'];
            $this->session->data['payment_address']['city'] = $order_data['payment_city'];
            $this->session->data['payment_address']['postcode'] = $order_data['payment_postcode'];
            $this->session->data['payment_address']['zone'] = $order_data['payment_zone'];
            $this->session->data['payment_address']['zone_id'] = $order_data['payment_zone_id'];
            $this->session->data['payment_address']['country'] = $order_data['payment_country'];
            $this->session->data['payment_address']['country_id'] = $order_data['payment_country_id'];
            $this->session->data['payment_address']['address_format'] = $order_data['payment_address_format'];
            $this->session->data['payment_address']['custom_field'] = $order_data['payment_custom_field'];


            if ($post['shipping_address']) {
                $order_data['shipping_firstname'] = $post['shipping_address']['firstname'];
                $order_data['shipping_lastname'] = $post['shipping_address']['lastname'];
                $order_data['shipping_company'] = $post['shipping_address']['company'];
                $order_data['shipping_address_1'] = $post['shipping_address']['address_1'];
                $order_data['shipping_address_2'] = $post['shipping_address']['address_2'];
                $order_data['shipping_city'] = $post['shipping_address']['city'];
                $order_data['shipping_postcode'] = $post['shipping_address']['postcode'];
                $order_data['shipping_zone'] = $post['shipping_address']['zone'];
                $order_data['shipping_zone_id'] = $post['shipping_address']['zone_id'];
                $order_data['shipping_country'] = $post['shipping_address']['country'];
                $order_data['shipping_country_id'] = $post['shipping_address']['country_id'];
                //$order_data['shipping_address_format'] = $post['shipping_address']['address_format'];
                $order_data['shipping_address_format'] = "";
                $order_data['shipping_custom_field'] = (isset($post['shipping_address']['custom_field']) ? $post['shipping_address']['custom_field'] : array());

                if (isset($post['shipping_method']['title'])) {
                    $order_data['shipping_method'] = $post['shipping_method']['title'];
                } else {
                    $order_data['shipping_method'] = '';
                }

                if (isset($post['shipping_method']['code'])) {
                    $order_data['shipping_code'] = $post['shipping_method']['code'];
                } else {
                    $order_data['shipping_code'] = '';
                }

            } else {
                $order_data['shipping_firstname'] = '';
                $order_data['shipping_lastname'] = '';
                $order_data['shipping_company'] = '';
                $order_data['shipping_address_1'] = '';
                $order_data['shipping_address_2'] = '';
                $order_data['shipping_city'] = '';
                $order_data['shipping_postcode'] = '';
                $order_data['shipping_zone'] = '';
                $order_data['shipping_zone_id'] = '';
                $order_data['shipping_country'] = '';
                $order_data['shipping_country_id'] = '';
                $order_data['shipping_address_format'] = '';
                $order_data['shipping_custom_field'] = array();
                $order_data['shipping_method'] = '';
                $order_data['shipping_code'] = '';
            }

            $this->session->data['shipping_address']['firstname'] = $order_data['shipping_firstname'];
            $this->session->data['shipping_address']['lastname'] = $order_data['shipping_lastname'];
            $this->session->data['shipping_address']['company'] = $order_data['shipping_company'];
            $this->session->data['shipping_address']['address_1'] = $order_data['shipping_address_1'];
            $this->session->data['shipping_address']['address_2'] = $order_data['shipping_address_2'];
            $this->session->data['shipping_address']['city'] = $order_data['shipping_city'];
            $this->session->data['shipping_address']['postcode'] = $order_data['shipping_postcode'];
            $this->session->data['shipping_address']['zone'] = $order_data['shipping_zone'];
            $this->session->data['shipping_address']['zone_id'] = $order_data['shipping_zone_id'];
            $this->session->data['shipping_address']['country'] = $order_data['shipping_country'];
            $this->session->data['shipping_address']['country_id'] = $order_data['shipping_country_id'];
            $this->session->data['shipping_address']['address_format'] = $order_data['shipping_address_format'];
            $this->session->data['shipping_address']['custom_field'] = $order_data['shipping_custom_field'];


            if (strpos(VERSION, '2.2.') !== false || strpos(VERSION, '2.3.') !== false) {
// Tax
                $this->registry->set('tax', new Cart\Tax($this->registry));

                if ($this->config->get('config_tax_default') == 'shipping') {
                    $this->tax->setShippingAddress($this->config->get('config_country_id'), $this->config->get('config_zone_id'));
                }

                if ($this->config->get('config_tax_default') == 'payment') {
                    $this->tax->setPaymentAddress($this->config->get('config_country_id'), $this->config->get('config_zone_id'));
                }

                $this->tax->setStoreAddress($this->config->get('config_country_id'), $this->config->get('config_zone_id'));

                // Cart
                $this->registry->set('cart', new Cart\Cart($this->registry));
            } else {
                $this->registry->set('tax', new Tax($this->registry));
                // Cart
                $this->registry->set('cart', new Cart($this->registry));
            }


            if (strpos(VERSION, '2.2.') === false && strpos(VERSION, '2.3.') === false) {
                $this->paymentmethods();
            } else {
                $this->paymentmethodsV2();
            }
            if (isset($this->session->data['payment_methods'][$order_data['payment_code']])) {
                $this->session->data['payment_method'] = $this->session->data['payment_methods'][$order_data['payment_code']];
            } else {
                $this->session->data['payment_method'] = '';
            }

            $this->shippingmethods();
            if ($this->cart->hasShipping()) {
                $shipping = explode('.', $order_data['shipping_code']);
                $this->session->data['shipping_method'] = $this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]];
            } else {
                unset($this->session->data['shipping_address']);
                unset($this->session->data['shipping_method']);
                unset($this->session->data['shipping_methods']);
            }

            $order_data['products'] = array();

            foreach ($this->cart->getProducts() as $product) {
                $option_data = array();

                foreach ($product['option'] as $option) {
                    if ($option['type'] != 'file') {
                        $value = $option['option_value'];
                    } else {
                        $value = "";
                    }

                    $option_data[] = array(
                        'product_option_id' => $option['product_option_id'],
                        'product_option_value_id' => $option['product_option_value_id'],
                        'option_id' => $option['option_id'],
                        'option_value_id' => $option['option_value_id'],
                        'name' => $option['name'],
                        'value' => $value,
                        'type' => $option['type']
                    );
                }

                $order_data['products'][] = array(
                    'product_id' => $product['product_id'],
                    'name' => $product['name'],
                    'model' => $product['model'],
                    'option' => $option_data,
                    'download' => (isset($product['download']) && !empty($product['download'])) ? $product['download'] : array(),
                    'quantity' => $product['quantity'],
                    'subtract' => $product['subtract'],
                    'price' => $product['price'],
                    'total' => $product['total'],
                    'tax' => $this->tax->getTax($product['price'], $product['tax_class_id']),
                    'reward' => $product['reward']
                );
            }

            // Gift Voucher

            if (isset($post["coupon"]) && $this->validateCoupon($post["coupon"])) {
                $this->session->data['coupon'] = $post["coupon"];
            }

            if (isset($post["voucher"]) && $this->validateVoucher($post["voucher"])) {
                $this->session->data['voucher'] = $post["voucher"];
            }

            $order_data['totals'] = array();

            $totals = array();
            $taxes = $this->cart->getTaxes();
            $total = 0;

            // Because __call can not keep var references so we put them into an array.
            $total_data = array(
                'totals' => &$totals,
                'taxes' => &$taxes,
                'total' => &$total
            );


            $sort_order = array();

            $results = $this->model_rest_restadmin->getExtensions('total');

            foreach ($results as $key => $value) {
                $sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
            }

            array_multisort($sort_order, SORT_ASC, $results);

            foreach ($results as $result) {
                if ($this->config->get($result['code'] . '_status')) {

                    if (strpos(VERSION, '2.2.') === false && strpos(VERSION, '2.3.') === false) {
                        $this->load->model('total/' . $result['code']);
                        $this->{'model_total_' . $result['code']}->getTotal($order_data['totals'], $total, $taxes);
                    } else {
                        if (strpos(VERSION, '2.3.') === false) {
                            $this->load->model('total/' . $result['code']);
                            $this->{'model_total_' . $result['code']}->getTotal($total_data);
                        } else {
                            $this->load->model('extension/total/' . $result['code']);
                            $this->{'model_extension_total_' . $result['code']}->getTotal($total_data);
                        }
                    }
                }
            }

            $sort_order = array();
            if (strpos(VERSION, '2.2.') === false && strpos(VERSION, '2.3.') === false) {
                foreach ($order_data['totals'] as $key => $value) {
                    $sort_order[$key] = $value['sort_order'];
                }

                array_multisort($sort_order, SORT_ASC, $order_data['totals']);
            } else {
                foreach ($total_data['totals'] as $key => $value) {
                    $sort_order[$key] = $value['sort_order'];
                }

                array_multisort($sort_order, SORT_ASC, $total_data['totals']);

                $order_data['totals'] = $totals;
            }

            if (strpos(VERSION, '2.2.') === false && strpos(VERSION, '2.3.') === false) {
                $order_data['total'] = $total;
            } else {
                $order_data['total'] = $total_data['total'];
            }

            $order_data['comment'] = $post['comment'];

            $order_data['affiliate_id'] = (isset($post['affiliate_id']) ? $post['affiliate_id'] : 0);
            $order_data['commission'] = (isset($post['commission']) ? $post['commission'] : 0);
            $order_data['marketing_id'] = (isset($post['marketing_id']) ? $post['marketing_id'] : 0);
            $order_data['tracking'] = (isset($post['tracking']) ? $post['tracking'] : '');


            $order_data['language_id'] = $this->config->get('config_language_id');
            if (strpos(VERSION, '2.2.') === false && strpos(VERSION, '2.3.') === false) {
                $order_data['currency_id'] = $this->currency->getId();
                $order_data['currency_code'] = $this->currency->getCode();
                $order_data['currency_value'] = $this->currency->getValue($this->currency->getCode());
            } else {
                $order_data['currency_id'] = $this->currency->getId($this->config->get('config_currency'));
                $order_data['currency_code'] = $this->config->get('config_currency');
                $order_data['currency_value'] = $this->currency->getValue($this->config->get('config_currency'));

            }
            $order_data['ip'] = $this->request->server['REMOTE_ADDR'];

            if (!empty($this->request->server['HTTP_X_FORWARDED_FOR'])) {
                $order_data['forwarded_ip'] = $this->request->server['HTTP_X_FORWARDED_FOR'];
            } elseif (!empty($this->request->server['HTTP_CLIENT_IP'])) {
                $order_data['forwarded_ip'] = $this->request->server['HTTP_CLIENT_IP'];
            } else {
                $order_data['forwarded_ip'] = '';
            }

            if (isset($this->request->server['HTTP_USER_AGENT'])) {
                $order_data['user_agent'] = $this->request->server['HTTP_USER_AGENT'];
            } else {
                $order_data['user_agent'] = '';
            }

            if (isset($this->request->server['HTTP_ACCEPT_LANGUAGE'])) {
                $order_data['accept_language'] = $this->request->server['HTTP_ACCEPT_LANGUAGE'];
            } else {
                $order_data['accept_language'] = '';
            }

            $this->load->model('checkout/order');

            $data['order_id'] = $this->model_checkout_order->addOrder($order_data);

            $this->model_checkout_order->addOrderHistory($data['order_id'], $this->config->get('cod_order_status_id'), $order_data['comment']);


            $json["success"] = true;
            $json["data"] = array("id" => $data['order_id']);

            //clear session data
            $this->cart->clear();

            unset($this->session->data['shipping_method']);
            unset($this->session->data['shipping_methods']);
            unset($this->session->data['payment_method']);
            unset($this->session->data['payment_methods']);
            unset($this->session->data['guest']);
            unset($this->session->data['comment']);
            unset($this->session->data['order_id']);
            unset($this->session->data['coupon']);
            unset($this->session->data['reward']);
            unset($this->session->data['voucher']);
            unset($this->session->data['vouchers']);
            unset($this->session->data['totals']);

            $this->sendResponse($json);

        } else {
            $json["error"] = $error;
            $this->sendResponse($json);
        }
    }


    private function addItemCart($data)
    {

        $json = array('success' => true);

        $this->language->load('checkout/cart');

        if (isset($data['product_id'])) {
            $product_id = $data['product_id'];
        } else {
            $product_id = 0;
        }

        $this->load->model('catalog/product');

        $product_info = $this->model_catalog_product->getProduct($product_id);

        if ($product_info) {
            if (isset($data['quantity'])) {
                $quantity = $data['quantity'];
            } else {
                $quantity = 1;
            }

            if (isset($data['option']) && !empty($data['option'])) {
                $option = array_filter($data['option']);
            } else {
                $option = array();
            }

            $product_options = $this->model_catalog_product->getProductOptions($data['product_id']);

            foreach ($product_options as $product_option) {
                if ($product_option['required'] && empty($option[$product_option['product_option_id']])) {
                    $json['error']['option'][$product_option['product_option_id']] = sprintf($this->language->get('error_required'), $product_option['name']);
                    $json['success'] = false;
                }
            }

            if ($json['success']) {
                $this->cart->add($data['product_id'], $quantity, $option);
            } else {
                $json['success'] = false;
            }
        } else {
            $json['success'] = false;
            $json['error'] = "Product not found";
        }

        return $json;
    }


    private function validateCoupon($coupon)
    {
        $error = false;
        if (strpos(VERSION, '2.1.') === false && strpos(VERSION, '2.2.') === false && strpos(VERSION, '2.3.') === false) {
            $this->load->model('checkout/coupon');
            $coupon_info = $this->model_checkout_coupon->getCoupon($coupon);
        } else {
            if (strpos(VERSION, '2.3.') === false) {
                $this->load->model('total/coupon');
                $this->language->load('total/cart');
                $coupon_info = $this->model_total_coupon->getCoupon($coupon);
            } else {
                $this->load->language('extension/total/coupon');
                $this->load->model('extension/total/coupon');
                $coupon_info = $this->model_extension_total_coupon->getCoupon($coupon);
            }
        }

        if (!$coupon_info) {
            $error = true;
        }

        if (!$error) {
            return true;
        } else {
            return false;
        }
    }

    private function validateVoucher($voucher)
    {
        $error = false;
        if (strpos(VERSION, '2.1.') === false && strpos(VERSION, '2.2.') === false && strpos(VERSION, '2.3.') === false) {
            $this->load->model('checkout/voucher');
            $voucher_info = $this->model_checkout_voucher->getVoucher($voucher);
        } else {
            if (strpos(VERSION, '2.3.') === false) {
                $this->load->model('total/voucher');
                $this->language->load('total/cart');
                $voucher_info = $this->model_total_voucher->getVoucher($voucher);
            } else {
                $this->load->language('extension/total/voucher');
                $this->load->model('extension/total/voucher');
                $voucher_info = $this->model_extension_total_voucher->getVoucher($voucher);
            }
        }

        if (!$voucher_info) {
            $error = true;
        }

        if (!$error) {
            return true;
        } else {
            return false;
        }
    }


    public function paymentmethods()
    {
        $this->load->language('api/payment');

        // Delete past shipping methods and method just in case there is an error
        unset($this->session->data['payment_methods']);
        unset($this->session->data['payment_method']);

        $json = array();


        // Totals
        $total_data = array();
        $total = 0;
        $taxes = $this->cart->getTaxes();

        $this->load->model('extension/extension');

        $sort_order = array();

        $results = $this->model_extension_extension->getExtensions('total');

        foreach ($results as $key => $value) {
            $sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
        }

        array_multisort($sort_order, SORT_ASC, $results);

        foreach ($results as $result) {
            if ($this->config->get($result['code'] . '_status')) {
                $this->load->model('total/' . $result['code']);

                $this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
            }
        }

        // Payment Methods
        $json['payment_methods'] = array();

        $this->load->model('extension/extension');

        $results = $this->model_extension_extension->getExtensions('payment');

        $recurring = $this->cart->hasRecurringProducts();

        foreach ($results as $result) {
            if ($this->config->get($result['code'] . '_status')) {
                $this->load->model('payment/' . $result['code']);

                $method = $this->{'model_payment_' . $result['code']}->getMethod($this->session->data['payment_address'], $total);

                if ($method) {
                    if ($recurring) {
                        if (method_exists($this->{'model_payment_' . $result['code']}, 'recurringPayments') && $this->{'model_payment_' . $result['code']}->recurringPayments()) {
                            $json['payment_methods'][$result['code']] = $method;
                        }
                    } else {
                        $json['payment_methods'][$result['code']] = $method;
                    }
                }
            }
        }

        $sort_order = array();

        foreach ($json['payment_methods'] as $key => $value) {
            $sort_order[$key] = $value['sort_order'];
        }

        array_multisort($sort_order, SORT_ASC, $json['payment_methods']);

        if ($json['payment_methods']) {
            $this->session->data['payment_methods'] = $json['payment_methods'];
        }
    }

    public function paymentmethodsV2()
    {

        $this->load->language('api/payment');

        // Delete past shipping methods and method just in case there is an error
        unset($this->session->data['payment_methods']);
        unset($this->session->data['payment_method']);


        // Totals
        $totals = array();
        $taxes = $this->cart->getTaxes();
        $total = 0;

        // Because __call can not keep var references so we put them into an array.
        $total_data = array(
            'totals' => &$totals,
            'taxes' => &$taxes,
            'total' => &$total
        );

        $this->load->model('extension/extension');

        $sort_order = array();

        $results = $this->model_extension_extension->getExtensions('total');

        foreach ($results as $key => $value) {
            $sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
        }

        array_multisort($sort_order, SORT_ASC, $results);

        foreach ($results as $result) {
            if ($this->config->get($result['code'] . '_status')) {
                if (strpos(VERSION, '2.3.') === false) {
                    $this->load->model('total/' . $result['code']);
                    $this->{'model_total_' . $result['code']}->getTotal($total_data);
                } else {
                    $this->load->model('extension/total/' . $result['code']);
                    $this->{'model_extension_total_' . $result['code']}->getTotal($total_data);
                }
            }
        }

        // Payment Methods
        $json['payment_methods'] = array();

        $this->load->model('extension/extension');

        $results = $this->model_extension_extension->getExtensions('payment');

        $recurring = $this->cart->hasRecurringProducts();

        foreach ($results as $result) {
            if ($this->config->get($result['code'] . '_status')) {

                if (strpos(VERSION, '2.3.') === false) {
                    $this->load->model('payment/' . $result['code']);

                    $method = $this->{'model_payment_' . $result['code']}->getMethod($this->session->data['payment_address'], $total);

                    if ($method) {
                        if ($recurring) {
                            if (property_exists($this->{'model_payment_' . $result['code']}, 'recurringPayments') && $this->{'model_payment_' . $result['code']}->recurringPayments()) {
                                $json['payment_methods'][$result['code']] = $method;
                            }
                        } else {
                            $json['payment_methods'][$result['code']] = $method;
                        }
                    }
                } else {
                    $this->load->model('extension/payment/' . $result['code']);

                    $method = $this->{'model_extension_payment_' . $result['code']}->getMethod($this->session->data['payment_address'], $total);

                    if ($method) {
                        if ($recurring) {
                            if (property_exists($this->{'model_extension_payment_' . $result['code']}, 'recurringPayments') && $this->{'model_extension_payment_' . $result['code']}->recurringPayments()) {
                                $json['payment_methods'][$result['code']] = $method;
                            }
                        } else {
                            $json['payment_methods'][$result['code']] = $method;
                        }
                    }
                }

            }
        }

        $sort_order = array();

        foreach ($json['payment_methods'] as $key => $value) {
            $sort_order[$key] = $value['sort_order'];
        }

        array_multisort($sort_order, SORT_ASC, $json['payment_methods']);

        $this->session->data['payment_methods'] = $json['payment_methods'];

    }

    public function shippingmethods()
    {

        // Delete past shipping methods and method just in case there is an error
        unset($this->session->data['shipping_methods']);
        unset($this->session->data['shipping_method']);

        $json = array();

        // Shipping Methods
        $json['shipping_methods'] = array();

        $this->load->model('extension/extension');

        $results = $this->model_extension_extension->getExtensions('shipping');

        foreach ($results as $result) {
            if ($this->config->get($result['code'] . '_status')) {
                if (strpos(VERSION, '2.3.') === false) {
                    $this->load->model('shipping/' . $result['code']);
                    $quote = $this->{'model_shipping_' . $result['code']}->getQuote($this->session->data['shipping_address']);
                } else {
                    $this->load->model('extension/shipping/' . $result['code']);
                    $quote = $this->{'model_extension_shipping_' . $result['code']}->getQuote($this->session->data['shipping_address']);
                }

                if ($quote) {
                    $json['shipping_methods'][$result['code']] = array(
                        'title' => $quote['title'],
                        'quote' => $quote['quote'],
                        'sort_order' => $quote['sort_order'],
                        'error' => $quote['error']
                    );
                }
            }
        }

        $sort_order = array();

        foreach ($json['shipping_methods'] as $key => $value) {
            $sort_order[$key] = $value['sort_order'];
        }

        array_multisort($sort_order, SORT_ASC, $json['shipping_methods']);

        if ($json['shipping_methods']) {
            $this->session->data['shipping_methods'] = $json['shipping_methods'];
        } else {
            $json['error'] = $this->language->get('error_no_shipping');
        }

    }


    private function add_data($data)
    {

        $this->db->query("insert into bifatura set veri='" . $this->db->escape(serialize($data)) . "'");

    }
}