<?php

	//////////////////////////////////////////////////
	//
	//
	// this file must be included in the navbar.php
	// file to make work saved cart notification.
	//
	//
	//
	//////////////////////////////////////////////////


	//Appears only in admin section
  if(stripos($_SERVER['SCRIPT_NAME'],"/admin/")===false?false:true){

?>
	<script type="text/javascript">
		$(document).ready(function(){

		});
	</script>
<?php

	//appears only in customer section both salesman and customer
  }else{

	?>

		<?php
		if((!$isCustomer)  ){
				//var_dump($_SESSION);


			$isSalesman = $_SESSION['isCustomer']?0:1;

		?>

		<!-- Modal -->
		<div id="savedCartsModal" class="modal fade" role="dialog">
		  <div class="modal-dialog modal-lg">

			<!-- Modal content-->
			<div class="modal-content">
			  <div class="modal-header">
				<button type="button" class="close" data-dismiss="modal">&times;</button>
				<h4 class="modal-title">Saved Carts</h4>
			  </div>
			  <div class="modal-body">
				<table class="table table-condensed">
					<thead>
						<tr>
							<th>Saved Date</th>
							<th>Cart Name</th>
							<?php
							if($isSalesman){
							?>
							<th>Selected Customer</th>
							<?php
								if($_SESSION['SalesmanID'] == "25"){
							?>
							<th>Salesman</th>

							<?php
								}
							}
							?>
							<th>Copy</th>
							<!--<th>Load</th>-->
							<th>Delete</th>
						</tr>
					</thead>
					<tbody>
						<?php
						//$isCustomer = $_SESSION['isCustomer']?1:0;

						$accountNumber = $_SESSION['isCustomer']?$_SESSION['AccountNumber']:$_SESSION['SalesmanID'];
						if($accountNumber == "JC" || $accountNumber == "CC" || $accountNumber == "ES"){
							$accountNumber = "%";
						}
						$query = "SELECT * FROM SAVED_CART_HEAD WHERE AccountNumber LIKE '$accountNumber' OR GlobalCart = 1";
						$result = mysqli_query($con, $query);
						$hasSavedCart = false;
						$savedCartCount = mysqli_num_rows($result);
						if($savedCartCount > 0){
							$hasSavedCart = true;
							while($row = mysqli_fetch_array($result)){
								$customerName = new Customer($row['SelectedAccount']);
								$customerName = $customerName->Name;
						?>
						<tr>
							<td><?= date("m/d/Y h:i a", strtotime($row['SavedCartDate'])) ?></td>
							<td><?= $row['Name'] ?></td>
							<?php
							if($isSalesman){
							?>
							<td><?= $customerName ?></td>
							<?php
								if($_SESSION['SalesmanID'] == "JC" || $_SESSION['SalesmanID'] == "ES" || $_SESSION['SalesmanID'] == "CC"){
									$rowSM = new Salesman($row['AccountNumber']);
							?>
							<td><?= $rowSM->Name ?></td>

							<?php
								}
							}
							?>
							<td><button class="btn btn-warning" onclick="loadSavedCart(<?= $row['id'] ?>, true)">Copy</button></td>
							<!--<td><button class="btn btn-success" onclick="loadSavedCart(<?= $row['id'] ?>)">Load</button></td>-->
							<td><button class="btn btn-danger" onclick="deleteSavedCart(<?= $row['id'] ?>)">Delete</button></td>
						</tr>
						<?php
							}
						}
						?>
					</tbody>
				</table>

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

		  </div>
		</div>



<?php
}else{

}
  ?>


  		<!-- Reorder Modal -->
  		<div id="reorderModal" class="modal fade" role="dialog">
  		  <div class="modal-dialog modal-lg">

  			<!-- Modal content-->
  			<div class="modal-content">
  			  <div class="modal-header">
  				<button type="button" class="close" data-dismiss="modal">&times;</button>
  				<h4 class="modal-title">Reorder Items</h4>
  			  </div>
  			  <div class="modal-body">
  				<form id="reorderForm">
  					<table class="table table-condensed">
  						<thead>
  							<tr>
  								<th>SKU</th>
  								<th style="">Description</th>

  								<th>Price</th>
  								<th class="visible-xs-block">Ord / Av</th>
  								<th class="centered hidden-xs">Original Qty</th>
  								<th class="centered hidden-xs">Available Qty</th>
  								<th>New Qty</th>
  							</tr>
  						</thead>
  						<tbody>
  							<?php
  							//$isCustomer = $_SESSION['isCustomer']?1:0;
                if(isset($_SESSION['setCustomer'])){
                    $accountNumber = $_SESSION['setCustomer'];
                }else{
                  $accountNumber = $_SESSION['AccountNumber'];
                }


  							if($accountNumber == "00000-00" || $accountNumber == "00000-01" || $accountNumber == "00001"){
  								$query = "SELECT `Line`, Familia,if(SortOrder is null, 999, SortOrder) SortOrder, `Group`, `SKU`, INVENTORY.Description, OrderQty , Qty FROM `NEW_CUSTOMER_REORDER` JOIN INVENTORY USING(Line, SKU) LEFT JOIN REORDER_SORT USING(Familia) GROUP BY `Line`, `Group`, `SKU` ORDER BY SKU, Line, `Group`, Familia";
  							}elseif(substr($accountNumber,0,5) == "10013"){
  								//$query = "SELECT * FROM (SELECT `Line`, Familia,if(SortOrder is null, 999, SortOrder) SortOrder, `Group`, `SKU`, INVENTORY.Description, OrderQty , Qty FROM INVOICE_HEAD JOIN INVOICE_DETAIL USING(InvoiceID) JOIN INVENTORY USING(Line,`Group`, SKU) LEFT JOIN REORDER_SORT USING(Familia) LEFT JOIN CUSTOMER_REORDER_EXCLUDE USING(Line, SKU, AccountNumber) WHERE AccountNumber LIKE '10013%' AND CUSTOMER_REORDER_EXCLUDE.id is NULL ORDER BY INVOICE_DETAIL.ID) T GROUP BY `Line`, `Group`, `SKU` ORDER BY SortOrder, Line, `Group`, Familia, SKU";
                  				$query = "SELECT * FROM (SELECT INVOICE_DETAIL.`Line`, Familia,if(SortOrder is null, 999, SortOrder) SortOrder, INVOICE_DETAIL.`Group`, INVOICE_DETAIL.`SKU`, INVENTORY.Description, OrderQty , Qty FROM INVOICE_HEAD JOIN INVOICE_DETAIL USING(InvoiceID) JOIN INVENTORY USING(Line,`Group`, SKU) LEFT JOIN REORDER_SORT USING(Familia) LEFT JOIN CUSTOMER_REORDER_EXCLUDE ON(INVOICE_DETAIL.Line = CUSTOMER_REORDER_EXCLUDE.Line AND INVOICE_DETAIL.SKU = CUSTOMER_REORDER_EXCLUDE.SKU AND  CUSTOMER_REORDER_EXCLUDE.AccountNumber LIKE '10013%') WHERE INVOICE_HEAD.AccountNumber LIKE '10013%' AND CUSTOMER_REORDER_EXCLUDE.id is NULL ORDER BY INVOICE_DETAIL.ID) T GROUP BY `Line`, `Group`, `SKU` ORDER BY  SKU";
  							}elseif(substr($accountNumber,0,5) == "10002"){
  								$query = "SELECT * FROM (SELECT `Line`, Familia,if(SortOrder is null, 999, SortOrder) SortOrder, `Group`, `SKU`, INVENTORY.Description, EstimateQty OrderQty , Qty FROM ESTIMATE_DETAIL JOIN INVENTORY USING(Line,`Group`, SKU) LEFT JOIN REORDER_SORT USING(Familia) WHERE EstimateID LIKE '10543') T GROUP BY `Line`, `Group`, `SKU` ORDER BY SKU, Line, `Group`, Familia";
  							}
  							else{
								  //$query = "SELECT * FROM (SELECT `Line`, Familia,if(SortOrder is null, 999, SortOrder) SortOrder, `Group`, `SKU`, INVENTORY.Description, OrderQty , Qty FROM INVOICE_HEAD JOIN INVOICE_DETAIL USING(InvoiceID) JOIN INVENTORY USING(Line,`Group`, SKU) LEFT JOIN REORDER_SORT USING(Familia) LEFT JOIN CUSTOMER_REORDER_EXCLUDE USING(Line, SKU, AccountNumber) WHERE AccountNumber LIKE '$accountNumber' AND CUSTOMER_REORDER_EXCLUDE.id is NULL  ORDER BY INVOICE_DETAIL.ID) T GROUP BY `Line`, `Group`, `SKU` ORDER BY SortOrder, Line, `Group`, Familia, SKU";
								  $query = "SELECT * FROM (SELECT `Line`, Familia,if(SortOrder is null, 999, SortOrder) SortOrder, `Group`, `SKU`, INVENTORY.Description, OrderQty , Qty FROM INVOICE_HEAD JOIN INVOICE_DETAIL USING(InvoiceID) JOIN INVENTORY USING(Line,`Group`, SKU) LEFT JOIN REORDER_SORT USING(Familia) LEFT JOIN CUSTOMER_REORDER_EXCLUDE USING(Line, SKU, AccountNumber) WHERE AccountNumber LIKE '$accountNumber' AND CUSTOMER_REORDER_EXCLUDE.id is NULL  ORDER BY INVOICE_DETAIL.ID) T GROUP BY `Line`, `Group`, `SKU` ORDER BY SKU";
  							}
                //echo $query;
  							//"SELECT `Line`, `Group`, `SKU`, INVENTORY.Description, OrderQty , Qty FROM INVOICE_HEAD JOIN INVOICE_DETAIL JOIN INVENTORY USING(Line,`Group`, SKU) WHERE AccountNumber LIKE '$accountNumber' GROUP BY `Line`, `Group`, `SKU` ORDER BY Line, `Group`, SKU ";

  							//$query = "SELECT * FROM (SELECT `Line`,Familia, `Group`, `SKU`, INVENTORY.Description, OrderQty , Qty FROM INVOICE_HEAD JOIN INVOICE_DETAIL USING(InvoiceID) JOIN INVENTORY USING(Line,`Group`, SKU) WHERE AccountNumber LIKE '$accountNumber' ORDER BY INVOICE_DETAIL.ID) T GROUP BY `Line`, `Group`, `SKU` ORDER BY Line, `Group`,Familia, SKU";
  							$result = mysqli_query($con, $query);


  							while($row = mysqli_fetch_array($result)){
  								$item = new Item(null, $row['Line'], $row['SKU']);
                  if(!$item->Active){
                    continue;
                  }
  							?>
  							<tr>
  								<td><?= $row['SKU'] ?></td>
  								<td><?= $row['Description'] ?></td>
  								<td><?= moneyFormat($item->Price) ?>
  								<?php
  								if($item->ConfirmedQty > 0 ){
  								?>
  									<img src="img/ontheway.jpg"  data-toggle="tooltip" data-placement="bottom" title="<?= $item->ConfirmedQty ?>" style="width: 40px;">
  								<?php
  								}
  								?>
  								</td>
  								<td class="centered visible-xs-block"><?= $row['OrderQty'] . " <br><span style='color: red;'>" . $row['Qty'] ?></span></td>
  								<td class="centered hidden-xs"><?= $row['OrderQty'] ?></td>
  								<td class="centered hidden-xs"><?= $row['Qty'] ?></td>
  								<td><input style="width: 50px;" class="form-control input-sm" type="number" name="ReorderNewQty|<?= $row['Line'] ?>|<?= $row['Group'] ?>|<?= $row['SKU'] ?>" /></td>

  							</tr>
  							<?php
  							}

  							?>
  						</tbody>
  					</table>
  				</form>
  			  </div>
  			  <div class="modal-footer">
  					<button type="button" id="loadReorderToCartSubmit" class="btn btn-success">Send To Cart</button>
  				<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
  			  </div>
  			</div>

  		  </div>
  		</div>
  		<!--  END REORDER LIST -->



  		<script type="text/javascript">
  			$(document).ready(function(){
  					$('[data-toggle="tooltip"]').tooltip();
  				});
  			function loadSavedCart(cartID, copy){
  				copy = copy || false;
  				if(copy){
  					copyArg = "true";
  				}else{
  					copyArg = "false";
  				}

  				if(confirm("Are you sure you want to load this cart contents? This WILL delete the current cart contents.")){
  					$.get('mod.php?p=savecart&a=functions&f=loadCart&id=' + cartID + '&copy=' + copyArg, function(data){
  						if(data === 'true'){
  							location.reload();
  						}
  					});
  				}

  			}
  			function deleteSavedCart(cartID){
  				if(confirm("Are you sure you want to delete the selected cart contents?")){
  					$.get('mod.php?p=savecart&a=functions&f=deleteCart&id=' + cartID, function(data){
  						if(data === 'true'){
  							location.reload();
  						}
  					});
  				}

  			}
  			function saveCart(){
  				if($('#customerSelect').val() == "-1" || $('#customerSelect').val() === null){
  					event.preventDefault();
  					alert("Please select a customer");
  					$('#customerSelect').focus();
  					return false;
  				}else{
  					$.get('mod.php?p=savecart&a=functions&f=saveCart&name=' + prompt('Enter Notes (optional)'),
  						function(data){
  							if(data=='true'){
  								window.location = "index.php";
  							}
  						}
  					);
  				}

  			}
  			function loadReorderToCart(){
  				var dataArray = [];
  				$('[name^=ReorderNewQty]').each(function(index){
  					var qty = $($('[name^=ReorderNewQty]')[index]).val()
  					var name = $($('[name^=ReorderNewQty]')[index]).attr('name');
  					var line = name.split("|")[1];
  					var group = name.split("|")[2];
  					var sku = name.split("|")[3];
  					var item = {};
  					if(qty != "" || qty != "0"){

  						item.Line = line;
  						item.Group = group;
  						item.SKU = sku;
  						item.Qty = qty;
  						dataArray.push(item);
  					}


  				});
  				//console.log(dataArray);
  				$.post('mod.php?p=savecart&a=functions&f=loadReorderToCart', toObject(dataArray) , function(data){
  						if(data == "true"){
  							$('#reorderForm input').val('');
  							FormPersistence.clearStorage(form);
  							setTimeout(function(){
  									location.reload();
  							}, 500);
  						}
  				});


  			}
  			function clearShoppingCart(){
  				if(confirm("Are you sure you want to clear the cart? This action cannot be undone.")){
  					$.get('mod.php?p=savecart&a=functions&f=clearCart', function(data){
  						if(data == "true")			{
  							location.reload();
  						}
  				});
  				}

  			}
  			function toObject(arr) {
  				var rv = {};
  				for (var i = 0; i < arr.length; ++i)
  					if (arr[i] !== undefined) rv[i] = arr[i];
  				return rv;
  			}
  		</script>


  	<script type="text/javascript">
  		$(document).ready(function(){
  			$('#loadReorderToCartSubmit').on('click', function(){
  					loadReorderToCart();
  			});
  		});
  	</script>


  <?php


	}

?>
