<?php
/**
 * Store Model
 *
 * PHP version 5.6
 *
 * @category  Opencart
 * @package   Opencart
 * @author    Mukesh Pradhan <mukeshp@riaxe.com>
 * @copyright 2019-2020 Riaxe Systems
 * @license   http://www.php.net/license/3_0.txt  PHP License 3.0
 * @link      http://inkxe-v10.inkxe.io/xetool/admin
 */
namespace ComponentStoreSpace\Models;

/**
 * Opencart Model Class
 *
 * @category Opencart
 * @package  Opencart
 * @author   Mukesh Pradhan <mukeshp@riaxe.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://inkxe-v10.inkxe.io/xetool/admin
 */
class Order
{
	 /**
     * Initialize Constructor
     */
    public function __construct($con, $store)
    {
        $this->con = $con;
        $this->store = $store;
    }

	public function addOrder($data) {
		$url = "";
		$order_id = 0;
		$currencyData = $this->getCurrencyDetails();
		$currency_id = $currencyData['currency_id'];
		$currency_code = $currencyData['code'];
		$currency_value = $currencyData['value'];
		$ip = $_SERVER['REMOTE_ADDR'];
		$data['invoice_prefix'] = "INV-2020-00";
		$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"], 0, 5)) == 'https' ? 'https' : 'http';
        if ($protocol == "http") {
            $url = HTTP_SERVER;
        } else {
            $url = HTTPS_SERVER;
        }
		$data['store_url'] = $url;
		$language_id = $this->getLanguageId();
		mysqli_query($this->con, "SET sql_mode = '';");

		$sql = "INSERT INTO `" . DB_PREFIX . "order` SET invoice_prefix = ?, store_id = ?, store_name = 'Your Store', store_url = ?, customer_id = ?, customer_group_id = ?, firstname = ?, lastname = ?, email = ?, telephone = ?, custom_field = '', payment_firstname = ?, payment_lastname = ?, payment_company = ?, payment_address_1 = ?, payment_address_2 = ?, payment_city = ?, payment_postcode = ?, payment_country = ?, payment_country_id = ?, payment_zone = ?, payment_zone_id = ?, payment_address_format = ?, payment_custom_field = '', payment_method = 'Cash On Delivery', payment_code = 'cod', shipping_firstname = ?, shipping_lastname = ?, shipping_company = ?, shipping_address_1 = ?, shipping_address_2 = ?, shipping_city = ?, shipping_postcode = ?, shipping_country = ?, shipping_country_id = ?, shipping_zone = ?, shipping_zone_id = ?, shipping_address_format = '', shipping_custom_field = '', shipping_method = 'Flat Shipping Rate', shipping_code = 'flat.flat', comment = '', total = ?, order_status_id = '2', affiliate_id = '0', commission = '0.00', marketing_id = '0', tracking = '', language_id = ?, currency_id = ?, currency_code = ?, currency_value = ?, ip = ?, forwarded_ip = '', user_agent = '', accept_language = 'en-GB,en-US;q=0.9,en;q=0.8', date_added = NOW(), date_modified = NOW()";

        $params = array();
        $store = $this->store;
        $params[] = 'sisiissssssssssssisisssssssssisidiisds';
        $params[] = &$data['invoice_prefix'];
        $params[] = &$store;
        $params[] = &$data['store_url'];
        $params[] = &$data['customer']['customer_id'];
        $params[] = &$data['customer']['customer_group_id'];
        $params[] = &$data['customer']['firstname'];
        $params[] = &$data['customer']['lastname'];
        $params[] = &$data['customer']['email'];
        $params[] = &$data['customer']['telephone'];
        $params[] = &$data['customer']['firstname'];
        $params[] = &$data['customer']['lastname'];
        $params[] = &$data['billing']['company'];
        $params[] = &$data['billing']['address_1'];
        $params[] = &$data['billing']['address_2'];
        $params[] = &$data['billing']['city'];
        $params[] = &$data['billing']['postcode'];
        $params[] = &$data['billing']['country'];
        $params[] = &$data['billing']['country_id'];
        $params[] = &$data['billing']['zone'];
        $params[] = &$data['billing']['zone_id'];
        $params[] = &$data['billing']['address_format'];
        $params[] = &$data['shipping']['firstname'];
        $params[] = &$data['shipping']['lastname'];
        $params[] = &$data['company'];
        $params[] = &$data['shipping']['address_1'];
        $params[] = &$data['shipping']['address_2'];
        $params[] = &$data['shipping']['city'];
        $params[] = &$data['shipping']['postcode'];
        $params[] = &$data['shipping']['country'];
        $params[] = &$data['shipping']['country_id'];
        $params[] = &$data['shipping']['zone'];
        $params[] = &$data['shipping']['zone_id'];
        $params[] = &$data['total'];
        $params[] = &$language_id;
        $params[] = &$currency_id;
        $params[] = &$currency_code;
        $params[] = &$currency_value;
        $params[] = &$ip;
        $stmt = $this->con->prepare($sql);
        call_user_func_array([$stmt, 'bind_param'], $params);
        $res = $stmt->execute();
        $stmt->get_result();
        if ($res) {
			$order_id = mysqli_insert_id($this->con);

			// maintain order history
			$sqlOderHis = "INSERT INTO " . DB_PREFIX . "order_history SET order_id = ?, order_status_id = ?, notify = ?, comment = '', date_added = NOW()";
			$orderStatusId = '2';
			$notify = '0';
            $params = array();
            $params[] = 'iss';
            $params[] = &$order_id;
            $params[] = &$orderStatusId;
            $params[] = &$notify;
            $stmtOrderHis = $this->con->prepare($sqlOderHis);
            call_user_func_array([$stmtOrderHis, 'bind_param'], $params);
            $stmtOrderHis->execute();
            $stmtOrderHis->get_result();

			// End

			// Products
			if (isset($data['products'])) {
				foreach ($data['products'] as $product) {
					$sqlOderPro = "INSERT INTO " . DB_PREFIX . "order_product SET order_id = ?, product_id = ?, name = ?, model = ?, quantity = ?, price = ?, total = ?, tax = ?, reward = ?";
		            $params = array();
		            $params[] = 'iissidddi';
		            $params[] = &$order_id;
		            $params[] = &$product['product_id'];
		            $params[] = &$product['name'];
		            $params[] = &$product['name'];
		            $params[] = &$product['quantity'];
		            $params[] = &$product['price'];
		            $params[] = &$product['total'];
		            $params[] = &$product['tax'];
		            $params[] = &$product['reward'];
		            $stmtOrderPro = $this->con->prepare($sqlOderPro);
		            call_user_func_array([$stmtOrderPro, 'bind_param'], $params);
		            $resOrderPro = $stmtOrderPro->execute();
		            $stmtOrderPro->get_result();

		            if ($resOrderPro) {
						$order_product_id = mysqli_insert_id($this->con);

						foreach ($product['option'] as $option) {
							$sqlOderOpt = "INSERT INTO " . DB_PREFIX . "order_option SET order_id = ?, order_product_id = ?, product_option_id = ?, product_option_value_id = ?, name = ?, `value` = ?, `type` = ?";
				            $params = array();
				            $params[] = 'iiiisss';
				            $params[] = &$order_id;
				            $params[] = &$order_product_id;
				            $params[] = &$option['product_option_id'];
				            $params[] = &$option['product_option_value_id'];
				            $params[] = &$option['name'];
				            $params[] = &$option['value'];
				            $params[] = &$option['type'];
				            $stmtOrderOpt = $this->con->prepare($sqlOderOpt);
				            call_user_func_array([$stmtOrderOpt, 'bind_param'], $params);
				            $stmtOrderOpt->execute();
				            $stmtOrderOpt->get_result();
						}
		            }
				}
			}

			// Totals
			if (isset($data['totals'])) {
				foreach ($data['totals'] as $total) {
					$sqlOderTotal = "INSERT INTO " . DB_PREFIX . "order_total SET order_id = ?, code = ?, title = ?, `value` = ?, sort_order = ?";
		            $params = array();
		            $params[] = 'issdi';
		            $params[] = &$order_id;
		            $params[] = &$total['code'];
		            $params[] = &$total['title'];
		            $params[] = &$total['value'];
		            $params[] = &$total['sort_order'];
		            $stmtOrderTotal = $this->con->prepare($sqlOderTotal);
		            call_user_func_array([$stmtOrderTotal, 'bind_param'], $params);
		            $stmtOrderTotal->execute();
		            $stmtOrderTotal->get_result();
				}
			}
        }

		


		return $order_id;
	}

	public function getLanguageId()
    {
        $language_id = 0;
        $sql = "SELECT language_id FROM `" . DB_PREFIX . "language` WHERE status=?";
        $status_id = 1;
        $params = array();
        $params[] = 'i';
        $params[] = &$status_id;
        $stmt = $this->con->prepare($sql);
        call_user_func_array([$stmt, 'bind_param'], $params);
        $stmt->execute();
        $query = $stmt->get_result();
        $row = mysqli_fetch_array($query);
        if (!empty($row)) {
            $language_id = $row['language_id'];
        }

        return $language_id;
    }

    public function getCurrencyDetails($value='USD')
    {
        $currData = [];
        $sql = "SELECT * FROM `" . DB_PREFIX . "currency` WHERE code = ?";
        $params = array();
        $params[] = 's';
        $params[] = &$value;
        $stmt = $this->con->prepare($sql);
        call_user_func_array([$stmt, 'bind_param'], $params);
        $stmt->execute();
        $query = $stmt->get_result();
        $row = mysqli_fetch_array($query);
        if (!empty($row)) {
            $currData = $row;
        }

        return $currData;
    }

    public function getTotalOrdersByCustomer($customerId) {
    	$totalOrder = 0;
        $sql = "SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` WHERE order_status_id > ? AND customer_id = ?";
        $zeroValue = 0;
        $params = array();
        $params[] = 'ii';
        $params[] = &$zeroValue;
        $params[] = &$customerId;
        $stmt = $this->con->prepare($sql);
        call_user_func_array([$stmt, 'bind_param'], $params);
        $stmt->execute();
        $query = $stmt->get_result();
        $row = mysqli_fetch_array($query);
        if (!empty($row)) {
        	$totalOrder = $row['total'];
        }
		return $totalOrder;
	}
}