<?php
include("../connect.php");
include("../session.php");

$isAdmin = $_SESSION['isAdmin'];
if (!$isAdmin) {
	header("Location: logout.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 == "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($function == "productLookup"){
	productLookup($_REQUEST['term'], $_REQUEST['an']);
}
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);
	$invoice->Finalize();
}
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%'";
 	$query = $query1 . " UNION " . $query2 . " UNION " . $query3 . " UNION " . $query4 . " UNION " . $query5 . " 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 ?></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 style="width: 5%" class="centered">Ordered</th>
			<th style="width: 5%" class="centered">Shipped</th>
			<?php
			if(false){
			?>
			<th style="width: 5%; text-align: right;">Cost</th>
			<?php
			}
			?>
 	        <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;
			foreach($invoice->Items 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"><?= $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>";
						}
						?>
						</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">
						<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>
					<?php
						if(false){
					?>
					<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>
					<?php
						}
					?>
 	        		<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="5" 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=addNewItem&invoice=<?= $invoice->InvoiceID ?>&sku=' + $('#newItemSKU').val(), function(data){
							if(data == "true"){
								refreshReviewTable();
							}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();
								
						   });
				});
				</script>
 	      	</tr>
			<tr class="borderless">
 	      		<td colspan="7" 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="7" 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="8" 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->Terms} 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{
		//echo mysqli_error($con);
		return "false";
	}
	
}
function saveReviewField($invoice, $data){
	global $con;
	$invoice = new Invoice($invoice);
	$id = $data['id'];
	if($data['id'] == "Terms"){
		$invoice->setTerms($data['value']);
	}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']} = strtoupper($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 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 FROM INVOICE_HEAD, CUSTOMER WHERE INVOICE_HEAD.AccountNumber = CUSTOMER.AccountNumber AND Status = FALSE AND Void != 1 AND (DeliveryMethod LIKE '%SAME%DA%' OR Notes  LIKE '%SAME%DA%')
UNION
SELECT 2 Priority, INVOICE_HEAD.*, CUSTOMER.Name, CUSTOMER.DueDays FROM INVOICE_HEAD, CUSTOMER WHERE INVOICE_HEAD.AccountNumber = CUSTOMER.AccountNumber AND Status = FALSE AND Void != 1 AND (DeliveryMethod LIKE '%PICKUP%' OR Notes  LIKE '%RECOGER%')
UNION
SELECT 3 Priority, INVOICE_HEAD.*, CUSTOMER.Name, CUSTOMER.DueDays FROM INVOICE_HEAD, CUSTOMER WHERE INVOICE_HEAD.AccountNumber = CUSTOMER.AccountNumber AND Status = FALSE AND Void != 1 AND (DeliveryMethod NOT LIKE '%SAME%DA%' AND Notes NOT LIKE '%SAME%DA%' AND DeliveryMethod NOT LIKE '%PICKUP%' AND Notes NOT LIKE '%RECOGER%')
ORDER BY Priority, InvoiceID ASC";
	$result = mysqli_query($con, $query);
	$return = [];
	//echo $query;
	while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
		$invoice = new Invoice($row['InvoiceID']);
		
		$row['ItemCount'] = count($invoice->Items);
		
		
		//$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);
	}
	echo json_encode($return);
}
function setOriginalInvoice($OriginalInvoice, $CurrentInvoice, $Line, $SKU){
	global $con;
	
	$invoice = new Invoice($CurrentInvoice);
	
	$item = $invoice->getInvoiceItem($Line, $SKU);
	//
	//die("inside");
	$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);		
		}
		echo json_encode($return);
	}else{
		$return->Error = "MySQL Error: " . mysqli_error($con);
		echo json_encode($return);
	}
	
	
	
}


?>