<?php
$nSearch = nSanitizeGeneralText($_GET["term"]);

if(!$nSearch){ return; }

require("../../inc/stop_cache.php");
require("../../inc/secure_page.php");
require("../../../inc/dbconnect.php");

$nDataARRAY = array();

// Search orders
$nSubDataARRAY = array();
$Query = "SELECT nID,nOrderNum FROM nOrderInfo WHERE (nOrderNum LIKE '%".$nSearch."%') LIMIT 0,20";
mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
while($Row = mysql_fetch_array($Result)){
	$nSubDataARRAY["category"] = "Orders";
	$nSubDataARRAY["label"] = "Order# ".$Row["nOrderNum"];
	$nSubDataARRAY["value"] = $Row["nOrderNum"];
	$nSubDataARRAY["id"] = $Row["nID"];
	$nDataARRAY[] = $nSubDataARRAY;
}

// Search products
$nSubDataARRAY = array();
$Query = "SELECT nID,nProdName FROM nProdInfo WHERE (nProdName LIKE '%".$nSearch."%' OR nProdSKU OR nSKUAll LIKE '%".$nSearch."%')
	ORDER BY 
	(CASE WHEN nProdName LIKE '%$nSearch%' THEN 1 ELSE 0 END) + 
	(CASE WHEN nProdSKU LIKE '%$nSearch%' THEN 1 ELSE 0 END) 
	DESC 
	LIMIT 0,20";
mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
while($Row = mysql_fetch_array($Result)){
	$nSubDataARRAY["category"] = "Products";
	$nSubDataARRAY["label"] = $Row["nProdName"];
	$nSubDataARRAY["value"] = $Row["nProdName"];
	$nSubDataARRAY["id"] = $Row["nID"];
	$nDataARRAY[] = $nSubDataARRAY;
}

// Search customers
$nSubDataARRAY = array();
$Query = "SELECT nID,nContactName,nCompanyName FROM nCustomerInfo WHERE (nCompanyName LIKE '%".$nSearch."%' OR nContactName LIKE '%".$nSearch."%' OR nCustID LIKE '%".$nSearch."%' OR nLoginUser LIKE '%".$nSearch."%' OR nBillName LIKE '%".$nSearch."%' OR nShipName LIKE '%".$nSearch."%')
	ORDER BY 
	(CASE WHEN nCompanyName LIKE '%$nSearch%' THEN 1 ELSE 0 END) + 
	(CASE WHEN nContactName LIKE '%$nSearch%' THEN 1 ELSE 0 END) + 
	(CASE WHEN nCustID LIKE '%$nSearch%' THEN 1 ELSE 0 END) + 
	(CASE WHEN nLoginUser LIKE '%$nSearch%' THEN 1 ELSE 0 END) + 
	(CASE WHEN nBillName LIKE '%$nSearch%' THEN 1 ELSE 0 END) + 
	(CASE WHEN nShipName LIKE '%$nSearch%' THEN 1 ELSE 0 END) 
	DESC 
	LIMIT 0,20";
mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
while($Row = mysql_fetch_array($Result)){
	$nSubDataARRAY["category"] = "Customers";
	$nSubDataARRAY["label"] = $Row["nContactName"];
	if($Row["nCompanyName"]){ $nSubDataARRAY["label"] = $Row["nContactName"]." (".$Row["nCompanyName"].")"; }
	$nSubDataARRAY["value"] = $Row["nContactName"];
	$nSubDataARRAY["id"] = $Row["nID"];
	$nDataARRAY[] = $nSubDataARRAY;
}

// Output
echo json_encode($nDataARRAY);

function nSanitizeGeneralText($nText){
	$notAllowed = array("<",">","1=1","1 =1","1= 1","1 = 1");
	$nText = trim(str_replace($notAllowed,"",$nText));
	$nText = trim(str_replace("\"","&quot;",$nText));
	return $nText;
}

require("../../inc/db_close.php");
?>
