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

$isAdmin = $_SESSION['isAdmin'];
if (!$isAdmin) {
	header("Location: logout.php");
}
$invoice = new Invoice($_REQUEST['id']);
//error_reporting(E_ALL);


 ?>
 <!DOCTYPE html>
  <html lang="en">
    <head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title><?= $config['CompanyName'] ?></title>

      <!-- Bootstrap -->
      <link href="<?= $root ?>css/bootstrap.min.css" rel="stylesheet">
      <link rel="stylesheet" href="<?= $root ?>css/bootstrap-combobox.css" />

      <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
      <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
      <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
        <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
            <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
            <!-- Include all compiled plugins (below), or include individual files as needed -->
            <script src="<?= $root ?>js/bootstrap.min.js"></script>
			<script type="text/javascript" src="../js/functions.js" />
			<script type="text/javascript" src="../js/jquery.jeditable.js" />
			<script type="text/javascript" src="../js/jquery.jeditable.autogrow.js" />
			<script type="text/javascript" src="../js/jquery.jeditable.charcounter.js" />
			<script type="text/javascript" src="../js/jquery.jeditable.checkbox.js" />
			<script type="text/javascript" src="../js/jquery.jeditable.datepicker.js" />

			<script type="text/javascript" src="../js/jquery.jeditable.masked.js" />
			<script type="text/javascript" src="../js/jquery.jeditable.time.js" />
        	 <script src="<?= $root ?>js/bootstrap-combobox.js"></script>
            <script type="text/javascript">
              $(document).ready(function(){
								$('#PackingUser').trigger('change');
								$('.edit').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);
							   });
				});
				$('.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();

						   });
				});

                //$('.combobox').bscombobox();
        //        $('.grpline').css("width", "100px");
              });
			  function changeCustomer(){
					alert("BETA!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n\nThis function is NOT DONE (log), it changes only the customer, does not change anything else (salesperson, prices,etc)");
					var newAccountNumber = prompt("Enter new AccountNumber:");
					$.get('mod.php', {
						"p":	"invoice",
						"a":	"functions",
						"f":	"changeInvoiceCustomer",
						"invoice": "<?= $_REQUEST['id'] ?>",
						"an": 	newAccountNumber
					}, function (data){
						if(data=="true"){
							alert("Successfully changed");
							location.reload();
						}else if(data =="false"){
							alert("Error: maybe customer was not found or some bad characters breaking the program. But at least got response from the server");

						}else{
							alert("Unexpected error");
						}
						});
				}
            </script>

      <![endif]-->
 	<link rel="stylesheet" href="<?= $root ?>css/styles.css"/>
    </head>
    <body>

    <!-- Stack the columns on mobile by making one full-width and the other half-width -->
 <div class="container-fluid" style="margin-top: -50px;">
	<img class="img-responsive" style="width: 100px;" src="<?= $root ?>img/<?= $config['Logo'] ?>" alt="" />
 	<div class="row">
 	  <div class="col-xs-4">

 	  	<p>
			<div class="pull-left" style="width: 50px; height: 100px;"><b>Bill To: </b></div>
 	  		<div>
				<input type="text" class="edit allcaps" id="BillToName" value="<?= $invoice->BillToName; ?>" /><br />
				<input type="text" class="edit allcaps" id="BillToAddress1" value="<?= $invoice->BillToAddress1?$invoice->BillToAddress1 . "":"" ?>" /><br />
				<input type="text" class="edit allcaps" id="BillToAddress2" value="<?= $invoice->BillToAddress2?$invoice->BillToAddress2 . "":"" ?>" /><br />
				<input type="text" class="edit allcaps" id="BillToCity" value="<?= $invoice->BillToCity ?>" />,
				<input type="text" style="width: 25px;" class="edit allcaps" id="BillToState" value="<?= $invoice->BillToState ?>" />
				<input type="text" style="width: 100px;" class="edit allcaps" id="BillToZip" value="<?=  $invoice->BillToZip ?>" />

			</div>
 	  </p>

 	  </div>
  	  <div class="col-xs-4">
		<p>
			<div class="pull-left" style="width: 60px; height: 100px;"><b>Ship To: </b></div>
 	  		<div>
				<input type="text" class="edit allcaps" id="ShipToName" value="<?= $invoice->ShipToName; ?>" /><br />
				<input type="text" class="edit allcaps" id="ShipToAddress1" value="<?= $invoice->ShipToAddress1?$invoice->ShipToAddress1 . "":"" ?>" /><br />
				<input type="text" class="edit allcaps" id="ShipToAddress2" value="<?= $invoice->ShipToAddress2?$invoice->ShipToAddress2 . "":"" ?>" /><br />
				<input type="text" class="edit allcaps" id="ShipToCity" value="<?= $invoice->ShipToCity ?>" />,
				<input type="text" style="width: 25px;" class="edit  allcaps" id="ShipToState" value="<?= $invoice->ShipToState ?>" />
				<input type="text" style="width: 100px;" class="edit allcaps" id="ShipToZip" value="<?=  $invoice->ShipToZip ?>" />

			</div>
		</p>

	  </div>
 	  <div class="col-xs-2" style="margin-top: -10px;">
 		  <h3>Invoice Review</h3>
 		  <p>
 		  	<b>Invoice ID: <span style="font-style: italic;"><?= $invoice->InvoiceID ?></span></b><br>
 		  <b>Date: </b><?= date("m/d/Y",strtotime($invoice->InvoiceDate)) . " "  . date("g:i a",strtotime($invoice->InvoiceDate)) ?><br>
		  <b>Due Date: </b><span id="DueDate"><?= $invoice->DueDate?date("m/d/Y", strtotime($invoice->DueDate)):"" ?></span>


 		  </p>
 	  </div>
	  <div class="col-xs-2" style="font-size: 16px;">

 	  	<p>

 	  		<div>
				<a target="_blank" href="manage.php?a=customers&autoedit=<?= $invoice->AccountNumber ?>">View/Edit Customer Profile</a><br>
				<?php
				$invoices = $invoice->Customer->getInvoices();
				$totalAccountDue = 0;
				$daysDue = 0;
				foreach($invoices as $oldInvoice){
					$days = ceil((time() - strtotime($oldInvoice['InvoiceDate']))/(24*60*60));
					$oldInvoiceTotal = $oldInvoice['Subtotal']+$oldInvoice['Tax1Total']+$oldInvoice['Tax2Total'];
					$totalAccountDue += $oldInvoiceTotal;
					if($oldInvoiceTotal > 0){
						$daysDue = max($days, $daysDue);
					}
				}
			?>
			<b>Acct. Due Days: </b><span style="font-size: 20px; <?= $daysDue>=60?"color: red;":"" ?>"><?= $daysDue ?></span><br>
			<b>Acct. Total Due: </b><span style="font-size: 20px;  <?= $daysDue>=60?"color: red;":"" ?>"><?= moneyFormat($totalAccountDue) ?></span><br>
			<b>Price Level: </b> <?php

			if($invoice->Customer->PriceLevel == "A"){
				echo "Reseller";
			}elseif($invoice->Customer->PriceLevel == "B"){
				echo "End User";
			 }else{
				echo "Level " . $invoice->Customer->PriceLevel;
			 }

			?>

			</div>
 	  </p>

 	  </div>
	  <table class="table table-condensed centered">
		<thead>
			<tr class="centered">
				<th class="centered">Customer #</th>
				<th class="centered">Order ID</th>
				<th class="centered">Purchase Order</th>
				<th class="centered">Salesperson</th>
				<th class="centered">Terms</th>
				<th class="centered">Picker</th>
				<th class="centered">Delivery Method</th>
				<th class="centered">Package Count</th>
				<th class="centered">Delivery Date</th>
			</tr>
		</thead>
		<tbody>
			<tr class="centered">
				<td id="">
				<span id="invoiceAccountNumber"><?= $invoice->AccountNumber ?></span><br>
				<button class="btn btn-primary btn-xs" onclick="changeCustomer();">Change</button>
				</td>
				<td><?= $invoice->OrderID ?></td>
				<td><input name="PONumber" class="edit allcaps form-control input-sm centered" id="PONumber" style="font-size: 20px;" type="text" value="<?= $invoice->PONumber ?>" /></td>
				<td><select name="Salesman" id="Salesman" class="edit form-control input-sm">
					<?php
						$query = "SELECT * FROM SALESMAN ORDER BY FullName ASC";
						$result = mysqli_query($con, $query);
						while($row = mysqli_fetch_array($result)){
					?>
						<option <?= $row['ID']==$invoice->Salesman->ID?"selected":"" ?> value="<?= $row['ID'] ?>"><?= $row['FullName'] ?></option>
					<?php
						}
					?>

				</select></td>
				<td>
					<select class="editItem form-control input-sm" name="Terms" id="Terms">
						<option <?= $invoice->Terms==0?"selected":"" ?> value="0">COD</option>
						<option <?= $invoice->Terms==7?"selected":"" ?> value="7">7 days</option>
						<option <?= $invoice->Terms==15?"selected":"" ?> value="15">15 days</option>
						<option <?= $invoice->Terms==30?"selected":"" ?> value="30">30 days</option>
						<option <?= $invoice->Terms==45?"selected":"" ?> value="45">45 days</option>
						<option <?= $invoice->Terms==60?"selected":"" ?> value="60">60 days</option>
						<option <?= $invoice->Terms==90?"selected":"" ?> value="90">90 days</option>
						<option <?= $invoice->Terms=="2/15 net 16"?"selected":"" ?> value="2/15 net 16">2/15 Net 16</option>
						<option value="0">Credit</option>

					</select>

				<td class="center">
					<!--<input name="PackingUser" class="edit allcaps centered form-control input-sm col-xs-2" id="PackingUser" type="text" value="<?= $invoice->PackingUser ?>"/>-->
					<select class="editItem form-control input-sm" name="PackingUser" id="PackingUser">
						<option <?= $invoice->PackingUser=="A MARRERO"?"selected":"" ?> value="A MARRERO">Alejandro Marrero</option>
						<option <?= $invoice->PackingUser=="C CORDOVA"?"selected":"" ?> value="C CORDOVA">Carlos Cordova</option>
						<option <?= $invoice->PackingUser=="E SANCHEZ"?"selected":"" ?> value="E SANCHEZ">Eli Sanchez</option>
						<option <?= $invoice->PackingUser=="J CORREA"?"selected":"" ?> value="J CORREA">Jose Correa</option>
						<option <?= $invoice->PackingUser=="L MARRERO"?"selected":"" ?> value="L MARRERO">Luis Marrero</option>
						<option <?= $invoice->PackingUser=="R PORTELA"?"selected":"" ?> value="R PORTELA">Ramon Portela</option>

					</select>
				</td>
				<td><?= $invoice->DeliveryMethod ?></td>
				<td>
					<div class="col-xs-6 col-xs-offset-3">
						<input name="PackageCount" id="PackageCount" class="edit form-control input-sm"  type="text" value="<?= $invoice->PackageCount ?>" />
					</div>
				</td>
				<td>

						<input name="DeliveryDate" id="DeliveryDate" class="edit form-control input-sm"  type="date" value="<?= ($invoice->DeliveryDate)?date("Y-m-d", strtotime($invoice->DeliveryDate)):"" ?>" />

				</td>
			</tr>
		</tbody>
	  </table>

 	  <table id="invoiceReviewTable" class="table table-condensed">
 	    <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);

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

						?>

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

						?>
						<?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 ?>" onclick="addReference(<?= $item->ID ?>)" id="<?= $item->ID ?>-AddRef" 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();
						}

					});

				</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->Subtotal+$invoice->Tax1Total+$invoice->Tax2Total); ?>


				</td>
 	      	</tr>


 	    </tbody>
 	  </table>
 	</div>
 	<div class="modal fade" id="AddReferenceModal" tabindex="-1" role="dialog">
		<div class="modal-dialog" role="document">
		  <div class="modal-content">
			<div class="modal-header">
			  <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
			  <h4 class="modal-title">Add Reference</h4>
			</div>
			<div class="modal-body">
			  <p>
				<input type="hidden" id="AddReferenceID" />
				<input type="hidden" id="AddReferenceLine" />
				<input type="hidden" id="AddReferenceSKU" />

				<select class="form-control" name="AddReferenceType" id="AddReferenceType">
					<option value="-1">Select Reference Type</option>
					<option value="OriginalInvoice">Originally from other Invoice</option>
					<option value="Substitute">Substitute for another item</option>
					<option value="Warranty">Warranty</option>
					<option value="Custom">Custom Message</option>
				</select>
				<div id="AddReferenceDataDiv">

				</div>
			  </p>
			</div>
			<div class="modal-footer">
			  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
			  <button type="button" class="btn btn-primary">Save changes</button>
			</div>
			<script type="text/javascript">
				function addReference(id){
					$($('#AddReferenceType option')[0]).prop('selected', true);
					if(parseInt($('#' + id + '-ShippedQty').val())<0){
						$('option[value="Substitute"]').hide();
						$('option[value="Custom"]').show();
						$('option[value="OriginalInvoice"]').show();
						$('option[value="Warranty"]').show();
					}else{
						$('option[value="Substitute"]').show();
						$('option[value="Custom"]').show();
						$('option[value="OriginalInvoice"]').hide();
					}
					$('#AddReferenceLine').val($('#' + id + '-Line').text());
					$('#AddReferenceSKU').val($('#' + id + '-SKU').text());
					$('#AddReferenceModal').modal('toggle');
				}

				$('#AddReferenceType').on('change', function(){
					$('#AddReferenceDataDiv').html('');
					var refType = $('#AddReferenceType').val();
					var input;
					switch(refType){
						case "Custom":
							input = $("<input />").addClass('form-control').attr("name", "AddReferenceCustom").attr("id", "AddReferenceCustom").attr("type", "text").attr('placeholder', 'Custom Message');
							$('#AddReferenceDataDiv').append(input);
							break;
						case "Substitute":
							input = $("<input />").addClass('form-control').attr("name", "AddReferenceSubstitute").attr("id", "AddReferenceSubstitute").attr("type", "text").attr('placeholder', 'SKU');
							$('#AddReferenceDataDiv').append(input);
							break;
						case "OriginalInvoice":
							var an = $("#invoiceAccountNumber").text();
							var line = $('#AddReferenceLine').val();
							var sku = $('#AddReferenceSKU').val();
							$.get('mod.php?p=invoice&a=functions&f=getPreviousPurchases&an=' + an + "&line=" + line + "&sku=" + sku, function(data){
								$('#ItemHistoryTable').html('');
								data = JSON.parse(data);
								if(data.Result){
									for(i=0; i< data.Data.length; i++){
										var item = $('<tr/>')
											.append(
													$('<td/>').text(data.Data[i].InvoiceID))
											.append($('<td/>').text(data.Data[i].InvoiceDate))
											.append($('<td/>').text(data.Data[i].ShippedQty))
											.append($('<td/>').append($('<button>').attr('onclick', 'setOriginalInvoice("' + data.Data[i].InvoiceID + '", "' + line + '","' + sku + '")').addClass('btn btn-default').text('Go')));
									$('#ItemHistoryTable').append(item);
									}
								$('#ItemHistoryModal').modal('toggle');
								}else{
									alert(data.Error);
								}

							});
							break;
						case "Warranty":
							var an = $("#invoiceAccountNumber").text();
							var line = $('#AddReferenceLine').val();
							var sku = $('#AddReferenceSKU').val();
							$.get('mod.php?p=invoice&a=functions&f=getPreviousPurchases&an=' + an + "&line=" + line + "&sku=" + sku, function(data){
								$('#ItemHistoryTable').html('');
								data = JSON.parse(data);
								if(data.Result){
									for(i=0; i< data.Data.length; i++){
										var item = $('<tr/>')
											.append(
													$('<td/>').text(data.Data[i].InvoiceID))
											.append($('<td/>').text(data.Data[i].InvoiceDate))
											.append($('<td/>').text(data.Data[i].ShippedQty))
											.append($('<td/>').append($('<button>').attr('onclick', 'setWarrantyInvoice("' + data.Data[i].InvoiceID + '", "' + line + '","' + sku + '")').addClass('btn btn-default').text('Go')));
									$('#ItemHistoryTable').append(item);
									}
								$('#ItemHistoryModal').modal('toggle');
								}else{
									alert(data.Error);
								}

							});
							break;
					}


				});
				function setOriginalInvoice(OriginalInvoice, line, sku){
					$.get('mod.php', {
						"p"	: "invoice",
						"a"	:	"functions",
						"f"	:	"setReference",
						"type" :	"OriginalInvoice",
						"Line" : line,
						"SKU"	: sku,
						"origInvoice"	:	OriginalInvoice,
						"currentInvoice":	"<?= $invoice->InvoiceID ?>",
						}, function(data){
							if(data=="true"){
								$('#ItemHistoryModal').modal('toggle');
								$('#AddReferenceModal').modal('toggle');
								refreshReviewTable();
							}
						});
				}
				function setWarrantyInvoice(OriginalInvoice, line, sku){
					$.get('mod.php', {
						"p"	: "invoice",
						"a"	:	"functions",
						"f"	:	"setReference",
						"type" :	"Warranty",
						"Line" : line,
						"SKU"	: sku,
						"origInvoice"	:	OriginalInvoice,
						"currentInvoice":	"<?= $invoice->InvoiceID ?>",
						}, function(data){
							if(data=="true"){
								$('#ItemHistoryModal').modal('toggle');
								$('#AddReferenceModal').modal('toggle');
								refreshReviewTable();
							}
						});
				}
			</script>
		  </div><!-- /.modal-content -->
		</div><!-- /.modal-dialog -->

	</div><!-- /.modal -->



	<div class="modal fade" id="ItemHistoryModal" tabindex="-1" role="dialog">
		<div class="modal-dialog" role="document">
		  <div class="modal-content">
			<div class="modal-header">
			  <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
			  <h4 class="modal-title">Purchase History</h4>
			</div>
			<div class="modal-body">
			  <p>
				<table class="table">
					<thead>
						<tr>
							<td>Invoice</td>
							<td>Date</td>
							<td>Ordered</td>
						</tr>
					</thead>
					<tbody id="ItemHistoryTable">

					</tbody>
				</table>


			  </p>
			</div>
			<div class="modal-footer">
			  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

			</div>
			<script type="text/javascript">

			</script>
		  </div><!-- /.modal-content -->
		</div><!-- /.modal-dialog -->

	</div><!-- /.modal -->
 <style>
	.borderless {
		border: hidden;
		border-top: hidden;
		border-left-style: none;
		border-right-style: none;
		border-bottom-style: none;
	}
 </style>
 <style type="text/css" media="print">
	body { margin: 0; background-image: none; font-size: 1em }


 </style>
 </div>
        <div class="panel panel-default">
          <div class="panel-body">
			<div class="row">
				<span><b>Delivery Crates:</b></span><br />
				<div class="col-xs-3">

					<input type="text" id="crateEntry" class="form-control col-xs-3" >
				</div>

				<div class="col-xs-12" id="crateContainer">
					<?php
						foreach($invoice->getCrates() as $value){


					?>
					<div class="col-xs-2 shipcontainer" data-container="<?= $value['CrateNumber'] ?>">
						<img src="/img/shipcrate.png"  style="width: 100px;"/>
						<div class="shipcrate_number">#<?= $value['CrateNumber'] ?><br>
						<button onclick="removeCrate('<?= $value['CrateNumber'] ?>')" class="btn btn-danger btn-sm">Delete</button>
						</div>
					</div>
					<?php
						}
					?>


				</div>
				<style>
					.shipcontainer {
						position: relative;
						text-align: center;
						color: red;
					}
					.shipcrate_number{

						font-size: 22px;

					}
				</style>
				<script type="text/javascript">
					function padLeft(nr, n, str){
						return Array(n-String(nr).length+1).join(str||'0')+nr;
					}
					function removeCrate(crateNumber){
						$.get('mod.php?p=invoice&a=functions&f=removeCrate&crateNumber=' + crateNumber + '&invoice=<?= $invoice->InvoiceID ?>', function(data){
							if(data == "true"){
								$('.shipcontainer[data-container="' + crateNumber + '"]').remove();
							}
						});
					}
					$('#crateEntry').keyup(function(e){
						var crateNumber = $('#crateEntry').val();
						crateNumber = padLeft(crateNumber,3);

						if(e.keyCode == 13){

							if($('[data-container=' + crateNumber +']').length > 0){
								alert('Crate Already Exists in this Invoice');
								return;
							}
							if(crateNumber == ""){
								alert("Please enter a crate number");
								return;
							}else{
								$.get('mod.php?p=invoice&a=functions&f=setCrate&crateNumber=' + crateNumber + '&invoice=<?= $invoice->InvoiceID ?>', function(data){
									if(data == "true"){
										var crateDiv = '<div class="col-xs-2 shipcontainer" data-container="' + crateNumber + '">\
													<img src="/img/shipcrate.png"  style="width: 100px;"/>\
													<div class="shipcrate_number">#' + crateNumber + '<br><button onclick="removeCrate(\'' + crateNumber + '\')" class="btn btn-danger btn-sm">Delete</button></div>\
											</div>';
										$('#crateContainer').append(crateDiv);
										$('#crateEntry').val('');
									}else{
										alert("Unexpected error");
									}
								});
							}

						}
						});

				</script>
			</div>
			<br>
            <span><b>Invoice Notes:</b></span><br />
           <textarea id="Notes" class="form-control edit"><?= $invoice->Notes ?></textarea>
          </div>
        </div>
        <div style="float: right;" >
					<button id="printPicking" class="btn btn-primary">Print Picking</button>
			<button id="finalizeInvoice" class="btn btn-success">Finalize Invoice</button>
			<button class="btn btn-primary" onclick="window.location='mod.php?p=invoice&a=queue';">Save & Close</button>
			<script>
				function updateDueDateWithDeliveryDate(){
					setTimeout(function(){
						$.get('mod.php?p=invoice&a=functions&f=updateDueDateWithDeliveryDate&id=<?= $invoice->InvoiceID ?>', function(data){
								$('#DueDate').text(data);
						});
					}, 500);
				}
				$('#DeliveryDate').on("change", function(){
					updateDueDateWithDeliveryDate();
				});
				$('#Terms').on("change", function(){
					updateDueDateWithDeliveryDate();
				});
				$('#finalizeInvoice').on('click', function(){
					$('#PackingUser').change();
					$.get('mod.php?p=invoice&a=functions&f=setInvoiceFinalize&invoice=<?= $invoice->InvoiceID ?>', function(data){
						if(data == "true"){
							window.location = 'mod.php?p=invoice&a=view&id=<?= $invoice->InvoiceID ?>&print=true';
						}else{
							alert(data);
						}

					});
				});
				$('#printPicking').on("click",function(){
					window.open("mod.php?p=invoice&a=picking&invoice=<?= $invoice->InvoiceID ?>");
				});
				function refreshReviewTable(callback){
					//alert(callback2);
					$.get('mod.php?p=invoice&a=functions&f=generateReviewTable&invoice=<?= $invoice->InvoiceID ?>', function(data){
						$('#invoiceReviewTable').html(data);
						//console.log(callback2);
						if(callback){
							focusAddSKUField();
						}

					});

				}
				function focusAddSKUField(){
					//alert("fired");
					$('#newItemSKU').focus();
				}
				function focusSearchField(){
					$('#productLookupSearchTerm').focus();
				}
				function deleteInvoiceItem(id){
					$.get('mod.php?p=invoice&a=functions&f=deleteInvoiceItem&invoice=<?= $invoice->InvoiceID ?>&id=' + id, function(data){
						if(data == "true"){
							$.get('mod.php?p=invoice&a=functions&f=generateReviewTable&invoice=<?= $invoice->InvoiceID ?>', function(data){
									$('#invoiceReviewTable').html(data);
								});
						}else{
							alert("Error");
						}
						});
				}
			</script>
		</div>


		<div style="float: right;" >

		</div>

		<!-- Product Lookup Modal -->
			<div class="modal fade" id="productLookupModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
			  <div class="modal-dialog modal-lg">
				<div class="modal-content">
				  <div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
					<h4 class="modal-title" id="myModalLabel">Product Lookup</h4>
				  </div>
				  <div class="modal-body">
					<div class="form-group">
						<input type="text" class="form-control" id="productLookupSearchTerm" placeholder="Seach by SKU/Interchange/Description" />
						<div id="productLookupResults">

						</div>
					</div>
				  </div>
				  <div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
				  </div>
				</div>
			  </div>
			  <script type="text/javascript">
				var keyTimerProductSearch = setTimeout(null, 0);

				$('#productLookupSearchTerm').on("keyup", function(e){
					clearTimeout(keyTimerProductSearch);
					if(e.keyCode == 13 || e.keyCode == 0){
						executeProductSearch();
					}
					keyTimerProductSearch = setTimeout(function(){
						executeProductSearch();
					}, 1000);
				});
				function executeProductSearch(){
					clearTimeout(keyTimerProductSearch);
					$.get("mod.php?p=invoice&a=functions&f=productLookup",{
						"term" 	: 	$('#productLookupSearchTerm').val(),
						"an"	:	"<?= $invoice->AccountNumber ?>"
						},function(data){

							$("#productLookupResults").html(data);
						});

				}
				function addLookupItem(Line, SKU){
					$('#newItemSKU').val(SKU);
					$('#AddNewItemButton').click();
				}
				$('#productLookupModal').on('shown.bs.modal', function(){
						$('#productLookupSearchTerm').val('');
						$('#productLookupSearchTerm').focus();
					});
			  </script>
			</div>
			<!-- Product Lookup Modal End -->

			<!-- Add Product Qty -->
			<div class="modal fade" id="productQtyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
			  <div class="modal-dialog modal-sm">
				<div class="modal-content">
				  <div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
					<h4 class="modal-title" id="">Enter Qty</h4>
				  </div>
				  <div class="modal-body">
					<div class="form-group">
						<input type="text" class="form-control" id="productInputQty" placeholder="Qty" />
					</div>
				  </div>
				  <div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
					<button type="button" id="productQtyModalAdd" class="btn btn-success">Add</button>
				  </div>
				</div>
			  </div>
			  <script type="text/javascript">
				$('#productQtyModal').on('shown.bs.modal', function(){
						$('#productInputQty').focus();
					});
				function askForQty(id){
					$('#productQtyModalAdd').unbind('click');
					$('#productInputQty').unbind('keyup');
					$('#productInputQty').val('');
					$('#productQtyModalAdd').on('click', function(){
						submitQtyModal(id);
					});
					$('#productInputQty').on('keyup', function(e){
						if(e.keyCode == "13"){
							submitQtyModal(id);
						}
					});
					$('#productQtyModal').modal('toggle');
				}
				function submitQtyModal(id){
					var qty = $('#productInputQty').val();
					$('#' + id + "-OrderQty").val(qty);
					$('#' + id + "-ShippedQty").val(qty);
					$('#' + id + "-ShippedQty").trigger('change');
					$('#' + id + "-OrderQty").trigger('change');
					$('#productQtyModal').modal('toggle');

				}
			  </script>
			</div>
			<!-- Add Product Qty Modal End -->

    </body>
  </html>
