<?php 
function is_session_started()
{
    if ( php_sapi_name() !== 'cli' ) {
        if ( version_compare(phpversion(), '5.4.0', '>=') ) {
            return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
        } else {
            return session_id() === '' ? FALSE : TRUE;
        }
    }
    return FALSE;
}

if ( is_session_started() === FALSE ) session_start();
require_once("connect.php");
include("classes/ClassLoader.php");
$config = include("config.php");

//$_GET['a'] triggered fucntions
if(isset($_REQUEST['action']) > 0){
	checkLogin();
	switch ($_REQUEST['action']) {
		case "addToCart":
			$Qty = intval($_GET['Qty']);
			addToCart($_GET['Group'], $_GET['Line'], $_GET['SKU'], $Qty, $_GET['OnOrder']);
			break;
		case "updateCartItem":
			updateCartItem($_REQUEST['ID'], $_REQUEST['Qty']);
			break;
		case "deleteCartItem":
			deleteCartItem($_REQUEST['ID']);
			break;
		case "changePassword":
			$oldPass = urldecode($_REQUEST['old']);
			$oldPass = md5($oldPass);
			$newPass = urldecode($_REQUEST['new']);
			changePassword($oldPass, $newPass);
			break;
		case "changePasswordAdmin":
			$oldPass = urldecode($_REQUEST['old']);
			$oldPass = ($oldPass);
			$newPass = urldecode($_REQUEST['new']);
			changePasswordAdmin($oldPass, $newPass);
			break;
		case "getCustomerInfo":
			getCustomerInfo(urldecode($_REQUEST['customer']));
			break;
		case "saveCustomerInfo":
			saveCustomerInfo($_POST);
			break;
		case "setLanguage":
			setLanguage(substr(strtoupper($_REQUEST['language']), 0,2));
			break;
		case "getSalesmanInfo":
			getSalesmanInfo(urldecode($_REQUEST['salesman']));
			break;
		case "saveSalesmanInfo":
			saveSalesmanInfo($_POST);
			break;
		case "sendPasswordReset":
			$account = mysqli_real_escape_string($con, $_REQUEST['accountNumber']);
			sendPasswordReset($account);
			break;
		case "resetPassword":
			$hash = mysqli_real_escape_string($con, $_REQUEST['key']);
			$password = $_REQUEST['pw'];
			resetPassword($hash, $password);
			break;
		case "saveFields":
			saveFields($_GET['OrderNotes'], $_GET['PONumber']);
			break;
		case "backup":
			backup_db();
			break;
		case "deleteCustomer":
			$AccountNumber =  $_REQUEST['accountNumber'];
			deleteCustomer($AccountNumber);
			break;
		case "deleteSalesman":
			$SalesmanID =  $_REQUEST['salesmanID'];
			deleteSalesman($SalesmanID);
			break;
		case "getGroupInfo":
			$Code = $_REQUEST['groupCode'];
			getGroupInfo($Code);
			break;
		case "saveGroupInfo":
			saveGroupInfo($_REQUEST);
			break;
		case "deleteGroup":
			$Code = mysqli_real_escape_string($con, $_REQUEST['groupCode']);
			deleteGroup($Code);
			break;
		case "getLineInfo":
			$Code = $_REQUEST['lineCode'];
			getLineInfo($Code);
			break;
		case "saveLineInfo":
			saveLineInfo($_REQUEST);
			break;
		case "deleteLine":
			$Code = mysqli_real_escape_string($con, $_REQUEST['lineCode']);
			deleteLine($Code);
			break;
		case "getProductDescription":
			$line = mysqli_real_escape_string($con, $_REQUEST['line']);
			$sku = mysqli_real_escape_string($con, $_REQUEST['sku']);
			getProductDescription($line, $sku);
			break;
		case "savePickupLine":
			$line = mysqli_real_escape_string($con, $_REQUEST['line']);
			$sku = mysqli_real_escape_string($con, $_REQUEST['sku']);
			$qty = mysqli_real_escape_string($con, $_REQUEST['qty']);
			$invoiceNumber = mysqli_real_escape_string($con, $_REQUEST['invoice']);
			$orderID = mysqli_real_escape_string($con, $_REQUEST['order']);
			$reason = mysqli_real_escape_string($con, $_REQUEST['reason']);
			savePickupLine($line, $sku, $qty, $invoiceNumber, $orderID,$reason);
			break;
		case "deletePickupLine":
			$id = mysqli_real_escape_string($con, $_REQUEST['id']);
			$query = "DELETE FROM PICKUP_CART WHERE id = $id";
			$result = mysqli_query($con, $query);
			if ($result) {
				echo("true");
			}else {
				echo "false";
			}
			break;
		case "getProductLines":
			$sku = mysqli_real_escape_string($con, $_REQUEST['sku']);
			getProductLines($sku);
			break;
		case "getReasonInfo":
			$Code = $_REQUEST['reasonCode'];
			getReasonInfo($Code);
			break;
		case "saveReasonInfo":
			saveReasonInfo($_REQUEST);
			break;
		case "deleteReason":
			$Code = mysqli_real_escape_string($con, $_REQUEST['reasonCode']);
			deleteReason($Code);
			break;
		case "getEventDetails":
			getEventDetails($_REQUEST['id']);
			break;
		case "getPricePlanCalcInfo":
			getPricePlanCalcInfo($_REQUEST['accountNumber']);
			break;
		case "savePricePlanCalcInfo":
			savePricePlanCalcInfo($_REQUEST);
			break;
		case "deletePricePlanCalc":
			deletePricePlanCalc($_REQUEST['accountNumber']);
			break;
		case "setPricePlanMode":
			if (isset($_REQUEST['accountNumber'])) {
				$accountNumber = $_REQUEST['accountNumber'];
			} else {
				$accountNumber = '';
			
			}
			setPricePlanMode($_REQUEST['ppAction'], $accountNumber);
			break;
		case "getCatalogData":
			getCatalogData($_REQUEST['cid']);
			break;
		case "getCatalogItemInfo":
			getCatalogItemInfo($_REQUEST['id']);
			break;
		case "saveCatalogItemInfo":
			saveCatalogItemInfo($_REQUEST);
			break;
		case "deleteCatalogItem":
			$id = $_REQUEST['ID'];
			deleteCatalogItem($id);
			break;
		case "getCatalogCategoryInfo":
			getCatalogCategoryInfo($_REQUEST['id']);
			break;
		case "saveCatalogCategoryInfo":
			saveCatalogCategoryInfo($_REQUEST);
			break;
		case "deleteCatalogCategory":
			deleteCatalogCategory($_REQUEST['id']);
			break;
		case "getAltasData":
			getAltasData($_REQUEST['id']);
			break;
		case "getSpecialsData":
			getSpecialsData();
			break;
		case "getAltasItemInfo":
			getAltasItemInfo($_REQUEST['id']);
			break;
		case "saveAltasItemInfo":
			saveAltasItemInfo($_REQUEST);
			break;
		case "deleteAltasItem":
			$id = $_REQUEST['ID'];
			deleteAltasItem($id);
			break;
		case "getAltasInfo":
			getAltasInfo($_REQUEST['id']);
			break;
		case "saveAltasInfo":
			saveAltasInfo($_REQUEST);
			break;
		case "deleteAltas":
			deleteAltas($_REQUEST['id']);
			break;
		case "setCustomer":
			setCustomer($_REQUEST['id']);
			break;
		case "clearSetCustomer":
			clearSetCustomer();
			break;
		case "catalogItemExists":
			catalogItemExists($_REQUEST['line'], $_REQUEST['sku']);
			break;
		case "setPickupStatus":
			setPickupStatus($_REQUEST['a'], $_REQUEST['pickupID'], $_REQUEST['value'], $_REQUEST['notes']);
			break;
		case "getPickupStatusInfo":
			getPickupStatusInfo($_REQUEST['a'], $_REQUEST['pickupID']);
			break;
		case "savePickupStatusNotes":
			savePickupStatusNotes($_REQUEST['a'], $_REQUEST['pickupID'], $_REQUEST['notes']);
			break;
		case "getOrderDetails";
			getOrderDetails($_REQUEST['orderID']);
			break;
		case "saveOrderDetail":
			saveOrderDetail($_REQUEST);
			break;
		case "getOrderHistory":
			getOrderHistory($_REQUEST['an'], $_REQUEST['line'], $_REQUEST['sku']);
			break;
		case "getInvoiceNumber":
			getInvoiceNumber($_REQUEST['id']);
			break;
		case "voidPickup":
			voidPickup($_REQUEST['pid'], $_REQUEST['Reason']);
			break;
		case "voidPickupDetails":
			voidPickupDetails($_REQUEST['pid']);
			break;
		case "getBuyersGuideDefinition":
			getBuyersGuideDefinition($_REQUEST['id']);
			break;
		case "saveBuyersGuideDefinition":
			saveBuyersGuideDefinition($_REQUEST);
			break;
		case "deleteBuyersGuideDefinition":
			deleteBuyersGuideDefinition($_REQUEST['id']);
			break;
		case "setUpdateData":
			setUpdateData();
			break;
	}		
	
}


function checkLogin() {
	if(isset($_SESSION['LoggedIn'])){
		if($_SESSION['LoggedIn'] != 1){
			header("Location: login.php");
		}
	}
}
function moneyFormat($amt){
	setlocale(LC_MONETARY,"en_US");
	$amt = round($amt,2);
	return money_format('%.2n', $amt);
}
function changePassword($old, $new) {
	global $con;
	if ($_SESSION['isCustomer']) {
		$customer = new Customer($_SESSION['AccountNumber']);
		$query = "SELECT * FROM CUSTOMER WHERE AccountNumber LIKE '$customer->AccountNumber'";	
		$result = mysqli_query($con, $query);
		$row = mysqli_fetch_array($result);
		$new = md5($new);
		if ($row['Password'] == $old) {
			$query = "UPDATE CUSTOMER SET Password = '$new' WHERE AccountNumber LIKE '$customer->AccountNumber'";
			$result = mysqli_query($con, $query);
			if($result){
				echo 'success';
			}else{
				echo 'failure';
			}
		}else{
			echo "failure";
		}
		
	}else {
		$salesman = new Salesman($_SESSION['SalesmanID']);
		$query = "SELECT * FROM SALESMAN WHERE id LIKE '$salesman->ID'";	
		$result = mysqli_query($con, $query);
		$row = mysqli_fetch_array($result);
		$new = md5($new);
		if ($row['Password'] == $old) {
			$query = "UPDATE SALESMAN SET Password = '$new' WHERE id LIKE '$salesman->ID'";
			$result = mysqli_query($con, $query);
			if($result){
				echo 'success';
			}else{
				echo 'failure';
			}
		}else{
			echo "failure";
		}
	}	
}
function changePasswordAdmin($old, $new) {
	global $con;
	
	$isAdmin = $_SESSION['isAdmin'];
	if (!$isAdmin) {
		return false;
	}
	
	
	$username = $_SESSION['Username'];
	$query = "SELECT * FROM ADMINISTRATOR WHERE Username LIKE '$username'";	
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result);
	$new = mysqli_real_escape_string($con, $new);
	if ($row['Password'] == $old) {
		$query = "UPDATE ADMINISTRATOR SET Password = '$new' WHERE Username LIKE '$username'";
		event_log($_SESSION['Username'], "CHANGE ADMIN PASS", "");
		$result = mysqli_query($con, $query);
		if($result){
			echo 'success';
		}else{
			echo 'failure';
		}
	}else{
		echo "failure";
	}
}	

function addToCart($Group, $Line, $SKU, $Qty, $OnOrder){
	global $con;
	//check if customer or salesman
	if(!isset($_SESSION['isCustomer'])){
		include("session.php");
	}
	$isCustomer = $_SESSION['isCustomer'];
	if($isCustomer){
		$customer = new Customer($_SESSION['AccountNumber']);
		if ($OnOrder == "true") {
			if ($Qty > 0) {
				$query = "UPDATE SHOPPING_CART SET Qty = $Qty WHERE AccountNumber LIKE '" . $customer->AccountNumber . "' AND `Group` LIKE '$Group' AND `Line` LIKE '$Line' AND `SKU` LIKE '$SKU'";
			}else {
				$query = "DELETE FROM SHOPPING_CART WHERE AccountNumber LIKE '" . $customer->AccountNumber . "' AND `Group` LIKE '$Group' AND `Line` LIKE '$Line' AND `SKU` LIKE '$SKU'";
			}
			
			
		}else {
			$query = "INSERT INTO SHOPPING_CART (AccountNumber, `Group`, `Line`, `SKU`, `Qty`) VALUES ('" . $customer->AccountNumber . "', '$Group', '$Line', '$SKU', $Qty)";
			
		}
		mysqli_query($con, $query);
		$priceRate = getPricePlanCalculatedRate($customer->AccountNumber);
		$column = "Cost";
		switch ($customer->PriceLevel) {
			case "F":
				$column = "PriceA";
				break;
			case "C":
				$column = "PriceB";
				break;
			case "G":
				$column = "PriceC";
				break;
			default:
				$column = "Cost";
		}
		$query = "SELECT SUM(SHOPPING_CART.Qty * ROUND($column * $priceRate, 2) + SHOPPING_CART.Qty * Core) AS CartTotal FROM SHOPPING_CART, INVENTORY WHERE INVENTORY.`Group` = SHOPPING_CART.`Group` AND INVENTORY.`Line` = SHOPPING_CART.`Line` AND INVENTORY.`SKU` = SHOPPING_CART.`SKU` AND AccountNumber = '" . $customer->AccountNumber . "'";
		$result = mysqli_query($con, $query);
		$row = mysqli_fetch_array($result);
		if ($row['CartTotal'] == null) {
			echo("0.00");	
		}else{
			echo $row['CartTotal'];
		}
		return mysqli_insert_id($con);
	}else{
		$salesman = new Salesman($_SESSION['SalesmanID']);
		if ($_SESSION['pricePlanMode']) {
			$priceRate = getPricePlanCalculatedRate($_SESSION['AccountNumber']);
		}else {
			$priceRate = 1;
		}
		if ($OnOrder == "true") {
			if ($Qty > 0) {
				$query = "UPDATE SHOPPING_CART SET Qty = $Qty WHERE AccountNumber LIKE '" . $salesman->ID . "' AND `Group` LIKE '$Group' AND `Line` LIKE '$Line' AND `SKU` LIKE '$SKU'";
			}else {
				$query = "DELETE FROM SHOPPING_CART WHERE AccountNumber LIKE '" . $salesman->ID . "' AND `Group` LIKE '$Group' AND `Line` LIKE '$Line' AND `SKU` LIKE '$SKU'";
			}
			
		} else {
			$query = "INSERT INTO SHOPPING_CART (AccountNumber, `Group`, `Line`, `SKU`, `Qty`, `SalesmanCart`) VALUES ('" . $salesman->ID . "', '$Group', '$Line', '$SKU', $Qty, 1)";
		}
		
		mysqli_query($con, $query);
		
		$column = "Cost";
		if (isset($_SESSION['setCustomerMode']) && $_SESSION['setCustomerMode']) {
			$customer = new Customer($_SESSION['setCustomer']);
			switch ($customer->PriceLevel) {
				case "F":
					$column = "PriceA";
					break;
				case "C":
					$column = "PriceB";
					break;
				case "G":
					$column = "PriceC";
					break;
				default:
					$column = "Cost";
			}
		}
		
		$query = "SELECT SUM(SHOPPING_CART.Qty * ROUND($column * $priceRate, 2) + SHOPPING_CART.Qty * Core) AS CartTotal FROM SHOPPING_CART, INVENTORY WHERE INVENTORY.`Group` = SHOPPING_CART.`Group` AND INVENTORY.`Line` = SHOPPING_CART.`Line` AND INVENTORY.`SKU` = SHOPPING_CART.`SKU` AND SalesmanCart = True AND AccountNumber = '" . $salesman->ID . "'";
		$result = mysqli_query($con, $query);
		$row = mysqli_fetch_array($result);
		if ($row['CartTotal'] == null) {
			echo("0.00");	
		}else{
			echo $row['CartTotal'];
		}
		return mysqli_insert_id($con);
	}
}
function sendOrder($orderID) {
	global $config;
	global $root;
	$order = new Order($orderID);
	
	
	$to = $config['OrderEmail'];
	$subject = "Orden de Compra Web #$orderID";
	$key = md5($orderID . "EJAS");
	$key = substr($key, -16);
	
	$pdf = false;
	if ($pdf) {
		//
		system('./wkhtmltopdf-amd64 "' . $root . 'webConfirmation.php?order=' . $orderID . '&key=' . $key . '" "./tmp/' . $orderID . '.pdf"', $systemResult);
		$message = "Nueva orden de compra para $name \r\n Adjunto copia de la confirmacion de la orden.";
		$cc = $order->Customer->Salesman->Email;
		$bcc = "";
		if($customerEmail != ""){
			$bcc = $customerEmail;
		}
		$result = mail_attachment($orderID . '.pdf', "./tmp/", $to, $config['FromEmail'], $config['FromEmailName'], $config['FromEmail'], $subject, $message, $cc, $bcc);
		if (!$result) {
			error_log("Error al enviar email de orden #$orderID \r\n Mensaje: $message \r\n Para: $to \r\n CC: $cc \r\n BCC: $bcc");	
		}
	}else{
		/**
		$headers = "From: \"" . $config['FromEmailName'] . "\" <" . $config['FromEmail'] . "> \r\n";
		$headers .= "Reply-To: " . $config['FromEmail'] . "\r\n";
		$headers .= "CC: " . $order->Customer->Salesman->Email . "\r\n";
		$customerEmail = $order->Customer->Email;
		if($customerEmail != ""){
			$headers .= "BCC: " . $customerEmail . "\r\n";
		}
		$headers .= "MIME-Version: 1.0\r\n";
		$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
		
		$name = $order->Customer->Name;
		$message = "Nueva orden de compra para $name <br /> Haga click en el siguiente enlace para ver la confirmacion de la orden.<br />
		<a href=\"$root" . "webConfirmation.php?order=$orderID&key=$key\">Ver Orden #$orderID</a>";
		
		$status = mail($to, $subject, $message, $headers);
		if (!$status) {
			error_log("Error al enviar email de orden #$orderID \r\n Mensaje: $message \r\n Para: $to \r\n");
		}
		**/
		
		require_once './assets/PHPMailerAutoload.php';
		 
		$results_messages = array();
		 
		$mail = new PHPMailer(true);
		$mail->CharSet = 'utf-8';
		 
		class phpmailerAppException extends phpmailerException {}
		 
		try {
		
		if(!PHPMailer::validateAddress($to)) {
		  throw new phpmailerAppException("Email address " . $to . " is invalid -- aborting!");
		}
		$mail->isMail();
		$mail->addReplyTo($config['FromEmail']);
		$mail->From       = $config['FromEmail'];
		$mail->FromName   = $config['FromEmailName'];
		$mail->addAddress($to);
		/*
		if ($order->Customer->Salesman->Email != "" || $order->Customer->Salesman->Email != null) {
			$mail->addCC($order->Customer->Salesman->Email);	
		}
		*/
		$customerEmail = $order->Customer->Email;
		if($customerEmail != ""){
			$mail->addCC($customerEmail);
		}
		
		$mail->Subject  = $subject;
		$title = $config["FromEmailName"];
		$body = 
		'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
		<html>
		<head>
		  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		  <title>' . $title . '</title>
		</head>
		<body>
		  <div style="width: 640px; font-family: Arial, Helvetica, sans-serif; font-size: 16px;">
		    <img src="'.$root.'/img/'. $config['SmallLogo'] .'" style="width: 150px;" />
		    <p>Nueva orden de compra para ' . $order->Customer->Name . ' <br />
		    Numero de Cuenta: ' . $order->Customer->AccountNumber . '<br />
		    Total: ' . moneyFormat($order->OrderTotal) . ' <br />
		    Notas: ' . $order->OrderNotes . '<br /> 
		    <a href="' . $root . 'webConfirmation.php?order=' . $orderID . '&key=' . $key . '">Ver Orden #' . $orderID . '</a>
		    </p>
		    <div align="center">
		      
		    </div>
		    
		  </div>
		</body>
		</html>';
		$mail->WordWrap = 78;
		$mail->msgHTML($body, dirname(__FILE__), true); //Create message bodies and embed images
		//$mail->addAttachment('images/phpmailer_mini.png','phpmailer_mini.png');  // optional name
		//$mail->addAttachment('images/phpmailer.png', 'phpmailer.png');  // optional name
		
		$privatekeyfile = 'dkim_private.key';
        //Make a new key pair
        //(2048 bits is the recommended minimum key length -
        //gmail won't accept less than 1024 bits)
        $pk = openssl_pkey_new(
            array(
                'private_key_bits' => 2048,
                'private_key_type' => OPENSSL_KEYTYPE_RSA
            )
        );
        openssl_pkey_export_to_file($pk, $privatekeyfile);
		
		$mail->DKIM_domain = 'eurojaponautosupply.com';
		$mail->DKIM_private = $privatekeyfile;
		$mail->DKIM_selector = 'phpmailer';
		$mail->DKIM_passphrase = ''; //key is not encrypted
		
		
		try {
		  $mail->send();
		  unlink($privatekeyfile);
		  $results_messages[] = "Message has been sent using MAIL";
		}
		catch (phpmailerException $e) {
		  throw new phpmailerAppException('Unable to send to: ' . $to. ': '.$e->getMessage());
		}
		}
		catch (phpmailerAppException $e) {
		  $results_messages[] = $e->errorMessage();
		}
	}
}

function getCartTotal() {
	global $con;
	$isCustomer = false;
	if (isset($_SESSION['isCustomer'])) {
		$isCustomer = $_SESSION['isCustomer'];	
	}else {
		header("Location: index.php");
	}
	if($isCustomer){
		$customer = new Customer($_SESSION['AccountNumber']);
		$priceRate = getPricePlanCalculatedRate($customer->AccountNumber);
		$column = "Cost";
		switch ($customer->PriceLevel) {
			case "F":
				$column = "PriceA";
				break;
			case "C":
				$column = "PriceB";
				break;
			case "G":
				$column = "PriceC";
				break;
			default:
				$column = "Cost";
		}
		$query = "SELECT SUM(SHOPPING_CART.Qty * ROUND($column * $priceRate, 2) + SHOPPING_CART.Qty * Core) AS CartTotal FROM SHOPPING_CART, INVENTORY WHERE INVENTORY.`Group` = SHOPPING_CART.`Group` AND INVENTORY.`Line` = SHOPPING_CART.`Line` AND INVENTORY.`SKU` = SHOPPING_CART.`SKU` AND AccountNumber = '" . $customer->AccountNumber . "'";	
		$result = mysqli_query($con, $query);
		$row = mysqli_fetch_array($result);
		return $row['CartTotal'];
	}else{
		if ($_SESSION['pricePlanMode']) {
			$priceRate = getPricePlanCalculatedRate($_SESSION['AccountNumber']);	
		}else {
			$priceRate = 1;
		}
		
		$salesman = new Salesman($_SESSION['SalesmanID']);
		$column = "Cost";
		if (isset($_SESSION['setCustomerMode']) && $_SESSION['setCustomerMode']) {
			$customer = new Customer($_SESSION['setCustomer']);
			switch ($customer->PriceLevel) {
				case "F":
					$column = "PriceA";
					break;
				case "C":
					$column = "PriceB";
					break;
				case "G":
					$column = "PriceC";
					break;
				default:
					$column = "Cost";
			}
		}
		$query = "SELECT SUM(SHOPPING_CART.Qty * ROUND($column * $priceRate, 2) + SHOPPING_CART.Qty * Core) AS CartTotal FROM SHOPPING_CART, INVENTORY WHERE INVENTORY.`Group` = SHOPPING_CART.`Group` AND INVENTORY.`Line` = SHOPPING_CART.`Line` AND INVENTORY.`SKU` = SHOPPING_CART.`SKU` AND AccountNumber = '" . $salesman->ID . "'";
		$result = mysqli_query($con, $query);
		$row = mysqli_fetch_array($result);
		return $row['CartTotal'];
	}
}
function updateCartItem($ID, $Qty) {
	global $con;
	$Qty = intval($Qty);
	$isCustomer = $_SESSION['isCustomer'];
	if ($isCustomer) {
		$customer = new Customer($_SESSION['AccountNumber']);
		if($Qty < 1){
			$query = "DELETE FROM SHOPPING_CART WHERE AccountNumber = '" . $customer->AccountNumber . "' AND id = " . $ID;	
		}else{
			$query = "UPDATE SHOPPING_CART SET Qty = " . $Qty . " WHERE AccountNumber = '" . $customer->AccountNumber . "' AND id = " . $ID;
		}
	}else{
		$salesman = new Salesman($_SESSION['SalesmanID']);
		if($Qty < 1){
			$query = "DELETE FROM SHOPPING_CART WHERE AccountNumber = '" . $salesman->ID . "' AND id = " . $ID;	
		}else{
			$query = "UPDATE SHOPPING_CART SET Qty = " . $Qty . " WHERE AccountNumber = '" . $salesman->ID . "' AND id = " . $ID;
		}
	}
	//echo($query);
	mysqli_query($con, $query);
}
function getCustomerInfo($AccountNumber) {
	global $con;
	$isAdmin = $_SESSION['isAdmin'];
	if (!$isAdmin) {
		return false;
	}
	$customer = new Customer($AccountNumber);
	echo json_encode($customer);
	
}
function setLanguage($language) {
	global $con;
	$number = 0;
	$isCustomer = $_SESSION['isCustomer'];
	if ($isCustomer) {
		$query = "UPDATE CUSTOMER SET Language = '$language' WHERE AccountNumber = '" . $_SESSION['AccountNumber'] . "'";
	}else {
		$query = "UPDATE SALESMAN SET Language = '$language' WHERE ID = '" . $_SESSION['SalesmanID'] . "'";
	}
	if (mysqli_query($con, $query)) {
		echo("true");
		return true;
	}else {
		echo("false");
		return false;
	}
	
	return;
}
function saveCustomerInfo($CustomerData) {
	global $con;
	$isAdmin = $_SESSION['isAdmin'];
	$isNew = $CustomerData['IsNew'];
	$samePass = false;

	if($CustomerData['Password'] == "NOCHANGE"){
		$samePass = true;
	}
	if (!$isAdmin) {
		return false;
	}
	if($isNew == "1"){
		$query = "INSERT INTO CUSTOMER (`Name`, `City`, `Phone`,`Contact`,`AccountNumber`, Email, `PriceLevel`, Password, Salesman, `Active`, `DisableCheck`, `CreditLimit`, `DiscountDays`, `Comments`) VALUES ('" . mysqli_real_escape_string($con, $CustomerData['Name']) . "', '" . mysqli_real_escape_string($con, $CustomerData['City']) . "', '" . mysqli_real_escape_string($con, $CustomerData['Phone']) . "', '" . mysqli_real_escape_string($con, $CustomerData['Contact']) . "', '" . mysqli_real_escape_string($con, $CustomerData['AccountNumber']) . "', '" . mysqli_real_escape_string($con, $CustomerData['Email']) . "', '" . mysqli_real_escape_string($con, $CustomerData['PriceLevel']) . "', '" . md5($CustomerData['Password']) . "', '{$CustomerData['Salesman']}', {$CustomerData['Active']}, {$CustomerData['DisableCheck']}, {$CustomerData['CreditLimit']}, {$CustomerData['DiscountDays']}, '" . mysqli_real_escape_string($con, $CustomerData['Comments']) . "')";	
		event_log($_SESSION['Username'], "INSERT NEW CUSTOMER", print_r($CustomerData, true));	
	}elseif ($isNew == "0") {
		if ($samePass) {
			$query = "UPDATE CUSTOMER SET `Name` = '" . mysqli_real_escape_string($con, $CustomerData['Name']) . "', `City` = '" . mysqli_real_escape_string($con, $CustomerData['City']) . "', `Phone` = '" . mysqli_real_escape_string($con, $CustomerData['Phone']) . "', `Contact` = '" . mysqli_real_escape_string($con, $CustomerData['Contact']) . "', Email = '{$CustomerData['Email']}', PriceLevel = '{$CustomerData['PriceLevel']}', `Salesman` = '{$CustomerData['Salesman']}', `Active` = {$CustomerData['Active']}, `DisableCheck` = {$CustomerData['DisableCheck']}, `CreditLimit` = {$CustomerData['CreditLimit']}, `DiscountDays` = {$CustomerData['DiscountDays']}, `Comments` = '" . mysqli_real_escape_string($con, $CustomerData['Comments']) . "'  WHERE AccountNumber = '{$CustomerData['AccountNumber']}'";
		}else{
			$query = "UPDATE CUSTOMER SET `Name` = '" . mysqli_real_escape_string($con, $CustomerData['Name']) . "', `City` = '{$CustomerData['City']}', `Phone` = '" . mysqli_real_escape_string($con, $CustomerData['Phone']) . "', `Contact` = '" . mysqli_real_escape_string($con, $CustomerData['Contact']) . "', Email = '{$CustomerData['Email']}', PriceLevel = '{$CustomerData['PriceLevel']}', `Password` = '" . md5($CustomerData['Password']) . "', `Salesman` = '{$CustomerData['Salesman']}', `Active` = {$CustomerData['Active']}, `DisableCheck` = {$CustomerData['DisableCheck']}, `CreditLimit` = {$CustomerData['CreditLimit']}, `DiscountDays` = {$CustomerData['DiscountDays']}, `Comments` = '" . mysqli_real_escape_string($con, $CustomerData['Comments']) . "' WHERE AccountNumber = '{$CustomerData['AccountNumber']}'";
		}
		event_log($_SESSION['Username'], "UPDATE CUSTOMER", print_r($CustomerData, true));
	}
	$result = mysqli_query($con, $query);
	if($result){
		$return['result'] = true;
		$return['query'] = $query;
		echo json_encode($return);
		
	}else {
		$return['result'] = false;
		$return['query'] = $query;
		$return['error'] = mysqli_error($con);
		echo json_encode($return);
		//echo($query);
	}
	
}
function deleteCustomer($AccountNumber) {
	global	$con;
	$query = "DELETE FROM CUSTOMER WHERE AccountNumber = '$AccountNumber'";
	$result = mysqli_query($con, $query);
	$return['result'] = $result;
	event_log($_SESSION['Username'], "DELETE CUSTOMER", "CUSTOMER: $AccountNumber");
	echo(json_encode($return));
}
function getSalesmanInfo($ID) {
	global $con;
	$isAdmin = $_SESSION['isAdmin'];
	if (!$isAdmin) {
		return false;
	}
	$salesman = new Salesman($ID);
	echo json_encode($salesman);
	
}
function saveSalesmanInfo($SalesmanData) {
	global $con;
	$isNew = $SalesmanData['IsNew'];
	$isAdmin = $_SESSION['isAdmin'];
	$samePass = false;
	if($SalesmanData['Password'] == "NOCHANGE"){
		$samePass = true;
	}
	if (!$isAdmin) {
		return false;
	}
	if($isNew == "1"){
		$query = "INSERT INTO SALESMAN (`ID`, `FullName`, `Username`, Email, Password) VALUES ('{$SalesmanData['ID']}', '{$SalesmanData['Name']}', '{$SalesmanData['Username']}', '{$SalesmanData['Email']}', '" . md5($SalesmanData['Password']) . "')";
		event_log($_SESSION['Username'], "INSERT NEW SALESMAN", print_r($SalesmanData, true));
	}elseif ($isNew == "0") {
		if ($samePass) {
			$query = "UPDATE SALESMAN SET `FullName` = '{$SalesmanData['Name']}', `Username` = '{$SalesmanData['Username']}', Email = '{$SalesmanData['Email']}' WHERE ID = '{$SalesmanData['ID']}'";
		} else {
			$query = "UPDATE SALESMAN SET `FullName` = '{$SalesmanData['Name']}', `Username` = '{$SalesmanData['Username']}', Email = '{$SalesmanData['Email']}', `Password` = '" . md5($SalesmanData['Password']) . "' WHERE ID = '{$SalesmanData['ID']}'";
		}
		event_log($_SESSION['Username'], "UPDATE SALESMAN", print_r($SalesmanData, true));
	}
	$result = mysqli_query($con, $query);
	if($result){
		echo("true");
	}else {
		echo "false";
	}
	
}
function deleteSalesman($SalesmanID) {
	global	$con;
	$query = "DELETE FROM SALESMAN WHERE ID = '$SalesmanID'";
	$result = mysqli_query($con, $query);
	$return['result'] = $result;
	event_log($_SESSION['Username'], "DELETE SALESMAN", "SALESMAN: $SalesmanID");
	echo(json_encode($return));
}

function getGroupInfo($Code) {
	global $con;
	$isAdmin = $_SESSION['isAdmin'];
	if (!$isAdmin) {
		return false;
	}
	$query = "SELECT * FROM `GROUP` WHERE `Code` = '$Code'";
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result, MYSQL_ASSOC);
	
	echo json_encode($row);

}
function saveGroupInfo($GroupData) {
	global $con;
	$isNew = $GroupData['IsNew'];
	$isAdmin = $_SESSION['isAdmin'];
	if($isNew == "1"){
		$query = "INSERT INTO `GROUP` (`Code`, `Name`, `NameEN`) VALUES ('" . mysqli_real_escape_string($con, $GroupData['Code']) . "', '" . mysqli_real_escape_string($con, $GroupData['Name']) . "', '" . mysqli_real_escape_string($con, $GroupData['NameEN']) . "')";
		event_log($_SESSION['Username'], "INSERT NEW GROUP", print_r($GroupData,true));
	}elseif ($isNew == "0") {
		$query = "UPDATE `GROUP` SET `Name` = '" . mysqli_real_escape_string($con, $GroupData['Name']) . "', `NameEN` = '" . mysqli_real_escape_string($con, $GroupData['NameEN']) . "' WHERE `Code` = '" . mysqli_real_escape_string($con, $GroupData['Code']) . "'";
		event_log($_SESSION['Username'], "UPDATE GROUP", print_r($GroupData, true));
	}
	$result = mysqli_query($con, $query);
	if($result){
		$return['result'] = true;
		$return['query'] = $query;
		echo json_encode($return);
		
	}else {
		$return['result'] = false;
		$return['query'] = $query;
		$return['error'] = mysqli_error($con);
		echo json_encode($return);
		//echo($query);
	}
	
	
}
function deleteGroup($Code) {
	global	$con;
	$query = "DELETE FROM `GROUP` WHERE `Code` = '$Code'";
	$result = mysqli_query($con, $query);
	$return['result'] = $result;
	$return['query'] = $query;
	event_log($_SESSION['Username'], "DELETE GROUP", "Code: $Code");
	echo(json_encode($return));
}

function getLineInfo($Code) {
	global $con;
	$isAdmin = $_SESSION['isAdmin'];
	if (!$isAdmin) {
		return false;
	}
	$query = "SELECT * FROM `LINE` WHERE `Code` = '$Code'";
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result, MYSQL_ASSOC);
	
	echo json_encode($row);

}
function saveLineInfo($LineData) {
	global $con;
	$isNew = $LineData['IsNew'];
	$isAdmin = $_SESSION['isAdmin'];
	if($isNew == "1"){
		$query = "INSERT INTO `LINE` (`Code`, `Name`, `NameEN`) VALUES ('" . mysqli_real_escape_string($con, $LineData['Code']) . "', '" . mysqli_real_escape_string($con, $LineData['Name']) . "', '" . mysqli_real_escape_string($con, $LineData['NameEN']) . "')";
		event_log($_SESSION['Username'], "INSERT NEW LINE", print_r($LineData,true));
	}elseif ($isNew == "0") {
		$query = "UPDATE `LINE` SET `Name` = '" . mysqli_real_escape_string($con, $LineData['Name']) . "',  `NameEN` = '" . mysqli_real_escape_string($con, $LineData['NameEN']) . "' WHERE `Code` = '" . mysqli_real_escape_string($con, $LineData['Code']) . "'";
		event_log($_SESSION['Username'], "UPDATE LINE", print_r($LineData,true));
	}
	$result = mysqli_query($con, $query);
	if($result){
		$return['result'] = true;
		$return['query'] = $query;
		echo json_encode($return);
		
	}else {
		$return['result'] = false;
		$return['query'] = $query;
		$return['error'] = mysqli_error($con);
		echo json_encode($return);
		
	}
	
	
}
function deleteLine($Code) {
	global	$con;
	$query = "DELETE FROM `LINE` WHERE `Code` = '$Code'";
	$result = mysqli_query($con, $query);
	$return['result'] = $result;
	$return['query'] = $query;
	event_log($_SESSION['Username'], "DELETE LINE", "Code: $Code");
	echo(json_encode($return));
}

function deleteCartItem($ID) {
	global $con;
	$isCustomer = $_SESSION['isCustomer'];
	if ($isCustomer) {
		$customer = new Customer($_SESSION['AccountNumber']);
		$query = "DELETE FROM SHOPPING_CART WHERE AccountNumber = '" . $customer->AccountNumber . "' AND id = " . $ID;
	}else {
		$salesman = new Salesman($_SESSION['SalesmanID']);
		$query = "DELETE FROM SHOPPING_CART WHERE AccountNumber = '" . $salesman->ID . "' AND id = " . $ID;
	}
	//echo $query;
	mysqli_query($con, $query);
}
function saveFields($OrderNotes, $PONumber) {
	$_SESSION['OrderNotes'] = $OrderNotes;
	$_SESSION['PONumber'] = $PONumber;
}

//Get the result of the query as a CSV stream.
//http://www.bin-co.com/php/scripts/csv_import_export/
function CSVExport($query) {
	global $con;
    $sql_csv = mysqli_query($con, $query) or die("Error: " . mysqli_error($con)); //Replace this line with what is appropriate for your DB abstraction layer
    
    header("Content-type:text/octect-stream");
    header("Content-Disposition:attachment;filename=data.csv");
    while($row = mysqli_fetch_row($sql_csv)) {
        print '"' . stripslashes(implode('","',$row)) . "\"\n";
    }
    exit;
}

//Import the contents of a CSV file after uploading it
//http://www.bin-co.com/php/scripts/csv_import_export/
//Aruguments : $table - The name of the table the data must be imported to
//                $fields - An array of fields that will be used
//                $csv_fieldname - The name of the CSV file field
function CSVImport($table, $fields, $csv_fieldname='csv', $additionalParams = array()) {
    //if(!$_FILES[$csv_fieldname]['name']) return;
	global $con;
    $handle = fopen($csv_fieldname,'r');
    //var_dump($additionalParams);
    if(!$handle) die('Cannot open uploaded file.');
	if (isset($additionalParams['AddToAltas'])) {
		if ($additionalParams['AddToAltas']) {
			$query = "INSERT INTO ALTAS_HEAD (Name, NameEN, DateLine,ReceiptDate,Active) VALUES ('" . date("Y-m-d") . "','" . date("Y-m-d") . "','" . date("m-d-Y") . "',NOW(), true)";
			mysqli_query($con, $query);
			
			$altaID = mysqli_insert_id($con);	
		}
		
	}
    $row_count = 0;
	if(count($fields) == 1){
		$sql_query = "INSERT INTO $table (" . $fields[0] .") VALUES(";	
	}else{
		$sql_query = "INSERT INTO $table (". implode(',',$fields) .") VALUES(";
	}
    
//echo $sql_query;
    //$rows = array();
	ini_set("auto_detect_line_endings", "1");
    //Read the file as csv
    $return['trueCount'] = 0;
    $return['falseCount'] = 0;
	$dateCols = array();
	foreach($fields as $key =>$value){
		if(stripos($value, "date") != false)
			array_push($dateCols, $key);
		
	}
	
    while (($data = fgetcsv($handle, 1000)) !== false) {
    	
		if(count($fields) == 1){
			$sql_query = "INSERT INTO $table (" . $fields[0] .") VALUES(";	
		}else{
			$sql_query = "INSERT INTO $table (". implode(',',$fields) .") VALUES(";
		}
		
        $row_count++;
		$numcols = count($data);
		$correctNumCols = count($fields);
		if ($numcols > $correctNumCols) {
			for ($i = $numcols; $i < $correctNumCols; $i++) {
				unset($data[$i]);
			}
		}
		//echo $sql_query;
        if ($numcols > 0) {
        	foreach($data as $key=>$value) {
				
				if(array_search($key,$dateCols) === false){
					$data[$key] = "'" . addslashes(str_replace(",","",$value)) . "'";
				}else{
					$oldDate = $data[$key];
					$newDate = date('Y-m-d', strtotime($oldDate));
					$data[$key] = "'" . addslashes($newDate) . "'";	
				}
        	}
			
    		$row = implode(",",$data);	
    		$sql_query .= $row . ") ON DUPLICATE KEY UPDATE "; 
    		foreach ($fields as $key => $value) {
    			$sql_query .= $value . " = VALUES(" . $value . "), ";
    		}
    		$sql_query = rtrim($sql_query,", ");
    		//echo($sql_query . "<br />");
			//echo $sql_query;
	    	$result[$row_count-1] = mysqli_query($con, $sql_query); // and insert the new ones.
	    	if (mysqli_error($con) == "" || mysqli_error($con) == null) {
	    		
	    	}else {
	    		$return['errors'][$row_count-1] = mysqli_error($con) . "\nQuery: " . $sql_query;
	    	}
	    	
	    	if ($result[$row_count-1]) {
	    		$return['trueCount']++;
	    	}else {
	    		$return['falseCount']++;
	    	}
	    	
	    	//Add To Altas
	    	if (isset($additionalParams['AddToAltas'])) {
	    		if ($additionalParams['AddToAltas']) {
	    			if (trim( str_ireplace( "'", "", $data[2] ) ) != "") {
	    				$query = "INSERT INTO ALTAS_DETAIL (`AltaID`, `Line`, `Group`, `SKU`) VALUES ($altaID, $data[1], $data[0], $data[2])";
	    				mysqli_query($con, $query);
	    			}
	    			
	    		}
	    		
	    	}
    	
        }
    }
    
    $return['rowCount'] = $row_count;
    
    fclose($handle);
	
    if($return['trueCount'] > 0) { //If some recores  were found,
        //Replace these line with what is appropriate for your DB abstraction layer
        //mysqli_query($con, "TRUNCATE TABLE $table") or die("MySQL Error: " . mysqli_error($con)); //Delete the existing records
        //mysqli_query($con, $sql_query) or die("MySQL Error: " . mysqli_error($con)); // and insert the new ones.
        $return['result'] = "true";
		return ($return);
        //print 'Successfully imported '.$row_count.' record(s)';
    } else {
    	$return['result'] = "false";
		$return['mysqlerror'] = mysqli_error($con);
    	return ($return);
    }
} 
function sendPasswordReset($account) {
	global $con;
	global $root;
	global $config;
	$query = "SELECT * FROM CUSTOMER WHERE AccountNumber = '$account' AND Email != ''";
	$result = mysqli_query($con, $query);
	$rowcount = mysqli_num_rows($result);
	
	if ($rowcount > 0) {
		$row = mysqli_fetch_array($result);
		unset($result);
		$key = generateRandomString(32);
		$query = "UPDATE CUSTOMER SET `ResetHash` = '" . $key . "' WHERE AccountNumber = '$account'";
		if (mysqli_query($con, $query)) {
			$message = "You asked to reset your password. Please click the following link to enter a new one. \n
			$root"."resetpassword.php?key=$key";
			if(mail($row['Email'], "Reset Password" , $message, "From: " . $config['FromEmailName'] . " <" . $config['FromEmail'] . ">")){
				$result['result'] = true;
				echo(json_encode($result));
				return true;
			}else {
				$result['result'] = false;
				$result['error'] = "There was an error sending the email";
				$result['message'] = $message;
				echo(json_encode($result));
				return false;	
			}
		}else {
			$result['result'] = false;
			$result['error'] = "There was an error updating the customer database.";
			echo(json_encode($result));
			return false;
		}
	}else {
		unset($result);
		$result['result'] = false;
		$result['error'] = "Cannot find any account with this account number or there is not an email address associated with that account";
		$result['query'] = $query;
		$result['rowcount'] = $rowcount;
		echo(json_encode($result));
		return false;
	}
}
function resetPassword($hash, $newPassword) {
	global $con;
	global $root;
	$query = "SELECT * FROM CUSTOMER WHERE ResetHash = '$hash'";
	$result = mysqli_query($con, $query);
	$rowcount = mysqli_num_rows($result);
	if ($rowcount > 0) {
		$row = mysqli_fetch_array($result);
		$query = "UPDATE CUSTOMER SET ResetHash = '', Password = '" . md5($newPassword) . "' WHERE ResetHash = '$hash'";
		if (mysqli_query($con, $query)) {
			$result['result'] = true;
			echo(json_encode($result));
			return true;
		}else {
			$result['result'] = false;
			$result['error'] = "There was an error updating the customer database.";
			echo(json_encode($result));
			return false;
		}
	}else {
		$result['result'] = false;
		$result['error'] = "Cannot find any account with this reset key";
		echo(json_encode($result));
		return false;
	}
}
function generateRandomString($length = 20) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message, $cc = "", $bcc = "") {
    $file = $path.$filename;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
    $uid = md5(uniqid(time()));
    $name = basename($file);
    $header = "From: ".$from_name." <".$from_mail.">\r\n";
    $header .= "Reply-To: ".$replyto."\r\n";
    if ($cc != "") {
    	$header .= "CC: " . $cc . "\r\n";
    }
    if ($bcc != "") {
    	$header .= "BCC: " . $bcc . "\r\n";
    }
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message."\r\n\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
    $header .= $content."\r\n\r\n";
    $header .= "--".$uid."--";
    if (mail($mailto, $subject, "", $header)) {
        //echo "mail send ... OK"; // or use booleans here
        return true;
    } else {
        return false;
    }
}

function backup_db(){
	global $con;
	/* Store All Table name in an Array */
	$allTables = array();
	$result = mysqli_query($con, 'SHOW TABLES');
	while($row = mysqli_fetch_row($result)){
	     $allTables[] = $row[0];
	}
	$return = "";
	foreach($allTables as $table){
	$result = mysqli_query($con, 'SELECT * FROM `'.$table . "`");
	$num_fields = mysqli_num_fields($result);
	
	$return .= 'DROP TABLE IF EXISTS `'.$table.'`;';
	$row2 = mysqli_fetch_row(mysqli_query($con, 'SHOW CREATE TABLE `'.$table . "`"));
	$return.= "\n\n".$row2[1].";\n\n";
	
	for ($i = 0; $i < $num_fields; $i++) {
	while($row = mysqli_fetch_row($result)){
	   $return.= 'INSERT INTO `'.$table.'` VALUES(';
	     for($j=0; $j<$num_fields; $j++){
	       $row[$j] = addslashes($row[$j]);
	       $row[$j] = str_replace("\n","\\n",$row[$j]);
	       if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } 
	       else { $return.= '""'; }
	       if ($j<($num_fields-1)) { $return.= ','; }
	     }
	   $return.= ");\n";
	}
	}
	$return.="\n\n";
	}
	
	// Create Backup Folder
	$folder = 'DB_Backup/';
	if (!is_dir($folder))
	mkdir($folder, 0777, true);
	chmod($folder, 0777);
	
	$date = date('m-d-Y-H-i-s', time()); 
	$filename = $folder."db-backup-".$date; 
	
	$handle = fopen($filename.'.sql','w+');
	fwrite($handle,$return);
	fclose($handle);
}



function sendTestOrder($orderID) {
	//disabled
	//return;
	//disabled
	
	global $config;
	global $root;
	require("./assets/PHPMailerAutoload.php");
	$order = new Order($orderID);
	
	
	$to = "wvalle@eurojaponautosupply.com";
	$subject = "Orden de Compra Web #$orderID";
	$key = md5($orderID . "EJAS");
	$key = substr($key, -16);
	
	$pdf = false;
	if ($pdf) {
		//
		system('./wkhtmltopdf-amd64 "' . $root . 'webConfirmation.php?order=' . $orderID . '&key=' . $key . '" "./tmp/' . $orderID . '.pdf"', $systemResult);
		$message = "Nueva orden de compra para $name \r\n Adjunto copia de la confirmacion de la orden.";
		$cc = $order->Customer->Salesman->Email;
		$bcc = "";
		if($customerEmail != ""){
			$bcc = $customerEmail;
		}
		$result = mail_attachment($orderID . '.pdf', "./tmp/", $to, $config['FromEmail'], $config['FromEmailName'], $config['FromEmail'], $subject, $message, $cc, $bcc);
		if (!$result) {
			error_log("Error al enviar email de orden #$orderID \r\n Mensaje: $message \r\n Para: $to \r\n CC: $cc \r\n BCC: $bcc");	
		}
	}else{
		
		require_once './assets/PHPMailerAutoload.php';
		 
		$results_messages = array();
		 
		$mail = new PHPMailer(true);
		$mail->CharSet = 'utf-8';
		 
		class phpmailerAppException extends phpmailerException {}
		 
		try {
		
		if(!PHPMailer::validateAddress($to)) {
		  throw new phpmailerAppException("Email address " . $to . " is invalid -- aborting!");
		}
		$mail->isMail();
		$mail->addReplyTo($config['FromEmail']);
		$mail->From       = $config['FromEmail'];
		$mail->FromName   = $config['FromEmailName'];
		$mail->addAddress($to);
		//$mail->addCC("elisamuel40@gmail.com");
		//$mail->addCC("elisamuel40@yahoo.com");
		$customerEmail = $order->Customer->Email;
		if($customerEmail != ""){
			//$mail->addBCC($customerEmail);
		}
		
		$mail->Subject  = $subject;
		$title = $config["FromEmailName"];
		$body = 
		'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
		<html>
		<head>
		  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		  <title>' . $title . '</title>
		</head>
		<body>
		  <div style="width: 640px; font-family: Arial, Helvetica, sans-serif; font-size: 16px;">
		    <img src="'.$root.'img/'. $config['SmallLogo'] .'" style="width: 150px;" />
		    <p>Nueva orden de compra para ' . $order->Customer->Name . ' <br />
		    Numero de Cuenta: ' . $order->Customer->AccountNumber . '<br />
		    Total: ' . moneyFormat($order->OrderTotal) . ' <br />
		    Notas: ' . $order->OrderNotes . '<br /> 
		    <a href="' . $root . 'webConfirmation.php?order=' . $orderID . '&key=' . $key . '">Ver Orden #' . $orderID . '</a>
		    </p>
		    <div align="center">
		      
		    </div>
		    
		  </div>
		</body>
		</html>';
		$mail->WordWrap = 78;
		$mail->msgHTML($body, dirname(__FILE__), true); //Create message bodies and embed images
		//$mail->addAttachment('images/phpmailer_mini.png','phpmailer_mini.png');  // optional name
		//$mail->addAttachment('images/phpmailer.png', 'phpmailer.png');  // optional name
		 
		try {
		  $mail->send();
		  $results_messages[] = "Message has been sent using MAIL";
		}
		catch (phpmailerException $e) {
		  throw new phpmailerAppException('Unable to send to: ' . $to. ': '.$e->getMessage());
		}
		}
		catch (phpmailerAppException $e) {
		  $results_messages[] = $e->errorMessage();
		}
		 
		
		
	}
}
function getProductDescription($line, $sku) {
	global $con;
	$sku = str_ireplace("-", "", $sku);
	$query = "SELECT * FROM INVENTORY WHERE `Line` = '$line' AND REPLACE(`SKU`,\"-\",\"\") = '$sku'";
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result);
	if ($row != null) {
		echo($row['Description'] . " " . $row['Notes']);
	}else {
		echo("false");
	}	
}
function savePickupLine($line, $sku, $qty, $invoiceNumber, $orderNumber, $reason) {
	global $con;
	$isCustomer = $_SESSION['isCustomer'];
	if ($isCustomer) {
		exit('error');
	}
	$salesman = new Salesman($_SESSION['SalesmanID']);
	$query = "INSERT INTO PICKUP_CART (`SalesmanID`, `Line`, `SKU`, `Qty`, `OrderID`, `InvoiceNumber`, `Reason`) VALUES ('{$salesman->ID}', '" . $line . "', '" . $sku . "', '" . $qty . "', '$orderNumber', '" . $invoiceNumber . "', '" . $reason . "')";

	$result = mysqli_query($con, $query);
	
	if ($result) {
		$result = array();
		
		$result['id'] = mysqli_insert_id($con);
		$result['result'] = "true";
		$result = json_encode($result);
		
		echo($result);
	}else {
		
		$result = array();
		
		
		$result['result'] = "false";
		$result = json_encode($result);
		
		echo($result);
	}
	
	
	
}
class Pickup {
	public $PickupID, $PickupTicket, $Customer, $PickupDate, $Items, $PickupNotes, $Packages, $Salesman, $AccountNumber;
	public $RequestedBy, $Void, $VoidID, $VoidDate, $VoidReason, $VoidUser,$Loaded, $Via;
	public $PackageDetails;
	public function __construct($PickupID) {
		$query = "SELECT * FROM PICKUP_HEAD WHERE PickupID = $PickupID";
		global $con;
		$result = mysqli_query($con, $query);
		$row = mysqli_fetch_array($result);
		$this->PickupID = $row['PickupID'];
		$this->PickupTicket = $row['PickupTicket'];
		$this->AccountNumber = $row['AccountNumber'];
		$this->Customer = new Customer($row['AccountNumber']);
		$this->PickupDate = $row['PickupDate'];
		$this->PickupNotes = $row['PickupNotes'];
		$this->Packages = $row['Packages'];
		$this->Salesman = new Salesman($row['Salesman']);
		$this->RequestedBy	= $row['RequestedBy'];
		$this->Via	= $row['Via'];
		$this->Loaded = false;
		$this->Void = $row['Void'];
		if($row['Void']){
			$query = "SELECT * FROM PICKUP_VOID WHERE PickupID = " . $row['PickupID'];
			$result = mysqli_query($con, $query);
			$row2 = mysqli_fetch_array($result);
			$this->VoidID = $row2['ID'];
			$this->VoidReason = $row2['Reason'];
			$this->VoidDate = $row2['VoidDate'];
			$this->VoidUser = $row2['User'];
		}
		$this->Items = array();
		$query = "SELECT id FROM PICKUP_DETAIL WHERE PickupID = $PickupID";
		$result = mysqli_query($con, $query);
		while($row = mysqli_fetch_array($result)){
			$item = new PickupItem($row['id']);
			array_push($this->Items, $item);
			unset($item);
		}
		
		$this->PackageDetails = array();
		$query = "SELECT * FROM PICKUP_RECEIVE_PACKAGE WHERE PickupID = $PickupID";
		$result = mysqli_query($con, $query);
		while($row = mysqli_fetch_array($result)){
			$package = new StdClass();
			$package->Received = true;
			$package->ReceivedDate = $row['ReceiveDate'];
			$package->Receiver = $row['User'];
			$this->PackageDetails[$row['PackageNumber']] = $package;
		}
		
		for($i = 1; $i <= $this->Packages; $i++){
			//$value = $i . "";
			if(!in_array($i, $this->PackageDetails)){
				$package = new StdClass();
				$package->Received = false;
				$this->PackageDetails[$i] = $package;
			}
		}
		
		
	}
	public function Void($reason){
		global $con;
		$reason = mysqli_real_escape_string($con,$reason);
		if(trim($reason) == ""){
			die("Invalid Reason");
		}
		/*
		$query = "UPDATE PAYMENT_HEAD SET CashAmount = 0, CheckAmount = 0, ProcessDate = NOW(), Processed = 1, Void = TRUE WHERE id = " . $this->PaymentID . ";";
		$query .= "UPDATE PAYMENT_DETAIL SET InvoiceNumber = CONCAT(InvoiceNumber,'V'), PartialPayment = 0, SubtotalAmount = 0, DiscountAmount = 0, TaxAmount = 0, PaymentAmount = 0, Reference = '' WHERE PaymentID = " . $this->PaymentID . ";";
		$query .= "UPDATE PAYMENT_CREDIT SET CreditNumber = CONCAT(CreditNumber,'V'), Subtotal = 0, Discount = 0, Tax = 0, Total = 0, Reference = '' WHERE PaymentID = " . $this->PaymentID . ";";
		$query .= "INSERT PAYMENT_VOID (PaymentID, Reason, User, VoidDate) VALUES (" . $this->PaymentID . ", '$reason', '" . $_SESSION['Username'] . "', NOW());";
		*/
		$reasonText = "THIS PICKUP REQUEST WAS VOIDED BECAUSE OF THE FOLLOWING REASON:" . $reason;
		$query = "UPDATE PICKUP_HEAD SET ToPickup = NOW(), ToPickupUser = '" . $_SESSION['Username'] . "', AtWarehouse = NOW(), AtWarehouseUser = '" . $_SESSION['Username'] . "', PickupStatus = 'VOID', PickupStatusUser = '" . $_SESSION['Username'] . "', PickupStatusNotes = '$reasonText', Void = TRUE WHERE PickupID = " . $this->PickupID . ";";
		$query .= "INSERT PICKUP_VOID (PickupID, Reason, User, VoidDate) VALUES (" . $this->PickupID . ", '$reason', '" . $_SESSION['Username'] . "', NOW());";
		
		
		if(!mysqli_multi_query($con, $query)){
			$data['result'] = false;
			$data['error'] = mysqli_error($con);
			$data['sql'] = $query;
			echo json_encode($data);
		}else{
			$data['result'] = "true";
			echo json_encode($data);
		}
		//echo $query;
		event_log($_SESSION['Username'],"PICKUP VOID", "Pickup Void \n\Pickup ID: " . $this->PickupID . " \nCustomer: " . $this->Customer->AccountNumber . " - " . $this->Customer->Name . "\nUser: " . $_SESSION['User'] . "\nReason: " . $reason);
	}
	public function GetVoidDetails(){
		global $con;
		$data['Pickup'] = $this->PickupID;
		$data['VoidDate'] = $this->VoidDate;
		$data['VoidReason'] = $this->VoidReason;
		$data['VoidUser'] = $this->VoidUser;
		//var_dump($this);
		echo json_encode($data);
	}
}

class PickupItem {
	public $Line, $SKU, $Description, $InvoiceNumber, $OrderID, $Reason, $Qty, $ReasonText;
	public function __construct($id) {
		$query = "SELECT PICKUP_DETAIL.*, CONCAT(CONCAT(INVENTORY.Description, ' '),INVENTORY.Notes) AS Description FROM PICKUP_DETAIL, INVENTORY WHERE `id` = $id AND PICKUP_DETAIL.SKU = INVENTORY.SKU AND PICKUP_DETAIL.LINE = INVENTORY.LINE";
		global $con;
		$result = mysqli_query($con, $query);
		$row = mysqli_fetch_array($result);
		$this->Line = $row['Line'];
		$this->SKU = $row['SKU'];
		$this->Description = $row['Description'];
		$this->OrderID = $row['OrderID'];
		$this->InvoiceNumber = $row['InvoiceNumber'];
		$this->Reason = $row['Reason'];
		$this->Qty = $row['Qty'];
		$this->ReasonText = getReasonText($row['Reason']);
		
	}	
}
function voidPickup($pickupID, $reason){
    if($reason == ""){
        die('Invalid Reason!');
    }
    $pickup = new Pickup($pickupID);
    $pickup->Void($reason);
}
function voidPickupDetails($pickupID){
    $pickup = new Pickup($pickupID);
       echo $pickup->GetVoidDetails();
}
function sendPickup($pickupID) {
	global $config;
	global $root;
	$pickup = new Pickup($pickupID);
	
	
	$to = $config['PickupEmail'];
	$subject = "Pedido de Recogido y Devolucion #$pickupID";
	$key = md5($pickupID . "EV");
	$key = substr($key, -16);
	
	$pdf = false;
	if ($pdf) {
		//
		system('./wkhtmltopdf-amd64 "' . $root . 'pickupRequest.php?pickup=' . $pickupID . '&key=' . $key . '" "./tmp/' . $pickupID . '.pdf"', $systemResult);
		$message = "Nueva solicitud de recogido para $name \r\n Adjunto copia de la solicitud de recogido y devoluci&oacute;n.";
		$cc = $pickup->Customer->Salesman->Email;
		$bcc = "";
		if($customerEmail != ""){
			$bcc = $customerEmail;
		}
		$result = mail_attachment($pickupID . '.pdf', "./tmp/", $to, $config['FromEmail'], $config['FromEmailName'], $config['FromEmail'], $subject, $message, $cc, $bcc);
		if (!$result) {
			error_log("Error al enviar email de orden #$pickupID \r\n Mensaje: $message \r\n Para: $to \r\n CC: $cc \r\n BCC: $bcc");	
		}
	}else{
		
		
		require_once './assets/PHPMailerAutoload.php';
		 
		$results_messages = array();
		 
		$mail = new PHPMailer(true);
		$mail->CharSet = 'utf-8';
		 
		class phpmailerAppException extends phpmailerException {}
		 
		try {
		
		if(!PHPMailer::validateAddress($to)) {
		  throw new phpmailerAppException("Email address " . $to . " is invalid -- aborting!");
		}
		$mail->isMail();
		$mail->addReplyTo($config['FromEmail']);
		$mail->From       = $config['FromEmail'];
		$mail->FromName   = $config['FromEmailName'];
		$mail->addAddress($to);
		$customerEmail = $pickup->Customer->Email;
		if($customerEmail != ""){
			$mail->addCC($customerEmail);
		}
		
		$mail->Subject  = $subject;
		$title = $config["FromEmailName"];
		$body = 
		'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
		<html>
		<head>
		  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		  <title>' . $title . '</title>
		</head>
		<body>
		  <div style="width: 640px; font-family: Arial, Helvetica, sans-serif; font-size: 16px;">
		    <img src="'.$root.'/img/'. $config['SmallLogo'] .'" style="width: 150px;" />
		    <p>Nueva solicitud de recogido para ' . $pickup->Customer->Name . ' <br />
		    Numero de Cuenta: ' . $pickup->Customer->AccountNumber . '<br />
		    Notas: ' . $pickup->PickupNotes . '<br /> 
		    Numero de Bultos: ' . $pickup->Packages . '<br /> 
		    <a href="' . $root . 'pickupRequest.php?pickup=' . $pickupID . '&key=' . $key . '">Ver Pickup #' . $pickupID . '</a>
		    </p>
		    <div align="center">
		      
		    </div>
		    
		  </div>
		</body>
		</html>';
		$mail->WordWrap = 78;
		$mail->msgHTML($body, dirname(__FILE__), true); //Create message bodies and embed images
		//$mail->addAttachment('images/phpmailer_mini.png','phpmailer_mini.png');  // optional name
		//$mail->addAttachment('images/phpmailer.png', 'phpmailer.png');  // optional name
		
		$privatekeyfile = 'dkim_private.key';
        //Make a new key pair
        //(2048 bits is the recommended minimum key length -
        //gmail won't accept less than 1024 bits)
        $pk = openssl_pkey_new(
            array(
                'private_key_bits' => 2048,
                'private_key_type' => OPENSSL_KEYTYPE_RSA
            )
        );
        openssl_pkey_export_to_file($pk, $privatekeyfile);
		
		$mail->DKIM_domain = 'eurojaponautosupply.com';
		$mail->DKIM_private = $privatekeyfile;
		$mail->DKIM_selector = 'phpmailer';
		$mail->DKIM_passphrase = ''; //key is not encrypted
		
		
		try {
		  $mail->send();
		  unlink($privatekeyfile);
		  $results_messages[] = "Message has been sent using MAIL";
		}
		catch (phpmailerException $e) {
		  throw new phpmailerAppException('Unable to send to: ' . $to. ': '.$e->getMessage());
		}
		}
		catch (phpmailerAppException $e) {
		  $results_messages[] = $e->errorMessage();
		}
	}
}
function getReasonText($key) {
	global $con;
	$query = "SELECT `Value` FROM PICKUP_REASON WHERE `Key` = '$key'";
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result);
	return $row['Value'];
	
	
	
}
function getProductLines($sku) {
	global $con;
	$sku = mysqli_real_escape_string($con, $sku);
	$sku = str_ireplace("-", "", $sku);

	$query = "SELECT `SKU`, `Line` FROM INVENTORY WHERE REPLACE(`SKU`,\"-\",\"\") LIKE '$sku'";
	$result = mysqli_query($con, $query);
	$lines = array();
	while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
		$lines[] = $row;
	}
	echo json_encode($lines);
}
function getReasonInfo($Key) {
	global $con;
	$isAdmin = $_SESSION['isAdmin'];
	if (!$isAdmin) {
		return false;
	}
	$query = "SELECT * FROM `PICKUP_REASON` WHERE `Key` = '$Key'";
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result, MYSQL_ASSOC);
	
	echo json_encode($row);

}
function saveReasonInfo($ReasonData) {
	global $con;
	$isNew = $ReasonData['IsNew'];
	$isAdmin = $_SESSION['isAdmin'];
	if($isNew == "1"){
		$query = "INSERT INTO `PICKUP_REASON` (`Key`, `Value`) VALUES ('" . mysqli_real_escape_string($con, $ReasonData['Key']) . "', '" . mysqli_real_escape_string($con, $ReasonData['Value']) . "')";
		event_log($_SESSION['Username'], "INSERT NEW PICKUP REASON", print_r($ReasonData,true));
	}elseif ($isNew == "0") {
		$query = "UPDATE `PICKUP_REASON` SET `Value` = '" . mysqli_real_escape_string($con, $ReasonData['Value']) . "' WHERE `Key` = '" . mysqli_real_escape_string($con, $ReasonData['Key']) . "'";
		event_log($_SESSION['Username'], "UPDATE PICKUP REASON", print_r($ReasonData,true));
	}
	$result = mysqli_query($con, $query);
	if($result){
		$return['result'] = true;
		$return['query'] = $query;
		echo json_encode($return);
		
	}else {
		$return['result'] = false;
		$return['query'] = $query;
		$return['error'] = mysqli_error($con);
		echo json_encode($return);
		
	}
	
	
}
function deleteReason($Key) {
	global	$con;
	$query = "DELETE FROM `PICKUP_REASON` WHERE `Key` = '$Key'";
	$result = mysqli_query($con, $query);
	$return['result'] = $result;
	$return['query'] = $query;
	event_log($_SESSION['Username'], "DELETE PICKUP REASON", "Key: $Key");
	echo(json_encode($return));
}
function event_log($user, $action, $data = "") {
	global $con;
	$query = "INSERT INTO EVENT_LOG (`DATE_TIME`, `USER`, `ACTION`, `DATA`) VALUES (NOW(), '$user', '$action', '$data')";
	$result = mysqli_query($con, $query);	
	//var_dump(mysqli_error($con));
}
function getEventDetails($id) {
	global $con;
	$query = "SELECT * FROM EVENT_LOG WHERE ID = $id";
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result, MYSQL_ASSOC);
	echo json_encode($row);
}

function getPricePlanCalcInfo($AccountNumber) {
	global $con;
	$isAdmin = $_SESSION['isAdmin'];
	if (!$isAdmin) {
		return false;
	}
	$query = "SELECT * FROM `PRICE_PLAN_CALC` WHERE `AccountNumber` = '$AccountNumber'";
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result, MYSQL_ASSOC);
	
	echo json_encode($row);

}
function savePricePlanCalcInfo($PricePlanData) {
	global $con;
	$isNew = $PricePlanData['IsNew'];
	$isAdmin = $_SESSION['isAdmin'];
	$result = false;
	if (customerExists($PricePlanData['AccountNumber'])) {
		
		if($isNew == "1"){
			$query = "INSERT INTO `PRICE_PLAN_CALC` (`AccountNumber`, `Percent`) VALUES ('" . mysqli_real_escape_string($con, $PricePlanData['AccountNumber']) . "', " . mysqli_real_escape_string($con, $PricePlanData['Percent']) . ")";
			event_log($_SESSION['Username'], "INSERT NEW PRICE PLAN", print_r($PricePlanData,true));
		}elseif ($isNew == "0") {
			$query = "UPDATE `PRICE_PLAN_CALC` SET `Percent` = " . mysqli_real_escape_string($con, $PricePlanData['Percent']) . " WHERE `AccountNumber` = '" . mysqli_real_escape_string($con, $PricePlanData['AccountNumber']) . "'";
			event_log($_SESSION['Username'], "UPDATE PRICE PLAN", print_r($PricePlanData,true));
		}
		$result = mysqli_query($con, $query);
	}
	if($result){
		$return['result'] = true;
		$return['query'] = $query;
		echo json_encode($return);
		
	}else {
		$return['result'] = false;
		$return['query'] = $query;
		$return['error'] = mysqli_error($con);
		echo json_encode($return);
		
	}
	
	
}
function deletePricePlanCalc($AccountNumber) {
	global	$con;
	$query = "DELETE FROM `PRICE_PLAN_CALC` WHERE `AccountNumber` = '$AccountNumber'";
	$result = mysqli_query($con, $query);
	$return['result'] = $result;
	$return['query'] = $query;
	event_log($_SESSION['Username'], "DELETE PRICE PLAN (CALCULATED)", "Account Number: $AccountNumber");
	echo(json_encode($return));
}
function getPricePlanCalculatedRate($AccountNumber) {
	global $con;
	$AccountNumber = trim($AccountNumber);
	if ($AccountNumber == "") {
		return 1;
	}
	$query = "SELECT * FROM `PRICE_PLAN_CALC` WHERE `AccountNumber` LIKE '$AccountNumber%'";
	$result = mysqli_query($con, $query);
	if (mysqli_num_rows($result) > 0) {
		$row = mysqli_fetch_array($result);
		return 1+$row['Percent'];
	}else {
		$row = 1;
		return $row;
	}
	
}
function setPricePlanMode($action, $accountNumber = '') {

	if ($action == "reset") {
		$_SESSION['pricePlanMode'] = false;	
		$_SESSION['AccountNumber'] = '';
		return;
	}
	
	if ($action == "set") {	
		$accountNumber = $_REQUEST['accountNumber'];
		$_SESSION['pricePlanMode'] = true;
		$_SESSION['AccountNumber'] = $accountNumber;
		return;
	}
	
}
function customerExists($accountNumber, $getCount = false) {
	global $con;
	if ($accountNumber == "") {
		return false;
	}
	
	$query = "SELECT AccountNumber FROM CUSTOMER WHERE AccountNumber LIKE '$accountNumber%'";
	$result = mysqli_query($con, $query);
	$count = mysqli_num_rows($result);
	if ($getCount) {
		return	$count;
	}else {
		return $count > 0;
	}
}
function getAltasData($AltasID) {
	global $con;
	$isCustomer = $_SESSION['isCustomer'];
	if($isCustomer){
		$accountNumber = ($_SESSION['AccountNumber']);
	} else {
		$accountNumber = $_SESSION['SalesmanID'];
	}
	$sort = array();
	$query = "SELECT * FROM ALTAS_HEAD WHERE ID = " . $AltasID;
	$result = mysqli_query($con, $query);	
	$row = mysqli_fetch_array($result);
	$sort = explode(",", $row['Sort']);
	$sortString = "";
	for ($i = 0; $i < count($sort); $i++) {
		if ($i == 0) {
			$sortString = " ORDER BY ";
		}
		$sortString .= "INVENTORY." . trim($sort[$i]);
		if ($i != count($sort)-1) {
			$sortString .= ", ";	
		}else {
			$sortString .= " ASC";
		}
	}
	
	
	$query = "SELECT ALTAS_DETAIL.*, INVENTORY.*, SHOPPING_CART.Qty AS OnOrder FROM ALTAS_DETAIL, INVENTORY LEFT JOIN SHOPPING_CART ON INVENTORY.SKU = SHOPPING_CART.SKU AND INVENTORY.LINE = SHOPPING_CART.LINE AND INVENTORY.GROUP = SHOPPING_CART.GROUP AND AccountNumber LIKE '" . $accountNumber . "' WHERE ALTAS_DETAIL.SKU = INVENTORY.SKU AND ALTAS_DETAIL.LINE = INVENTORY.LINE AND ALTAS_DETAIL.Group = INVENTORY.Group AND ALTAS_DETAIL.AltaID = " . $AltasID . $sortString;
	$result = mysqli_query($con, $query);
	$data = array();
	
	while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
		$_SESSION['AccountNumber'] = isset($_SESSION['AccountNumber'])?$_SESSION['AccountNumber']:null;
		$row['Cost'] = moneyFormat($row['Cost'] * getPricePlanCalculatedRate($_SESSION['AccountNumber']));
		$row['Image'] = hasImage($row['Line'], $row['SKU'])?getImage($row['Line'], $row['SKU']):false;
		array_push($data, $row);
	}
	
	echo json_encode($data);	
	//echo $query;
}
function getSpecialsData() {
	global $con;
	$isCustomer = $_SESSION['isCustomer'];
	if($isCustomer){
		$accountNumber = ($_SESSION['AccountNumber']);
	} else {
		$accountNumber = $_SESSION['SalesmanID'];
	}
	
	
	$query = "SELECT SPECIAL.*, Cost, INVENTORY.`Group`, INVENTORY.Description, INVENTORY.Notes, INVENTORY.Interchange, INVENTORY.Qty, SHOPPING_CART.Qty AS OnOrder FROM INVENTORY, SPECIAL LEFT JOIN SHOPPING_CART ON `SPECIAL`.SKU = SHOPPING_CART.SKU AND SPECIAL.`Line` = SHOPPING_CART.`Line` AND SHOPPING_CART.`AccountNumber` = '$accountNumber' WHERE SPECIAL.SKU = INVENTORY.SKU AND SPECIAL.Line = INVENTORY.Line ORDER BY Line, SKU";
	$result = mysqli_query($con, $query);
	$data = array();
	
	while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
		$row['Cost'] = moneyFormat($row['Cost'] * getPricePlanCalculatedRate($_SESSION['AccountNumber']));
		$row['RegularPrice'] = moneyFormat($row['RegularPrice'] * getPricePlanCalculatedRate($_SESSION['AccountNumber']));
		array_push($data, $row);
	}
	
	echo json_encode($data);	
	
}
function getAltasItemInfo($ID, $return = false) {
	global $con;
	$isAdmin = $_SESSION['isAdmin'];
	if (!$isAdmin) {
		return false;
	}
	$query = "SELECT * FROM `ALTAS_DETAIL` WHERE `id` = '$ID'";
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result, MYSQL_ASSOC);
	$row['Image'] = getImage($row['Line'], $row['SKU'],true);
	if ($return) {
		return $row;
	}else {
		echo json_encode($row);	
	}
	
}
function saveAltasItemInfo($AltaData) {
	global $con;
	$isNew = $AltaData['IsNew'];
	$isAdmin = $_SESSION['isAdmin'];
	$result = false;
	if (isset($AltaData['AltaID'])) {
		if($isNew == "1"){
			$query = "INSERT INTO `ALTAS_DETAIL` (`AltaID`, `Line`, `Group`, `SKU`) VALUES (" . mysqli_real_escape_string($con, $AltaData['AltaID']) . ", '" . mysqli_real_escape_string($con, $AltaData['Line']) . "', '" . mysqli_real_escape_string($con, $AltaData['Group']) . "', '" . mysqli_real_escape_string($con, $AltaData['SKU']) . "')";
			event_log($_SESSION['Username'], "INSERT NEW ALTA ITEM", print_r($AltaData,true));
		}elseif ($isNew == "0") {
			
			
		}
		$result = mysqli_query($con, $query);
	}
	if($result){
		$return['result'] = true;
		$return['query'] = $query;
		echo json_encode($return);
		
	}else {
		$return['result'] = false;
		$return['query'] = $query;
		$return['error'] = mysqli_error($con);
		echo json_encode($return);
		
	}
	
	
}
function deleteAltasItem($itemID) {
	global	$con;
	$item = getAltasItemInfo($itemID, true);
	$query = "DELETE FROM `ALTAS_DETAIL` WHERE `id` = '$itemID'";
	$result = mysqli_query($con, $query);
	$return['result'] = $result;
	$return['query'] = $query;
	event_log($_SESSION['Username'], "DELETE ALTA ITEM", "Item: " . print_r($item, true));
			
	echo(json_encode($return));
}
function getAltasInfo($ID, $return = false) {
	global $con;
	$isAdmin = $_SESSION['isAdmin'];
	if (!$isAdmin) {
		return false;
	}
	$query = "SELECT * FROM `ALTAS_HEAD` WHERE `ID` = $ID";
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result, MYSQL_ASSOC);
	if ($return) {
		return $row;
	}else {
		echo json_encode($row);	
	}
	

}
function saveAltasInfo($AltaData) {
	global $con;
	$isNew = $AltaData['IsNew'];
	$isAdmin = $_SESSION['isAdmin'];
	if($isNew == "1"){
		$query = "INSERT INTO `ALTAS_HEAD` (`Name`, `NameEN`, `DateLine`, `Active`, `Sort`) VALUES ('" . mysqli_real_escape_string($con, $AltaData['Name']) . "', '" . mysqli_real_escape_string($con, $AltaData['NameEN']) . "', '" . mysqli_real_escape_string($con, $AltaData['DateLine']) . "', " . mysqli_real_escape_string($con, $AltaData['Active']) . ", '" . $AltaData['Sort'] . "')";
		event_log($_SESSION['Username'], "INSERT NEW ALTA", print_r($AltaData,true));
	}elseif ($isNew == "0") {
		$query = "UPDATE `ALTAS_HEAD` SET `NameEN` = '" . mysqli_real_escape_string($con, $AltaData['NameEN']) . "', `Name` =  '" . mysqli_real_escape_string($con, $AltaData['Name']) . "', `DateLine` =  '" . mysqli_real_escape_string($con, $AltaData['DateLine']) . "', `Active` =  " . mysqli_real_escape_string($con, $AltaData['Active']) . ", `Sort` = '" . mysqli_real_escape_string($con, $AltaData['Sort']) . "' WHERE `ID` = '" . mysqli_real_escape_string($con, $AltaData['AltaID']) . "'";
		event_log($_SESSION['Username'], "UPDATE ALTA", print_r($AltaData,true));
	}
	$result = mysqli_query($con, $query);
	if($result){
		$return['result'] = true;
		$return['query'] = $query;
		if ($isNew == "1") {
			$return['ID'] = mysqli_insert_id($con);	
		}
		echo json_encode($return);
		
	}else {
		$return['result'] = false;
		$return['query'] = $query;
		$return['error'] = mysqli_error($con);
		echo json_encode($return);	
	}
}
function deleteAltas($ID) {
	global	$con;
	$alta = getAltasInfo($ID, true);
	$query = "DELETE FROM `ALTAS_HEAD` WHERE `ID` = $ID";
	$result = mysqli_query($con, $query);
	$return['queryA'] = $query;
	$return['result'] = $result;
	$query = "DELETE FROM `ALTAS_DETAIL` WHERE `AltaID` = $ID";
	$result = mysqli_query($con, $query);
	$return['result'] = $return['result'] && $result;
	$return['queryB'] = $query;
	event_log($_SESSION['Username'], "DELETE ALTA", "Price List: " . print_r($alta, true));
			
	echo(json_encode($return));
}
class Alta {
	public $ID, $NameEN, $Name, $Date;
	function __construct($AltaID) {
		global $con;
		$query = "SELECT * FROM ALTAS_HEAD WHERE ID = $AltaID";
		$result = mysqli_query($con, $query);
		$row = mysqli_fetch_array($result);
		$this->ID = $AltaID;
		$this->NameEN = $row['NameEN'];
		$this->Name = $row['Name'];
		$this->Date = $row['DateLine'];
	}
	
}
function hasImage($line, $sku, $admin = false) {
	$formats = "jpg,jpeg,png,gif,bmp";
	$formats = explode(",", $formats);
	$hasImage = false;
	$prefix = ".";
	if ($admin) {
		$prefix = "..";
	}
	foreach ($formats as $key => $value) {
		$hasImage = $hasImage || file_exists($prefix . "/img/catalog/" . $line . " " . $sku . ".$value");
		if ($hasImage) {
			break;
		}
	}
	return $hasImage;
	
}
function getImage($line, $sku, $admin = false) {
	$formats = "jpg,jpeg,png,gif,bmp";
	$formats = explode(",", $formats);
	$hasImage = false;
	$prefix = ".";
	if ($admin) {
		$prefix = "..";
	}
	foreach ($formats as $key => $value) {
		$hasImage = $hasImage || file_exists("./img/catalog/" . $line . " " . $sku . ".$value");
		if ($hasImage) {
			return $prefix . "/img/catalog/" . $line . " " . $sku . ".$value?time=" . filemtime("./img/catalog/" . $line . " " . $sku . ".$value");
		}
	}
	return $prefix . "/img/catalog/noimage.png";
	
	
}
function getCatalogData($CategoryID) {
	global $con;
	$isCustomer = $_SESSION['isCustomer'];
	if($isCustomer){
		$accountNumber = ($_SESSION['AccountNumber']);
	} else {
		$accountNumber = $_SESSION['SalesmanID'];
	}
	$sort = array();
	$query = "SELECT * FROM CATALOG_CATEGORY WHERE CatalogID = " . $CategoryID;
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result);
	$sort = explode(",", $row['Sort']);
	$sortString = "";
	for ($i = 0; $i < count($sort); $i++) {
		if ($i == 0) {
			$sortString = " ORDER BY ";
		}
		$sortString .= "INVENTORY." . trim($sort[$i]);
		if ($i != count($sort)-1) {
			$sortString .= ", ";	
		}else {
			$sortString .= " ASC";
		}
	}
	$query = "SELECT CATALOG_DETAIL.*, INVENTORY.*, SHOPPING_CART.Qty AS OnOrder FROM CATALOG_DETAIL, INVENTORY LEFT JOIN SHOPPING_CART ON INVENTORY.SKU = SHOPPING_CART.SKU AND INVENTORY.LINE = SHOPPING_CART.LINE AND INVENTORY.GROUP = SHOPPING_CART.GROUP AND AccountNumber LIKE '" . $accountNumber . "' WHERE CATALOG_DETAIL.SKU = INVENTORY.SKU AND CATALOG_DETAIL.LINE = INVENTORY.LINE AND CategoryID = " . $CategoryID . $sortString;
	$result = mysqli_query($con, $query);
	$data = array();
	
	while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
		$row['Image'] = getImage($row['Line'], $row['SKU']);
		$row['Cost'] = moneyFormat(getCustomerPrice($row['Group'], $row['Line'], $row['SKU']) * getPricePlanCalculatedRate($_SESSION['AccountNumber']));
		array_push($data, $row);
	}
	echo json_encode($data);	
	
}
function getCatalogItemInfo($ID, $return = false) {
	global $con;
	$isAdmin = $_SESSION['isAdmin'];
	if (!$isAdmin) {
		return false;
	}
	$query = "SELECT * FROM `CATALOG_DETAIL` WHERE `id` = '$ID'";
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result, MYSQL_ASSOC);
	$row['Image'] = getImage($row['Line'], $row['SKU'],true);
	if ($return) {
		return $row;
	}else {
		echo json_encode($row);	
	}
	
}

function saveCatalogItemInfo($CatalogData) {
	global $con;
	$isNew = $CatalogData['IsNew'];
	$isAdmin = $_SESSION['isAdmin'];
	$result = false;
	if (isset($CatalogData['CategoryID'])) {
		if($isNew == "1"){
			$query = "INSERT INTO `CATALOG_DETAIL` (`CategoryID`, `Line`, `SKU`) VALUES (" . mysqli_real_escape_string($con, $CatalogData['CategoryID']) . ", '" . mysqli_real_escape_string($con, $CatalogData['Line']) . "', '" . mysqli_real_escape_string($con, $CatalogData['SKU']) . "')";
			event_log($_SESSION['Username'], "INSERT NEW CATALOG ITEM", print_r($CatalogData,true));
		}elseif ($isNew == "0") {
			
			
		}
		$result = mysqli_query($con, $query);
	}
	if($result){
		$return['result'] = true;
		$return['query'] = $query;
		echo json_encode($return);
		
	}else {
		$return['result'] = false;
		$return['query'] = $query;
		$return['error'] = mysqli_error($con);
		echo json_encode($return);
		
	}
	
	
}
function deleteCatalogItem($itemID) {
	global	$con;
	$item = getCatalogItemInfo($itemID, true);
	$query = "DELETE FROM `CATALOG_DETAIL` WHERE `id` = '$itemID'";
	$result = mysqli_query($con, $query);
	$return['result'] = $result;
	$return['query'] = $query;
	event_log($_SESSION['Username'], "DELETE CATEGORY ITEM", "Item: " . print_r($item, true));
			
	echo(json_encode($return));
}

function getCatalogCategoryInfo($ID, $return = false) {
	global $con;
	$isAdmin = $_SESSION['isAdmin'];
	if (!$isAdmin) {
		return false;
	}
	$query = "SELECT * FROM `CATALOG_CATEGORY` WHERE `CatalogID` = '$ID'";
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result, MYSQL_ASSOC);
	if ($return) {
		return $row;
	}else {
		echo json_encode($row);	
	}
	

}
function saveCatalogCategoryInfo($CatalogCategoryData) {
	global $con;
	$isNew = $CatalogCategoryData['IsNew'];
	$isAdmin = $_SESSION['isAdmin'];
	if($isNew == "1"){
		$query = "INSERT INTO `CATALOG_CATEGORY` (`Name`, `NameEN`, `Sort`) VALUES ('" . mysqli_real_escape_string($con, $CatalogCategoryData['Name']) . "', '" . mysqli_real_escape_string($con, $CatalogCategoryData['NameEN']) . "', '" . $CatalogCategoryData['Sort'] . "')";
		event_log($_SESSION['Username'], "INSERT NEW CATALOG CATEGORY", print_r($CatalogCategoryData,true));
	}elseif ($isNew == "0") {
		$query = "UPDATE `CATALOG_CATEGORY` SET `NameEN` = '" . mysqli_real_escape_string($con, $CatalogCategoryData['NameEN']) . "', `Name` =  '" . mysqli_real_escape_string($con, $CatalogCategoryData['Name']) . "', `Sort` = '" . mysqli_real_escape_string($con, $CatalogCategoryData['Sort']) . "' WHERE `CatalogID` = '" . mysqli_real_escape_string($con, $CatalogCategoryData['CategoryID']) . "'";
		event_log($_SESSION['Username'], "UPDATE CATALOG CATEGORY", print_r($CatalogCategoryData,true));
	}
	$result = mysqli_query($con, $query);
	if($result){
		$return['result'] = true;
		$return['query'] = $query;
		if ($isNew == "1") {
			$return['ID'] = mysqli_insert_id($con);	
		}
		echo json_encode($return);
		
	}else {
		$return['result'] = false;
		$return['query'] = $query;
		$return['error'] = mysqli_error($con);
		echo json_encode($return);	
	}
}
function deleteCatalogCategory($ID) {
	global	$con;
	$catalogCategory = getCatalogCategoryInfo($ID, true);
	$query = "DELETE FROM `CATALOG_CATEGORY` WHERE `CatalogID` = $ID";
	
	$result = mysqli_query($con, $query);
	$return['result'] = $result;
	$return['query'] = $query;
	event_log($_SESSION['Username'], "DELETE CATALOG CATEGORY", "Price List: " . print_r($catalogCategory, true));
			
	echo(json_encode($return));
}
function deleteProductImage($line, $sku) {
	$isAdmin = $_SESSION['isAdmin'];
	if ($isAdmin) {
		
		event_log($_SESSION['Username'], "DELETE CATALOG IMAGE", "Line: " . $line . "\n" . "SKU: " . $sku);
	}
	
}
function getCustomerPrice($Group, $Line, $SKU, $accountNumber = null) {
	global $con;
	$price = 999999.99;
	$query = "SELECT * FROM INVENTORY WHERE `Group` = '$Group' AND `Line` = '$Line' AND `SKU` = '$SKU'";
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result);
	$isCustomer = isset($_SESSION['isCustomer'])?$_SESSION['isCustomer']:false;	
	$priceLevel = "X";
	if ($isCustomer) {
		$customer = new Customer($_SESSION['AccountNumber']);
		$priceLevel = $customer->PriceLevel;
	}elseif (isset($_SESSION['setCustomerMode']) && $_SESSION['setCustomerMode']) {
		$customer = new Customer($_SESSION['setCustomer']);
		$priceLevel = $customer->PriceLevel;
	} elseif ($accountNumber != null) {
		$customer = new Customer($accountNumber);
		$priceLevel = $customer->PriceLevel;
	}
	switch ($priceLevel) {
		case "X":
			$price = $row['Cost'];		
			break;
		case "F":
			$price = $row['PriceA'];		
			break;							
		case "C":
			$price = $row['PriceB'];		
			break;							
		case "G":
			$price = $row['PriceC'];		
			break;							
		default:
			$price = $row['Cost'];		
			break;								
	}	
	return $price;
}
function setCustomer($accountNumber) {
	if (!$_SESSION['isCustomer']) {
		$_SESSION['setCustomerMode'] = true;
		$_SESSION['setCustomer'] = $accountNumber;
		$result['result'] = true;
		echo json_encode($result);
	}else {
		$result['result'] = false;
		echo json_encode($result);
	}
}
function clearSetCustomer() {
	//echo("loool");
	//var_dump($_SESSION);
	if (!$_SESSION['isCustomer']) {
		$_SESSION['setCustomerMode'] = false;
		$_SESSION['setCustomer'] = "";
		$result['result'] = true;
		echo json_encode($result);
	}else {
		$result['result'] = false;
		echo json_encode($result);
	}
}
function catalogItemExists($line, $sku) {
	global $con;
	$query = "SELECT Name, SKU, Line FROM CATALOG_DETAIL, CATALOG_CATEGORY WHERE `SKU` = '$sku' AND `Line` = '$line' AND CATALOG_CATEGORY.CatalogID = CATALOG_DETAIL.CategoryID";
	$result = mysqli_query($con, $query);
	$return = array();
	$return['rowCount'] = mysqli_num_rows($result);
	$return['rows'] = array();
	if (mysqli_num_rows($result) > 0) {
		while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
			array_push($return['rows'], $row);
		}	
	}
	echo(json_encode($return));
}
function setPickupStatus($action, $pickupID, $value, $notes = "") {
	global $con;
	$isAdmin = $_SESSION['isAdmin'];
	if (!$isAdmin) {
			return false;
	}
	if ($action == "pickup") {
		$query = "UPDATE PICKUP_HEAD SET ToPickup = '$value', ToPickupUser = '" . $_SESSION['Username'] . "' WHERE PickupID = $pickupID";
		$result = mysqli_query($con, $query);
		event_log($_SESSION['Username'], "SEND TO PICKUP", "PickupID: $pickupID.\nDate: $value");
		if ($result) {
			$return['result'] = true;
			echo json_encode($return);
		}else {
			$return['result'] = false;
			$return['error'] = mysqli_error($con);
			echo json_encode($return);			
		}
		return $result;
	}else if ($action == "warehouse"){
		$query = "UPDATE PICKUP_HEAD SET AtWarehouse = '$value', AtWarehouseNotes = '$notes', AtWarehouseUser = '" . $_SESSION['Username'] . "' WHERE PickupID = $pickupID";
		event_log($_SESSION['Username'], "SET PICKUP AT WAREHOUSE", "PickupID: $pickupID.\nDate: $value\nNotes: $notes");
		$result = mysqli_query($con, $query);
		if ($result) {
			$return['result'] = true;
			echo json_encode($return);
		}else {
			$return['result'] = false;
			$return['error'] = mysqli_error($con);
			echo json_encode($return);			
		}
		return $result;
	}else if ($action == "status"){
		$query = "UPDATE PICKUP_HEAD SET PickupStatus = '$value', PickupStatusNotes = '$notes', PickupStatusUser = '" . $_SESSION['Username'] . "' WHERE PickupID = $pickupID";
		event_log($_SESSION['Username'], "SET PICKUP FINAL STATUS", "PickupID: $pickupID.\nStatus: $value\nNotes: $notes");
		$result = mysqli_query($con, $query);
		if ($result) {
			$return['result'] = true;
			echo json_encode($return);
		}else {
			$return['result'] = false;
			$return['error'] = mysqli_error($con);
			echo json_encode($return);			
		}
		return $result;
	}
	
}
function getPickupStatusInfo($action, $pickupID) {
	global	$con;
	switch ($action) {
		case "pickup":
			$query = "SELECT ToPickup, ToPickupUser, FullName FROM PICKUP_HEAD, ADMINISTRATOR WHERE PickupID = $pickupID AND Username = ToPickupUser";
			$result = mysqli_query($con, $query);
			$row = mysqli_fetch_array($result);
			$row['ToPickup'] = date("m/d/Y g:i a",strtotime($row['ToPickup']));
			echo json_encode($row);			
			break;
		case "warehouse":
			$query = "SELECT AtWarehouse, AtWarehouseUser, AtWarehouseNotes, FullName FROM PICKUP_HEAD, ADMINISTRATOR WHERE PickupID = $pickupID AND Username = AtWarehouseUser";
			$result = mysqli_query($con, $query);
			$row = mysqli_fetch_array($result);
			$row['AtWarehouse'] = date("m/d/Y g:i a",strtotime($row['AtWarehouse']));
			echo json_encode($row);			
			break;
		case "status":
			$query = "SELECT PickupStatus, PickupStatusUser, AtWarehouseNotes, PickupStatusNotes, FullName FROM PICKUP_HEAD, ADMINISTRATOR WHERE PickupID = $pickupID AND Username = PickupStatusUser";
			$result = mysqli_query($con, $query);
			$row = mysqli_fetch_array($result);
			echo json_encode($row);			
			break;
	}
}
function savePickupStatusNotes($action, $pickupID, $notes) {
	global $con;
	$field = "";
	switch ($action) {
		case "warehouse":
			$field = "AtWarehouseNotes";
			$name = "AT WAREHOUSE NOTES";
			break;
		case "status":
			$field = "PickupStatusNotes";
			$name = "STATUS NOTES";
			break;
	}
	$query = "SELECT `$field` FROM PICKUP_HEAD WHERE PickupID = $pickupID";
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result);
	$oldNotes = $row[$field];
	$query = "UPDATE PICKUP_HEAD SET `$field` = '$notes' WHERE PickupID = $pickupID";
	
	event_log($_SESSION['Username'], "UPDATE PICKUP $name", "PickupID: $pickupID.\nOriginal Text: $oldNotes\nNew Text: $notes");
	$result = mysqli_query($con, $query);
	if ($result) {
		echo("true");
	}else {
		echo("false");
	}
	
}
function getOrderDetails($orderID) {
	global $con;
	$order = new Order($orderID);
	$order->Customer = $order->Customer->AccountNumber;
	$order->Salesman = $order->Salesman->ID;
	echo json_encode($order);
}
function saveOrderDetail($data) {
	global $con;
	$items = $data["Items"];
	$log = "Order ID: " . $data['OrderID'] . "\n";
	$log .= "Items with Changes: \n";
	$result = true;
	foreach ($items as $item) {
		$query = "UPDATE ORDER_DETAIL SET OrderQty = " . $item["NewQty"] . " WHERE ID = " . $item["ID"] . " AND OrderID = " . $data['OrderID'] . " AND OrderQty = " . $item['OriginalQty'] . ";";
		//echo $query . "\n";
		$result = $result && mysqli_query($con, $query);
		$log .= $item['ItemKey'] . " -->  Original Qty: " . $item['OriginalQty'] . " | " . "New Qty: " . $item["NewQty"] . "\n";
		
	}
	if($result)
	echo "true";
	event_log($_SESSION['Username'], "UPDATE ORDER #" . $data['OrderID'] . " ITEMS QTY", $log);
	//echo "Log Entry: \n" . $log;

}
function getOrderHistory($customer, $line, $sku){
	global $con;
	$query = "SELECT ORDER_DETAIL.*,ORDER_HEAD.* FROM ORDER_DETAIL, ORDER_HEAD WHERE ORDER_HEAD.OrderID = ORDER_DETAIL.OrderID AND AccountNumber LIKE '$customer' AND SKU LIKE '$sku' AND `Line` LIKE '$line'";
	$result = mysqli_query($con, $query);
	$data = array();
	while($row = mysqli_fetch_array($result)){
		$orderID = $row['OrderID'];
		$orderDate = $row['OrderDate'];
		$orderQty = $row['OrderQty'];
		$orderPrice = $row['Cost'];
		$item = array();
		$item['ID'] = $orderID;
		$item['Date'] = $orderDate;
		$item['Qty'] = $orderQty;
		$item['Price'] = $orderPrice;
		$item['InvoiceNumber'] = getInvoiceNumber($orderID,true);
		
		array_push($data,$item);
	}
	echo json_encode($data);
}
function getInvoiceNumber($orderNumber, $return = false){
	global $con;
	$query = "SELECT InvoiceNumber FROM PAYMENT_HEAD, PAYMENT_DETAIL, ORDER_HEAD WHERE ORDER_HEAD.OrderID = $orderNumber AND PAYMENT_HEAD.ID = PaymentID AND PAYMENT_HEAD.AccountNumber = ORDER_HEAD.AccountNumber AND (Reference LIKE '$orderNumber%' OR Reference LIKE '%/$orderNumber%')";
	$query2 = "SELECT InvoiceNumber FROM INVOICE, ORDER_HEAD WHERE ORDER_HEAD.OrderID = $orderNumber AND ORDER_HEAD.AccountNumber = INVOICE.AccountNumber AND (Reference LIKE '$orderNumber%' OR Reference LIKE '%/$orderNumber%')";
	$query3 = $query . " UNION " . $query2;
	$result = mysqli_query($con, $query3);
	$row = mysqli_fetch_array($result);
	if($return){
		return $row['InvoiceNumber'];
	}else{
		//echo $query3;
		echo $row['InvoiceNumber'];
	}
}
function runBetweenDateRange($FromDateObject, $ToDateObject){
	$now = new DateTime("now", new DateTimeZone("America/Puerto_Rico"));
	if($now >= 	$FromDateObject && $now <= $ToDateObject){
		return true;
	}else{
		return false;
	}
}
function getBuyersGuideDefinition($DefinitionID){
	global $con;
	$query = "SELECT * FROM BUYERS_GUIDE_DEFINITIONS WHERE ID = " . $DefinitionID;
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result);
	$data['data'] = $row;
	$data['error'] = mysqli_error($con);
	echo json_encode($data);
}
function saveBuyersGuideDefinition($DefinitionData){
	global $con;
	$isNew = $DefinitionData['IsNew'];
	if($isNew){
		$query = "INSERT INTO BUYERS_GUIDE_DEFINITIONS (`Line`, `Group`, `Type`, `CatalogID`, `Suppliers`) VALUES ('" . $DefinitionData['Line'] . "','" . $DefinitionData['Group'] . "','" . $DefinitionData['Type'] . "','" . $DefinitionData['CatalogID'] . "','" . $DefinitionData['Suppliers'] . "');";
	}else{
		$query = "UPDATE BUYERS_GUIDE_DEFINITIONS SET `Line` = '" . $DefinitionData['Line'] . "',  `Group` = '" . $DefinitionData['Group'] . "', `Type` = '" . $DefinitionData['Type'] . "', `CatalogID` = '" . $DefinitionData['CatalogID'] . "', `Suppliers` = '" . $DefinitionData['Suppliers'] . "' WHERE `ID` = " . $DefinitionData['ID'] . ";";
		
	}
	$result = mysqli_query($con, $query);
	if($result){
		$data['result'] = true;
		echo json_encode($data);
	}else{
		$data['result'] = false;
		$data['error'] = mysqli_error($con);
		$data['query'] = $query;
		echo json_encode($data);
	}
	
}
function deleteBuyersGuideDefinition($DefinitionID){
	global $con;
	$query = "DELETE FROM BUYERS_GUIDE_DEFINITIONS WHERE ID = " . $DefinitionID;
	if(mysqli_query($con, $query)){
		$data['result'] = true;
	}else{
		$data['result'] = false;
		$data['error'] = mysqli_error($con);
		$data['query'] = $query;
	}
	echo json_encode($data);
}
function getSetting($setting){
	global $con;
	
	$query = "SELECT * FROM SETTING WHERE SettingName LIKE '$setting'";
	$return['result'] = mysqli_query($con,$query);
	$return['value'] = mysqli_fetch_array($return['result'],MYSQLI_ASSOC);
	return $return;
}
function setSetting($setting, $value){
	global $con;
	$query = "INSERT INTO SETTING (SettingName,`Value`) VALUES ('" . mysqli_real_escape_string($con, $setting) . "','" . mysqli_real_escape_string($con, $value) . "') ON DUPLICATE KEY UPDATE `Value`='" . mysqli_real_escape_string($con, $value) . "';";
	//$query = "SELECT * FROM SETTING WHERE SettingName LIKE '$setting'";
	$return['result'] = mysqli_query($con,$query);
}

function LoginLog($Type, $Username, $Result){
	global $con;
	if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
		$forwared = $_SERVER['HTTP_X_FORWARDED_FOR'];
	}else{
		$forwared = '';
	}
	$query = "INSERT INTO LOGIN_LOG (`Type`, `Username`, `IPAddress`,`ForwardIP`, `LoginDate`, `Result`) VALUES ('$Type', '" . mysqli_real_escape_string($con, $Username) . "', '" . $_SERVER['REMOTE_ADDR'] . "', '" . $forwared . "', DATE_ADD(NOW(), INTERVAL -4 HOUR), '$Result');";
	$result = mysqli_query($con, $query);
}

function file_get_contents_curl($url){
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_HEADER, false);
	$data = curl_exec($curl);
	curl_close($curl);
	return $data;
}
function file_post_contents($url,$fields = array()) {
    //extract data from the post
	//set POST variables
	//$url = 'http://domain.com/get-post.php';
	
	
	
	foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
	rtrim($fields_string, '&');
	
	//open connection
	$ch = curl_init();
	
	//set the url, number of POST vars, POST data
	curl_setopt($ch,CURLOPT_URL, $url);
	curl_setopt($ch,CURLOPT_POST, count($fields));
	curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	curl_setopt($ch, CURLOPT_MAXREDIRS, 4);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
	
	//execute post
	$result = curl_exec($ch);
	
	//close connection
	curl_close($ch);
	return ($result);
}
function setUpdateData(){
	global $con;
	if($_SESSION['isCustomer']){
		$query = "INSERT INTO CUSTOMER_UPDATE (AccountNumber, UpdateDate) VALUES ('" . $_SESSION['AccountNumber'] . "', DATE_ADD(NOW(), INTERVAL -4 HOUR))";	
	}else{
		$query = "INSERT INTO CUSTOMER_UPDATE (AccountNumber, UpdateDate) VALUES ('" . $_SESSION['SalesmanID'] . "', DATE_ADD(NOW(), INTERVAL -4 HOUR))";	
		
	}
	
	if(mysqli_query($con, $query)){
		echo "true";
	}else{
		echo "false";
	}
}


?>