<?php
//die("Don't panic, this is a test.");
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']);
			$warrantyReason = mysqli_real_escape_string($con, $_REQUEST['warrantyReason']);
			savePickupLine($line, $sku, $qty, $invoiceNumber, $orderID,$reason, $warrantyReason);
			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;
		case "getWarrantyReasonInfo":
			$Code = $_REQUEST['reasonCode'];
			getWarrantyReasonInfo($Code);
			break;
		case "saveWarrantyReasonInfo":
			saveWarrantyReasonInfo($_REQUEST);
			break;
		case "deleteWarrantyReason":
			$Code = mysqli_real_escape_string($con, $_REQUEST['reasonCode']);
			deleteWarrantyReason($Code);
			break;		
		case "getPromoGroupData":
			getPromoGroupData($_REQUEST['group']);
			break;
		case "exportOfflineData":
			exportOfflineData($_REQUEST['sm']);
			break;
		case "getProductDetails":
			getProductDetails($_REQUEST['line'], $_REQUEST['sku']);
			break;
		case "getGroupsByLine":
			getGroupsByLine($_REQUEST['line']);
			break;
		case "getLinesByGroup":
			getLinesByGroup($_REQUEST['group']);
			break;
		case "saveToSession":
			saveToSession($_REQUEST['key'], $_REQUEST['data']);
			break;
		case "getDataFromSession":
			echo json_encode(getDataFromSession($_REQUEST['key']));
			break;
		case "deleteDataFromServer":
			deleteDataFromServer($_REQUEST['key']);
			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){
	AddCartLogEntry("ADD ITEM", $Group, $Line, $SKU, $Qty);
	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);
		
		echo getCartTotal();
		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 = "Price";
		//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 = "Price";
		//	}
		//}
		//
		//$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'];
		//}
		echo getCartTotal();
		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 . "WestingPR");
	$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 = $estimate->Customer->Salesman->Email;
		$bcc = "";
		if($customerEmail != "" && $customer->SendOrderEmail){
			$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: " . $estimate->Customer->Salesman->Email . "\r\n";
		$customerEmail = $estimate->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 = $estimate->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 {}
		$customerEmail = $estimate->Customer->Email;
		try {
		
			if($customerEmail != ""){
			
				$to = explode(",",$customerEmail);
				foreach($to as $email){
					$mail->addCC($email);	
				}
				
			}else{
				
			}
		
		
		$mail->isMail();
		$mail->addReplyTo($config['FromEmail']);
		$mail->From       = $config['FromEmail'];
		$mail->FromName   = $config['FromEmailName'];
		
		
		
		/*
		if ($estimate->Customer->Salesman->Email != "" || $estimate->Customer->Salesman->Email != null) {
			$mail->addCC($estimate->Customer->Salesman->Email);	
		}
		*/
		$customerEmail = $order->Customer->Email;
		if($customerEmail != "" && $customer->SendOrderEmail){
			//$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 />
		    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 = '';
		$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 sendEstimate($estimateID) {
	global $config;
	global $root;
	$estimate = new Estimate($estimateID);
	
	$subject = "New Estimate #$estimateID";
	$key = md5($estimateID . "WestingPR");
	$key = substr($key, -16);
	
	$pdf = false;
	if ($pdf) {
		//
		system('./wkhtmltopdf-amd64 "' . $root . 'webConfirmation.php?order=' . $estimateID . '&key=' . $key . '" "./tmp/' . $estimateID . '.pdf"', $systemResult);
		$message = "Nueva orden de compra para $name \r\n Adjunto copia de la confirmacion de la orden.";
		$cc = $estimate->Customer->Salesman->Email;
		$bcc = "";
		if($customerEmail != "" && $customer->SendOrderEmail){
			$bcc = $customerEmail;
		}
		$result = mail_attachment($estimateID . '.pdf', "./tmp/", $to, $config['FromEmail'], $config['FromEmailName'], $config['FromEmail'], $subject, $message, $cc, $bcc);
		if (!$result) {
			error_log("Error al enviar email de orden #$estimateID \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 {}
		$customerEmail = $estimate->Customer->Email;
		try {
			if($customerEmail != ""){
			
				$to = explode(",",$customerEmail);
				foreach($to as $email){
					$mail->addCC($email);	
				}
				
			}else{
				//$to = $config['EstimateEmail'];
				//$mail->addAddress($to);
			}
		
		
		$mail->isMail();
		
		$mail->addReplyTo($config['FromEmail']);
		$mail->From       = $config['FromEmail'];
		$mail->FromName   = $config['FromEmailName'];
		
		
		
		//error_log(print_r($estimate,true));
		if ($estimate->Salesman->Email != "" || $estimate->Salesman->Email != null) {
			$mail->addCC($estimate->Salesman->Email);	
		}
		
		
		
		$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>New Estimate for ' . $estimate->Customer->Name . ' <br />
		    Notes: ' . $estimate->EstimateNotes . '<br /> 
		    <a href="' . $root . 'viewEstimate.php?id=' . $estimateID . '&key=' . $key . '">View Estimate #' . $estimateID . '</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 = 'westingpr.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";
		  var_dump($results_messages);
		  return $results_messages;
		}
		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 = "Price";
		switch ($customer->PriceLevel) {
			case "F":
				$column = "PriceA";
				break;
			case "C":
				$column = "PriceB";
				break;
			case "G":
				$column = "PriceC";
				break;
			default:
				$column = "Price";
		}
		$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 = "Price";
		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 = "Price";
			}
		}
		$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 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 = "PriceA";
		switch ($customer->PriceLevel) {
			case "A":
				$column = "PriceA";
				break;
			case "B":
				$column = "PriceB";
				break;
			case "C":
				$column = "PriceC";
				break;
			case "D":
				$column = "PriceD";
				break;
			case "E":
				$column = "PriceE";
				break;
			default:
				$column = "PriceA";
		}
		//$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 . "'";	
		$query = "SELECT INVENTORY.`Group`, SHOPPING_CART.`Line`, INVENTORY.`SKU`, SHOPPING_CART.Qty as OrderQty, ROUND($column * $priceRate, 2) as Price,SHOPPING_CART.Qty * Core as Core 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 . "'";
		//
		$cartTotal = 0;
		$result = mysqli_query($con, $query);
		while($row = mysqli_fetch_array($result)){
			//var_dump($row['Group']);
			//var_dump($row['SKU']);
			//var_dump($row['Line']);
			$row['Price'] = round(getCustomerPrice($row['Group'], $row['Line'], $row['SKU']) * $priceRate, 2);
			
			$row = updateQtyBreaks($row);
			
			$cartTotal += $row['Price']*$row['OrderQty'] + $row['Core'];
		}
		
		return $cartTotal;
	}else{
		if ($_SESSION['pricePlanMode']) {
			$priceRate = getPricePlanCalculatedRate($_SESSION['AccountNumber']);	
		}else {
			$priceRate = 1;
		}
		
		$salesman = new Salesman($_SESSION['SalesmanID']);
		$column = "PriceA";
		if (isset($_SESSION['setCustomerMode']) && $_SESSION['setCustomerMode']) {
			$customer = new Customer($_SESSION['setCustomer']);
			switch ($customer->PriceLevel) {
				case "A":
					$column = "PriceA";
					break;
				case "B":
					$column = "PriceB";
					break;
				case "C":
					$column = "PriceC";
					break;
				case "D":
					$column = "PriceD";
					break;
				case "E":
					$column = "PriceE";
					break;
				default:
					$column = "PriceA";
			}
		}
		//$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 . "'";
		$query = "SELECT  INVENTORY.`Group`, SHOPPING_CART.`Line`, INVENTORY.`SKU`, SHOPPING_CART.Qty as OrderQty, ROUND($column * $priceRate, 2) as Price,SHOPPING_CART.Qty * Core as Core 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);
		$cartTotal = 0;
		$result = mysqli_query($con, $query);
		while($row = mysqli_fetch_array($result)){
			$row['Price'] = round(getCustomerPrice($row['Group'], $row['Line'], $row['SKU']) * $priceRate, 2);
			$row = updateQtyBreaks($row);
			//$row['Price'] = getCustomerPrice($row['Group'], $row['Line'], $row['SKU']);
			$cartTotal += $row['Price']*$row['OrderQty'] + $row['Core'];
		}
		
		return $cartTotal;
	}
}
function updateCartItem($ID, $Qty) {
	AddCartLogEntryByID("UPDATE", $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 safe_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`,
			`SendOrderEmail`,
			`Address1`,
			`Address2`,
			`State`,
			`ZipCode`,
			`ShipToAddress1`,
			`ShipToAddress2`,
			`ShipToState`,
			`ShipToZip`) 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']) . "',
		" . $CustomerData['SendOrderEmail'] . ",
		'" . mysqli_real_escape_string($con, $CustomerData['Address1']) . "',
		'" . mysqli_real_escape_string($con, $CustomerData['Address2']) . "',
		'" . mysqli_real_escape_string($con, $CustomerData['State']) . "',
		'" . mysqli_real_escape_string($con, $CustomerData['ZipCode']) . "',
		'" . mysqli_real_escape_string($con, $CustomerData['ShipToAddress1']) . "',
		'" . mysqli_real_escape_string($con, $CustomerData['ShipToAddress2']) . "',
		'" . mysqli_real_escape_string($con, $CustomerData['ShipToState']) . "',
		'" . mysqli_real_escape_string($con, $CustomerData['ShipToZip']) . "')";	
		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']},
				`Terms` = '{$CustomerData['CustomerTerms']}',
				`Comments` = '" . mysqli_real_escape_string($con, $CustomerData['Comments']) . "',
				`SendOrderEmail` = " . $CustomerData['SendOrderEmail'] . ",
				`Address1` = '" . mysqli_real_escape_string($con, $CustomerData['Address1']) . "',
				`Address2` = '" . mysqli_real_escape_string($con, $CustomerData['Address2']) . "',
				`State` = '" . mysqli_real_escape_string($con, $CustomerData['State']) . "',
				`ZipCode` = '" . mysqli_real_escape_string($con, $CustomerData['ZipCode']) . "',
				
				`ShipToAddress1` = '" . mysqli_real_escape_string($con, $CustomerData['CustomerShipToAddress1']) . "',
				`ShipToAddress2` = '" . mysqli_real_escape_string($con, $CustomerData['CustomerShipToAddress2']) . "',
				`ShipToCity` = '" . mysqli_real_escape_string($con, $CustomerData['CustomerShipToCity']) . "',
				`ShipToState` = '" . mysqli_real_escape_string($con, $CustomerData['CustomerShipToState']) . "',
				`ShipToZip` = '" . mysqli_real_escape_string($con, $CustomerData['CustomerShipToZip']) . "',
				`TaxID1` = '" . mysqli_real_escape_string($con, $CustomerData['CustomerTaxID1']) . "',
				`TaxIDExpiration1` = '" . mysqli_real_escape_string($con, $CustomerData['CustomerTaxID1Expiration']) . "',
				`TaxID2` = '" . mysqli_real_escape_string($con, $CustomerData['CustomerTaxID2']) . "',
				`TaxIDExpiration2` = '" . mysqli_real_escape_string($con, $CustomerData['CustomerTaxID2Expiration']) . "',
				`TaxExempt1` = " . mysqli_real_escape_string($con, $CustomerData['TaxExempt1']) . ",
				`TaxExempt2` = " . mysqli_real_escape_string($con, $CustomerData['TaxExempt2']) . "
				
				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']) . "',
			`SendOrderEmail` = " . $CustomerData['SendOrderEmail'] . ",
			`Address1` = '" . mysqli_real_escape_string($con, $CustomerData['Address1']) . "',
			`Address2` = '" . mysqli_real_escape_string($con, $CustomerData['Address2']) . "',
			`State` = '" . mysqli_real_escape_string($con, $CustomerData['State']) . "',
			`ZipCode` = '" . mysqli_real_escape_string($con, $CustomerData['ZipCode']) . "',
			`ShipToAddress1` = '" . mysqli_real_escape_string($con, $CustomerData['CustomerShipToAddress1']) . "',
			`ShipToAddress2` = '" . mysqli_real_escape_string($con, $CustomerData['CustomerShipToAddress2']) . "',
			`ShipToCity` = '" . mysqli_real_escape_string($con, $CustomerData['CustomerShipToCity']) . "',
			`ShipToState` = '" . mysqli_real_escape_string($con, $CustomerData['CustomerShipToState']) . "',
			`ShipToZip` = '" . mysqli_real_escape_string($con, $CustomerData['CustomerShipToZip']) . "',
			`TaxID1` = '" . mysqli_real_escape_string($con, $CustomerData['CustomerTaxID1']) . "',
			`TaxIDExpiration1` = '" . mysqli_real_escape_string($con, $CustomerData['CustomerTaxID1Expiration']) . "',
			`TaxID2` = '" . mysqli_real_escape_string($con, $CustomerData['CustomerTaxID2']) . "',
			`TaxIDExpiration2` = '" . mysqli_real_escape_string($con, $CustomerData['CustomerTaxID2Expiration']) . "',
			`TaxExempt1` = " . mysqli_real_escape_string($con, $CustomerData['TaxExempt1']) . ",
				`TaxExempt2` = " . mysqli_real_escape_string($con, $CustomerData['TaxExempt2']) . "

			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, Phone, Password) VALUES ('{$SalesmanData['ID']}', '{$SalesmanData['Name']}', '{$SalesmanData['Username']}', '{$SalesmanData['Email']}', '{$SalesmanData['Phone']}', '" . 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']}', Phone = '{$SalesmanData['Phone']}' WHERE ID = '{$SalesmanData['ID']}'";
		} else {
			$query = "UPDATE SALESMAN SET `FullName` = '{$SalesmanData['Name']}', `Username` = '{$SalesmanData['Username']}', Email = '{$SalesmanData['Email']}', Phone = '{$SalesmanData['Phone']}', `Password` = '" . md5($SalesmanData['Password']) . "' WHERE ID = '{$SalesmanData['ID']}'";
		}
		///echo $query;
		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) {
	AddCartLogEntryByID("DELETE", $ID, 0);
	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;
//}
function CSVExport($query, $filename) {
	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
    $file = fopen($filename, "w");

    //header("Content-type:text/octect-stream");
    //header("Content-Disposition:attachment;filename=data.csv");
    while($row = mysqli_fetch_row($sql_csv)) {
		$file_row = (implode('","',array_map(addslashes,$row)));
		fwrite($file, '"' . $file_row . "\"\n");
        
    }
	

    return fclose($file);
}

//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);
	$query = "UPDATE INVOICE SET Reference = CONCAT(Reference, '/KYB') WHERE (InvoiceNumber = '732917' OR InvoiceNumber = '732913') AND Reference NOT LIKE '%KYB%'";
	mysqli_query($con, $query);
    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 = "Saludos, Usted pidio cambiar su contraseña. Por favor haga click en el siguiente enlace para crear una nueva. Gracias. \n
			$root"."resetpassword.php?key=$key";
			if(mail($row['Email'], "Reset Password" , $message, "From: " . $config['FromEmailName'] . " <" . $config['FromEmail'] . ">")){
				$result['result'] = true;
				$result['email'] = $row['Email'];
				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'] = "No se encontro una cuenta con ese numero o no tiene un email asociado. Favor de llamar a la oficina o a su vendedor.";
		$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 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, $warrantyReason = "") {
	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`, `WarrantyReason`) VALUES ('{$salesman->ID}', '" . $line . "', '" . $sku . "', '" . $qty . "', '$orderNumber', '" . $invoiceNumber . "', '" . $reason . "', '" . $warrantyReason . "')";
	$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);
	}
}
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 = '';
		$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;
	
	mysqli_set_charset($con, "utf8");
	$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;
	if(isset($_REQUEST['debug'])){
		echo $query;
	}
	$result = mysqli_query($con, $query);
	$data = array();
	
	while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
		
		$_SESSION['AccountNumber'] = isset($_SESSION['AccountNumber'])?$_SESSION['AccountNumber']:null;
		$row['Price'] = moneyFormat($row['Price'] * getPricePlanCalculatedRate($_SESSION['AccountNumber']));
		$row['Image'] = hasImage($row['Line'], $row['SKU'])?getImage($row['Line'], $row['SKU']):false;
		$row['Description'] = mysqli_real_escape_string($con, $row['Description']);
		array_push($data, $row);
	}
	if(isset($_REQUEST['tesing'])){
		foreach ($data as $string) {
			//echo 'Decoding: ' . $string;
			echo json_encode($data);
		
			switch (json_last_error()) {
				case JSON_ERROR_NONE:
					echo ' - No errors';
				break;
				case JSON_ERROR_DEPTH:
					echo ' - Maximum stack depth exceeded';
				break;
				case JSON_ERROR_STATE_MISMATCH:
					echo ' - Underflow or the modes mismatch';
				break;
				case JSON_ERROR_CTRL_CHAR:
					echo ' - Unexpected control character found';
				break;
				case JSON_ERROR_SYNTAX:
					echo ' - Syntax error, malformed JSON';
				break;
				case JSON_ERROR_UTF8:
					echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
				break;
				default:
					echo ' - Unknown error';
				break;
			}
		
			echo PHP_EOL;
		}
		
	}
	
	
	
	echo json_encode($data);	
	//echo $query;
}
function getPromoGroupData($Group) {
	global $con;
	
	mysqli_set_charset($con, "utf8");
	$isCustomer = $_SESSION['isCustomer'];
	if($isCustomer){
		$accountNumber = ($_SESSION['AccountNumber']);
	} else {
		$accountNumber = $_SESSION['SalesmanID'];
	}
	$sort = array();
	//$query = "SELECT * FROM INVENTORY WHERE Line = 'KOR' AND `Group` LIKE '" . $Group. "'";
	//$result = mysqli_query($con, $query);	
	
	
	$query = "SELECT INVENTORY.*, SHOPPING_CART.Qty AS OnOrder FROM 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 INVENTORY.Line = 'KOR' AND INVENTORY.`Group` LIKE '" . $Group . "' AND INVENTORY.Qty > 0";
	if(isset($_REQUEST['debug'])){
		echo $query;
	}
	$result = mysqli_query($con, $query);
	$data = array();
	
	while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
		
		$_SESSION['AccountNumber'] = isset($_SESSION['AccountNumber'])?$_SESSION['AccountNumber']:null;
		$row['Price'] = moneyFormat($row['PriceA'] * getPricePlanCalculatedRate($_SESSION['AccountNumber']));
		$row['Image'] = hasImage($row['Line'], $row['SKU'])?getImage($row['Line'], $row['SKU']):false;
		$row['Description'] = mysqli_real_escape_string($con, $row['Description']);
		array_push($data, $row);
	}
	if(isset($_REQUEST['tesing'])){
		foreach ($data as $string) {
			//echo 'Decoding: ' . $string;
			echo json_encode($data);
		
			switch (json_last_error()) {
				case JSON_ERROR_NONE:
					echo ' - No errors';
				break;
				case JSON_ERROR_DEPTH:
					echo ' - Maximum stack depth exceeded';
				break;
				case JSON_ERROR_STATE_MISMATCH:
					echo ' - Underflow or the modes mismatch';
				break;
				case JSON_ERROR_CTRL_CHAR:
					echo ' - Unexpected control character found';
				break;
				case JSON_ERROR_SYNTAX:
					echo ' - Syntax error, malformed JSON';
				break;
				case JSON_ERROR_UTF8:
					echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
				break;
				default:
					echo ' - Unknown error';
				break;
			}
		
			echo PHP_EOL;
		}
		
	}
	
	
	
	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.*, Price, 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['Price'] = moneyFormat($row['PriceA'] * 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($prefix . "/img/catalog/" . $line . " " . $sku . ".$value");
		if ($hasImage) {
			return $prefix . "/img/catalog/" . $line . " " . $sku . ".$value?time=" . @filemtime($prefix . "/img/catalog/" . $line . " " . $sku . ".$value");
		}
	}
	global $con;
	$item = new Item(null,$line, $sku);
	if($item->ImageURL){
		return $item->ImageURL;
	}else{
		return $prefix . "/img/no_image_available.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['SortOrder']);
	$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();
	
	//var_dump($query);
	while($row = mysqli_fetch_array($result)) {
		$item = new Item('%', $row['Line'], $row['SKU']);
		$row['Image'] = getImage($row['Line'], $row['SKU']);
		$row['ConfirmedQty'] = $item->ConfirmedQty;
		$row['Price'] = moneyFormat(getCustomerPrice($row['Group'], $row['Line'], $row['SKU']) * getPricePlanCalculatedRate($_SESSION['AccountNumber']));
		array_push($data, $row);
	}
	
	//var_dump($data);
	echo safe_json_encode($data);
	//var_dump(json_last_error());
	
}
function safe_json_encode($value, $options = 0, $depth = 512){
   
	$encoded = json_encode($value, $options, $depth);
	 
    switch (json_last_error()) {
        case JSON_ERROR_NONE:
            return $encoded;
        case JSON_ERROR_DEPTH:
            return 'Maximum stack depth exceeded'; // or trigger_error() or throw new Exception()
        case JSON_ERROR_STATE_MISMATCH:
            return 'Underflow or the modes mismatch'; // or trigger_error() or throw new Exception()
        case JSON_ERROR_CTRL_CHAR:
            return 'Unexpected control character found';
        case JSON_ERROR_SYNTAX:
            return 'Syntax error, malformed JSON'; // or trigger_error() or throw new Exception()
        case JSON_ERROR_UTF8:
			
            $clean = utf8ize($value);
            return safe_json_encode($clean, $options, $depth);
        default:
            return 'Unknown error'; // or trigger_error() or throw new Exception()

    }
}

function utf8ize($mixed) {
	//die( var_dump(is_object($mixed)));
    if (is_array($mixed)) {
        foreach ($mixed as $key => $value) {
            $mixed[$key] = utf8ize($value);
        }
    } else if(is_object($mixed)){
		foreach ($mixed as $key => $value) {
            $mixed->$key = utf8ize($value);
        }
	}else if (is_string ($mixed)) {
        return utf8_encode($mixed);
    }
    return $mixed;
}

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, MYSQLI_ASSOC);
	//var_dump($row);
	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;
	echo $_SESSION['AccountNumber'];
	$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;
	}
	if(!isset($customer)){
		$customer = new stdClass();
		$customer->AccountNumber = "000000";
	}
	switch ($priceLevel) {
		case "A":
			$price = $row['PriceA'];		
			break;
		case "B":
			$price = $row['PriceB'];		
			break;							
		case "C":
			$price = $row['PriceC'];		
			break;							
		case "D":
			$price = $row['PriceD'];		
			break;
		case "E":
			$price = $row['PriceE'];		
			break;							
		default:
			$price = $row['PriceA'];		
			break;								
	}
	
	//check for pricing plan
	$query = "SELECT * FROM PRICE_PLAN_LIST_DEF, PRICE_PLAN_LIST_DETAIL, PRICE_PLAN_LIST_CUSTOMER WHERE PRICE_PLAN_LIST_DEF.id = PRICE_PLAN_LIST_DETAIL.PriceListID AND PRICE_PLAN_LIST_DEF.id = PRICE_PLAN_LIST_CUSTOMER.PriceListID AND PRICE_PLAN_LIST_CUSTOMER.AccountNumber = '" . $customer->AccountNumber . "' AND `Line` = '$Line' AND `SKU` = '$SKU'";
	$result = mysqli_query($con, $query);
	//echo mysqli_num_rows($result);
	//echo $price;
	if(mysqli_num_rows($result) > 0){
		//echo "alert";
		$row = mysqli_fetch_array($result);
		$price = $row['Price'];
	}

	
	return $price;
}
function setCustomer($accountNumber) {
	if (!$_SESSION['isCustomer']) {
		$_SESSION['setCustomerMode'] = true;
		$_SESSION['setCustomer'] = $accountNumber;
		$result['result'] = true;
		//var_dump($accountNumber);
		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);
	$estimate->Customer = $estimate->Customer->AccountNumber;
	$estimate->Salesman = $estimate->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.*, GROUP_CONCAT(PickupID) AS Pickups, SUM(IF(PICKUP_DETAIL.Qty IS NULL, 0, PICKUP_DETAIL.Qty)) as ReturnedQty, PICKUP_DETAIL.SKU, DATEDIFF(NOW(),ORDER_HEAD.OrderDate) as Elapsed FROM (ORDER_DETAIL, ORDER_HEAD) LEFT JOIN PICKUP_DETAIL ON(PICKUP_DETAIL.OrderID = ORDER_HEAD.OrderID AND PICKUP_DETAIL.SKU LIKE ORDER_DETAIL.SKU AND PICKUP_DETAIL.`Line` LIKE ORDER_DETAIL.Line)  WHERE ORDER_HEAD.OrderID = ORDER_DETAIL.OrderID AND AccountNumber LIKE '$customer' AND ORDER_DETAIL.SKU LIKE '$sku' AND ORDER_DETAIL.`Line` LIKE '$line' GROUP BY ORDER_HEAD.OrderID, ORDER_DETAIL.SKU";
	$result = mysqli_query($con, $query);
	$data = array();
	while($row = mysqli_fetch_array($result)){
		$orderID = $row['OrderID'];
		$orderDate = $row['OrderDate'];
		$orderQty = $row['OrderQty'];
		$returnedQty = $row['ReturnedQty'];
		$returnableQty = $orderQty-$returnedQty;
		$orderPrice = $row['Price'];
		$orderElapsed = $row['Elapsed'];
		$item = array();
		$item['ID'] = $orderID;
		$item['Date'] = $orderDate;
		$item['Elapsed'] = $orderElapsed;
		$item['Qty'] = $orderQty;
		$item['ReturnableQty'] = $returnableQty;
		$item['Pickups'] = $row['Pickups'];
		$item['Price'] = $orderPrice;
		$item['InvoiceNumber'] = getInvoiceNumber($orderID . "/" . $line ,true, true);
		
		array_push($data,$item);
	}
	echo json_encode($data);
}
function getInvoiceNumber($orderNumber, $return = false, $multiple = false){
	global $con;
	$line = isset(explode("/", $orderNumber)[1])?explode("/", $orderNumber)[1]:"";
	$orderNumber = explode("/", $orderNumber)[0];
	$subfilter = "";
	if($line == "KYB" || $line == "NIP" || $line == "DHI" ){
		$subfilter = " AND (Reference LIKE '%$line%')";
	}elseif($line != ""){
		$subfilter = " AND (Reference NOT LIKE '%DHI%' AND Reference NOT LIKE '%NIP%' AND Reference NOT LIKE '%KYB%')";
	}
	$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%') $subfilter";
	$query3 = $query . " UNION " . $query2;
	
	$result = mysqli_query($con, $query3);
	$index = 0;
	$multipleInvoice = array();
	
	while($row = mysqli_fetch_array($result)){
		if($index === 0 && !$multiple){
			if($return){
				return $row['InvoiceNumber'];
			}else{
				//echo $query3;
				echo $row['InvoiceNumber'];
			}
		}
		array_push($multipleInvoice,$row['InvoiceNumber']);
		$index++;
	}
	return implode("/",$multipleInvoice);
	
}
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['query']=$query;
	if(mysqli_num_rows($return['result']) == 0){
		die("Setting not found");
	}
	$return['value'] = mysqli_fetch_array($return['result'],MYSQLI_ASSOC)['Value'];
	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";
	}
}
function updateQtyBreaks($cartRow, $QtyBreakArray = null){
	global $con;
	if($QtyBreakArray === null){
		$query = "SELECT * FROM QUANTITY_BREAK WHERE `Active` = True AND `Line` LIKE '" . $cartRow['Line'] . "' AND SKU LIKE '" . $cartRow['SKU'] . "' AND QtyBreak <= " . $cartRow['OrderQty'] . " ORDER BY QtyBreak DESC";
		//echo $query;
		$result = mysqli_query($con, $query);
		//var_dump($query);
		if(mysqli_num_rows($result) > 0){
			$row = mysqli_fetch_array($result);
			$SpQtyBreak = $row['QtyBreak'];
			$SpQtyToAdd = $row['QtyToAdd'];
			if(floor($cartRow['OrderQty']/$SpQtyBreak) >= 1){
				$cartRow['Special'] = True;
			}else{
				$cartRow['Special'] = False;
			}
			$cartRowTotal = $cartRow['Price'] * $cartRow['OrderQty'];
			$cartRow['OrderQty'] += floor($cartRow['OrderQty']/$SpQtyBreak)*$SpQtyToAdd;
			
			//echo "Eli=" . round(100*$cartRow['Price']*(1-$row['DiscountRate']))/100;
			if($cartRow['Special']){
				//$cartRow['Price'] = round(100*$cartRow['Price']*(1-$row['DiscountRate']))/100;
				$cartRow['Price'] = round((100*$cartRowTotal/$cartRow['OrderQty'])*(1-$row['DiscountRate']))/100;	
			}
			
			
			return $cartRow;	
		}else{
			return $cartRow;
		}
	}else{
		$SpQtyBreak = $QtyBreakArray['QtyBreak'];
		$SpQtyToAdd = $QtyBreakArray['QtyToAdd'];
		if(floor($cartRow['OrderQty']/$SpQtyBreak) >= 1){
			$cartRow['Special'] = True;
		}else{
			$cartRow['Special'] = False;
		}
		$cartRowTotal = $cartRow['Price'] * $cartRow['OrderQty'];
		$cartRow['OrderQty'] += floor($cartRow['OrderQty']/$SpQtyBreak)*$SpQtyToAdd;
		//$cartRow['Price'] = round(100*$cartRowTotal/$cartRow['OrderQty'])/100;
		
		if($cartRow['Special']){
			$cartRow['Price'] = round(100*$cartRow['Price']*(1-$row['DiscountRate']))/100;	
		}
		return $cartRow;
	}
}
function isQtyBreakSpecial($Line, $SKU){
	global $con;
	$query = "SELECT * FROM QUANTITY_BREAK WHERE Line = '$Line' AND SKU = '$SKU' AND Active = TRUE;";
	$result = mysqli_query($con, $query);
	
	if(mysqli_num_rows($result) > 0){
		return true;
	}else{
		return false;
	}
}
function getWarrantyReasonText($key) {
	global $con;
	$query = "SELECT `Value` FROM PICKUP_WARRANTY_REASON WHERE `Key` = '$key'";
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result);
	return $row['Value'];
}

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

}
function saveWarrantyReasonInfo($ReasonData) {
	global $con;
	$isNew = $ReasonData['IsNew'];
	$isAdmin = $_SESSION['isAdmin'];
	if($isNew == "1"){
		$query = "INSERT INTO `PICKUP_WARRANTY_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_WARRANTY_REASON` SET `Value` = '" . mysqli_real_escape_string($con, $ReasonData['Value']) . "' WHERE `Key` = '" . mysqli_real_escape_string($con, $ReasonData['Key']) . "'";
		event_log($_SESSION['Username'], "UPDATE WARRANTY 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 deleteWarrantyReason($Key) {
	global	$con;
	$query = "DELETE FROM `PICKUP_WARRANTY_REASON` WHERE `Key` = '$Key'";
	$result = mysqli_query($con, $query);
	$return['result'] = $result;
	$return['query'] = $query;
	event_log($_SESSION['Username'], "DELETE WARRANTY REASON", "Key: $Key");
	echo(json_encode($return));
}
class PriceList {
	public $ID, $Account, $Name, $Items, $Customers;
	function __construct($PriceListId) {
		global $con;
		$query = "SELECT * FROM PRICE_PLAN_LIST_DEF WHERE id = $PriceListId";
		$result = mysqli_query($con, $query);
		$row = mysqli_fetch_array($result);
		$this->ID = $PriceListId;
		$this->Account = $row['AccountNumber'];
		$this->Name = $row['Name'];
		$this->Items = array();
		$query2 = "SELECT * FROM PRICE_PLAN_LIST_DETAIL WHERE priceListID = $PriceListId";
		
		$result2 = mysqli_query($con, $query2);
		while ($row2 = mysqli_fetch_array($result2)) {
					$item = new Item($row2['Group'], $row2['Line'], $row2['SKU'], $PriceListId);
					array_push($this->Items, $item);
		}
		$this->Customers = array();
		$query3 = "SELECT * FROM PRICE_PLAN_LIST_CUSTOMER WHERE PriceListID = $PriceListId";
		
		$result3 = mysqli_query($con, $query3);
		while ($row3 = mysqli_fetch_array($result3)) {
					$customer = new Customer($row3['AccountNumber']);
					array_push($this->Customers, $customer);
		}
	}
	
}

function AddCartLogEntryByID($action, $ID, $qty = -1){
	global $con;
	$query = "SELECT `Group`, `Line`, `SKU`, `Qty` FROM SHOPPING_CART WHERE ID = $ID";
	
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_assoc($result);
	if($qty == -1){
		AddCartLogEntry($action, $row['Group'], $row['Line'], $row['SKU'], $row['Qty']);
	}
	else{
		AddCartLogEntry($action, $row['Group'], $row['Line'], $row['SKU'], $qty);
	}
}
function AddCartLogEntry($action, $group = "", $line = "", $sku = "", $qty = ""){
	global $con;
	$isCustomer = $_SESSION['isCustomer'];
	if($isCustomer){
		$accountNumber = ($_SESSION['AccountNumber']);
	} else {
		$accountNumber = $_SESSION['SalesmanID'];
	}
	$query = "INSERT INTO CART_LOG (`Action`,`Group`,`Line`,`SKU`,`Qty`,`User`, `TransactionDate`) VALUES ('$action', '$group', '$line', '$sku', $qty, '$accountNumber', DATE_ADD(NOW(), INTERVAL -4 HOUR))";
	mysqli_query($con, $query);
}

function dateDifference($date_1 , $date_2 , $differenceFormat = '%a' )
{
    $datetime1 = date_create($date_1);
    $datetime2 = date_create($date_2);
    
    $interval = date_diff($datetime1, $datetime2);
    
    return $interval->format($differenceFormat);
    
}
/**
 * Encode array from latin1 to utf8 recursively
 * @param $dat
 * @return array|string
 */
    function convert_from_latin1_to_utf8_recursively($dat)
   {
      if (is_string($dat)) {
         return utf8_encode($dat);
      } elseif (is_array($dat)) {
         $ret = [];
         foreach ($dat as $i => $d) $ret[ $i ] = convert_from_latin1_to_utf8_recursively($d);

         return $ret;
      } elseif (is_object($dat)) {
         foreach ($dat as $i => $d) $dat->$i = convert_from_latin1_to_utf8_recursively($d);

         return $dat;
      } else {
         return $dat;
      }
   }
function getProductDetails($Line, $SKU){
	global $con;
	$item = new Item("",$Line, $SKU);
	$item = convert_from_latin1_to_utf8_recursively($item);
	$item->ImageURL = $item->getImage();
	$item = json_encode($item);
	
	echo $item;
}
function exportOfflineData($salesmanID){
	header('Access-Control-Allow-Origin: *');  
	global $con;
	if(is_null($salesmanID) || $salesmanID == ""){
		echo "false";
		return;
	}
	$salesmanFolder = $salesmanID;
	if($salesmanID == "25" || $salesmanID == "99"){
		$salesmanID = "%";
	}
	//check if salesman folder exists
	if(!file_exists("offlineupdate/" . $salesmanFolder)){
		mkdir("offlineupdate/" . $salesmanFolder);
	}
	//create csv export files
	CSVExport("SELECT * FROM INVENTORY", "offlineupdate/" . $salesmanFolder . "/inventory.csv");
	CSVExport("SELECT * FROM SALESMAN", "offlineupdate/" . $salesmanFolder . "/salesman.csv");
	CSVExport("SELECT * FROM CUSTOMER WHERE Salesman LIKE '" . $salesmanID . "'", "offlineupdate/" . $salesmanFolder . "/customer.csv");
	CSVExport("SELECT INVOICE.* FROM INVOICE JOIN CUSTOMER ON(SUBSTRING(CUSTOMER.AccountNumber,1,6) = INVOICE.AccountNumber) WHERE Salesman LIKE '" . $salesmanID . "'", "offlineupdate/" . $salesmanFolder . "/invoice.csv");
	CSVExport("SELECT INVOICE_ADJUST.* FROM (INVOICE JOIN CUSTOMER ON(SUBSTRING(CUSTOMER.AccountNumber,1,6) = INVOICE.AccountNumber)) JOIN INVOICE_ADJUST USING(InvoiceNumber) WHERE Salesman LIKE '" . $salesmanID . "'", "offlineupdate/" . $salesmanFolder . "/invoice_adjust.csv");
	CSVExport("SELECT CREDIT.* FROM CREDIT JOIN CUSTOMER ON(SUBSTRING(CUSTOMER.AccountNumber,1,6) = CREDIT.AccountNumber) WHERE Salesman LIKE '" . $salesmanID . "'", "offlineupdate/" . $salesmanFolder . "/credit.csv");
	CSVExport("SELECT PAYMENT_HEAD.ID, OfflineID FROM PAYMENT_HEAD JOIN CUSTOMER USING(AccountNumber) WHERE Salesman LIKE '" . $salesmanID . "' and OfflineID LIKE 'OL0" . $salesmanID . "%' and Void = 0", "offlineupdate/" . $salesmanFolder . "/payment_id_exchange.csv");
	CSVExport("SELECT PAYMENT_DETAIL.* FROM `PAYMENT_DETAIL` JOIN `PAYMENT_HEAD` ON(PAYMENT_HEAD.ID = PAYMENT_DETAIL.PaymentID) WHERE SalesmanID LIKE '" . $salesmanID . "'", "offlineupdate/" . $salesmanFolder . "/payment_detail_online.csv");
	//create zip file
	$zip = new ZipArchive;
	
	if ($zip->open("offlineupdate/$salesmanFolder.zip",$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) === TRUE) {
		$directory = "offlineupdate/$salesmanFolder/";
		$scanned_directory = array_diff(scandir($directory), array('..', '.'));
		foreach($scanned_directory as $key => $value){
			$zip->addFile("offlineupdate/$salesmanFolder/$value", $value);	
		}
		$zip->close();
		echo 'true';
	} else {
		echo 'false';
	}
	
	
	
}
function getGroupsByLine($line){
	global $con;
	if($line == ""){
		$line = "%";
	}
	$query = "SELECT `GROUP`.`Code`, `Name` FROM `GROUP` JOIN INVENTORY ON(`GROUP`.`Code` = INVENTORY.`Group`) WHERE `Line` LIKE '$line' GROUP BY `Group`";
	//$query = mysqli_real_escape_string($con, $query);
	//echo $query;
	$result = mysqli_query($con, $query);
	$arrGroups = [];
	$line = new stdClass();
		$line->Code = "%";
		$line->Name = "All";
		array_push($arrGroups,$line);
	while($row = mysqli_fetch_array($result)){
		$line = new stdClass();
		$line->Code = $row['Code'];
		$line->Name = $row['Name'];
		array_push($arrGroups,$line);
	}
	if(count($arrGroups) == 0){
		
	}
	echo json_encode($arrGroups);
}
function getLinesByGroup($group){
	global $con;
	if($group == ""){
		$group = "%";
	}
	$query = "SELECT `LINE`.`Code`, `Name` FROM `LINE` JOIN INVENTORY ON(`LINE`.`Code` = INVENTORY.`Line`) WHERE `Group` LIKE '$group' GROUP BY `Line`";
	//$query = mysqli_real_escape_string($con, $query);
	$result = mysqli_query($con, $query);
	$arrLines = [];
	while($row = mysqli_fetch_array($result)){
		$group = new stdClass();
		$group->Code = $row['Code'];
		$group->Name = $row['Name'];
		array_push($arrLines,$group);
	}
	echo json_encode($arrLines);
}
function sendSMS($user, $message){
	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 ($estimate->Customer->Salesman->Email != "" || $estimate->Customer->Salesman->Email != null) {
			$mail->addCC($estimate->Customer->Salesman->Email);	
		}
		*/
		$customerEmail = $estimate->Customer->Email;
		if($customerEmail != "" && $customer->SendOrderEmail){
			//$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 ' . $estimate->Customer->Name . ' <br />
		    Numero de Cuenta: ' . $estimate->Customer->AccountNumber . '<br />
		    Total: ' . moneyFormat($estimate->OrderTotal) . ' <br />
		    Notas: ' . $estimate->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 = '';
		$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 formatPhone($phone_number)
{
    $cleaned = preg_replace('/[^[:digit:]]/', '', $phone_number);
    preg_match('/(\d{3})(\d{3})(\d{4})/', $cleaned, $matches);
    return "({$matches[1]}) {$matches[2]}-{$matches[3]}";
}
function strposX($haystack, $needle, $number){
    if($number == '1'){
        return strpos($haystack, $needle);
    }elseif($number > '1'){
        return strpos($haystack, $needle, strposX($haystack, $needle, $number - 1) + strlen($needle));
    }else{
        return error_log('Error: Value for parameter $number is out of range');
    }
}
function saveToSession($key, $data ){
	if($_SESSION[$key] = $data){
		echo "true";
	}else{
		echo "false";
	}
}
function getDataFromSession($key){
	
	if(isset($_SESSION[$key])){
		return ($_SESSION[$key]);	
	}else{
		return false;
	}
	
}
function deleteDataFromServer($key){
	$_SESSION[$key] = new stdClass();
	return;
}
?>