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

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

 ?>
 <!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">
				var indexHash = new HashTable({});
              $(document).ready(function(){
				$('.edit').on('change', function(){
					$.post("mod.php?p=purchasing&a=functions&f=saveReviewField&po=<?= $_REQUEST['id'] ?>",
						   { id: $(this).attr('id'), value: $(this).val() }, function(data){
								$(this).val(data);
								recalculateOrder();
								
						   });
				});
				$('.editItem').on('change', function(){
					$.post("mod.php?p=purchasing&a=functions&f=saveReviewFieldItem&id=<?= $_REQUEST['id'] ?>",
						   { id: $(this).attr('id'), value: $(this).val() }, function(data){
								$(this).val(data);
									
								recalculateOrder();
						   });
				});
                //$('.combobox').bscombobox();
        //        $('.grpline').css("width", "100px");
				
			  });
			  
            </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: 120px;" 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>Vendor: </b></div>
 	  		<div style="margin-left: 60px;">
				 
				<?= $po->Vendor->Name ?><br />
				<?= $po->Vendor->PostalAddress1 ?><br />
				<?= $po->Vendor->PostalAddress2 ?><br />
				<?= $po->Vendor->PostalCity ?>, <?= $po->Vendor->PostalState ?> <?= $po->Vendor->PostalZip ?><br />
				<?= $po->Vendor->PostalCountry ?><br />
				
				
			</div>
 	  </p>
 	  
 	  </div>
  	  <div class="col-xs-4">
		<p>
			<div class="pull-left" style="width: 60px; height: 100px;"><b>Ship To: </b></div>
 	  		<div>
				<?= $po->ShipToName; ?><br />
				<?= $po->ShipToAddress1 ?><br />
				<?= $po->ShipToAddress2 ?><br />
				<?= $po->ShipToCity ?>, <?= $po->ShipToState ?> <?=  $po->ShipToZip ?>
				
			</div>
		</p>
		
	  </div>
 	  <div class="col-xs-4" style="margin-top: -20px;">
 		  <h3>Purchase Order Confirmation</h3>
 		  <p>
 		  	<b>Purchase Order ID: </b><span style="font-style: italic;"><?= $po->PurchaseOrderID ?></span><br>
 		  <b>PO Date: </b><?= date("m/d/Y",strtotime($po->PODate)) . " "  . date("g:i a",strtotime($po->PODate)) ?><br>
		  
 		  </p>
 	  </div>
	  <table class="table table-condensed centered">
		<thead>
			<tr class="centered">
				<th style="width: 20%;" class="centered">Account Number #</th>
				<th style="width: 20%;" class="centered">Vendor Invoice</th>
				<th style="width: 15%;" class="centered">Terms</th>
				<th style="width: 20%;" class="centered">Invoice Date</th>
				<th style="width: 8%;" class="centered">Packages</th>
				<th style="width: 20%;" class="centered">Ship Via</th>
				
				<th></th>
			</tr>
		</thead>
		<tbody>
			<tr class="centered">
				<td id="OurAccountNumber"><?= $po->Vendor->OurAccountNumber ?></td>
				
				<td><input name="InvoiceNumber" class="edit allcaps form-control input-sm centered" id="InvoiceNumber" type="text" value="<?= $po->InvoiceNumber ?>" /></td>
				
				<td>
					<select class="edit form-control input-sm" name="PaymentTerms" id="PaymentTerms">
						<option <?= $po->PaymentTerms==0?"selected":"" ?> value="0">COD</option>
						<option <?= $po->PaymentTerms==7?"selected":"" ?> value="7">7 days</option>
						<option <?= $po->PaymentTerms==15?"selected":"" ?> value="15">15 days</option>
						<option <?= $po->PaymentTerms==30?"selected":"" ?> value="30">30 days</option>
						<option <?= $po->PaymentTerms==45?"selected":"" ?> value="45">45 days</option>
						<option <?= $po->PaymentTerms==60?"selected":"" ?> value="60">60 days</option>
						<option <?= $po->PaymentTerms==90?"selected":"" ?> value="90">90 days</option>
						
					</select>
					
				<td class="center">
					<div class="col-sm-8 col-sm-offset-2">
						<input name="InvoiceDate" class="edit allcaps centered form-control input-sm col-xs-2" id="InvoiceDate" type="date" value="<?= $po->InvoiceDate ?>"/>
					</div>
				</td>
				<td>
					<input type="number"  id="Packages" class="edit form-control input-sm" name="Packages" value="<?= ($po->Packages) ?>" />
				</td>
				<td>
					<div>
						<input name="ShippingTerms" id="ShippingTerms" class="edit centered form-control input-sm"  type="text" value="<?= $po->ShippingTerms ?>" />		
					</div>
				</td>
				<td>
					<button onclick="$('#ReviewItemsModal').modal('toggle');" class="btn btn-primary">Review</button>
				</td>
				
			</tr>
		</tbody>
	  </table>
	  
 	  <table id="poReviewTable" 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 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;">Extension</th>
			<?php
			if(!$po->Sent){
			?>
			<th></th>
			<?php
			}
			?>
 	      </tr>
 	    </thead>
 	  	<tbody id="poReviewTableBody">
 	  	<?php
 	  		
 	  		$index = 0;
			$totalItems = 0;
			$invoiceTotal = 0;
			foreach($po->Items as $key => $item){
			//DIE('ELI');
				$item = new PurchaseOrderItem($item->id);
			
 	  		
 	  	?>
 	  		<tr data-id="<?= $item->id ?>">
					<script type="text/javascript">
						indexHash.setItem("<?= $item->SKU ?>", "<?= $item->id ?>");
					</script>
 	    			<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 ?>
						</span>
 	        			
					</td>
					<td>
						
					</td>
					<td class="centered">
						<input <?= $po->Sent?"readonly":"" ?> 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 ?>-ConfirmedQty" class="editItem centered form-control input-sm" type="text" id="<?= $item->id ?>-ConfirmedQty" value="<?= $item->ConfirmedQty ?>"/>
 	        		</td>
					<td style="text-align: right;">
						
						<input name="<?= $item->id ?>-Cost" class="editItem centered form-control input-sm" type="text" id="<?= $item->id ?>-Cost" value="<?= $item->Cost ?>"/>
						
					</td>
 	        		
 	        		
 	        		<td style="text-align: right;" id="<?= $item->id ?>-Extension" >
						<?php
							echo moneyFormat($item->Cost*$item->ConfirmedQty);
							$poTotal+= ($item->Cost*$item->ConfirmedQty);
						?>
 	        		</td>
				<?php
				if(!$po->Sent){
				?>
					<td><a onclick="deletePOItem(<?= $item->id ?>); return false;" class="btn btn-sm btn-danger"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
					</a></td>
				<?php
				}
				?>
 	      	</tr>
 	      	<?php 
 	      	$index++;	 
 	      	}?>
			
		</tbody>
		<tfoot>
 	      	<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></td>
 	      		<td colspan="4" style="text-align: right;"><span style="font-weight: bold; text-align: right;">Subtotal</span></td>
				<td id="POSubtotal" style="text-align: right;"><?= moneyFormat($po->getConfirmedSubtotal()); ?></td>
				<script type="text/javascript">
					$('#AddNewItemButton').on("click", function(){
						$.get('mod.php?p=purchasing&a=functions&f=addNewItem&po=<?= $po->PurchaseOrderID ?>&sku=' + $('#newItemSKU').val(), function(data){
							if(data == "true"){
								location.reload();
							}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="5" class="borderless" style="text-align: right;"><span style="font-weight: bold;">Freight:</span></td>
				<td colspan="2" style="text-align: left;"><input id="Freight" type="text" class="edit form-control input-sm" name="Freight" value="<?= ($po->Freight); ?>" /></td>
				<td style="text-align: right;" id="FreightLabel"><?= moneyFormat($po->Freight); ?></td>
 	      	</tr>
			<tr class="borderless">
 	      		
 	      		<td colspan="5" class="borderless" style="text-align: right;"><span style="font-weight: bold;">Other Charges:</span></td>
				<td colspan="2" style="text-align: left;"><input type="number"  id="MiscCharges" class="edit form-control input-sm" name="MiscCharges" value="<?= ($po->MiscCharges) ?>" /></td>
				<td style="text-align: right;" id="MiscChargesLabel"><?= moneyFormat($po->MiscCharges); ?></td>
 	      	</tr>
			<tr class="borderless">
 	      		
 	      		<td colspan="7" class="borderless" style="text-align: right;"><span style="font-weight: bold;">Total</span></td>
				<td style="text-align: right;" id="POTotal"><?= moneyFormat($po->getConfirmedTotal()); ?></td>
 	      	</tr>
			
 	      </tr>
 	    </tfoot>
 	  </table>
 	</div>
	
	<div class="modal fade" id="ReviewItemsModal" tabindex="-1" role="dialog">
		<div class="modal-dialog modal-sm" 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">Confirm Items</h4>
			</div>
			<div class="modal-body">
			  <div id="ReviewItemsAlertDiv"></div>	
			  <div class="form-group">
				<input type="text" class="form-control" name="ReviewItemsSKU" id="ReviewItemsSKU" placeholder="SKU"/><br> 
				<input type="text" class="form-control" name="ReviewItemsQty" id="ReviewItemsQty" placeholder="Qty" data-toggle="tooltip" data-placement="left" title="Press enter to SUM or click Replace to REPLACE QTY."/><br>
				<button type="button" onclick="confirmItem(true);" name="ReviewItemsConfirm" class="btn btn-primary pull-right">Replace</button>
			  </div>
			  <div id="ReviewItemsConfirmed">
				
			  </div>
			</div>
			<div class="modal-footer">
			  <button type="button" class="btn btn-default" data-dismiss="modal">Done</button>
			  
			</div>
			<script type="text/javascript">
				$('#ReviewItemsModal').on('show.bs.modal', function () {
					$('#ReviewItemsConfirmed').html('');
					setTimeout(function(){
							$('#ReviewItemsSKU').focus();
					},500);
					//if (!data) return e.preventDefault() // stops modal from being shown
				  })
				$('#ReviewItemsQty').tooltip({trigger: 'focus'});
				$('#ReviewItemsSKU').on('keyup', function(e){
					if(e.keyCode == 13 || e.keyCode === 0){
						var id = indexHash.getItem($('#ReviewItemsSKU').val());
						var confirmedQty = parseInt($('#' + id + "-ConfirmedQty").val());
						if(indexHash.hasItem($('#ReviewItemsSKU').val())){
							if(confirmedQty !== 0){
								$('#ReviewItemsConfirmed').html("Qty Confirmed: " + confirmedQty);	
							}
							
							$('#ReviewItemsQty').focus();	
						}else{
							playSound("no");
							alertBox("danger", "Item not in order!", "#ReviewItemsAlertDiv");
						}
						
					}
				});
				function confirmItem(replace){
					if(typeof replace == "undefined"){
						replace = false;
					}
					var id = indexHash.getItem($('#ReviewItemsSKU').val());
					var enteredQty = parseInt($('#ReviewItemsQty').val());
					var orderedQty = parseInt($('#' + id + "-OrderQty").val());
					var confirmedQty = parseInt($('#' + id + "-ConfirmedQty").val());
					if(isNaN(enteredQty)){
						enteredQty = 0;
					}
					if(replace){
						if(confirm('Are you sure you want to replace the Shipped Qty to ' + enteredQty + "?")){
							
						}else{
							$('#ReviewItemsQty').focus();
							return false;
						}
						if(enteredQty > orderedQty){
							if(confirm("Entered Qty is bigger than the Ordered Qty, do you want to confirm this anyway?")){
								$('#' + id + "-ConfirmedQty").val(enteredQty);	
								$('#' + id + "-ConfirmedQty").trigger('change');
								$('#ReviewItemsSKU').val('');
								$('#ReviewItemsQty').val('');
								$('#ReviewItemsConfirmed').html('');
								$('#ReviewItemsSKU').focus();
								
							}else{
								return false;	
							}
						}else{
							$('#' + id + "-ConfirmedQty").val(enteredQty);
							$('#' + id + "-ConfirmedQty").trigger('change');
							$('#ReviewItemsSKU').val('');
							$('#ReviewItemsQty').val('');
							$('#ReviewItemsConfirmed').html('');
							$('#ReviewItemsSKU').focus();
							
						}
						
					}else{
						if((confirmedQty+enteredQty) > orderedQty){
							if(confirm("Entered Qty is bigger than the Ordered Qty, do you want to confirm this anyway?")){
								$('#' + id + "-ConfirmedQty").val(enteredQty+confirmedQty);
								$('#' + id + "-ConfirmedQty").trigger('change');
								$('#ReviewItemsSKU').val('');
								$('#ReviewItemsQty').val('');
								$('#ReviewItemsConfirmed').html('');
								$('#ReviewItemsSKU').focus();
								
								
							}else{
								return false;	
							}
						}else{
							$('#' + id + "-ConfirmedQty").val(enteredQty+confirmedQty);
							$('#' + id + "-ConfirmedQty").trigger('change');
							$('#ReviewItemsSKU').val('');
							$('#ReviewItemsQty').val('');
							$('#ReviewItemsConfirmed').html('');
							$('#ReviewItemsSKU').focus();		
						}
						
					}
					
						
				}
				$('#ReviewItemsQty').on('keyup', function(e){
					if(e.keyCode == 13 || e.keyCode === 0){
						confirmItem();
					}
				});
				
					  
			</script>
		  </div><!-- /.modal-content -->
		</div><!-- /.modal-dialog -->
		
	</div><!-- /.modal -->
	
 	<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="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">
				
			</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">
				
			</div>
			<br>
            <span><b>Purchase Order Notes:</b></span><br />
           <textarea id="Notes" class="form-control edit"><?= $po->Notes ?></textarea> 
          </div>
        </div>
        <div style="float: right;" >
			<button id="finalizePO" class="btn btn-success">Confirm Purchase Order</button>
			<button class="btn btn-primary" onclick="window.close();">Save & Close</button>
			<script>
				$('#finalizePO').on('click', function(){
					if(confirm("Are you sure you want to confirm this order?")){
						$.get('mod.php?p=purchasing&a=functions&f=setPOFinalize&po=<?= $po->PurchaseOrderID ?>', function(data){
						window.close();
					});	
					}else{
						return;
					}
					
				});
				function refreshReviewTable(){
					recalculateOrder();
				}
				function deletePOItem(id){
					if(confirm("Are you sure you want to delete this item?")){
						$.get('mod.php?p=purchasing&a=functions&f=deletePOItem&id=' + id, function(data){
							if(data == "true"){
								$('#' + id + '-SKU').parent().parent().remove();
								recalculateOrder();
							}else{
								alert("Error");
							}
						});	
					}
					
				}
				function recalculateOrder(){
					var poTotal = 0;
					$('#poReviewTableBody tr').each(function(){
						var id = $(this).data('id');
						var confirmedQty = $("#" + id + "-ConfirmedQty").val();
						var cost = $("#" + id + "-Cost").val();
						$('#' + id + '-Extension').text(moneyFormat(confirmedQty*cost));
						poTotal += confirmedQty*cost;
					});
					$("#POSubtotal").text(moneyFormat(poTotal));
					poTotal += parseFloat($('#Freight').val());
					poTotal += parseFloat($('#MiscCharges').val());
					
					$('#FreightLabel').text(moneyFormat($('#Freight').val()));
					$('#MiscChargesLabel').text(moneyFormat($('#MiscCharges').val()));
					$('#POTotal').text(moneyFormat(poTotal));
				}
			</script>
		</div>
		<div style="float: right;" >
			
		</div>
      
	  
	  
    </body>
  </html>