<?php
// ini_set("display_errors", 1);
// error_reporting( E_ALL);
$isAdmin = stripos($_SERVER['SCRIPT_NAME'],"/admin/")===false?false:true;
if (!$isAdmin) {
  include_once("connect.php");
  include_once("session.php");
}else{
  include_once("../connect.php");
  include_once("../session.php");
}



$function = $_REQUEST['f'];
if($function == "processOrder"){
    processOrder($_REQUEST);
}elseif($function == "getPendingInvoices"){
	getPendingInvoices();
}elseif($function == "saveReviewField"){
	saveReviewField($_REQUEST['invoice'], $_POST);
}elseif($function == "setReviewInvoice"){

	setReviewInvoice();
}elseif($function == "addNewItem"){
	addNewItem($_REQUEST['invoice'], $_REQUEST['sku']);
}elseif($function == "addNewItem2"){
	addNewItem2($_REQUEST['invoice'], $_REQUEST['sku']);
}elseif($function == "deleteInvoiceItem"){
	deleteInvoiceItem($_REQUEST['invoice'], $_REQUEST['id']);
}elseif($function == "setInvoiceFinalize"){
	setInvoiceFinalize($_REQUEST['invoice']);

}elseif($function == "generateReviewTable"){
	generateReviewTable($_REQUEST['invoice']);
}elseif($function == "createNewInvoice"){
	echo createNewInvoice($_REQUEST['accountNumber']);
}elseif($function == "sendEstimateToShoppingCart"){
	$estimate = new Estimate($_REQUEST['eid']);
	if($estimate->sendToShoopingCart()){
		echo "true";
	}else{
		echo "false";
	}
}elseif($function == "voidInvoice"){
	voidInvoice($_REQUEST['id'], $_REQUEST['reason']);
}elseif($function == "setCrate"){
	setCrate($_REQUEST['invoice'], $_REQUEST['crateNumber']);
}elseif($function == "removeCrate"){
	removeCrate($_REQUEST['invoice'], $_REQUEST['crateNumber']);
}elseif($function == "getPreviousPurchases"){
	getPreviousPurchases($_REQUEST['an'],$_REQUEST['line'], $_REQUEST['sku']);
}elseif($function == "setReference"){
	if($_REQUEST['type'] == "OriginalInvoice"){
		//die('here');
		setOriginalInvoice($_REQUEST['origInvoice'], $_REQUEST['currentInvoice'], $_REQUEST['Line'], $_REQUEST['SKU']);
	}elseif ($_REQUEST['type'] == "Warranty") {
    setWarrantyInvoice($_REQUEST['origInvoice'], $_REQUEST['currentInvoice'], $_REQUEST['Line'], $_REQUEST['SKU']);
  }

}elseif($function == "productLookup"){
	productLookup($_REQUEST['term'], $_REQUEST['an']);
}elseif($function == "changeInvoiceCustomer"){
	changeInvoiceCustomer($_REQUEST['invoice'], $_REQUEST['an']);
}elseif($function == "updateDueDateWithDeliveryDate"){
	$invoice = new Invoice($_REQUEST['id']);
	$invoice->updateDueDateWithDeliveryDate();
	echo date("m/d/Y", strtotime($invoice->DueDate));
}elseif($function == "resendInvoice"){
  $invoice = new Invoice($_REQUEST['id']);
  if($invoice->sendEmail()){
    echo "Invoice sent to: " . $invoice->Customer->Email;
  }
}elseif($function == "setInvoicesAsDelivered"){
	//die("test");
	$invoices = $_REQUEST['invoiceList'];
	include_once("functions.php");


	foreach($invoices as $invoice){
    if(substr($invoice,0,1) == "A"){

      $assignment = new Assignment($invoice);
      //die("test");
      $assignment->DeliveryDate = "NOW()";
      $assignment->Completed = 1;
      $assignment->save();
    }else{
      $invoiceObj = new Invoice($invoice);
      //var_dump($invoiceObj);
      $invoiceObj->deliverInvoice();
    }

	}
	echo "true";
}
function changeInvoiceCustomer($invoiceID, $accountNumber){
	global $con;
	//still doesnt recalculate customer prices
	$newCustomer = new Customer($accountNumber);
	if($newCustomer->Name != ""){
		$query = "UPDATE INVOICE_HEAD SET AccountNumber = '$accountNumber',
		ShipToName = '" . $newCustomer->Name . "',
		ShipToAddress1 = '" . $newCustomer->ShipToAddress1 . "',
		ShipToAddress2 = '" . $newCustomer->ShipToAddress2 . "',
		ShipToCity = '" . $newCustomer->ShipToCity . "',
		ShipToState = '" . $newCustomer->ShipToState . "',
		ShipToZip = '" . $newCustomer->ShipToZip . "',
		BillToName = '" . $newCustomer->Name . "',
		BillToAddress1 = '" . $newCustomer->Address1 . "',
		BillToAddress2 = '" . $newCustomer->Address2 . "',
		BillToCity = '" . $newCustomer->City . "',
		BillToState = '" . $newCustomer->State . "',
		BillToZip = '" . $newCustomer->ZipCode . "'
		WHERE InvoiceID = $invoiceID";
		$result = mysqli_query($con, $query);
		if($result){
			echo "true";
		}else{
			echo "false";
		}
	}else{
		echo "false";
	}

}
function setCrate($invoice, $crateNumber){
	global $con;
	$invoice = new Invoice($invoice);
	if($invoice->setCrate($crateNumber)){
		echo "true";
	}else{
		echo "false";
	}

}
function removeCrate($invoice, $crateNumber){
	global $con;
	//echo $invoice;
	$invoice = new Invoice($invoice);
	if($invoice->removeCrate($crateNumber)){
		echo "true";
	}else{
		echo "false";
	}

}
function setInvoiceFinalize($invoiceID){
	$invoice = new Invoice($invoiceID);
	if($invoice->Finalize()){
		echo "true";
	}
}
function productLookup($term, $accountNumber){
	global $con;
	$term = mysqli_real_escape_string($con, $term);
	if(true){
 		if (true) {
 			$term = "%" . str_ireplace(" ", "%", $term) . "%";
 		}

 	}
 	$query1 = "SELECT INVENTORY.*, 1 SortOrder, 0 as Reference, \"\" AS Supplier FROM `INVENTORY` WHERE INVENTORY.`SKU` LIKE '$term'";
 	$query2 = "SELECT INVENTORY.*, 2 SortOrder, 0 as Reference, \"\" AS Supplier FROM `INVENTORY` WHERE REPLACE(INVENTORY.`SKU`,\"-\",\"\") LIKE '" . str_ireplace("-", "", $term) . "'" . $line . $group;
 	$query3 = "SELECT INVENTORY.*, 2 SortOrder, 0 as Reference, \"\" AS Supplier FROM `INVENTORY` WHERE `Interchange` LIKE '%$term%'";
	$query3 .= "UNION SELECT
			INVENTORY.*, 1.5 SortOrder, `Reference`, Supplier
		FROM `INVENTORY`
			LEFT JOIN
			`INTERCHANGE` ON `INVENTORY`.SKU = INTERCHANGE.SKU

		WHERE

			REPLACE(INTERCHANGE.Reference, \"-\", \"\") LIKE '" . str_ireplace("-", "", $term) . "'";

 	$where = "";
 	$index = 0;
 	if ((true)) { //if wc=1
 		$partGroup = explode("%", $term);
 	}else{
 		$partGroup = explode(" ", $term);
 	}

 	$partCount = count($partGroup);
 	foreach ($partGroup as $key => $value) {
 		$index++;
 		$where .= "CONCAT_WS(' ', `Description`, `Notes`) LIKE '%$value%'";
 		if ($index < $partCount) {
 			$where .= " AND ";
 		}
 	}
 	/*
 	$query4 = "SELECT INVENTORY.*, SHOPPING_CART.Qty AS OnOrder FROM `INVENTORY` LEFT JOIN SHOPPING_CART
 			ON `INVENTORY`.SKU = SHOPPING_CART.SKU
 				AND INVENTORY.`Group` = SHOPPING_CART.`Group`
 				AND `INVENTORY`.Line = SHOPPING_CART.Line
 				AND SHOPPING_CART.`AccountNumber` = '$AccountNumber' WHERE `Description` LIKE '%$term%'" . $line . $group;
 	*/
 	$query4 = "SELECT INVENTORY.*, 2 SortOrder, 0 as Reference, \"\" AS Supplier FROM `INVENTORY` WHERE " . $where;

 	$query5 = "SELECT INVENTORY.*, 2 SortOrder, 0 as Reference, \"\" AS Supplier FROM `INVENTORY` WHERE `Notes` LIKE '%$term%'";
	$query6 = "SELECT INVENTORY.*, 2 SortOrder, 0 as Reference, \"\" AS Supplier FROM `INVENTORY` JOIN PRODUCT_UPC USING(Line, SKU) WHERE `UPC` LIKE '%$term%'";
 	$query = $query1 . " UNION " . $query2 . " UNION " . $query3 . " UNION " . $query4 . " UNION " . $query5 . " UNION " . $query6 . " ORDER BY SortOrder, `sku`";
 /**/
	$queryPLS = $query2 . " UNION " . $query3 . " UNION " . $query4 . " UNION " . $query5 . " ORDER BY SortOrder, `sku`";
	$queryPLS = str_ireplace(" UNION ", " AND INVENTORY.Qty <= 0 GROUP BY `Group`, SKU UNION ",$queryPLS);
	$queryPLS = str_ireplace(" ORDER BY ", " AND INVENTORY.Qty <= 0 GROUP BY `Group`, SKU ORDER BY ",$queryPLS);
	$result = mysqli_query($con, $query);
	if(mysqli_num_rows($result)){
	?>
		<table class="table table-condensed">
			<thead>
				<tr>
					<th>Line</th>
					<th>SKU</th>
					<th>Description</th>
					<th>Qty</th>
					<th>Committed</th>
					<th>Price</th>
					<th>Add</th>
				</tr>
			</thead>

			<tbody>
		<?php
		while($row = mysqli_fetch_array($result)){
			$product = new Item($row['Group'], $row['Line'], $row['SKU']);
		?>
			<tr>
				<td><?= $product->Line ?></td>
				<td><?= $product->SKU ?></td>
				<td>
				<?= $product->Description . " " , $product->Notes ?>
				<?php
				if($product->getUPC()){
					echo "<br>UPC: " . $product->getUPC() ;
				}
				?>
				</td>
				<td><?= $product->Qty ?></td>
				<td><?= $product->getCommittedQty(); ?></td>
				<td><?= getCustomerPrice($row['Group'], $row['Line'], $row['SKU'], $accountNumber) ?></td>
				<td><button onclick="addLookupItem('<?= $row['Line'] ?>','<?= $row['SKU'] ?>')" class="btn btn-sm btn-success">Add</button></td>
			</tr>
		<?php
		}
		?>
			</tbody>
		</table>
	<?php
	}else{
	?>
		<div class="" style="margin-top: 20px;"><center><h3>No results found.</h3></center></div>
	<?php
	}

}
function voidInvoice($invoiceID, $reason){
	$invoice = new Invoice($invoiceID);
	//var_dump($invoice->VoidInvoice($reason));
	if($invoice->VoidInvoice($reason)){
		$return = new stdClass();
		$return->Result = true;
		echo json_encode($return);
	}
}
function processOrder($data){

	$order = new Order($data['order']);
	if($order->Processed){
		$return = new stdClass();
		$return->Error = "Order already Processed";
		$return->Value = false;
		return $return;
	}else{

		$invoiceNumber = $order->generateInvoice();
		//$invoice = new Invoice($invoiceNumber);
		//$invoice->save();

	}
}
function generateReviewTable($invoiceID){
	$invoice = new Invoice($invoiceID);

	?>

	<thead>
 	      <tr>
 	        <th style="width: 10%">Line Group</th>
 	        <th style="width: 10%">Item</th>
			<th style="width: 50%">Description</th>
			<th></th>
			<th>On Hand</th>
			<th style="width: 5%" class="centered">Ordered</th>
			<th style="width: 5%" class="centered">Shipped</th>
			<th style="width: 5%; text-align: right;">Cost</th>
 	        <th style="width: 5%; text-align: right;">Price</th>
			<th style="width: 5%" class="centered">PM%</th>
 	        <th style="width: 5%; text-align: right;">Extension</th>
			<th></th>
 	      </tr>
 	    </thead>
 	  	<tbody>
 	  	<?php

 	  		$index = 0;
			$totalItems = 0;
			$invoiceTotal = 0;
      $itemArray = $invoice->Items;
			$locations = [];
			foreach($itemArray as $key => $item){
				$locations[$key] = $item->Location;
			}
			array_multisort($locations, SORT_ASC, $itemArray);
			foreach($itemArray as $key => $item){
				$currItem = new Item($item->Group, $item->Line, $item->SKU);


 	  	?>
 	  		<tr>
 	    			<td>
 	        			<span id="<?= $item->ID ?>-Line" class="itemInfo"><?= $item->Line ?></span>
 	        			<span id="<?= $item->ID ?>-Group" class="itemInfo"><?= $item->Group ?></span>
 	        		</td>
 	        		<td style="text-overflow: ellipsis;" >
 	        			<span id="<?= $item->ID ?>-SKU" class="itemInfo"><b><?= $item->SKU ?></b></span>
					</td>
					<td>
 	        			<span class="itemInfo">

						<?php
						if(substr($invoice->AccountNumber,0,5) == "10002" && $currItem->getAttribute("SearsItem")){
							echo "<b>" . $currItem->getAttribute("SearsItem") . "</b> - ";
						}
						?>

						<?= $item->Description . " " . $item->Notes ?>
						<?php
						if($currItem->getAttribute("Barcode")){
							echo "/ " . $currItem->getAttribute("Barcode");
						}

						?>
						<?php
            if($item->ReferenceType == "OriginalInvoice"){
							echo "<br>" . "<b>Originally from invoice: " . $item->Reference . "</b>";
						}elseif($item->ReferenceType == "Warranty"){
							echo "<br>" . "<b>Damaged Warranty item from invoice: " . $item->Reference . "</b>";
						}
						?>
						</span>

					</td>
					<td>
					<?php
						if($item->ShippedQty < 0){
					?>
						<button  data-id="<?= $item->ID ?>"  id="<?= $item->ID ?>-AddRef"  onclick="addReference(<?= $item->ID ?>)"  class="btn btn-primary btn-sm">Add Ref.</button>
					<?php
						}

					?>
					</td>
					<td class="centered">
						<?= $currItem->Qty ?>
					</td>
					<td class="centered">
						<input name="<?= $item->ID ?>-OrderQty" class="editItem centered form-control input-sm" type="text" id="<?= $item->ID ?>-OrderQty" value="<?= $item->OrderQty ?>"/>

					</td>
					<td class="centered">
						<input name="<?= $item->ID ?>-ShippedQty" class="editItem centered form-control input-sm" type="text" id="<?= $item->ID ?>-ShippedQty" value="<?= $item->ShippedQty ?>"/>
 	        		</td>
					<td style="text-align: right;">
						<?php

						if($item->AvgCost == 0){
						?>
						<input name="<?= $item->ID ?>-AvgCost" class="editItem centered form-control input-sm" type="text" id="<?= $item->ID ?>-AvgCost" value="<?= $item->AvgCost ?>"/>
						<?php
						}else{
							echo moneyFormat($item->AvgCost/.85);
						}
						?>
					</td>
 	        		<td style="text-align: right;">
						<input name="<?= $item->ID ?>-Price" style="text-align: right;" class="editItem form-control input-sm" type="text" id="<?= $item->ID ?>-Price" value="<?= $item->Price ?>"/>
 	        		</td>
 	        		<td class="centered">
						<?php
						if($item->Price == 0){
							echo "-100 %";

						}else{
							echo round((($item->Price-($item->AvgCost/.85))/$item->Price)*100,2) . " %";
						}
						?>
					</td>
 	        		<td style="text-align: right;" id="<?= $item->ID ?>-Extension" >
						<?php
							echo moneyFormat($item->Price*$item->ShippedQty);
							$invoiceTotal+= ($item->Price*$item->ShippedQty);
						?>
 	        		</td>
					<td><a onclick="deleteInvoiceItem(<?= $item->ID ?>); return false;" class="btn btn-sm btn-danger"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
					</a></td>
 	      	</tr>
 	      	<?php
 	      	$index++;
 	      	}?>


 	      	<tr>
				<td style="text-align: right;">Add New Item:</td>
				<td colspan="1"><input type="text" name="newItemSKU" id="newItemSKU" placeholder="SKU" /></td>
				<td><a id="AddNewItemButton" class="btn btn-primary btn-sm">Add</a>  <button onclick="$('#productLookupModal').modal('toggle');" class="btn btn-primary btn-sm">Product Lookup</button></td>
 	      		<td colspan="6" style="text-align: right;"><span style="font-weight: bold; text-align: right;">Subtotal</span></td>
				<td style="text-align: right;"><?= moneyFormat($invoice->InvoiceSubtotal); ?></td>
				<script type="text/javascript">
					$('#AddNewItemButton').on("click", function(){
						$.get('mod.php?p=invoice&a=functions&f=addNewItem2&invoice=<?= $invoice->InvoiceID ?>&master=1&sku=' + $('#newItemSKU').val(), function(data){
							if(data !== "false"){
								refreshReviewTable();
								askForQty(data);
							}else{
								alert("Error, maybe SKU does not exist.");
							}
							});
					});
					$('#newItemSKU').on("keyup", function(e){
						if(e.keyCode == 13){
							$('#AddNewItemButton').click();
						}
					});
					$('.editItem').on('change', function(){
					$.post("mod.php?p=invoice&a=functions&f=saveReviewField&invoice=<?= $_REQUEST['id'] ?>",
						   { id: $(this).attr('id'), value: $(this).val() }, function(data){
								$(this).val(data);

								refreshReviewTable(true);

						   });
				});
				</script>
 	      	</tr>
			<tr class="borderless">
 	      		<td colspan="8" style="text-align: right;"><span style="font-weight: bold; text-align: right;"><?= getSetting("Tax1Name")['value'] ?>
				</span></td>
				<td><input name="Tax1Rate" style="text-align: right;" class="editItem form-control input-sm" type="text" id="Tax1Rate" value="<?= $invoice->Tax1Rate ?>"/></td>
				<td style="text-align: right;"><?= moneyFormat($invoice->Tax1Total); ?></td>
 	      	</tr>
			<tr class="borderless">
 	      		<td colspan="8" style="text-align: right;"><span style="font-weight: bold; text-align: right;"><?= (getSetting("Tax2Name")['value']) ?>
				</span></td>
				<td><input name="Tax2Rate" style="text-align: right;" class="editItem form-control input-sm" type="text" id="Tax2Rate" value="<?= $invoice->Tax2Rate ?>"/></td>
				<td style="text-align: right;"><?= moneyFormat($invoice->Tax2Total); ?></td>
 	      	</tr>
			<tr class="borderless">

 	      		<td colspan="9" class="borderless" style="text-align: right;"><span style="font-weight: bold;">Total</span></td>
				<td style="text-align: right;"><?= moneyFormat($invoice->InvoiceTotal); ?></td>
 	      	</tr>
 	      </tr>
 	    </tbody>

	<?php



}
function createNewInvoice($accountNumber){
	global $con;
	$customer = new Customer($accountNumber);
	$query = "INSERT INTO INVOICE_HEAD (OrderID, AccountNumber, CreationDate, Salesman, Notes, PONumber,
			DeliveryMethod, InvoiceUser, SentPicking, Tax1Rate, Tax2Rate, Terms, DueDate,
			ShipToName, ShipToAddress1, ShipToAddress2, ShipToCity,  ShipToState, ShipToZip,  BillToName,
			BillToAddress1, BillToAddress2, BillToCity, BillToState, BillToZip) VALUES (
			'',
			'{$customer->AccountNumber}',
			DATE_ADD(NOW(), INTERVAL -4 HOUR),
			'{$customer->Salesman->ID}', '',
			'', 'Regular Delivery',
			'{$_SESSION['Username']}', DATE_ADD(NOW(), INTERVAL -4 HOUR),
			" . getSetting("Tax1Percent")['value'] . " ,
			" . getSetting("Tax2Percent")['value'] . ",
			'{$customer->Terms}',
			DATE_ADD(NOW(), INTERVAL {$customer->TermsDays} DAY),
			'{$customer->Name}',
			'{$customer->ShipToAddress1}',
			'{$customer->ShipToAddress2}',
			'{$customer->ShipToCity}',
			'{$customer->ShipToState}','{$customer->ShipToZip}',
			'{$customer->Name}','{$customer->Address1}',
			'{$customer->Address2}','{$customer->City}',
			'{$customer->State}','{$customer->ZipCode}')";
	if($result = mysqli_query($con, $query)){
		$id = mysqli_insert_id($con);
		return $id;
	}else{
		return "false";
	}

}
function saveReviewField($invoice, $data){
	global $con;
	$invoice = new Invoice($invoice);
	$id = $data['id'];
	if($data['id'] == "Terms"){
		$invoice->setTerms($data['value']);
		$invoice->updateCustomerInfo();
		$invoice->save();
	}elseif($data['id'] == "Salesman"){
		$invoice->setSalesman($data['value']);
	}elseif(stripos($id,"-Price")){
		$itemID = str_ireplace("-Price", "",$id);
		$invoice->setItemPrice($itemID, $data['value']);
		echo str_ireplace("$", "", moneyFormat($data['value']));
	}elseif(stripos($id, "-ShippedQty")){
		$itemID = str_ireplace("-ShippedQty", "",$id);
		$invoice->setItemShippedQty($itemID, intval($data['value']));
		echo intval($data['value']);
	}elseif(stripos($id, "-OrderQty")){
		$itemID = str_ireplace("-OrderQty", "",$id);
		$invoice->setItemOrderQty($itemID, intval($data['value']));
		echo intval($data['value']);
	}else{
		$invoice->{$data['id']} = $data['value'];
		$invoice->updateCustomerInfo();
		$invoice->save();
		echo $data['value'];
	}



}
function addNewItem($invoice, $sku){
	global $con;
	$invoice = new Invoice($invoice);
	if($invoice->addNewItem($sku, 1)){
		echo "true";
	}else{
		echo "false";
	}
}
function addNewItem2($invoice, $sku){
	global $con;
	$invoice = new Invoice($invoice);
	$result = $invoice->addNewItem2($sku, 1);
	//var_dump($result);
	if($result){
		echo $result;
	}else{
		echo "false";
	}
}
function setReviewInvoice(){
	global $con;
	$return['Result'] = true;
	echo json_encode($return);

}
function deleteInvoiceItem($invoice, $id){
	$invoice = new Invoice($invoice);

	if($invoice->deleteInvoiceItem($id)){
		echo "true";
	}else{
		echo "false";
	}
}
function getPendingInvoices(){
    global $con;
	//$query = "SELECT ORDER_HEAD.*, CUSTOMER.Name FROM ORDER_HEAD, CUSTOMER WHERE ORDER_HEAD.AccountNumber = CUSTOMER.AccountNumber AND Processed = FALSE AND (ProcessUser LIKE '' OR ProcessUser LIKE '" . $_SESSION['Username'] . "') AND DeleteOrder != 1";
	$query = "SELECT 1 Priority, INVOICE_HEAD.*, CUSTOMER.Name, CUSTOMER.DueDays, ORDER_HEAD.SalesmanOrder FROM INVOICE_HEAD LEFT JOIN CUSTOMER USING(AccountNumber) LEFT JOIN ORDER_HEAD USING(OrderID) WHERE Status = FALSE AND Void != 1 AND (INVOICE_HEAD.DeliveryMethod LIKE '%SAME%DA%' OR INVOICE_HEAD.Notes LIKE '%SAME%DA%') UNION
SELECT 2 Priority, INVOICE_HEAD.*, CUSTOMER.Name, CUSTOMER.DueDays, ORDER_HEAD.SalesmanOrder FROM INVOICE_HEAD LEFT JOIN CUSTOMER USING(AccountNumber) LEFT JOIN ORDER_HEAD USING(OrderID) WHERE Status = FALSE AND Void != 1 AND (INVOICE_HEAD.DeliveryMethod LIKE '%PICKUP%' OR INVOICE_HEAD.Notes LIKE '%RECOGER%') UNION
SELECT 3 Priority, INVOICE_HEAD.*, CUSTOMER.Name, CUSTOMER.DueDays, ORDER_HEAD.SalesmanOrder FROM INVOICE_HEAD LEFT JOIN CUSTOMER USING(AccountNumber) LEFT JOIN ORDER_HEAD USING(OrderID) WHERE Status = FALSE AND Void != 1 AND (INVOICE_HEAD.DeliveryMethod NOT LIKE '%SAME%DA%' AND INVOICE_HEAD.Notes NOT LIKE '%SAME%DA%'
  AND INVOICE_HEAD.DeliveryMethod NOT LIKE '%PICKUP%' AND INVOICE_HEAD.Notes NOT LIKE '%RECOGER%') ORDER BY Priority, InvoiceID ASC";
//echo $query;
//var_dump($con);
	$result = mysqli_query($con, $query);
	$return = [];
	//echo $query;
	while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
		$invoice = new Invoice($row['InvoiceID']);
		//$invoice->Salesman = new Salesman($invoice->Salesman);
		//$invoice->Salesman = $invoice->Salesman->FullName;
		$row['SalesmanName'] = $invoice->Salesman->Name;
		$row['ItemCount'] = count($invoice->Items);
		unlink($invoice->Items);
		$row['Subtotal'] = ($invoice->Subtotal);
		//$dueDays = new Customer($row['AccountNumber']);
		//$row['DueDays'] = $dueDays->getDueDays();

		$row['OnHoldDate'] = date("m/d/Y h:i A",strtotime($row['OnHoldDate']));
		$row['CreationDate'] = date("m/d/Y h:i A",strtotime($row['CreationDate']));
		$row['SentPicking'] = date("m/d/Y h:i A",strtotime($row['SentPicking']));
		array_push($return, $row);
	}
	//var_dump($return);
	echo safe_json_encode($return);
}

function setWarrantyInvoice($OriginalInvoice, $CurrentInvoice, $Line, $SKU){
	global $con;

	$invoice = new Invoice($CurrentInvoice);

	$item = $invoice->getInvoiceItem($Line, $SKU);
	//
	//die("inside");
	$oldItem = new Invoice($OriginalInvoice);
	$oldItem = $oldItem->getInvoiceItem($Line, $SKU);
	//var_dump($oldItem);
	$item->Price = $oldItem->Price;
	$item->ReferenceType="Warranty";
	$item->Reference = $OriginalInvoice;
	//var_dump($item);
	if($item->save()){

		echo "true";
		//return;
	}

}
function setOriginalInvoice($OriginalInvoice, $CurrentInvoice, $Line, $SKU){
	global $con;

	$invoice = new Invoice($CurrentInvoice);

	$item = $invoice->getInvoiceItem($Line, $SKU);
	//
	//die("inside");
	$oldItem = new Invoice($OriginalInvoice);
	$oldItem = $oldItem->getInvoiceItem($Line, $SKU);
	//var_dump($oldItem);
	$item->Price = $oldItem->Price;
	$item->ReferenceType="OriginalInvoice";
	$item->Reference = $OriginalInvoice;
	//var_dump($item);
	if($item->save()){

		echo "true";
		//return;
	}

}
function getPreviousPurchases($accountNumber, $line, $sku){
	global $con;
	$query = "SELECT * FROM INVOICE_HEAD JOIN INVOICE_DETAIL USING(InvoiceID) WHERE `Status` = 1 AND Void = 0 AND AccountNumber LIKE '$accountNumber' AND `Line` LIKE '$line' AND `SKU` LIKE '$sku'";
	//echo $query;
	$return = new stdClass();
	if($result = mysqli_query($con, $query)){
		$return->Result = true;
		$return->Data = [];
		while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
			array_push($return->Data, $row);
		}
		//var_dump($return);
		echo safe_json_encode($return);
	}else{
		$return->Error = "MySQL Error: " . mysqli_error($con);
		echo safe_json_encode($return);
	}



}


?>
