<?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 ) {
	//if($isAdmin){
	//	session_name("elite_admin");
	//}else{
	//	session_name("elite_sales");
	//}
	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 "saveCustomerInfo2":
			saveCustomerInfo2($_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 "setTruckMode":
			setTruckMode($_REQUEST['f'], $_REQUEST['wid']);
			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;
		case "sendTaxExpirationReminderEmail":
			error_reporting(E_ALL);
			sendTaxExpirationReminderEmail();
			break;
		case "getInventoryCSV":
			echo getInventoryCSV();
			break;
		case "sendInventoryToEmail":
			error_reporting(E_ALL);
			ini_set("display_errors", 1);
			require_once './assets/PHPMailerAutoload.php';
			global $config;
			$results_messages = array();
			$file = getInventoryCSV();
			$filename = "inventory_" . date("m-d-y", time()) . ".csv";
			$email = new PHPMailer();
			$email->SetFrom($config['FromEmail'], $config['EmailName']); //Name is optional
			$email->Subject   = 'Updated Inventory ' . date("m-d-y", time());
			$email->Body      = "Attached file.";
			$administrator = new Administrator($_SESSION['Username']);

			$email->AddAddress( $administrator->Email );

			$file_to_attach = $file;

			$email->AddAttachment( $file_to_attach , $filename );

			return $email->Send();
			break;
		case "downloadInventoryCSV":
			$file = getInventoryCSV();
			$filename = "inventory_" . date("m-d-y", time()) . ".csv";
			header('Content-Description: File Transfer');
			header('Content-Type: application/csv');
			header("Content-Transfer-Encoding: Binary");
			header('Content-Disposition: attachment; filename="'.$filename.'"');
			header('Expires: 0');
			header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
			header('Pragma: public');
			header('Content-Length: ' . filesize($file)); //Absolute URL

			ob_clean();
			flush();
			readfile($file); //Absolute URL
			exit();
			break;
		case "sendInventoryToSalesmen":
			//die("ee");
			sendInventoryToSalesmen();
			break;
		case "verifyEmail":
			verifyEmail($_REQUEST['email']);
			break;
		case "changeCustomer":
			$customer = $_REQUEST['an'];
			$invoice = new Invoice($_REQUEST['invoice']);
			$invoice->AccountNumber = ($customer);
			$invoice->save();
			$invoice = new Invoice($_REQUEST['invoice']);
			$invoice->updateCustomerInfo();
			$invoice->save();
            break;
        case "getImageList":
            getImageList();
			break;
		case "itemsWithoutImages":
			itemsWithoutImages();
			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 createDocument($type, $file , $strict = true){
  global $con;

  if(isset($file) && $strict){
    //grab files
    $target_dir = "uploads/documents/";
    $finalFilename = uniqid($file["POFile"]["name"],true);
    $target_file = $target_dir . basename($finalFilename);
    $OrigFilename = $file["POFile"]["name"];
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($OrigFilename,PATHINFO_EXTENSION));
    //var_dump($file["name"]);
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $imageFileType != "pdf" ) {
    	$uploadOk = 0;
    	//echo "Error Only photos (jpg, jpeg, png, gif) or pdf";
    }

    if ($uploadOk == 0) {
        //echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($file["POFile"]["tmp_name"], $target_file)) {
           //echo "The file ". basename( $_FILES["POFile"]["name"]). " has been uploaded.";
        } else {
            //echo "Sorry, there was an error uploading your file.";
        }
    }
    //////end grab files

    $query = "INSERT INTO DOCUMENT_RECORD (DocumentType, DocumentPath) VALUES ('$type', '" . mysqli_real_escape_string($con, $target_file) . "')";
    //error_log($query);

    if(mysqli_query($con, $query)){

      return mysqli_insert_id($con);
    }else{
      return false;
    }
  }
}
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']);
		$priceRate = getPricePlanCalculatedRate($_SESSION['AccountNumber']);
		
		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 = "New Purchase Order #$orderID for {$order->Customer->Name}";
	$key = md5($orderID . $config['SaltKey']);
	$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 {
			$mail->addAddress($to);
			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>' . $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 for {$estimate->Customer->Name}";
	$key = md5($estimateID . $config["SaltKey"]);
	$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 $config['RootFolder'] . '/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'];


		$mail->addCC($config['OrderEmail']);
		
		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 = 'eli-tpr.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(isset($_SESSION['TruckMode'])){
			if($_SESSION['TruckMode']){
				$query = "DELETE SHOPPING_CART FROM SHOPPING_CART LEFT JOIN MULTIPLE_WH_INVENTORY USING(Line, SKU) WHERE AccountNumber LIKE '{$_SESSION['SalesmanID']}' AND (WarehouseID != {$_SESSION['WarehouseID']} OR WarehouseID IS NULL)";
				$result = mysqli_query($con, $query);
			}
		}
		// if ($_SESSION['pricePlanMode']) {
		// 	$priceRate = getPricePlanCalculatedRate($_SESSION['AccountNumber']);
		// }else {
		// 	$priceRate = 1;
		// }


		$priceRate = getPricePlanCalculatedRate($_SESSION['setCustomer']);
		
		$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) {
	//error_reporting(E_ALL);
	//ini_set("display_errors", 1);
	global $con;
	//var_dump($_SESSION);
	$isAdmin = $_SESSION['isAdmin'];
	if (!$isAdmin) {
		return false;
	}
	$customer = new Customer($AccountNumber);
	//var_dump($customer);

	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 saveCustomerInfo2($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`,
			`Terms`,
			`Comments`,
			`SendOrderEmail`,
			`Address1`,
			`Address2`,
			`State`,
			`ZipCode`,
			`ShipToAddress1`,
			`ShipToAddress2`,
      `ShipToCity`,
			`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']},
		'{$CustomerData['Terms']}',
		'" . 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['CustomerShipToAddress1']) . "',
		'" . mysqli_real_escape_string($con, $CustomerData['CustomerShipToAddress2']) . "',
    '" . mysqli_real_escape_string($con, $CustomerData['CustomerShipToCity']) . "',
		'" . mysqli_real_escape_string($con, $CustomerData['CustomerShipToState']) . "',
		'" . mysqli_real_escape_string($con, $CustomerData['CustomerShipToZip']) . "')";
		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['Terms']}',
				`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']},
			`Terms` = '{$CustomerData['Terms']}',
			`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));
	}
	//error_log($query);
	$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 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`,
			`Terms`,
			`Comments`,
			`SendOrderEmail`,
			`Address1`,
			`Address2`,
			`State`,
			`ZipCode`,
			`ShipToAddress1`,
			`ShipToAddress2`,
      `ShipToCity`,
			`ShipToState`,
			`ShipToZip`,
      `TaxID1`,
      `TaxIDExpiration1`,
      `TaxID2`,
      `TaxIDExpiration2`,
      `TaxExempt1`,
      `TaxExempt2`) 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']},
		{$CustomerData['Terms']},
		'" . 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['CustomerShipToAddress1']) . "',
		'" . mysqli_real_escape_string($con, $CustomerData['CustomerShipToAddress2']) . "',
    '" . mysqli_real_escape_string($con, $CustomerData['CustomerShipToCity']) . "',
		'" . mysqli_real_escape_string($con, $CustomerData['CustomerShipToState']) . "',
		'" . mysqli_real_escape_string($con, $CustomerData['CustomerShipToZip']) . "',
    '" . mysqli_real_escape_string($con, $CustomerData['CustomerTaxID1']) . "',
    '" . mysqli_real_escape_string($con, $CustomerData['CustomerTaxID1Expiration']) . "',
    '" . mysqli_real_escape_string($con, $CustomerData['CustomerTaxID2']) . "',
    '" . mysqli_real_escape_string($con, $CustomerData['CustomerTaxID2Expiration']) . "',
    '" . mysqli_real_escape_string($con, $CustomerData['TaxExempt1']) . "',
    '" . mysqli_real_escape_string($con, $CustomerData['TaxExempt2']) . "')";
		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['Terms']}',
				`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']},
			`Terms` = '{$CustomerData['Terms']}',
			`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));
	}
	//error_log($query);
	$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);
  $salesman->MobileLoginBarcode = md5($salesman->SalesmanID . $salesman->Password);
	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, $columnNames = []) {
	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");
	if(count($columnNames)>0){
		$file_row = (implode('","',array_map('addslashes',$columnNames)));
		fwrite($file, '"' . $file_row . "\"\n");
	}
    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);
	//echo $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($PurchaseOrderID) {
	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 PURCHASE_ORDER_DETAIL.*, INVENTORY.*, SHOPPING_CART.Qty AS OnOrder FROM PURCHASE_ORDER_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 PURCHASE_ORDER_DETAIL.SKU = INVENTORY.SKU AND PURCHASE_ORDER_DETAIL.Line = INVENTORY.Line AND PURCHASE_ORDER_DETAIL.PurchaseOrderID = " . $PurchaseOrderID;
	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(getCustomerPrice($row['Group'], $row['Line'], $row['SKU'], $_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.ID, SPECIAL.RegularPrice, PriceA, INVENTORY.`Line`, INVENTORY.`SKU`,INVENTORY.`Group`, INVENTORY.Description, INVENTORY.Notes, INVENTORY.Interchange, INVENTORY.Qty, SHOPPING_CART.Qty AS OnOrder FROM INVENTORY JOIN SPECIAL USING(Line, SKU) LEFT JOIN SHOPPING_CART USING(Line, SKU) WHERE SHOPPING_CART.`AccountNumber` = '$accountNumber' OR SHOPPING_CART.`AccountNumber` IS NULL ORDER BY Line, SKU";
	//$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";
  //echo $query;
	$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']));
    $row['Image'] = hasImage($row['Line'], $row['SKU'])?getImage($row['Line'], $row['SKU']):false;
		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['Sort']);
	$sortString = "";
	for ($i = 0; $i < count($sort); $i++) {
		if ($i == 0) {
			$sortString = " ORDER BY ";
		}
		$sortString .= "INVENTORY." . trim($sort[$i]);
		if ($i != count($sort)-1) {
			$sortString .= ", ";
		}else {
			$sortString .= " ASC";
		}
	}
	$query = "SELECT CATALOG_DETAIL.*, INVENTORY.*, SHOPPING_CART.Qty AS OnOrder FROM CATALOG_DETAIL, INVENTORY LEFT JOIN SHOPPING_CART ON INVENTORY.SKU = SHOPPING_CART.SKU AND INVENTORY.LINE = SHOPPING_CART.LINE AND INVENTORY.GROUP = SHOPPING_CART.GROUP AND AccountNumber LIKE '" . $accountNumber . "' WHERE  Active = 1 AND ((Discontinued = 1 AND INVENTORY.Qty > 0) OR (Discontinued = 0)) AND  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);
	//echo json_last_error();
    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) {
    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);
	//echo $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;
	$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;
		$_SESSION['AccountNumber'] = $accountNumber;
		$result['result'] = true;
		echo json_encode($result);
	}else {
		$result['result'] = false;
		echo json_encode($result);
	}
}
function clearSetCustomer() {
	//echo("loool");
	//var_dump($_SESSION);
	if (!$_SESSION['isCustomer']) {
		$_SESSION['setCustomerMode'] = false;
		$_SESSION['setCustomer'] = "";
		$result['result'] = true;
		echo json_encode($result);
	}else {
		$result['result'] = false;
		echo json_encode($result);
	}
}
function catalogItemExists($line, $sku) {
	global $con;
	$query = "SELECT Name, SKU, Line FROM CATALOG_DETAIL, CATALOG_CATEGORY WHERE `SKU` = '$sku' AND `Line` = '$line' AND CATALOG_CATEGORY.CatalogID = CATALOG_DETAIL.CategoryID";
	$result = mysqli_query($con, $query);
	$return = array();
	$return['rowCount'] = mysqli_num_rows($result);
	$return['rows'] = array();
	if (mysqli_num_rows($result) > 0) {
		while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
			array_push($return['rows'], $row);
		}
	}
	echo(json_encode($return));
}
function setPickupStatus($action, $pickupID, $value, $notes = "") {
	global $con;
	$isAdmin = $_SESSION['isAdmin'];
	if (!$isAdmin) {
			return false;
	}
	if ($action == "pickup") {
		$query = "UPDATE PICKUP_HEAD SET ToPickup = '$value', ToPickupUser = '" . $_SESSION['Username'] . "' WHERE PickupID = $pickupID";
		$result = mysqli_query($con, $query);
		event_log($_SESSION['Username'], "SEND TO PICKUP", "PickupID: $pickupID.\nDate: $value");
		if ($result) {
			$return['result'] = true;
			echo json_encode($return);
		}else {
			$return['result'] = false;
			$return['error'] = mysqli_error($con);
			echo json_encode($return);
		}
		return $result;
	}else if ($action == "warehouse"){
		$query = "UPDATE PICKUP_HEAD SET AtWarehouse = '$value', AtWarehouseNotes = '$notes', AtWarehouseUser = '" . $_SESSION['Username'] . "' WHERE PickupID = $pickupID";
		event_log($_SESSION['Username'], "SET PICKUP AT WAREHOUSE", "PickupID: $pickupID.\nDate: $value\nNotes: $notes");
		$result = mysqli_query($con, $query);
		if ($result) {
			$return['result'] = true;
			echo json_encode($return);
		}else {
			$return['result'] = false;
			$return['error'] = mysqli_error($con);
			echo json_encode($return);
		}
		return $result;
	}else if ($action == "status"){
		$query = "UPDATE PICKUP_HEAD SET PickupStatus = '$value', PickupStatusNotes = '$notes', PickupStatusUser = '" . $_SESSION['Username'] . "' WHERE PickupID = $pickupID";
		event_log($_SESSION['Username'], "SET PICKUP FINAL STATUS", "PickupID: $pickupID.\nStatus: $value\nNotes: $notes");
		$result = mysqli_query($con, $query);
		if ($result) {
			$return['result'] = true;
			echo json_encode($return);
		}else {
			$return['result'] = false;
			$return['error'] = mysqli_error($con);
			echo json_encode($return);
		}
		return $result;
	}

}
function getPickupStatusInfo($action, $pickupID) {
	global	$con;
	switch ($action) {
		case "pickup":
			$query = "SELECT ToPickup, ToPickupUser, FullName FROM PICKUP_HEAD, ADMINISTRATOR WHERE PickupID = $pickupID AND Username = ToPickupUser";
			$result = mysqli_query($con, $query);
			$row = mysqli_fetch_array($result);
			$row['ToPickup'] = date("m/d/Y g:i a",strtotime($row['ToPickup']));
			echo json_encode($row);
			break;
		case "warehouse":
			$query = "SELECT AtWarehouse, AtWarehouseUser, AtWarehouseNotes, FullName FROM PICKUP_HEAD, ADMINISTRATOR WHERE PickupID = $pickupID AND Username = AtWarehouseUser";
			$result = mysqli_query($con, $query);
			$row = mysqli_fetch_array($result);
			$row['AtWarehouse'] = date("m/d/Y g:i a",strtotime($row['AtWarehouse']));
			echo json_encode($row);
			break;
		case "status":
			$query = "SELECT PickupStatus, PickupStatusUser, AtWarehouseNotes, PickupStatusNotes, FullName FROM PICKUP_HEAD, ADMINISTRATOR WHERE PickupID = $pickupID AND Username = PickupStatusUser";
			$result = mysqli_query($con, $query);
			$row = mysqli_fetch_array($result);
			echo json_encode($row);
			break;
	}
}
function savePickupStatusNotes($action, $pickupID, $notes) {
	global $con;
	$field = "";
	switch ($action) {
		case "warehouse":
			$field = "AtWarehouseNotes";
			$name = "AT WAREHOUSE NOTES";
			break;
		case "status":
			$field = "PickupStatusNotes";
			$name = "STATUS NOTES";
			break;
	}
	$query = "SELECT `$field` FROM PICKUP_HEAD WHERE PickupID = $pickupID";
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result);
	$oldNotes = $row[$field];
	$query = "UPDATE PICKUP_HEAD SET `$field` = '$notes' WHERE PickupID = $pickupID";

	event_log($_SESSION['Username'], "UPDATE PICKUP $name", "PickupID: $pickupID.\nOriginal Text: $oldNotes\nNew Text: $notes");
	$result = mysqli_query($con, $query);
	if ($result) {
		echo("true");
	}else {
		echo("false");
	}

}
function getOrderDetails($orderID) {
	global $con;
	$order = new Order($orderID);
	$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 getImageList(){
    global $con;
    $path = "img/catalog/";
    $fileList = array_diff(scandir($path), array('..', '.'));
    echo json_encode($fileList);

}
function exportOfflineData($salesmanID){
	header('Access-Control-Allow-Origin: *');
	global $con;
	if(is_null($salesmanID) || $salesmanID == ""){
		echo "false";
		return;
	}
	$salesmanFolder = $salesmanID;
	if($salesmanID == "CC" || $salesmanID == "ES"|| $salesmanID == "JC"){
		$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 ADMINISTRATOR", "offlineupdate/" . $salesmanFolder . "/administrator.csv");
	CSVExport("SELECT * FROM CUSTOMER WHERE Salesman LIKE '" . $salesmanID . "' OR AccountNumber LIKE '000%'", "offlineupdate/" . $salesmanFolder . "/customer.csv");
	CSVExport("SELECT INVOICE_HEAD.* FROM INVOICE_HEAD JOIN CUSTOMER USING(AccountNumber) WHERE CUSTOMER.Salesman LIKE '" . $salesmanID . "'", "offlineupdate/" . $salesmanFolder . "/invoice_head.csv");
	CSVExport("SELECT INVOICE_DETAIL.* FROM INVOICE_HEAD JOIN INVOICE_DETAIL USING(InvoiceID) JOIN CUSTOMER USING(AccountNumber) WHERE CUSTOMER.Salesman LIKE '" . $salesmanID . "'", "offlineupdate/" . $salesmanFolder . "/invoice_detail.csv");
    CSVExport("SELECT ORDER_HEAD.*, 1 as SentOffline FROM ORDER_HEAD JOIN CUSTOMER USING(AccountNumber) WHERE CUSTOMER.Salesman LIKE '" . $salesmanID . "'", "offlineupdate/" . $salesmanFolder . "/order_head.csv");
	CSVExport("SELECT ORDER_DETAIL.* FROM ORDER_HEAD JOIN ORDER_DETAIL USING(OrderID) JOIN CUSTOMER USING(AccountNumber) WHERE CUSTOMER.Salesman LIKE '" . $salesmanID . "'", "offlineupdate/" . $salesmanFolder . "/order_detail.csv");
	CSVExport("SELECT PAYMENT_HEAD.*, 1 as SentOffline FROM PAYMENT_HEAD JOIN CUSTOMER USING(AccountNumber) WHERE CUSTOMER.Salesman LIKE '" . $salesmanID . "' and Void = 0", "offlineupdate/" . $salesmanFolder . "/payment_head.csv");
	CSVExport("SELECT PAYMENT_DETAIL.* FROM `PAYMENT_DETAIL` JOIN `PAYMENT_HEAD` ON(PAYMENT_HEAD.ID = PAYMENT_DETAIL.PaymentID) JOIN CUSTOMER USING(AccountNumber) WHERE CUSTOMER.Salesman LIKE '" . $salesmanID . "'", "offlineupdate/" . $salesmanFolder . "/payment_detail.csv");
	
	CSVExport("SELECT CATALOG_CATEGORY.* FROM CATALOG_CATEGORY", "offlineupdate/" . $salesmanFolder . "/catalog_category.csv");
	CSVExport("SELECT CATALOG_DETAIL.* FROM CATALOG_DETAIL", "offlineupdate/" . $salesmanFolder . "/catalog_detail.csv");
	CSVExport("SELECT SUPPLIER_CATALOG_LINK.* FROM SUPPLIER_CATALOG_LINK", "offlineupdate/" . $salesmanFolder . "/supplier_catalog_link.csv");
	
	CSVExport("SELECT PRICE_PLAN_LIST_CUSTOMER.* FROM PRICE_PLAN_LIST_CUSTOMER", "offlineupdate/" . $salesmanFolder . "/price_plan_list_customer.csv");
	CSVExport("SELECT PRICE_PLAN_LIST_DEF.* FROM PRICE_PLAN_LIST_DEF", "offlineupdate/" . $salesmanFolder . "/price_plan_list_def.csv");
	CSVExport("SELECT PRICE_PLAN_LIST_DETAIL.* FROM PRICE_PLAN_LIST_DETAIL", "offlineupdate/" . $salesmanFolder . "/price_plan_list_detail.csv");
	CSVExport("SELECT PRICE_PLAN_CALC.* FROM PRICE_PLAN_CALC", "offlineupdate/" . $salesmanFolder . "/price_plan_list_calc.csv");

	CSVExport("SELECT ESTIMATE_HEAD.*, 1 as SentOffline FROM ESTIMATE_HEAD JOIN CUSTOMER USING(AccountNumber) WHERE CUSTOMER.Salesman LIKE '" . $salesmanID . "'", "offlineupdate/" . $salesmanFolder . "/estimate_head.csv");
	CSVExport("SELECT ESTIMATE_DETAIL.* FROM ESTIMATE_HEAD JOIN ESTIMATE_DETAIL USING(EstimateID) JOIN CUSTOMER USING(AccountNumber) WHERE CUSTOMER.Salesman LIKE '" . $salesmanID . "'", "offlineupdate/" . $salesmanFolder . "/estimate_detail.csv");
	CSVExport("SELECT ESTIMATE_CUSTOMER.* FROM ESTIMATE_HEAD JOIN ESTIMATE_CUSTOMER USING(EstimateID) JOIN CUSTOMER USING(AccountNumber) WHERE ESTIMATE_HEAD.Salesman LIKE '" . $salesmanID . "'", "offlineupdate/" . $salesmanFolder . "/estimate_customer.csv");
	
	CSVExport("SELECT CUSTOMER_REORDER_EXCLUDE.* FROM CUSTOMER_REORDER_EXCLUDE", "offlineupdate/" . $salesmanFolder . "/customer_reorder_exclude.csv");
	CSVExport("SELECT * FROM `LINE`", "offlineupdate/" . $salesmanFolder . "/line.csv");
	CSVExport("SELECT * FROM `GROUP`", "offlineupdate/" . $salesmanFolder . "/group.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);
	}

	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;
}
function sendTaxExpirationReminderEmail(){
	global $con, $root, $config;
	$days = 30;
	//Certificado de Registro de Comerciante
	$query = "SELECT AccountNumber, `Name`, TaxIDExpiration2 FROM CUSTOMER WHERE DATEDIFF(TaxIDExpiration2, NOW()) = $days";
	$result = mysqli_query($con, $query);
	while($row = mysqli_fetch_array($result)){
		$companyName = $row['Name'];
		$expirationDate = date("m/d/Y", strtotime($row['TaxIDExpiration2']));
		$emailText = <<<EOF


		<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
    <!--[if gte mso 9]><xml>
     <o:OfficeDocumentSettings>
      <o:AllowPNG/>
      <o:PixelsPerInch>96</o:PixelsPerInch>
     </o:OfficeDocumentSettings>
    </xml><![endif]-->
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width">
    <!--[if !mso]><!--><meta http-equiv="X-UA-Compatible" content="IE=edge"><!--<![endif]-->
    <title></title>
    <!--[if !mso]><!-- -->
	<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" type="text/css" />
	<!--<![endif]-->

    <style type="text/css" id="media-query">
      body {
  margin: 0;
  padding: 0; }

table, tr, td {
  vertical-align: top;
  border-collapse: collapse; }

.ie-browser table, .mso-container table {
  table-layout: fixed; }

* {
  line-height: inherit; }

a[x-apple-data-detectors=true] {
  color: inherit !important;
  text-decoration: none !important; }

[owa] .img-container div, [owa] .img-container button {
  display: block !important; }

[owa] .fullwidth button {
  width: 100% !important; }

[owa] .block-grid .col {
  display: table-cell;
  float: none !important;
  vertical-align: top; }

.ie-browser .num12, .ie-browser .block-grid, [owa] .num12, [owa] .block-grid {
  width: 600px !important; }

.ExternalClass, .ExternalClass p, .ExternalClass span, .ExternalClass font, .ExternalClass td, .ExternalClass div {
  line-height: 100%; }

.ie-browser .mixed-two-up .num4, [owa] .mixed-two-up .num4 {
  width: 200px !important; }

.ie-browser .mixed-two-up .num8, [owa] .mixed-two-up .num8 {
  width: 400px !important; }

.ie-browser .block-grid.two-up .col, [owa] .block-grid.two-up .col {
  width: 300px !important; }

.ie-browser .block-grid.three-up .col, [owa] .block-grid.three-up .col {
  width: 200px !important; }

.ie-browser .block-grid.four-up .col, [owa] .block-grid.four-up .col {
  width: 150px !important; }

.ie-browser .block-grid.five-up .col, [owa] .block-grid.five-up .col {
  width: 120px !important; }

.ie-browser .block-grid.six-up .col, [owa] .block-grid.six-up .col {
  width: 100px !important; }

.ie-browser .block-grid.seven-up .col, [owa] .block-grid.seven-up .col {
  width: 85px !important; }

.ie-browser .block-grid.eight-up .col, [owa] .block-grid.eight-up .col {
  width: 75px !important; }

.ie-browser .block-grid.nine-up .col, [owa] .block-grid.nine-up .col {
  width: 66px !important; }

.ie-browser .block-grid.ten-up .col, [owa] .block-grid.ten-up .col {
  width: 60px !important; }

.ie-browser .block-grid.eleven-up .col, [owa] .block-grid.eleven-up .col {
  width: 54px !important; }

.ie-browser .block-grid.twelve-up .col, [owa] .block-grid.twelve-up .col {
  width: 50px !important; }

@media only screen and (min-width: 620px) {
  .block-grid {
    width: 600px !important; }
  .block-grid .col {
    vertical-align: top; }
    .block-grid .col.num12 {
      width: 600px !important; }
  .block-grid.mixed-two-up .col.num4 {
    width: 200px !important; }
  .block-grid.mixed-two-up .col.num8 {
    width: 400px !important; }
  .block-grid.two-up .col {
    width: 300px !important; }
  .block-grid.three-up .col {
    width: 200px !important; }
  .block-grid.four-up .col {
    width: 150px !important; }
  .block-grid.five-up .col {
    width: 120px !important; }
  .block-grid.six-up .col {
    width: 100px !important; }
  .block-grid.seven-up .col {
    width: 85px !important; }
  .block-grid.eight-up .col {
    width: 75px !important; }
  .block-grid.nine-up .col {
    width: 66px !important; }
  .block-grid.ten-up .col {
    width: 60px !important; }
  .block-grid.eleven-up .col {
    width: 54px !important; }
  .block-grid.twelve-up .col {
    width: 50px !important; } }

@media (max-width: 620px) {
  .block-grid, .col {
    min-width: 320px !important;
    max-width: 100% !important;
    display: block !important; }
  .block-grid {
    width: calc(100% - 40px) !important; }
  .col {
    width: 100% !important; }
    .col > div {
      margin: 0 auto; }
  img.fullwidth, img.fullwidthOnMobile {
    max-width: 100% !important; }
  .no-stack .col {
    min-width: 0 !important;
    display: table-cell !important; }
  .no-stack.two-up .col {
    width: 50% !important; }
  .no-stack.mixed-two-up .col.num4 {
    width: 33% !important; }
  .no-stack.mixed-two-up .col.num8 {
    width: 66% !important; }
  .no-stack.three-up .col.num4 {
    width: 33% !important; }
  .no-stack.four-up .col.num3 {
    width: 25% !important; }
  .mobile_hide {
    min-height: 0px;
    max-height: 0px;
    max-width: 0px;
    display: none;
    overflow: hidden;
    font-size: 0px; } }

    </style>
</head>
<body class="clean-body" style="margin: 0;padding: 0;-webkit-text-size-adjust: 100%;background-color: #6FC1E1">
  <style type="text/css" id="media-query-bodytag">
    @media (max-width: 520px) {
      .block-grid {
        min-width: 320px!important;
        max-width: 100%!important;
        width: 100%!important;
        display: block!important;
      }

      .col {
        min-width: 320px!important;
        max-width: 100%!important;
        width: 100%!important;
        display: block!important;
      }

        .col > div {
          margin: 0 auto;
        }

      img.fullwidth {
        max-width: 100%!important;
      }
			img.fullwidthOnMobile {
        max-width: 100%!important;
      }
      .no-stack .col {
				min-width: 0!important;
				display: table-cell!important;
			}
			.no-stack.two-up .col {
				width: 50%!important;
			}
			.no-stack.mixed-two-up .col.num4 {
				width: 33%!important;
			}
			.no-stack.mixed-two-up .col.num8 {
				width: 66%!important;
			}
			.no-stack.three-up .col.num4 {
				width: 33%!important;
			}
			.no-stack.four-up .col.num3 {
				width: 25%!important;
			}
      .mobile_hide {
        min-height: 0px!important;
        max-height: 0px!important;
        max-width: 0px!important;
        display: none!important;
        overflow: hidden!important;
        font-size: 0px!important;
      }
    }
  </style>
  <!--[if IE]><div class="ie-browser"><![endif]-->
  <!--[if mso]><div class="mso-container"><![endif]-->
  <table class="nl-container" style="border-collapse: collapse;table-layout: fixed;border-spacing: 0;mso-table-lspace: 0pt;mso-table-rspace: 0pt;vertical-align: top;min-width: 320px;Margin: 0 auto;background-color: #6FC1E1;width: 100%" cellpadding="0" cellspacing="0">
	<tbody>
	<tr style="vertical-align: top">
		<td style="word-break: break-word;border-collapse: collapse !important;vertical-align: top">
    <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td align="center" style="background-color: #6FC1E1;"><![endif]-->

    <div style="background-color:transparent;">
      <div style="Margin: 0 auto;min-width: 320px;max-width: 600px;overflow-wrap: break-word;word-wrap: break-word;word-break: break-word;background-color: transparent;" class="block-grid ">
        <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;">
          <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="background-color:transparent;" align="center"><table cellpadding="0" cellspacing="0" border="0" style="width: 600px;"><tr class="layout-full-width" style="background-color:transparent;"><![endif]-->

              <!--[if (mso)|(IE)]><td align="center" width="600" style=" width:600px; padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:0px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><![endif]-->
            <div class="col num12" style="min-width: 320px;max-width: 600px;display: table-cell;vertical-align: top;">
              <div style="background-color: transparent; width: 100% !important;">
              <!--[if (!mso)&(!IE)]><!--><div style="border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent; padding-top:5px; padding-bottom:0px; padding-right: 0px; padding-left: 0px;"><!--<![endif]-->


                    <div align="center" class="img-container center  autowidth  fullwidth " style="padding-right: 0px;  padding-left: 0px;">
<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px;line-height:0px;"><td style="padding-right: 0px; padding-left: 0px;" align="center"><![endif]-->
<div style="line-height:25px;font-size:1px">&#160;</div>  <img class="center  autowidth  fullwidth" align="center" border="0" src="https://d1oco4z2z1fhwp.cloudfront.net/templates/default/20/rounder-up.png" alt="Image" title="Image" style="outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;clear: both;display: block !important;border: 0;height: auto;float: none;width: 100%;max-width: 600px" width="600">
<!--[if mso]></td></tr></table><![endif]-->
</div>


              <!--[if (!mso)&(!IE)]><!--></div><!--<![endif]-->
              </div>
            </div>
          <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]-->
        </div>
      </div>
    </div>
    <div style="background-color:transparent;">
      <div style="Margin: 0 auto;min-width: 320px;max-width: 600px;overflow-wrap: break-word;word-wrap: break-word;word-break: break-word;background-color: #FFFFFF;" class="block-grid ">
        <div style="border-collapse: collapse;display: table;width: 100%;background-color:#FFFFFF;">
          <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="background-color:transparent;" align="center"><table cellpadding="0" cellspacing="0" border="0" style="width: 600px;"><tr class="layout-full-width" style="background-color:#FFFFFF;"><![endif]-->

              <!--[if (mso)|(IE)]><td align="center" width="600" style=" width:600px; padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:5px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><![endif]-->
            <div class="col num12" style="min-width: 320px;max-width: 600px;display: table-cell;vertical-align: top;">
              <div style="background-color: transparent; width: 100% !important;">
              <!--[if (!mso)&(!IE)]><!--><div style="border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent; padding-top:5px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;"><!--<![endif]-->


                    <div align="center" class="img-container center  autowidth  " style="padding-right: 0px;  padding-left: 0px;">
<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px;line-height:0px;"><td style="padding-right: 0px; padding-left: 0px;" align="center"><![endif]-->
  <img class="center  autowidth " align="center" border="0" src="{$root}/img/Logo_500.png" alt="Image" title="Image" style="outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;clear: both;display: block !important;border: 0;height: auto;float: none;width: 100%;max-width: 500px" width="500">
<!--[if mso]></td></tr></table><![endif]-->
</div>



                    <div class="">
	<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px;"><![endif]-->
	<div style="color:#555555;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;line-height:150%; padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px;">
		<div style="font-size:12px;line-height:18px;color:#555555;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;text-align:left;"><p style="margin: 0;font-size: 14px;line-height: 21px;text-align: center">
			Reseller Certificate and Municipal Tax Exception Expiration Notification&#160;<br>
			Notificaci&oacute;n de Expiraci&oacute;n de Certificado de Revendedor y Exenci&oacute;n de IVU Municipal

		</p></div>
	</div>
	<!--[if mso]></td></tr></table><![endif]-->
</div>

              <!--[if (!mso)&(!IE)]><!--></div><!--<![endif]-->
              </div>
            </div>
          <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]-->
        </div>
      </div>
    </div>
    <div style="background-color:transparent;">
      <div style="Margin: 0 auto;min-width: 320px;max-width: 600px;overflow-wrap: break-word;word-wrap: break-word;word-break: break-word;background-color: #FFFFFF;" class="block-grid ">
        <div style="border-collapse: collapse;display: table;width: 100%;background-color:#FFFFFF;">
          <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="background-color:transparent;" align="center"><table cellpadding="0" cellspacing="0" border="0" style="width: 600px;"><tr class="layout-full-width" style="background-color:#FFFFFF;"><![endif]-->

              <!--[if (mso)|(IE)]><td align="center" width="600" style=" width:600px; padding-right: 0px; padding-left: 0px; padding-top:0px; padding-bottom:5px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><![endif]-->
            <div class="col num12" style="min-width: 320px;max-width: 600px;display: table-cell;vertical-align: top;">
              <div style="background-color: transparent; width: 100% !important;">
              <!--[if (!mso)&(!IE)]><!--><div style="border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent; padding-top:0px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;"><!--<![endif]-->


                    <div class="">
	<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px;"><![endif]-->
	<div style="color:#0D0D0D;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;line-height:120%; padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px;">
		<div style="line-height:14px;font-size:12px;color:#0D0D0D;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;text-align:left;"><p style="margin: 0;line-height: 14px;text-align: center;font-size: 12px"><span style="font-size: 28px; line-height: 33px;"><strong>{$companyName}</strong></span></p></div>
	</div>
	<!--[if mso]></td></tr></table><![endif]-->
</div>


                    <div align="center" class="img-container center  autowidth  " style="padding-right: 0px;  padding-left: 0px;">
<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px;line-height:0px;"><td style="padding-right: 0px; padding-left: 0px;" align="center"><![endif]-->
  <img class="center  autowidth " align="center" border="0" src="https://d1oco4z2z1fhwp.cloudfront.net/templates/default/20/divider.png" alt="Image" title="Image" style="outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;clear: both;display: block !important;border: 0;height: auto;float: none;width: 100%;max-width: 316px" width="316">
<!--[if mso]></td></tr></table><![endif]-->
</div>



                    <div class="">
	<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px;"><![endif]-->
	<div style="color:#555555;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;line-height:150%; padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px;">
		<div style="font-size:12px;line-height:18px;text-align:center;color:#555555;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;"><p style="margin: 0;font-size: 12px;line-height: 18px;text-align: center">According to our records the Reseller Certificate and Municipal Tax Exception (Form SC 2963) will expire on {$expirationDate}. Please send us the updated document as soon as posible. Thanks!</p></div>
	</div>
	<!--[if mso]></td></tr></table><![endif]-->
</div>


                    <div class="">
	<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px;"><![endif]-->
	<div style="color:#555555;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;line-height:150%; padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px;">
		<div style="font-size:12px;line-height:18px;color:#555555;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;text-align:left;"><p style="margin: 0;font-size: 12px;line-height: 18px;text-align: center">De acuerdo a nuestros archivos, el Certificado de Revendedor y Exención de IVU Municipal (Modelo SC 2963) expirará el {$expirationDate}. Tan pronto como sea posible envíenos el documento actualizado. ¡Muchas gracias!</p></div>
	</div>
	<!--[if mso]></td></tr></table><![endif]-->
</div>



<table border="0" cellpadding="0" cellspacing="0" width="100%" class="divider " style="border-collapse: collapse;table-layout: fixed;border-spacing: 0;mso-table-lspace: 0pt;mso-table-rspace: 0pt;vertical-align: top;min-width: 100%;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%">
    <tbody>
        <tr style="vertical-align: top">
            <td class="divider_inner" style="word-break: break-word;border-collapse: collapse !important;vertical-align: top;padding-right: 10px;padding-left: 10px;padding-top: 30px;padding-bottom: 10px;min-width: 100%;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%">
                <table class="divider_content" height="0px" align="center" border="0" cellpadding="0" cellspacing="0" width="100%" style="border-collapse: collapse;table-layout: fixed;border-spacing: 0;mso-table-lspace: 0pt;mso-table-rspace: 0pt;vertical-align: top;border-top: 0px solid transparent;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%">
                    <tbody>
                        <tr style="vertical-align: top">
                            <td style="word-break: break-word;border-collapse: collapse !important;vertical-align: top;font-size: 0px;line-height: 0px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%">
                                <span>&#160;</span>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
    </tbody>
</table>

              <!--[if (!mso)&(!IE)]><!--></div><!--<![endif]-->
              </div>
            </div>
          <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]-->
        </div>
      </div>
    </div>
    <div style="background-color:transparent;">
      <div style="Margin: 0 auto;min-width: 320px;max-width: 600px;overflow-wrap: break-word;word-wrap: break-word;word-break: break-word;background-color: #525252;" class="block-grid three-up ">
        <div style="border-collapse: collapse;display: table;width: 100%;background-color:#525252;">
          <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="background-color:transparent;" align="center"><table cellpadding="0" cellspacing="0" border="0" style="width: 600px;"><tr class="layout-full-width" style="background-color:#525252;"><![endif]-->

              <!--[if (mso)|(IE)]><td align="center" width="200" style=" width:200px; padding-right: 0px; padding-left: 0px; padding-top:0px; padding-bottom:0px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><![endif]-->
            <div class="col num4" style="max-width: 320px;min-width: 200px;display: table-cell;vertical-align: top;">
              <div style="background-color: transparent; width: 100% !important;">
              <!--[if (!mso)&(!IE)]><!--><div style="border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent; padding-top:0px; padding-bottom:0px; padding-right: 0px; padding-left: 0px;"><!--<![endif]-->


                    &#160;

              <!--[if (!mso)&(!IE)]><!--></div><!--<![endif]-->
              </div>
            </div>
              <!--[if (mso)|(IE)]></td><td align="center" width="200" style=" width:200px; padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:5px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><![endif]-->
            <div class="col num4" style="max-width: 320px;min-width: 200px;display: table-cell;vertical-align: top;">
              <div style="background-color: transparent; width: 100% !important;">
              <!--[if (!mso)&(!IE)]><!--><div style="border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent; padding-top:5px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;"><!--<![endif]-->


                    <div class="">
	<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top: 20px; padding-bottom: 0px;"><![endif]-->
	<div style="color:#a8bf6f;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;line-height:120%; padding-right: 0px; padding-left: 0px; padding-top: 20px; padding-bottom: 0px;">
		<div style="font-size:12px;line-height:14px;color:#a8bf6f;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;text-align:left;"><p style="margin: 0;font-size: 12px;line-height: 14px;text-align: center"><span style="color: rgb(255, 255, 255); font-size: 12px; line-height: 14px;"><span style="font-size: 12px; line-height: 14px; color: rgb(168, 191, 111);">Web:</span> {$root}</span></p></div>
	</div>
	<!--[if mso]></td></tr></table><![endif]-->
</div>

              <!--[if (!mso)&(!IE)]><!--></div><!--<![endif]-->
              </div>
            </div>
              <!--[if (mso)|(IE)]></td><td align="center" width="200" style=" width:200px; padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:5px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><![endif]-->
            <div class="col num4" style="max-width: 320px;min-width: 200px;display: table-cell;vertical-align: top;">
              <div style="background-color: transparent; width: 100% !important;">
              <!--[if (!mso)&(!IE)]><!--><div style="border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent; padding-top:5px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;"><!--<![endif]-->


                    <div class="">
	<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top: 20px; padding-bottom: 0px;"><![endif]-->
	<div style="color:#a8bf6f;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;line-height:120%; padding-right: 0px; padding-left: 0px; padding-top: 20px; padding-bottom: 0px;">
		<div style="font-size:12px;line-height:14px;color:#a8bf6f;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;text-align:left;"><p style="margin: 0;font-size: 12px;line-height: 14px;text-align: center">Email <span style="color: rgb(255, 255, 255); font-size: 12px; line-height: 14px;">{$config['OrderEmail']}</span></p></div>
	</div>
	<!--[if mso]></td></tr></table><![endif]-->
</div>

              <!--[if (!mso)&(!IE)]><!--></div><!--<![endif]-->
              </div>
            </div>
          <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]-->
        </div>
      </div>
    </div>
    <div style="background-color:transparent;">
      <div style="Margin: 0 auto;min-width: 320px;max-width: 600px;overflow-wrap: break-word;word-wrap: break-word;word-break: break-word;background-color: transparent;" class="block-grid ">
        <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;">
          <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="background-color:transparent;" align="center"><table cellpadding="0" cellspacing="0" border="0" style="width: 600px;"><tr class="layout-full-width" style="background-color:transparent;"><![endif]-->

              <!--[if (mso)|(IE)]><td align="center" width="600" style=" width:600px; padding-right: 0px; padding-left: 0px; padding-top:0px; padding-bottom:5px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><![endif]-->
            <div class="col num12" style="min-width: 320px;max-width: 600px;display: table-cell;vertical-align: top;">
              <div style="background-color: transparent; width: 100% !important;">
              <!--[if (!mso)&(!IE)]><!--><div style="border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent; padding-top:0px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;"><!--<![endif]-->


                    <div align="center" class="img-container center  autowidth  fullwidth " style="padding-right: 0px;  padding-left: 0px;">
<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px;line-height:0px;"><td style="padding-right: 0px; padding-left: 0px;" align="center"><![endif]-->
  <img class="center  autowidth  fullwidth" align="center" border="0" src="https://d1oco4z2z1fhwp.cloudfront.net/templates/default/20/rounder-dwn.png" alt="Image" title="Image" style="outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;clear: both;display: block !important;border: 0;height: auto;float: none;width: 100%;max-width: 600px" width="600">
<!--[if mso]></td></tr></table><![endif]-->
</div>




<table border="0" cellpadding="0" cellspacing="0" width="100%" class="divider " style="border-collapse: collapse;table-layout: fixed;border-spacing: 0;mso-table-lspace: 0pt;mso-table-rspace: 0pt;vertical-align: top;min-width: 100%;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%">
    <tbody>
        <tr style="vertical-align: top">
            <td class="divider_inner" style="word-break: break-word;border-collapse: collapse !important;vertical-align: top;padding-right: 30px;padding-left: 30px;padding-top: 30px;padding-bottom: 30px;min-width: 100%;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%">
                <table class="divider_content" align="center" border="0" cellpadding="0" cellspacing="0" width="100%" style="border-collapse: collapse;table-layout: fixed;border-spacing: 0;mso-table-lspace: 0pt;mso-table-rspace: 0pt;vertical-align: top;border-top: 0px solid transparent;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%">
                    <tbody>
                        <tr style="vertical-align: top">
                            <td style="word-break: break-word;border-collapse: collapse !important;vertical-align: top;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%">
                                <span></span>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
    </tbody>
</table>

              <!--[if (!mso)&(!IE)]><!--></div><!--<![endif]-->
              </div>
            </div>
          <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]-->
        </div>
      </div>
    </div>
   <!--[if (mso)|(IE)]></td></tr></table><![endif]-->
		</td>
  </tr>
  </tbody>
  </table>
  <!--[if (mso)|(IE)]></div><![endif]-->


</body></html>



EOF;
		$customer = new Customer($row['AccountNumber']);

		$to = $config['OrderEmail'];
		$subject = "Reseller Certificate and Municipal Tax Exemption Expiration Notification";


		require_once './assets/PHPMailerAutoload.php';

		$results_messages = array();

		$mail = new PHPMailer(true);
		$mail->CharSet = 'utf-8';

		class phpmailerAppException extends phpmailerException {}
		$customerEmail = $customer->Email;
		try {
			$mail->addAddress($to);
			if($customerEmail != ""){

				$to = explode(",",$customerEmail);
				foreach($to as $email){
					$mail->addCC($email);
				}

			}

			if($customer->Salesman->Email != ""){
				$mail->addCC($customer->Salesman->Email);
			}
		$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 = $emailText;
		$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 = 'eli-tpr.com';
		$mail->DKIM_private = $privatekeyfile;
		$mail->DKIM_selector = 'phpmailer';
		$mail->DKIM_passphrase = ''; //key is not encrypted
		try {
		  $mail->send();
		  unlink($privatekeyfile);
		  $results_messages[] = "Message has been sent using MAIL";
		}
		catch (phpmailerException $e) {
		  throw new phpmailerAppException('Unable to send to: ' . $to. ': '.$e->getMessage());
		}
		}
		catch (phpmailerAppException $e) {
		  $results_messages[] = $e->errorMessage();
		}
	}
}
function getWarehouses($type = "%"){
	global $con;
	$query = "SELECT * FROM MULTIPLE_WAREHOUSE WHERE WarehouseType LIKE '$type'";

	$return = new stdClass();
	if($result = mysqli_query($con, $query)){

		if(mysqli_num_rows($result)){

			$return->Result = true;
			$return->Data=[];
			while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
				array_push($return->Data,$row);
			}
			return $return;
		}else{
			$return->Result = false;
			$return->Error = "No warehouses of type ($type) found";
			return $return;
		}
	}else{
		$return->Result = false;
		$return->Error = mysqli_error($con);
		return $return;
	}
}
function setTruckMode($action, $WarehouseID){
	include_once("session.php");
	global $con;
	if ($action == "reset") {
		$_SESSION['TruckMode'] = false;
		$_SESSION['WarehouseID'] = '100';
		echo "true";
		return;
	}elseif ($action == "set") {
		if($WarehouseID === null || $WarehouseID == ""){
			setTruckMode("reset");
			return;
		}
		$query = "DELETE SHOPPING_CART FROM SHOPPING_CART LEFT JOIN MULTIPLE_WH_INVENTORY USING(Line, SKU) WHERE AccountNumber LIKE '{$_SESSION['SalesmanID']}' AND (WarehouseID != $WarehouseID OR WarehouseID IS NULL)";
		$result = mysqli_query($con, $query);
		$_SESSION['TruckMode'] = true;
		$_SESSION['WarehouseID'] = $WarehouseID;

		//var_dump($_SESSION);
		echo "true";
		return;
	}else{
		$_SESSION['TruckMode'] = false;
		$_SESSION['WarehouseID'] = '100';
		echo "true";
		return;
	}
}
function getInventoryCSV($xls = false){
	global $con;
	$query = "SELECT Line, SKU, Description, Qty, PriceA, PriceB FROM INVENTORY WHERE Qty > 0 AND SKU NOT LIKE 'TEST%' ORDER BY IF(`Group` = 'LED', 1, IF(`Group` = 'CFL', 2, 3)) , SKU";
	$result = mysqli_query($con, $query);
	if($xls){

		$heading = false;

		  while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
			if(!$heading) {
			  // display field/column names as a first row
			  echo implode("\t", array_keys($row)) . "\n";
			  $heading = true;
			}
			echo implode("\t", array_values($row)) . "\n";
		  }

	}else{



	$filename = "admin/csv/inventory_" . date("m-d-y", time()) . ".csv";
	$fileResult = CSVExport($query,$filename, ["Line", "SKU", "Description", "Qty", "PriceA", "PriceB"]);

	return $filename;
	}
}
function sendInventoryToSalesmen(){
	error_reporting(E_ALL);
	ini_set("display_errors", 1);
	global $con, $config;
	//echo "ee";
	$query = "SELECT Email FROM SALESMAN WHERE SendInventoryEmail = 1;";
	$result = mysqli_query($con, $query);

	require_once './assets/PHPMailerAutoload.php';

	$results_messages = array();
	$file = getInventoryCSV();
	$filename = "inventory_" . date("m-d-y", time()) . ".csv";
	$email = new PHPMailer();
	$email->SetFrom($config["FromEmail"],  $config["FromEmailName"]); //Name is optional
	$email->Subject   = 'Updated Inventory ' . date("m-d-y", time());
	$email->Body      = "Attached file.";

	while($row = mysqli_fetch_array($result)){
		$email->AddBCC( $row['Email'] );
	}


	$file_to_attach = $file;

	$email->AddAttachment( $file_to_attach , $filename );
	$result = $email->Send();
	if($result){
		
		return $result;
	}else{
		echo "error";
	}
	break;

}
function logEmail($to, $from, $subject, $content){
	global $con;
	$query = "INSERT INTO EMAIL_LOG (MailDate, ToAddress, FromAddress, Subject, Message) VALUES (NOW(), ";
	$query .= "'" . mysqli_real_escape_string($con, $to) . "', ";
	$query .= "'" . mysqli_real_escape_string($con, $from) . "', ";
	$query .= "'" . mysqli_real_escape_string($con, $subject) . "', ";
	$query .= "'" . mysqli_real_escape_string($con, $content) . "';";
	var_dump(mysqli_query($con, $query));

}


function sendPaymentDueEmail($accountNumber){
	global $con, $root, $config;
	$days = 30;
	//Certificado de Registro de Comerciante
	$query = "SELECT AccountNumber, `Name`, TaxIDExpiration2 FROM CUSTOMER WHERE DATEDIFF(TaxIDExpiration2, NOW()) = $days";
	$result = mysqli_query($con, $query);
	while($row = mysqli_fetch_array($result)){
		$companyName = $row['Name'];
		$expirationDate = date("m/d/Y", strtotime($row['TaxIDExpiration2']));
		$emailText = <<<EOF


		<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
    <!--[if gte mso 9]><xml>
     <o:OfficeDocumentSettings>
      <o:AllowPNG/>
      <o:PixelsPerInch>96</o:PixelsPerInch>
     </o:OfficeDocumentSettings>
    </xml><![endif]-->
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width">
    <!--[if !mso]><!--><meta http-equiv="X-UA-Compatible" content="IE=edge"><!--<![endif]-->
    <title></title>
    <!--[if !mso]><!-- -->
	<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" type="text/css" />
	<!--<![endif]-->

    <style type="text/css" id="media-query">
      body {
  margin: 0;
  padding: 0; }

table, tr, td {
  vertical-align: top;
  border-collapse: collapse; }

.ie-browser table, .mso-container table {
  table-layout: fixed; }

* {
  line-height: inherit; }

a[x-apple-data-detectors=true] {
  color: inherit !important;
  text-decoration: none !important; }

[owa] .img-container div, [owa] .img-container button {
  display: block !important; }

[owa] .fullwidth button {
  width: 100% !important; }

[owa] .block-grid .col {
  display: table-cell;
  float: none !important;
  vertical-align: top; }

.ie-browser .num12, .ie-browser .block-grid, [owa] .num12, [owa] .block-grid {
  width: 600px !important; }

.ExternalClass, .ExternalClass p, .ExternalClass span, .ExternalClass font, .ExternalClass td, .ExternalClass div {
  line-height: 100%; }

.ie-browser .mixed-two-up .num4, [owa] .mixed-two-up .num4 {
  width: 200px !important; }

.ie-browser .mixed-two-up .num8, [owa] .mixed-two-up .num8 {
  width: 400px !important; }

.ie-browser .block-grid.two-up .col, [owa] .block-grid.two-up .col {
  width: 300px !important; }

.ie-browser .block-grid.three-up .col, [owa] .block-grid.three-up .col {
  width: 200px !important; }

.ie-browser .block-grid.four-up .col, [owa] .block-grid.four-up .col {
  width: 150px !important; }

.ie-browser .block-grid.five-up .col, [owa] .block-grid.five-up .col {
  width: 120px !important; }

.ie-browser .block-grid.six-up .col, [owa] .block-grid.six-up .col {
  width: 100px !important; }

.ie-browser .block-grid.seven-up .col, [owa] .block-grid.seven-up .col {
  width: 85px !important; }

.ie-browser .block-grid.eight-up .col, [owa] .block-grid.eight-up .col {
  width: 75px !important; }

.ie-browser .block-grid.nine-up .col, [owa] .block-grid.nine-up .col {
  width: 66px !important; }

.ie-browser .block-grid.ten-up .col, [owa] .block-grid.ten-up .col {
  width: 60px !important; }

.ie-browser .block-grid.eleven-up .col, [owa] .block-grid.eleven-up .col {
  width: 54px !important; }

.ie-browser .block-grid.twelve-up .col, [owa] .block-grid.twelve-up .col {
  width: 50px !important; }

@media only screen and (min-width: 620px) {
  .block-grid {
    width: 600px !important; }
  .block-grid .col {
    vertical-align: top; }
    .block-grid .col.num12 {
      width: 600px !important; }
  .block-grid.mixed-two-up .col.num4 {
    width: 200px !important; }
  .block-grid.mixed-two-up .col.num8 {
    width: 400px !important; }
  .block-grid.two-up .col {
    width: 300px !important; }
  .block-grid.three-up .col {
    width: 200px !important; }
  .block-grid.four-up .col {
    width: 150px !important; }
  .block-grid.five-up .col {
    width: 120px !important; }
  .block-grid.six-up .col {
    width: 100px !important; }
  .block-grid.seven-up .col {
    width: 85px !important; }
  .block-grid.eight-up .col {
    width: 75px !important; }
  .block-grid.nine-up .col {
    width: 66px !important; }
  .block-grid.ten-up .col {
    width: 60px !important; }
  .block-grid.eleven-up .col {
    width: 54px !important; }
  .block-grid.twelve-up .col {
    width: 50px !important; } }

@media (max-width: 620px) {
  .block-grid, .col {
    min-width: 320px !important;
    max-width: 100% !important;
    display: block !important; }
  .block-grid {
    width: calc(100% - 40px) !important; }
  .col {
    width: 100% !important; }
    .col > div {
      margin: 0 auto; }
  img.fullwidth, img.fullwidthOnMobile {
    max-width: 100% !important; }
  .no-stack .col {
    min-width: 0 !important;
    display: table-cell !important; }
  .no-stack.two-up .col {
    width: 50% !important; }
  .no-stack.mixed-two-up .col.num4 {
    width: 33% !important; }
  .no-stack.mixed-two-up .col.num8 {
    width: 66% !important; }
  .no-stack.three-up .col.num4 {
    width: 33% !important; }
  .no-stack.four-up .col.num3 {
    width: 25% !important; }
  .mobile_hide {
    min-height: 0px;
    max-height: 0px;
    max-width: 0px;
    display: none;
    overflow: hidden;
    font-size: 0px; } }

    </style>
</head>
<body class="clean-body" style="margin: 0;padding: 0;-webkit-text-size-adjust: 100%;background-color: #6FC1E1">
  <style type="text/css" id="media-query-bodytag">
    @media (max-width: 520px) {
      .block-grid {
        min-width: 320px!important;
        max-width: 100%!important;
        width: 100%!important;
        display: block!important;
      }

      .col {
        min-width: 320px!important;
        max-width: 100%!important;
        width: 100%!important;
        display: block!important;
      }

        .col > div {
          margin: 0 auto;
        }

      img.fullwidth {
        max-width: 100%!important;
      }
			img.fullwidthOnMobile {
        max-width: 100%!important;
      }
      .no-stack .col {
				min-width: 0!important;
				display: table-cell!important;
			}
			.no-stack.two-up .col {
				width: 50%!important;
			}
			.no-stack.mixed-two-up .col.num4 {
				width: 33%!important;
			}
			.no-stack.mixed-two-up .col.num8 {
				width: 66%!important;
			}
			.no-stack.three-up .col.num4 {
				width: 33%!important;
			}
			.no-stack.four-up .col.num3 {
				width: 25%!important;
			}
      .mobile_hide {
        min-height: 0px!important;
        max-height: 0px!important;
        max-width: 0px!important;
        display: none!important;
        overflow: hidden!important;
        font-size: 0px!important;
      }
    }
  </style>
  <!--[if IE]><div class="ie-browser"><![endif]-->
  <!--[if mso]><div class="mso-container"><![endif]-->
  <table class="nl-container" style="border-collapse: collapse;table-layout: fixed;border-spacing: 0;mso-table-lspace: 0pt;mso-table-rspace: 0pt;vertical-align: top;min-width: 320px;Margin: 0 auto;background-color: #6FC1E1;width: 100%" cellpadding="0" cellspacing="0">
	<tbody>
	<tr style="vertical-align: top">
		<td style="word-break: break-word;border-collapse: collapse !important;vertical-align: top">
    <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td align="center" style="background-color: #6FC1E1;"><![endif]-->

    <div style="background-color:transparent;">
      <div style="Margin: 0 auto;min-width: 320px;max-width: 600px;overflow-wrap: break-word;word-wrap: break-word;word-break: break-word;background-color: transparent;" class="block-grid ">
        <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;">
          <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="background-color:transparent;" align="center"><table cellpadding="0" cellspacing="0" border="0" style="width: 600px;"><tr class="layout-full-width" style="background-color:transparent;"><![endif]-->

              <!--[if (mso)|(IE)]><td align="center" width="600" style=" width:600px; padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:0px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><![endif]-->
            <div class="col num12" style="min-width: 320px;max-width: 600px;display: table-cell;vertical-align: top;">
              <div style="background-color: transparent; width: 100% !important;">
              <!--[if (!mso)&(!IE)]><!--><div style="border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent; padding-top:5px; padding-bottom:0px; padding-right: 0px; padding-left: 0px;"><!--<![endif]-->


                    <div align="center" class="img-container center  autowidth  fullwidth " style="padding-right: 0px;  padding-left: 0px;">
<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px;line-height:0px;"><td style="padding-right: 0px; padding-left: 0px;" align="center"><![endif]-->
<div style="line-height:25px;font-size:1px">&#160;</div>  <img class="center  autowidth  fullwidth" align="center" border="0" src="https://d1oco4z2z1fhwp.cloudfront.net/templates/default/20/rounder-up.png" alt="Image" title="Image" style="outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;clear: both;display: block !important;border: 0;height: auto;float: none;width: 100%;max-width: 600px" width="600">
<!--[if mso]></td></tr></table><![endif]-->
</div>


              <!--[if (!mso)&(!IE)]><!--></div><!--<![endif]-->
              </div>
            </div>
          <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]-->
        </div>
      </div>
    </div>
    <div style="background-color:transparent;">
      <div style="Margin: 0 auto;min-width: 320px;max-width: 600px;overflow-wrap: break-word;word-wrap: break-word;word-break: break-word;background-color: #FFFFFF;" class="block-grid ">
        <div style="border-collapse: collapse;display: table;width: 100%;background-color:#FFFFFF;">
          <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="background-color:transparent;" align="center"><table cellpadding="0" cellspacing="0" border="0" style="width: 600px;"><tr class="layout-full-width" style="background-color:#FFFFFF;"><![endif]-->

              <!--[if (mso)|(IE)]><td align="center" width="600" style=" width:600px; padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:5px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><![endif]-->
            <div class="col num12" style="min-width: 320px;max-width: 600px;display: table-cell;vertical-align: top;">
              <div style="background-color: transparent; width: 100% !important;">
              <!--[if (!mso)&(!IE)]><!--><div style="border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent; padding-top:5px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;"><!--<![endif]-->


                    <div align="center" class="img-container center  autowidth  " style="padding-right: 0px;  padding-left: 0px;">
<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px;line-height:0px;"><td style="padding-right: 0px; padding-left: 0px;" align="center"><![endif]-->
  <img class="center  autowidth " align="center" border="0" src="{$root}/img/Logo_500.png" alt="Image" title="Image" style="outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;clear: both;display: block !important;border: 0;height: auto;float: none;width: 100%;max-width: 500px" width="500">
<!--[if mso]></td></tr></table><![endif]-->
</div>



                    <div class="">
	<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px;"><![endif]-->
	<div style="color:#555555;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;line-height:150%; padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px;">
		<div style="font-size:12px;line-height:18px;color:#555555;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;text-align:left;"><p style="margin: 0;font-size: 14px;line-height: 21px;text-align: center">
			Reseller Certificate and Municipal Tax Exception Expiration Notification&#160;<br>
			Notificaci&oacute;n de Expiraci&oacute;n de Certificado de Revendedor y Exenci&oacute;n de IVU Municipal

		</p></div>
	</div>
	<!--[if mso]></td></tr></table><![endif]-->
</div>

              <!--[if (!mso)&(!IE)]><!--></div><!--<![endif]-->
              </div>
            </div>
          <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]-->
        </div>
      </div>
    </div>
    <div style="background-color:transparent;">
      <div style="Margin: 0 auto;min-width: 320px;max-width: 600px;overflow-wrap: break-word;word-wrap: break-word;word-break: break-word;background-color: #FFFFFF;" class="block-grid ">
        <div style="border-collapse: collapse;display: table;width: 100%;background-color:#FFFFFF;">
          <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="background-color:transparent;" align="center"><table cellpadding="0" cellspacing="0" border="0" style="width: 600px;"><tr class="layout-full-width" style="background-color:#FFFFFF;"><![endif]-->

              <!--[if (mso)|(IE)]><td align="center" width="600" style=" width:600px; padding-right: 0px; padding-left: 0px; padding-top:0px; padding-bottom:5px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><![endif]-->
            <div class="col num12" style="min-width: 320px;max-width: 600px;display: table-cell;vertical-align: top;">
              <div style="background-color: transparent; width: 100% !important;">
              <!--[if (!mso)&(!IE)]><!--><div style="border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent; padding-top:0px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;"><!--<![endif]-->


                    <div class="">
	<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px;"><![endif]-->
	<div style="color:#0D0D0D;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;line-height:120%; padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px;">
		<div style="line-height:14px;font-size:12px;color:#0D0D0D;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;text-align:left;"><p style="margin: 0;line-height: 14px;text-align: center;font-size: 12px"><span style="font-size: 28px; line-height: 33px;"><strong>{$companyName}</strong></span></p></div>
	</div>
	<!--[if mso]></td></tr></table><![endif]-->
</div>


                    <div align="center" class="img-container center  autowidth  " style="padding-right: 0px;  padding-left: 0px;">
<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px;line-height:0px;"><td style="padding-right: 0px; padding-left: 0px;" align="center"><![endif]-->
  <img class="center  autowidth " align="center" border="0" src="https://d1oco4z2z1fhwp.cloudfront.net/templates/default/20/divider.png" alt="Image" title="Image" style="outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;clear: both;display: block !important;border: 0;height: auto;float: none;width: 100%;max-width: 316px" width="316">
<!--[if mso]></td></tr></table><![endif]-->
</div>



                    <div class="">
	<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px;"><![endif]-->
	<div style="color:#555555;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;line-height:150%; padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px;">
		<div style="font-size:12px;line-height:18px;text-align:center;color:#555555;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;"><p style="margin: 0;font-size: 12px;line-height: 18px;text-align: center">According to our records the Reseller Certificate and Municipal Tax Exception (Form SC 2963) will expire on {$expirationDate}. Please send us the updated document as soon as posible. Thanks!</p></div>
	</div>
	<!--[if mso]></td></tr></table><![endif]-->
</div>


                    <div class="">
	<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px;"><![endif]-->
	<div style="color:#555555;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;line-height:150%; padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 10px;">
		<div style="font-size:12px;line-height:18px;color:#555555;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;text-align:left;"><p style="margin: 0;font-size: 12px;line-height: 18px;text-align: center">De acuerdo a nuestros archivos, el Certificado de Revendedor y Exención de IVU Municipal (Modelo SC 2963) expirará el {$expirationDate}. Tan pronto como sea posible envíenos el documento actualizado. ¡Muchas gracias!</p></div>
	</div>
	<!--[if mso]></td></tr></table><![endif]-->
</div>



<table border="0" cellpadding="0" cellspacing="0" width="100%" class="divider " style="border-collapse: collapse;table-layout: fixed;border-spacing: 0;mso-table-lspace: 0pt;mso-table-rspace: 0pt;vertical-align: top;min-width: 100%;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%">
    <tbody>
        <tr style="vertical-align: top">
            <td class="divider_inner" style="word-break: break-word;border-collapse: collapse !important;vertical-align: top;padding-right: 10px;padding-left: 10px;padding-top: 30px;padding-bottom: 10px;min-width: 100%;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%">
                <table class="divider_content" height="0px" align="center" border="0" cellpadding="0" cellspacing="0" width="100%" style="border-collapse: collapse;table-layout: fixed;border-spacing: 0;mso-table-lspace: 0pt;mso-table-rspace: 0pt;vertical-align: top;border-top: 0px solid transparent;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%">
                    <tbody>
                        <tr style="vertical-align: top">
                            <td style="word-break: break-word;border-collapse: collapse !important;vertical-align: top;font-size: 0px;line-height: 0px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%">
                                <span>&#160;</span>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
    </tbody>
</table>

              <!--[if (!mso)&(!IE)]><!--></div><!--<![endif]-->
              </div>
            </div>
          <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]-->
        </div>
      </div>
    </div>
    <div style="background-color:transparent;">
      <div style="Margin: 0 auto;min-width: 320px;max-width: 600px;overflow-wrap: break-word;word-wrap: break-word;word-break: break-word;background-color: #525252;" class="block-grid three-up ">
        <div style="border-collapse: collapse;display: table;width: 100%;background-color:#525252;">
          <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="background-color:transparent;" align="center"><table cellpadding="0" cellspacing="0" border="0" style="width: 600px;"><tr class="layout-full-width" style="background-color:#525252;"><![endif]-->

              <!--[if (mso)|(IE)]><td align="center" width="200" style=" width:200px; padding-right: 0px; padding-left: 0px; padding-top:0px; padding-bottom:0px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><![endif]-->
            <div class="col num4" style="max-width: 320px;min-width: 200px;display: table-cell;vertical-align: top;">
              <div style="background-color: transparent; width: 100% !important;">
              <!--[if (!mso)&(!IE)]><!--><div style="border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent; padding-top:0px; padding-bottom:0px; padding-right: 0px; padding-left: 0px;"><!--<![endif]-->


                    &#160;

              <!--[if (!mso)&(!IE)]><!--></div><!--<![endif]-->
              </div>
            </div>
              <!--[if (mso)|(IE)]></td><td align="center" width="200" style=" width:200px; padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:5px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><![endif]-->
            <div class="col num4" style="max-width: 320px;min-width: 200px;display: table-cell;vertical-align: top;">
              <div style="background-color: transparent; width: 100% !important;">
              <!--[if (!mso)&(!IE)]><!--><div style="border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent; padding-top:5px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;"><!--<![endif]-->


                    <div class="">
	<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top: 20px; padding-bottom: 0px;"><![endif]-->
	<div style="color:#a8bf6f;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;line-height:120%; padding-right: 0px; padding-left: 0px; padding-top: 20px; padding-bottom: 0px;">
		<div style="font-size:12px;line-height:14px;color:#a8bf6f;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;text-align:left;"><p style="margin: 0;font-size: 12px;line-height: 14px;text-align: center"><span style="color: rgb(255, 255, 255); font-size: 12px; line-height: 14px;"><span style="font-size: 12px; line-height: 14px; color: rgb(168, 191, 111);">Web:</span> {$root}</span></p></div>
	</div>
	<!--[if mso]></td></tr></table><![endif]-->
</div>

              <!--[if (!mso)&(!IE)]><!--></div><!--<![endif]-->
              </div>
            </div>
              <!--[if (mso)|(IE)]></td><td align="center" width="200" style=" width:200px; padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:5px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><![endif]-->
            <div class="col num4" style="max-width: 320px;min-width: 200px;display: table-cell;vertical-align: top;">
              <div style="background-color: transparent; width: 100% !important;">
              <!--[if (!mso)&(!IE)]><!--><div style="border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent; padding-top:5px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;"><!--<![endif]-->


                    <div class="">
	<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top: 20px; padding-bottom: 0px;"><![endif]-->
	<div style="color:#a8bf6f;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;line-height:120%; padding-right: 0px; padding-left: 0px; padding-top: 20px; padding-bottom: 0px;">
		<div style="font-size:12px;line-height:14px;color:#a8bf6f;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;text-align:left;"><p style="margin: 0;font-size: 12px;line-height: 14px;text-align: center">Email <span style="color: rgb(255, 255, 255); font-size: 12px; line-height: 14px;">{$config['OrderEmail']}</span></p></div>
	</div>
	<!--[if mso]></td></tr></table><![endif]-->
</div>

              <!--[if (!mso)&(!IE)]><!--></div><!--<![endif]-->
              </div>
            </div>
          <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]-->
        </div>
      </div>
    </div>
    <div style="background-color:transparent;">
      <div style="Margin: 0 auto;min-width: 320px;max-width: 600px;overflow-wrap: break-word;word-wrap: break-word;word-break: break-word;background-color: transparent;" class="block-grid ">
        <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;">
          <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="background-color:transparent;" align="center"><table cellpadding="0" cellspacing="0" border="0" style="width: 600px;"><tr class="layout-full-width" style="background-color:transparent;"><![endif]-->

              <!--[if (mso)|(IE)]><td align="center" width="600" style=" width:600px; padding-right: 0px; padding-left: 0px; padding-top:0px; padding-bottom:5px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><![endif]-->
            <div class="col num12" style="min-width: 320px;max-width: 600px;display: table-cell;vertical-align: top;">
              <div style="background-color: transparent; width: 100% !important;">
              <!--[if (!mso)&(!IE)]><!--><div style="border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent; padding-top:0px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;"><!--<![endif]-->


                    <div align="center" class="img-container center  autowidth  fullwidth " style="padding-right: 0px;  padding-left: 0px;">
<!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px;line-height:0px;"><td style="padding-right: 0px; padding-left: 0px;" align="center"><![endif]-->
  <img class="center  autowidth  fullwidth" align="center" border="0" src="https://d1oco4z2z1fhwp.cloudfront.net/templates/default/20/rounder-dwn.png" alt="Image" title="Image" style="outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;clear: both;display: block !important;border: 0;height: auto;float: none;width: 100%;max-width: 600px" width="600">
<!--[if mso]></td></tr></table><![endif]-->
</div>




<table border="0" cellpadding="0" cellspacing="0" width="100%" class="divider " style="border-collapse: collapse;table-layout: fixed;border-spacing: 0;mso-table-lspace: 0pt;mso-table-rspace: 0pt;vertical-align: top;min-width: 100%;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%">
    <tbody>
        <tr style="vertical-align: top">
            <td class="divider_inner" style="word-break: break-word;border-collapse: collapse !important;vertical-align: top;padding-right: 30px;padding-left: 30px;padding-top: 30px;padding-bottom: 30px;min-width: 100%;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%">
                <table class="divider_content" align="center" border="0" cellpadding="0" cellspacing="0" width="100%" style="border-collapse: collapse;table-layout: fixed;border-spacing: 0;mso-table-lspace: 0pt;mso-table-rspace: 0pt;vertical-align: top;border-top: 0px solid transparent;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%">
                    <tbody>
                        <tr style="vertical-align: top">
                            <td style="word-break: break-word;border-collapse: collapse !important;vertical-align: top;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%">
                                <span></span>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
    </tbody>
</table>

              <!--[if (!mso)&(!IE)]><!--></div><!--<![endif]-->
              </div>
            </div>
          <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]-->
        </div>
      </div>
    </div>
   <!--[if (mso)|(IE)]></td></tr></table><![endif]-->
		</td>
  </tr>
  </tbody>
  </table>
  <!--[if (mso)|(IE)]></div><![endif]-->


</body></html>



EOF;
		$customer = new Customer($row['AccountNumber']);

		$to = $config['OrderEmail'];
		$subject = "Reseller Certificate and Municipal Tax Exemption Expiration Notification";


		require_once './assets/PHPMailerAutoload.php';

		$results_messages = array();

		$mail = new PHPMailer(true);
		$mail->CharSet = 'utf-8';

		class phpmailerAppException extends phpmailerException {}
		$customerEmail = $customer->Email;
		try {
			$mail->addAddress($to);
			if($customerEmail != ""){

				$to = explode(",",$customerEmail);
				foreach($to as $email){
					$mail->addCC($email);
				}

			}

			if($customer->Salesman->Email != ""){
				$mail->addCC($customer->Salesman->Email);
			}
		$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 = $emailText;
		$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 = 'eli-tpr.com';
		$mail->DKIM_private = $privatekeyfile;
		$mail->DKIM_selector = 'phpmailer';
		$mail->DKIM_passphrase = ''; //key is not encrypted
		try {
		  $mail->send();
		  unlink($privatekeyfile);
		  $results_messages[] = "Message has been sent using MAIL";
		}
		catch (phpmailerException $e) {
		  throw new phpmailerAppException('Unable to send to: ' . $to. ': '.$e->getMessage());
		}
		}
		catch (phpmailerAppException $e) {
		  $results_messages[] = $e->errorMessage();
		}
	}
}
function verifyEmail($email){
	global $config;
	// Initialize library class
	$mail = new VerifyEmail($email, $config['FromEmail'], 25);

	if($mail->verify()){
		echo "true";
	}else{
		if($mail->mx){
			echo "true";
		}else{
			echo "false";
		}
	}

}
function insertPrintButton(){
	echo "<button onclick=\"window.print();\" class=\"btn btn-primary hidden-print\">Print</button>";
}
function getInterchange($interchange){
  global $con;
  $query = "SELECT * FROM INTERCHANGE WHERE Reference LIKE '$interchange'";
  $result = mysqli_query($con, $query);
  $row = mysqli_fetch_array($result);
  return $row;
}
function itemsWithoutImages(){
	global $con;
	$query = "SELECT * FROM INVENTORY WHERE Active = 1 AND (Discontinued = 0 OR Qty > 0)";
	$result = mysqli_query($con, $query);
	while($row = mysqli_fetch_array($result)){
		$item = new Item("%", $row['Line'], $row["SKU"]);
		if(stripos($item->getImage(),"./img/") === 0){
			if(stripos($item->getImage(),"availa")>0){
				//echo $item->getImage() . "<br>";
				echo $item->SKU . "," . $item->Description . "\n";
			}
			
		}else{
			//echo $item->getImage() . "<br>";
			echo $item->SKU . "," . $item->Description . "\n";
		}
	}
}
?>
