<?php
/*
  $Id: createOrder.php,v 1.1.1.2 2020/06/04 23:37:57 devidash Exp $

  Loaded Commerce, Open Source E-Commerce Solutions
  https://www.loadedcommerce.com

  Copyright (c) 2020 Loaded Commerce

  Released under the GNU General Public License
*/

  class createOrder{

	public function __construct() {
		global $language;
	}  //end of __construct

	public function insertOrder() {
		global $order, $GLOBALS, $obj_catalog;

		$ipInfo = $obj_catalog->getCustomerIPInfo();
		$ip = $ipInfo['ip'];
		$isp = $ipInfo['isp'];

		
		$arrSessDebugdata = array();
		$arrSessDebugNode = array('customer_id', 'customer_default_address_id', 'customer_first_name', 'customer_last_name', 'customer_country_id', 'customer_zone_id', 'sendto', 'billto', 'payment');
		foreach($arrSessDebugNode as $snode) {
			if(isset($_SESSION[$snode])) {
				$arrSessDebugdata[$snode] = $_SESSION[$snode];
			}
		}
		$debug_data = array('ipinfo' => $ipInfo, 'orderObj' => $order, 'sessdata' => $arrSessDebugdata);
		$str_debug_data = json_encode($debug_data);	

		$sql_data_array = array('customers_id' => $_SESSION['customer_id'],
							  'customers_name' => $order->customer['firstname'] . ' ' . $order->customer['lastname'],
							  'customers_company' => $order->customer['company'],
							  'customers_street_address' => $order->customer['street_address'],
							  'customers_suburb' => $order->customer['suburb'],
							  'customers_city' => $order->customer['city'],
							  'customers_postcode' => $order->customer['postcode'],
							  'customers_state' => $order->customer['state'],
							  'customers_country' => $order->customer['country']['title'],
							  'customers_telephone' => $order->customer['telephone'],
							  'customers_email_address' => $order->customer['email_address'],
							  'customers_address_format_id' => $order->customer['format_id'],
							  'delivery_name' => $order->delivery['firstname'] . ' ' . $order->delivery['lastname'],
							  'delivery_company' => $order->delivery['company'],
							  'delivery_street_address' => $order->delivery['street_address'],
							  'delivery_suburb' => $order->delivery['suburb'],
							  'delivery_city' => $order->delivery['city'],
							  'delivery_postcode' => $order->delivery['postcode'],
							  'delivery_state' => $order->delivery['state'],
							  'delivery_country' => $order->delivery['country']['title'],
							  'delivery_address_format_id' => $order->delivery['format_id'],
							  'billing_name' => $order->billing['firstname'] . ' ' . $order->billing['lastname'],
							  'billing_company' => $order->billing['company'],
							  'billing_street_address' => $order->billing['street_address'],
							  'billing_suburb' => $order->billing['suburb'],
							  'billing_city' => $order->billing['city'],
							  'billing_postcode' => $order->billing['postcode'],
							  'billing_state' => $order->billing['state'],
							  'billing_country' => $order->billing['country']['title'],
							  'billing_address_format_id' => $order->billing['format_id'],
							  'payment_module_name' => $_SESSION['payment'],
							  'payment_method' => $order->info['payment_method'],
							  'payment_info' => (isset($GLOBALS['payment_info'])? $GLOBALS['payment_info'] : ''),
							  'cc_type' => (isset($order->info['cc_type']) ? $order->info['cc_type'] : ''),
							  'cc_owner' => (isset($order->info['cc_owner']) ? $order->info['cc_owner'] : ''),
							  'date_purchased' => 'now()',
							  'last_modified' => 'now()',
							  'orders_status' => $order->info['order_status'],
							  'currency' => $order->info['currency'],
							  /****************/
							  'delivery_telephone' => $order->delivery['telephone'],
							  'delivery_fax' => $order->delivery['fax'],
							  'delivery_email_address' => $order->delivery['email_address'],
							  'billing_telephone' => $order->billing['telephone'],
							  'billing_fax' => $order->billing['fax'],
							  'billing_email_address' => $order->billing['email_address'],

							  /****************/
							  'currency_value' => $order->info['currency_value'],
							  'debug_data' => $str_debug_data,
							  'ipaddy' => $ip,
							  'ipisp' => $isp);

		// added for PPSM
		if (isset($_SESSION['sub_payment']) && $_SESSION['sub_payment'] == 'paypal_wpp_dp') $sql_data_array['payment_method'] .= ' via CRE Secure';

		// EOF: WebMakers.com Added: Downloads Controller
		tep_db_perform(TABLE_ORDERS, $sql_data_array);
		$insert_id = tep_db_insert_id();
		return $insert_id;
	}

	public function appendDebugData($insert_id, $dataKey, $dataVal) {

		$query = "SELECT debug_data FROM ". TABLE_ORDERS ." WHERE orders_id=". (int) $insert_id;
		$data = tep_db_get_result($query);
		$debugData = json_decode($data[0]['debug_data'], true);
		$debugData[$dataKey] = $dataVal;
		$str_debug_data = json_encode($debugData);
		$query = "UPDATE ". TABLE_ORDERS ." SET debug_data='$str_debug_data' WHERE orders_id=". (int) $insert_id;
		tep_db_query($query);
	}

	public function insertOrderItem($insert_id) {
		global $order, $order_totals, $order_total_modules, $cre_RCI, $currencies;
		// initialized for the email confirmation
		  $products_ordered = '';
		  $subtotal = 0;
		  $total_tax = 0;

		  for ($i=0, $n=sizeof($order->products); $i<$n; $i++) {
		// Stock Update - Joao Correia
			if (STOCK_LIMITED == 'true') {
			  $downloadable_product = false;
			  if (DOWNLOAD_ENABLED == 'true') {
				// see if this product actually has a downloadable file in the attributes
				$download_check_query_raw = "SELECT products_quantity, pad.products_attributes_filename
									FROM " . TABLE_PRODUCTS . " p,
									" . TABLE_PRODUCTS_ATTRIBUTES . " pa,
									" . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad
									 WHERE p.products_id = '" . tep_get_prid($order->products[$i]['id']) . "'
									 and p.products_id=pa.products_id
									 and pad.products_attributes_id=pa.products_attributes_id ";

				$download_check_query = tep_db_query($download_check_query_raw);
				if (tep_db_num_rows($download_check_query) > 0) {
				  $downloadable_product = true;
				}
			  }  // end of downloadable product check
			  if ( !$downloadable_product ) {
				$stock_query = tep_db_query("select products_quantity,products_parent_id from " . TABLE_PRODUCTS . " where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
				$stock_values = tep_db_fetch_array($stock_query);

				//For update the Parent Product Quantity
				if ($stock_values['products_parent_id'] != 0) {
				  $product_parent_id_db = $stock_values['products_parent_id'];
				  $parent_query = tep_db_query("select products_quantity from " . TABLE_PRODUCTS . " where products_id = '" . tep_get_prid($product_parent_id_db) . "'");
				  $parent_values = tep_db_fetch_array($parent_query);
				  $parent_product_stock_left = $parent_values['products_quantity'] - $order->products[$i]['qty'];
				  tep_db_query("update " . TABLE_PRODUCTS . " set products_quantity = '" . $parent_product_stock_left . "' where products_id = '" . tep_get_prid($product_parent_id_db) . "'");
				}
				//End

				$stock_left = $stock_values['products_quantity'] - $order->products[$i]['qty'];
				tep_db_query("update " . TABLE_PRODUCTS . " set products_quantity = '" . $stock_left . "' where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
				if ( ($stock_left < 1) && (STOCK_ALLOW_CHECKOUT == 'false') ) {
				  tep_db_query("update " . TABLE_PRODUCTS . " set products_status = '0' where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
				}
			  }
			}

		// Update products_ordered (for bestsellers list)
			tep_db_query("update " . TABLE_PRODUCTS . " set products_ordered = products_ordered + " . sprintf('%d', $order->products[$i]['qty']) . " where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");

			$sql_data_array = array('orders_id' => $insert_id,
									'products_id' => tep_get_prid($order->products[$i]['id']),
									'products_model' => $order->products[$i]['model'],
									'products_name' => $order->products[$i]['name'],
									'products_price' => $order->products[$i]['price'],
									'final_price' => $order->products[$i]['final_price'],
									'products_tax' => $order->products[$i]['tax'],
									'products_quantity' => $order->products[$i]['qty']);
			tep_db_perform(TABLE_ORDERS_PRODUCTS, $sql_data_array);
			$order_products_id = tep_db_insert_id();
			$order_total_modules->update_credit_account($i);//ICW ADDED FOR CREDIT CLASS SYSTEM

		//------insert customer choosen option to order--------
			$products_ordered_attributes = '';
			if (isset($order->products[$i]['attributes'])) {
			  for ($j=0, $n2=sizeof($order->products[$i]['attributes']); $j<$n2; $j++) {

				$sql_data_array = array('orders_id' => $insert_id,
										'orders_products_id' => $order_products_id,
										'products_options' => $order->products[$i]['attributes'][$j]['option'],
										'products_options_values' => $order->products[$i]['attributes'][$j]['value'],
										'options_values_price' => $order->products[$i]['attributes'][$j]['price'],
										'price_prefix' => $order->products[$i]['attributes'][$j]['prefix'],
										'products_options_id' => $order->products[$i]['attributes'][$j]['option_id'],
										'products_options_values_id' => $order->products[$i]['attributes'][$j]['value_id']);
				tep_db_perform(TABLE_ORDERS_PRODUCTS_ATTRIBUTES, $sql_data_array);

				if (DOWNLOAD_ENABLED == 'true') {
				  $attributes_query = "select pad.products_attributes_maxdays, pad.products_attributes_maxcount , pad.products_attributes_filename
								   from " . TABLE_PRODUCTS_ATTRIBUTES . " pa,
										" . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad
									  where pa.products_id = '" . $order->products[$i]['id'] . "'
										and pa.options_id = '" . $order->products[$i]['attributes'][$j]['option_id'] . "'
										and pa.options_values_id = '" . $order->products[$i]['attributes'][$j]['value_id'] . "'
										and pa.products_attributes_id = pad.products_attributes_id";
				  $attributes = tep_db_query($attributes_query);

				  $attributes_values = tep_db_fetch_array($attributes);

				  if ( isset($attributes_values['products_attributes_filename']) && tep_not_null($attributes_values['products_attributes_filename']) ) {
					$sql_data_array = array('orders_id' => $insert_id,
											'orders_products_id' => $order_products_id,
											'orders_products_filename' => $attributes_values['products_attributes_filename'],
											'download_maxdays' => $attributes_values['products_attributes_maxdays'],
											'download_count' => $attributes_values['products_attributes_maxcount']);
					tep_db_perform(TABLE_ORDERS_PRODUCTS_DOWNLOAD, $sql_data_array);
				  }
				}
				$products_ordered_attributes .= "\n\t" . $order->products[$i]['attributes'][$j]['option'] . ' ' . $order->products[$i]['attributes'][$j]['value'] . ' ' . $order->products[$i]['attributes'][$j]['prefix'] . ' ' . $currencies->display_price($order->products[$i]['attributes'][$j]['price'], tep_get_tax_rate($products[$i]['tax_class_id']), 1);
			  }
			}
			//------insert customer choosen option eof ----
			$total_weight = isset($total_weight)? (float) $total_weight: 0;
			$total_tax = isset($total_tax)? (float) $total_tax: 0;
			$total_cost = isset($total_cost)? (float) $total_cost: 0;
			$total_products_price = isset($total_products_price)? (float) $total_products_price: 0;

			$total_weight += ($order->products[$i]['qty'] * $order->products[$i]['weight']);
			$total_tax += tep_calculate_tax($total_products_price, $products_tax) * $order->products[$i]['qty'];
			$total_cost += $total_products_price;

			$products_ordered .= $order->products[$i]['qty'] . ' x ' . tep_db_decoder($order->products[$i]['name']) . ' (' . $order->products[$i]['model'] . ') = ' . $currencies->display_price($order->products[$i]['final_price'], $order->products[$i]['tax'], $order->products[$i]['qty']) . $products_ordered_attributes . "\n";

			$cre_RCI->get('checkoutprocess', 'afterinsert', false);
		}
		return $products_ordered;
	}

	public function insertOrderTotals($insert_id) {
	  global $order_totals;
	  for ($i=0, $n=sizeof($order_totals); $i<$n; $i++) {
		$sql_data_array = array('orders_id' => $insert_id,
								'title' => $order_totals[$i]['title'],
								'text' => $order_totals[$i]['text'],
								'value' => $order_totals[$i]['value'],
								'class' => $order_totals[$i]['code'],
								'sort_order' => $order_totals[$i]['sort_order']);
		tep_db_perform(TABLE_ORDERS_TOTAL, $sql_data_array);
	  }
	}

	public function insertOrderHistory($insert_id, $data) {
		global $order;
		$customer_notification = $data['notification'];
		$orders_status_id = $data['order_status_id'];
		$comments = $data['comments'];
		$sql_data_array = array('orders_id' => $insert_id,
							  'orders_status_id' => $orders_status_id,
							  'date_added' => 'now()',
							  'customer_notified' => $customer_notification,
							  'comments' => $comments);
		tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
	}

	public function sendOrderEmail($insert_id, $data) {
		global $order, $order_totals;
		$comments = $data['comments'];
		$products_ordered = $data['products_ordered'];
		$noaccount = $data['noaccount'];
		$payment_class_title = $data['payment_class_title'];
		$payment_class_email_footer = $data['payment_class_email_footer'];

		if ( ! $noaccount ) {
			$email_order = STORE_NAME . "\n" .
						   EMAIL_SEPARATOR . "\n" .
						   EMAIL_TEXT_ORDER_NUMBER . ' ' . $insert_id . "\n" .
						   EMAIL_TEXT_INVOICE_URL . ' ' .
						   tep_href_link(FILENAME_ACCOUNT_HISTORY_INFO, 'order_id=' . $insert_id, 'SSL', false) . "\n" .
						   EMAIL_TEXT_DATE_ORDERED . ' ' . strftime(DATE_FORMAT_LONG) . "\n\n";
		} else {
			$email_order = STORE_NAME . "\n" .
						   EMAIL_SEPARATOR . "\n" .
						   EMAIL_TEXT_ORDER_NUMBER . ' ' . $insert_id . "\n" .
						   EMAIL_TEXT_DATE_ORDERED . ' ' . strftime(DATE_FORMAT_LONG) . "\n\n";
		}

		// EOF: daithik change for PWA

		if (!empty($comments)) {
			$email_order .= tep_db_output($comments) . "\n\n";
		}
		$email_order .= EMAIL_TEXT_PRODUCTS . "\n" .
					  EMAIL_SEPARATOR . "\n" .
					  $products_ordered .
					  EMAIL_SEPARATOR . "\n";

		for ($i=0, $n=sizeof($order_totals); $i<$n; $i++) {
			$email_order .= strip_tags($order_totals[$i]['title']) . ' ' . strip_tags($order_totals[$i]['text']) . "\n";
		}

		if ($order->content_type != 'virtual') {
			$email_order .= "\n" . EMAIL_TEXT_DELIVERY_ADDRESS . "\n" .
						EMAIL_SEPARATOR . "\n" .
						tep_address_label($_SESSION['customer_id'], $_SESSION['sendto'], 0, '', "\n") . "\n";
		}

		$email_order .= "\n" . EMAIL_TEXT_BILLING_ADDRESS . "\n" .
					  EMAIL_SEPARATOR . "\n" .
					  tep_address_label($_SESSION['customer_id'], $_SESSION['billto'], 0, '', "\n") . "\n\n";

		if(!empty($payment_class_title)) {
			$email_order .= EMAIL_TEXT_PAYMENT_METHOD . "\n" .
							EMAIL_SEPARATOR . "\n";
			$email_order .= $payment_class_title . "\n\n";
		}
		if(!empty($payment_class_email_footer)) {
			$email_order .= $payment_class_email_footer . "\n\n";
		}
		
		if (isset($_SESSION['is_std']) && $_SESSION['is_std'] === true) {
			if (defined('EMAIL_USE_HTML') && EMAIL_USE_HTML == 'true') {
			  $email_order .= '<a href="https://www.loadedcommerce.com" target="_blank">' . TEXT_POWERED_BY_CRE . '</a>' . "\n\n";
			} else {
			  $email_order .= TEXT_POWERED_BY_CRE . "\n\n";
			}
		}

		tep_mail($order->customer['firstname'] . ' ' . $order->customer['lastname'], $order->customer['email_address'], EMAIL_TEXT_SUBJECT, $email_order, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);
		// send emails to other people
		if (SEND_EXTRA_ORDER_EMAILS_TO != '') {
			tep_mail('', SEND_EXTRA_ORDER_EMAILS_TO, EMAIL_TEXT_SUBJECT, $email_order, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);
		}
	}

  }

?>