<?php
include("connect.php");
include("session.php");
$_SESSION['setCustomerMode'] = isset($_SESSION['setCustomerMode'])?$_SESSION['setCustomerMode']:false;
$isCustomer = $_SESSION['isCustomer'];
$orderTotal = getCartTotal();
$nowTime = "";
if(isset($_REQUEST['timedebug'])){
	$query = "SET SESSION time_zone = '-06:00'";
	mysqli_query($con, $query);
}
$fee = 0;
if ($isCustomer) {
	$customer = new Customer($_SESSION['AccountNumber']);
}else {
	$salesman = new Salesman($_SESSION['SalesmanID']);
	$pricePlanMode = $_SESSION['pricePlanMode'];
}
 ?>
 <!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, user-scalable=no" />

     <title><?= $config['CompanyName'] ?></title>

     <!-- Bootstrap -->
     <link href="css/bootstrap.min.css" rel="stylesheet">
     <link rel="stylesheet" href="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-2.2.4.min.js"></script>
		   <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/jquery.validate.min.js"></script>
		   <script src="js/functions.js"></script>
           <!-- Include all compiled plugins (below), or include individual files as needed -->
           <script src="js/bootstrap.min.js"></script>
       	 <script src="js/bootstrap-combobox.js"></script>
           <script type="text/javascript">
             $(document).ready(function(){
               CalculateDeliveryDate($('[name=deliveryMethod]'));
       //        $('.grpline').css("width", "100px");
             });
           </script>
     <![endif]-->
	<link rel="stylesheet" href="css/styles.css"/>
   </head>
   <body>
       <?php include("navbar.php"); ?>
   <!-- Stack the columns on mobile by making one full-width and the other half-width -->
   <img class="img-responsive visible-print-block" style="margin-top: -30px; width: 160px; position: absolute;" src="img/<?= $config['SmallLogo'] ?>" alt="" />
	<div class="spacer pull-right" style="padding-top: 00px;" >
		<!--<img src="img/wh_round_logo.png" style="display: block; width: 300px;" >-->
	</div>
     <div class="container " style="">

     <div class="page-header">
		<?php
		if(!$detect->isMobile()){ ?>
		<?php
		if(!$isCustomer){
			?>
			<a style="margin-left: 5px;"  class="btn btn-danger hidden-print pull-right" onclick="clearShoppingCart();" href="#"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Clear Cart</a> &nbsp;
			<?php
			if($hasSavedCart && ($salesman->ID != "CC")){
		?>
			<a  style="margin-left: 5px;" class="btn btn-primary hidden-print pull-right" onclick="$('#savedCartsModal').modal('toggle');" href="#"><span class="glyphicon glyphicon-list" aria-hidden="true"></span> Saved Carts</a>&nbsp;
		<?php

			}
			if($salesman->ID != "CC"){
		?>

		<a style="margin-left: 5px;"  class="btn btn-success hidden-print pull-right" onclick="saveCart()" href="#"><span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span> Save Cart</a> &nbsp;

		<?php
			}
		}
		?>

		<a class="btn btn-primary hidden-print pull-right" onclick="window.print();" href="#">Print</a>

		<?php
		}
		?>
		<div></div>
       <h3>Shopping Cart
       <?php
       if ($pricePlanMode) {
       	$customer = new Customer($_SESSION['AccountNumber']);
       	echo("<small>Price Plan Mode - <i>" . $customer->AccountNumber . " - " . $customer->Name . "</i></small>");
       }

        ?>

       </h3>

	   <?php
		if($detect->isMobile()){ ?>
		<div class="centered" style="text-align: center;">
			<a class="btn btn-primary hidden-print" href="index.php">Back to Order</a>
		<?php
		if(!$isCustomer){
			?>
			<a style="margin-left: 5px;"  class="btn btn-danger hidden-print" onclick="clearShoppingCart();" href="#"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Clear Cart</a> &nbsp;
			<?php
			if($hasSavedCart){
		?>
			<a  style="margin-left: 5px;" class="btn btn-primary hidden-print" onclick="$('#savedCartsModal').modal('toggle');" href="#"><span class="glyphicon glyphicon-list" aria-hidden="true"></span> Saved Carts</a>&nbsp;
		<?php

			}

		?>

		<a style="margin-left: 5px;"  class="btn btn-success hidden-print" onclick="saveCart();" href="#"><span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span> Save Cart</a> &nbsp;

		<?php
		}
		?>


		</div>
		<?php
		}
		?>
     </div>
 </div>
 <?php
 if (!$isCustomer) {
 	$sID = $salesman->ID;
 	//This IF will show salesman 25 all the customers (Salesman LIKE '%')
 	if ($sID === "CC" || $sID === "JC" || $sID === "ES" || $sID === "CG") {
 		$sID = "%";
 	}
 	if ($pricePlanMode) {
 		$query = "SELECT * FROM CUSTOMER, PRICE_PLAN_CALC WHERE CUSTOMER.AccountNumber = PRICE_PLAN_CALC.AccountNumber AND Salesman LIKE '" . $sID . "' ORDER BY Name";
 	}else {

 		if ($_SESSION['setCustomerMode']) {
 			$query = "SELECT * FROM CUSTOMER WHERE ( AccountNumber = '" . $_SESSION['setCustomer'] . "') ORDER BY Name";
 		}else {
 			$query = "SELECT * FROM CUSTOMER WHERE Salesman LIKE '" . $sID . "' OR AccountNumber LIKE '00000%' ORDER BY Name";
 		}

 	}

 	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result);
 ?>
 <div class="form-inline">
 	<label for="customerSelect">Customer:</label>
	<?= $row['Name'] ?>
	<input type="hidden" value="<?= $row['AccountNumber'] ?>" name="customer" id="customerSelect">
	<!--<select name="customer" id="customerSelect" class="form-control">
		<option value="-1">--Select a Customer--</option>
		<?php
			while ($row = mysqli_fetch_array($result)) {
		?>
				<option <?= ($_SESSION['setCustomerMode'])?"selected":"" ?> value="<?= $row['AccountNumber'] ?>"><?= $row['Name'] ?> - <?= $row['City'] ?></option>
	<?php
			}
	?>
	</select>
	<input type="text" id="custFilter" name="filter" class="form-control" placeholder="Name or Account Number" value="" />-->
	<?php
	if (!$_SESSION['isCustomer']) {
		if ($_SESSION['setCustomerMode']) {
			//echo '<a role="button" onclick="setCustomer(-1)" class="btn btn-warning">Clear Customer</a>';
		}else {
			//echo '<a role="button" onclick="setCustomer()" class="btn btn-success">Set Customer</a>';
		}
	} ?>
	<?php
	}
	?>

</div>

 <?php
 if($_SESSION['setCustomerMode']){
						$customer = new Customer($_SESSION['setCustomer']);

			}

 if ($isCustomer) {
	$customer = new Customer($_SESSION['AccountNumber']);
 	$priceRate = getPricePlanCalculatedRate($customer->AccountNumber);
 	$query = "SELECT `SHOPPING_CART`.`id`, `SHOPPING_CART`.`Line`, `SHOPPING_CART`.`Group`, `SHOPPING_CART`.`SKU`, `INVENTORY`.`Description`, `INVENTORY`.`Notes`, ROUND(`INVENTORY`.`PriceA` * $priceRate, 2) AS Price, `SHOPPING_CART`.`Qty` As OrderQty, `INVENTORY`.`Qty` As AvailableQty, `Interchange`, `Core`, `INVENTORY`.Taxable1, `INVENTORY`.Taxable2 FROM `SHOPPING_CART`, `INVENTORY` WHERE `INVENTORY`.`Group` = `SHOPPING_CART`.`Group` AND `INVENTORY`.`Line` = `SHOPPING_CART`.`Line` AND `INVENTORY`.`SKU` = `SHOPPING_CART`.`SKU` AND `SHOPPING_CART`.`AccountNumber` LIKE '{$customer->AccountNumber}' ORDER BY id";
//echo $query;
//var_dump($_SESSION);

 }else{
 	if ($pricePlanMode) {
 		$priceRate = getPricePlanCalculatedRate($_SESSION['AccountNumber']);
 	}else {
 		$priceRate = 1;
 	}

 $query = "SELECT `SHOPPING_CART`.`id`, `SHOPPING_CART`.`Line`, `SHOPPING_CART`.`Group`, `SHOPPING_CART`.`SKU`, `INVENTORY`.`Description`, `INVENTORY`.`Notes`, ROUND(`INVENTORY`.`PriceA` * $priceRate, 2) AS Price, `SHOPPING_CART`.`Qty` As OrderQty, `INVENTORY`.`Qty` As AvailableQty, `Interchange`, `Core`, INVENTORY.AvgCost, `INVENTORY`.Taxable1, `INVENTORY`.Taxable2 FROM `SHOPPING_CART`, `INVENTORY` WHERE `INVENTORY`.`Group` = `SHOPPING_CART`.`Group` AND `INVENTORY`.`Line` = `SHOPPING_CART`.`Line` AND `INVENTORY`.`SKU` = `SHOPPING_CART`.`SKU` AND `SHOPPING_CART`.`AccountNumber` LIKE '{$salesman->ID}' ORDER BY id";

 }
 $result = mysqli_query($con, $query);
 $rows = mysqli_num_rows($result);

 if ($rows < 1) {
 ?>
 <div class="well"><p>The Shopping Cart is Empty</p></div>
 <?php
 } else {
 	$result = mysqli_query($con, $query);
 ?>
 <script type="text/javascript">
 	var Line = [];
 	var Group = [];
 	var SKU = [];
 	var Qty = [];
 	function UpdateItem(id) {
 		var qty = $("[name=" + id + "Qty]").val();
 		qty = parseInt(qty);
 		qty = Math.abs(qty);
 		var request = $.get( "functions.php", {
 			action: "updateCartItem",
 			ID: id,
 			Qty: qty
 			} )
 		  .done(function( data ) {
			//alert(data);
 		    location.reload(true);
 		  });
 		  request.fail(function() {
 		  	alert( "There was an error, please check your internet connection" );
 		    });
 	}
 	function DeleteItem(id) {
 	 		var request = $.get( "functions.php", {
 	 			action: "deleteCartItem",
 	 			ID: id,
 	 			} )
 	 		  .done(function( data ) {

 	 		    location.reload(true);
 	 		  });
 	 		  request.fail(function() {
 	 		  	alert( "There was an error, please check your internet connection" );
 	 		    });
 	 	}
 </script>
 <table class="table">
   <thead>
     <tr>
       <th class="hidden-xs" style="width: 5%;">Line<br>Group</th>
       <th style="width: 50%">Item</th>
	   <th class="visible-md-block visible-lg-block" style="width: 5%;">Available Quantity</th>
       <th style="width: 8%">Order Quantity</th>
	   <?php
	   if(isset($_GET['showpercent'])){
		?>
			<th>GP</th>
		<?php
	   }
	   ?>
       <th style="width: 5% " class="hidden-xs">Price</th>
	   <th style="width: 5% " class="visible-xs">Price<br> <span style="color: red;">Extension</span></th>
       <th style="width: 5% " class="hidden-xs">Extension</th>
       <th style="width: 15%" class=""></th>
     </tr>
   </thead>
	<tbody>
	<?php
		$index = 0;
		$taxable1Total = 0;
		$taxable2Total = 0;
		while ($row = mysqli_fetch_array($result)) {
			$taxable1Total += $row['Taxable1']?$row['OrderQty'] * round($row['Price'], 2):0;
			$taxable2Total += $row['Taxable2']?$row['OrderQty'] * round($row['Price'], 2):0;
			$row['Price'] = getCustomerPrice($row['Group'], $row['Line'], $row['SKU'])*$priceRate;
			$row = (updateQtyBreaks($row));
			//var_dump($row);
		?>
		<tr>
   			<td class="hidden-xs">
       			<span class="itemInfo"><?= $row['Line'] ?></span>
       			<span class="itemInfo"><?= $row['Group'] ?></span>
       		</td>
       		<td>
       			<span class="itemInfo"><b><?= $row['SKU'] ?></b><?= ($row['Interchange'] != "")?" (" . $row['Interchange'] . ")":""?></span><br />
       			<span class="itemInfo hidden-xs"><?= $row['Description'] ?></span>
				<span class="itemInfo visible-xs"><?= substr($row['Description'], 0, strposX($row['Description'], " ", 5)) ?>...</span>
       			<span class="itemInfo"><?= $row['Notes'] ?></span>
       		</td>
       		<td class="centered visible-md-block visible-lg-block">
			<?php
				$qty = ($row['AvailableQty'] > 50)?"50+":$row['AvailableQty'];
				$qty = ($qty < 0)?"0":$qty;
			?>
       			<?= $qty ?>
       		</td>

       		<td class="centered">

       			<input class="form-control centered" type="number" name="<?= $row['id'] ?>Qty" value="<?= $row['OrderQty'] ?>" />


       		</td>
			<?php
				if(isset($_GET['showpercent'])){
				 ?>
					 <td><?= round(($row['Price']-$row['AvgCost'])/$row['Price']*100,2) ?></td>
				 <?php
				}
				?>
       		<td><?= moneyFormat($row['Price']) ?>
       			<?php
       				if(floatval($row['Core'])>0){
       					echo "<br><i><b>Core:</b> ". moneyFormat($row['Core']) . "</i>";
       		    	}
       			?>
				<span class="visible-xs-block" style="color: red;">
					<br>
					<?= moneyFormat($row['OrderQty'] * round($row['Price'], 2)) ?>
       			<?php
       				if(floatval($row['Core'])>0){
       					echo "<br><i><b>Core:</b> ". moneyFormat($row['OrderQty'] * $row['Core']) . "</i>";
       				}
       			?>
				</span>
       		</td>
       		<td class="hidden-xs">
       			<?= moneyFormat($row['OrderQty'] * round($row['Price'], 2)) ?>
       			<?php
       				if(floatval($row['Core'])>0){
       					echo "<br><i><b>Core:</b> ". moneyFormat($row['OrderQty'] * $row['Core']) . "</i>";
       				}
       			?>
       		</td>
       		<td>
       			<div>
       				<button class="btn btn-success"  id="item<?= $index; ?>" onclick="UpdateItem(<?= $row['id'] ?>)" type="button"><span class="glyphicon glyphicon-refresh" aria-hidden="true"></span></button>

       				<button class="btn btn-danger"  onclick="DeleteItem(<?= $row['id'] ?>)" type="button"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button>
       			</div>
       		</td>
     	</tr>

     <?php
     $index++;
     }
     ?>
     	<form method="post" id="cartForm" action="checkout.php" enctype="multipart/form-data">
     	<tr class="hidden-xs">
     		<td class="hidden-xs"></td>
     		<td class="hidden-xs"></td>
     		<td class="visible-md-block visible-lg-block"></td>

     		<td colspan="2" style="font-weight: bold; text-align: right;"><span >
			Subtotal:
			<br>
			<?= $config['Tax1Name'] ?>:
			<br>
			<?= $config['Tax2Name'] ?>:
			<br>
			Total:
			</span></td>
     		<td style="font-weight: bold; text-align: right;"><span>
			<?= moneyFormat(getCartTotal()) ?>
			<br>
			<?php

			$tax1 = $taxable1Total*($customer->TaxExempt1?0:$config['Tax1Rate']);
			echo moneyFormat($tax1) ?>
			<br>
			<?php
			$tax2 = $taxable2Total*($customer->TaxExempt2?0:$config['Tax2Rate']);
			echo moneyFormat($tax2) ?>
			<br>
			<?= moneyFormat(getCartTotal()+$tax1+$tax2) ?>
			</span></td>
			<td>
			<?php

			if($customer->AccountNumber == "00000-00" || $customer->AccountNumber == "00000-01"){
			?>

				<a class="btn btn-primary" name="askEstimatePicture" onclick="openEstimateInfoModal();" value="true">New Customer Order</a><br>
				<input type="hidden" name="approveOrder" id="approveOrder" value="" />
				<script type="text/javascript">
					function openEstimateInfoModal(){
						$.get('functions.php?action=getDataFromSession&key=newEstimateData', function(data){
							data = JSON.parse(data);
							if(Object.keys(data).length > 0){
								$('#NewCustomerInformationForm input').each(function(e){
									$(this).val(data[$(this).attr('id')]);
								});
								$('#NewCustomerInformationForm select').each(function(e){
									$(this).val(data[$(this).attr('id')]);
								});
								$('#NewCustomerInformationForm input[type="checkbox"]').each(function(e){
									if(data[$(this).attr('id')] == "on"){
										$(this).prop('checked', true);
									}else{
										$(this).prop('checked',false);
									}

								});
							}


						});
						if($('#PONumber').val() === ""){
							alert('Por favor entre un numero de PO o nombre de quien autoriza la orden o estimado.');
							return false;
						}else{
							$('#additionalEstimateInformation').modal('toggle');
							return false;
						}
					}



				</script>
				<button style="display: none;" class="btn btn-primary" name="Submit" value="true">Finish Order</button><br>
			<?php
			}else{
			?>
				<button class="btn btn-primary" name="Submit" value="true">Finish Order</button><br>
				<?php
			if(!$isCustomer){


			?>
			<br>
			<a class="btn btn-warning" name="askEstimatePicture" onclick="$('#additionalEstimateInformation').modal('toggle');" value="true">Estimate</a>
			<?php
			}
			}
			?>


			</td>
     	</tr>
		<tr class="visible-xs">
     		<td class="hidden-xs"></td>
     		<td class="hidden-xs"></td>
     		<td class="visible-md-block visible-lg-block"></td>

     		<td colspan="2" style="font-weight: bold; text-align: right;"><span >
			Subtotal:
			<br>
			<?= $config['Tax1Name'] ?>:
			<br>
			<?= $config['Tax2Name'] ?>:
			<br>
			Total:
			</span></td>
     		<td style="font-weight: bold; text-align: right;"><span>
			<?= moneyFormat(getCartTotal()) ?>
			<br>
			<?php
			$tax1 = getCartTotal()*($customer->TaxExempt1?0:$config['Tax1Rate']);
			echo moneyFormat($tax1) ?>
			<br>
			<?php
			$tax2 = getCartTotal()*($customer->TaxExempt2?0:$config['Tax2Rate']);
			echo moneyFormat($tax2) ?>
			<br>
			<?= moneyFormat(getCartTotal()+$tax1+$tax2) ?>
			</span></td>
			<td>


			</td>
     	</tr>


     <?php
     }?>
   </tbody>
 </table>
 <?php
 if($detect->isMobile()){
?>
	<div class="form-group" style="width: 100%; ">
<?php
 }else{
	?>
	<div class="form-group" style="width: 70%; float: left; ">
	<?php

 }
 ?>

 		<label for="orderNotes">Order Notes</label>
 		<textarea name="orderNotes" class="form-control" id="orderNotes" style="resize: none; height: auto;"><?php
 				if (isset($_SESSION['OrderNotes'])) {
 					echo trim($_SESSION['OrderNotes']);
 				}
 			?></textarea>
 	</div>
<?php
 if($detect->isMobile()){
?>
	<div class="form-group" style="width: 100%;">
<?php
 }else{
	?>
	<div class="form-group" style="width: 25%; float: right;">
	<?php

 }
 ?>

 		<label for="deliveryMethod">Delivery Method</label>

 		<select name="deliveryMethod" class="form-control" id="deliveryMethod">
			<?php
			if($_SESSION['TruckMode'] && !$isCustomer){
				$truck = new Warehouse($_SESSION['WarehouseID']);
				$truckName = $truck->WarehouseName;
			?>
			<option data-sku="<?= "TRUCK" ?>|<?= $_SESSION['WarehouseID'] ?>" value="<?= $truckName ?>"><?= $truckName ?></option>
			<?php
			}else{
				$CustomerCity = "";

				if($isCustomer){
					$CustomerCity = $customer->City;
				}else{
					if($_SESSION['setCustomerMode']){
						$customer = new Customer($_SESSION['setCustomer']);
						$CustomerCity = $customer->City;
					}
				}
				$trans = array(
							   "Monday" => "Lunes",
							   "Tuesday" => "Martes",
							   "Wednesday" => "Miercoles",
							   "Thursday" => "Jueves",
							   "Friday" => "Viernes",
							   "Saturday" => "Sabado",
							   "Sunday" => "Domingo",
							   );

				//mysqli_query($con,"SET time_zone = '+12:00';");
				$query = "SELECT  *, time(DATE_ADD(NOW(), INTERVAL -4 HOUR)) as NowTime,
IF(TIME(DATE_ADD(NOW(), INTERVAL -4 HOUR)) <= '16:30',
	IF(starttime >= '12:00:00',
		CONCAT(DATE_ADD(DATE(DATE_ADD(NOW(), INTERVAL -4 HOUR)), INTERVAL -1 DAY), ' ', StartTime),

		CONCAT(DATE_ADD(DATE(DATE_ADD(NOW(), INTERVAL -4 HOUR)), INTERVAL 0 DAY), ' ', StartTime)
	),
	IF(starttime >= '12:00:00',
		CONCAT(DATE_ADD(DATE(DATE_ADD(NOW(), INTERVAL -4 HOUR)), INTERVAL 0 DAY), ' ', StartTime),
		CONCAT(DATE_ADD(DATE(DATE_ADD(NOW(), INTERVAL -4 HOUR)), INTERVAL 0 DAY), ' ', StartTime)
	)
) <= DATE_ADD(NOW(), INTERVAL -4 HOUR)  AS ElegibleStart,

IF(TIME(DATE_ADD(NOW(), INTERVAL -4 HOUR)) <= '16:30',
	IF(starttime >= '12:00:00',
		CONCAT(DATE_ADD(DATE(DATE_ADD(NOW(), INTERVAL -4 HOUR)), INTERVAL -1 DAY), ' ', StartTime),

		CONCAT(DATE_ADD(DATE(DATE_ADD(NOW(), INTERVAL -4 HOUR)), INTERVAL 0 DAY), ' ', StartTime)
	),
	IF(starttime >= '12:00:00',
		CONCAT(DATE_ADD(DATE(DATE_ADD(NOW(), INTERVAL -4 HOUR)), INTERVAL 0 DAY), ' ', StartTime),
		CONCAT(DATE_ADD(DATE(DATE_ADD(NOW(), INTERVAL -4 HOUR)), INTERVAL 0 DAY), ' ', StartTime)
	)
) AS ElegibleStartTime,

IF(TIME(DATE_ADD(NOW(), INTERVAL -4 HOUR)) >= '16:30',
	CONCAT(DATE_ADD(DATE(DATE_ADD(NOW(), INTERVAL -4 HOUR)), INTERVAL 1 DAY), ' ', `Cutoff`),
	CONCAT(DATE_ADD(DATE(DATE_ADD(NOW(), INTERVAL -4 HOUR)), INTERVAL 0 DAY), ' ', `Cutoff`)
) >= DATE_ADD(NOW(), INTERVAL -4 HOUR) AS ElegibleCutoff ,
IF(TIME(DATE_ADD(NOW(), INTERVAL -4 HOUR)) >= '16:30',
	CONCAT(DATE_ADD(DATE(DATE_ADD(NOW(), INTERVAL -4 HOUR)), INTERVAL 1 DAY), ' ', `Cutoff`),
	CONCAT(DATE_ADD(DATE(DATE_ADD(NOW(), INTERVAL -4 HOUR)), INTERVAL 0 DAY), ' ', `Cutoff`)
) AS ElegibleCutoffTime,
IF(TIME(DATE_ADD(NOW(), INTERVAL -4 HOUR)) >= `Cutoff`,
	CONCAT(DATE_ADD(DATE(DATE_ADD(NOW(), INTERVAL -4 HOUR)), INTERVAL IF(`SameDay`, 1, 2) DAY), ' ', `DeliveredBy`),
	CONCAT(DATE_ADD(DATE(DATE_ADD(NOW(), INTERVAL -4 HOUR)), INTERVAL IF(`SameDay`, 0, 1) DAY), ' ', `DeliveredBy`)
)AS ExpectedDelivery

FROM DELIVERY_OPTION
	JOIN DELIVERY_ZONE ON DELIVERY_OPTION.id = `DELIVERY_ZONE`.`DeliveryID`
	JOIN DELIVERY_ZONE_CITY ON DELIVERY_ZONE_CITY.Zone LIKE DELIVERY_ZONE.Zone
WHERE City LIKE '$CustomerCity' HAVING (ElegibleStart AND ElegibleCutoff) ORDER BY Cutoff, `Name` ASC;";

				$result = mysqli_query($con,$query);
				//var_dump($con);
				$count = mysqli_num_rows($result);
				//RECUERDA QUE SE MODIFICO CLASE DE CUSTOMER Y SECCION EN ADMIN PARA WAIVE SHIPPING FEE
				$expectedDelivery = "";
				$firstDeliveryDate = "@-@-@";
				$firstDeliveryFee = "!-!-!";
				while($row = mysqli_fetch_array($result)){
					if($row['ExpectedDelivery'] != ""){
						$expectedTime = strtotime($row['ExpectedDelivery']);
						$expectedDayOfWeek = date("N", $expectedTime);
						if($row['SameDay'] && $expectedDayOfWeek == 6){
							$expectedTime += (2*24*60*60);
						}

						if($expectedDayOfWeek == 7){
							$expectedTime += (24*60*60);
						}
						$expectedDelivery = strtr(date("l j/M/y g:i a", $expectedTime), $trans);
					}else{
						$expectedDelivery = "";
					}
					if($firstDeliveryDate == "@-@-@"){
						$firstDeliveryDate = $expectedDelivery;
					}

					$nowTime = $row['NowTime'];

					if(isset($customer) && $customer->WaiveShipping){

					}else{
						eval($row['FeeRule']);
					}
					if($firstDeliveryFee == "!-!-!"){
						$firstDeliveryFee = $fee;

					}
					$shippingCostString = "";
					if($row['DisplayPrice']){
						$shippingCostString = ($fee == 0)?"FREE":moneyFormat($fee);
						$shippingCostString = " - Service Fee: " . $shippingCostString;
						//$shippingCostString = "";
					}

			?>

			<option value="<?= $row['Name'] ?>" data-sku="<?= $row['SKU'] ?>" data-fee="<?= $fee ?>" data-expected="<?= $expectedDelivery ?>"><?= $row['Name']  . $shippingCostString  ?></option>
			<?php

				}
				if($count === 0){
			?>
				<option data-sku="RD001" value="Regular Delivery">Regular Delivery</option>
			<?php
				}

			?>

 			<option data-sku="PICK" value="Pickup">Pickup</option>
			<?php
			}
			?>
 		</select>



		<!--<label for="expectedBy">Expected Delivery Before:</label>
		<input type="text" maxlength="212" disabled readonly name="expectedBy" class="form-control" id="expectedBy" value="<?= $firstDeliveryDate ?>">-->
 		<?php
 			$PONumber = "";
			//var_dump($_SESSION);
 			if (isset($_SESSION['PONumber'])) {
 				$PONumber = trim($_SESSION['PONumber']);

 			}


 		?>
 	<label for="PONumber">PO Number/Name <span style="color: red;"> *</span></label>
 	<input type="text" maxlength="64" style="text-transform: capitalize;" autocomplete="new-password" name="PONumber" class="form-control" id="PONumber" value="<?= $PONumber ?>">
	<label for="POFile">PO File<span style="color: red;"> *</span></label>
 	<input type="file" name="POFile" class="form-control" id="POFile" />
 	<input type="hidden" name="customerNumber" class="form-control" id="customerNumber">
	<input type="hidden" name="serviceFee" id="serviceFee" value="<?= $firstDeliveryFee ?>">
	<input type="hidden" name="deliverySKU" id="deliverySKU" value="">
	<input type="hidden" name="estimateImage" id="estimateImage" value="">
 </div>

	<div class="visible-xs">
     		<div colspan="4" style="text-align: right;">
				<?php
			if($_SESSION['setCustomerMode']){
						$customer = new Customer($_SESSION['setCustomer']);

			}
			if($customer->AccountNumber == "00000-00" || $customer->AccountNumber == "00000-01"){
			?>

				<a class="btn btn-primary" name="askEstimatePicture" onclick="openEstimateInfoModal();" value="true">New Customer Order</a><br>
				<button style="display: none;" class="btn btn-primary" name="Submit" value="true">Finish Order</button><br>
			<?php
			}else{
			?>
				<button class="btn btn-primary" name="Submit" value="true">Finish Order</button><br>
				<?php
			if(!$isCustomer){


			?>
			<br>
			<a class="btn btn-warning" name="askEstimatePicture" onclick="$('#additionalEstimateInformation').modal('toggle');" value="true">Estimate</a>
			<?php
			}
			}
			?>
			</div>

     	</div>
	<!-- Estimate Information Modal -->
	<div class="modal fade" tabindex="-1" id="additionalEstimateInformation" role="dialog">
		<div class="modal-dialog modal-lg" 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">Additional Estimate Information Required</h4>
			</div>
			<div style="min-height:150px;" class="modal-body">
			<?php
				if($customer->AccountNumber == "00000-00" || $customer->AccountNumber == "00000-01"){

			?>
				<script type="text/javascript" src="js/jquery.mask.js"></script>
				<script type="text/javascript">
					$(document).ready(function(){
						$('#EstimatePhone').mask('(000) 000-0000');
						$('#EstimateBillToZip').mask('00000-0000');
						$('#EstimateShipToZip').mask('00000-0000');
						function validateEmail(email) {
							var filter = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
							if (filter.test(sEmail)) {
								return true;
							} else {
								return false;
							}
						}
					});
				</script>
				  <h4>Contact Information</h4>
				  <div  id="NewCustomerInformationForm">
					<div class="row">

						<div class="col-sm-6">
							<div class="form-group">
								<span style="color: red;">* Fields with an asterisk (*) are <span style="text-decoration: underline;">required</span>.</span>
							</div>
							<div class="form-group">

								<label for="EstimateCompanyName">Company Name:</label>
								<input type="text" class="form-control required allcaps" autocomplete="false" value="" name="EstimateCompanyName" id="EstimateCompanyName">
							</div>

							<div class="form-group">
								<label for="EstimateContactTitle">Contact Title:</label>
								<select class="form-control required" style="width: 80px;" name="EstimateContactTitle" id="EstimateContactTitle">
									<option></option>
									<option>Sr.</option>
									<option>Sra.</option>
									<option>Mr.</option>
									<option>Mrs.</option>
								</select>
							</div>

							<div class="form-group">
								<label for="EstimateContactName">Contact Name:</label>
								<input type="text" style="text-transform: capitalize;" class="form-control required propercase" autocomplete="false" name="EstimateContactName" id="EstimateContactName"  value="">
							</div>
							<div class="form-group">
								<label for="EstimateTaxID">Tax ID State</label>
								<input type="text" class="form-control" autocomplete="false" name="EstimateTaxID" id="EstimateTaxID" value="">
							</div>
							<div class="form-group">
								<label for="EstimateTaxIDExpiration">Tax ID State Expiration Date</label>
								<input type="date" class="form-control" autocomplete="false" name="EstimateTaxIDExpiration" id="EstimateTaxIDExpiration" value="">
							</div>

						</div>
						<div class="col-sm-6">

							<div class="form-group">
								<label for="EstimatePhone">Phone</label>
								<input type="text" class="form-control required" autocomplete="false" name="EstimatePhone" id="EstimatePhone" value="">
							</div>
							<div class="form-group">
								<label for="EstimateEmail">Email</label>
								<input type="text" class="form-control required alllower" autocomplete="false" name="EstimateEmail" id="EstimateEmail" value="">
							</div>
							<div class="form-group">
								<label for="EstimateTaxID2">Tax ID Municipal <i>(If left blank taxes will be charged)</i></label>
								<input type="text" class="form-control" autocomplete="false" name="EstimateTaxID2" id="EstimateTaxID2" value="">
							</div>
							<div class="form-group">
								<label for="EstimateTaxIDExpiration2">Tax ID Municipal Expiration Date</label>
								<input type="date" class="form-control" autocomplete="false" name="EstimateTaxIDExpiration2" id="EstimateTaxIDExpiration2" value="">
							</div>
						</div>
					</div>
					<div class="row">

						<div class="col-sm-6">
							<h4>Billing Address</h4>
							<div class="form-group">
								<label for="EstimateBillToAddress1">Address 1</label>
								<input type="text" class="form-control required allcaps" autocomplete="false" name="EstimateBillToAddress1" id="EstimateBillToAddress1" value="">
							</div>
							<div class="form-group">
								<label for="EstimateBillToAddress2">Address 2</label>
								<input type="text" class="form-control allcaps" autocomplete="false" name="EstimateBillToAddress2" id="EstimateBillToAddress2" value="">
							</div>
							<div class="row">
								<div class="col-sm-6">
									<div class="form-group">
										<label for="EstimateBillToCity">City</label>
										<input type="text" class="form-control required allcaps" autocomplete="false" name="EstimateBillToCity" id="EstimateBillToCity" value="">
									</div>
								</div>
								<div class="col-sm-2">
									<div class="form-group">
										<label for="EstimateBillToState">State</label>
										<input type="text" class="form-control required allcaps" autocomplete="false" name="EstimateBillToState" id="EstimateBillToState" value="">
									</div>
								</div>
								<div class="col-sm-4">
									<div class="form-group">
										<label for="EstimateBillToZip">Zip Code</label>
										<input type="text" class="form-control required" autocomplete="false" name="EstimateBillToZip" id="EstimateBillToZip" value="">
									</div>
								</div>
								<div class="col-sm-4">
								  <div class="form-group form-inline" style="display: inline-block;">
									  <input class="form-control" style="display: inline-block;" type="checkbox" name="EstimateSameAddress" id="EstimateSameAddress" />
									  <label for="EstimateSameAddress" class="radio-inline">Same Address</label>
								  </div>
								</div>
								<style>

								</style>
								<script>
								  $('#EstimateSameAddress').on('change', function(e){
									  //alert(e.target);
									  //console.log($(e.target));

									  if($(e.target).prop('checked')){
										  $('#EstimateShipToAddress1').val($('#EstimateBillToAddress1').val());
										  $('#EstimateShipToAddress2').val($('#EstimateBillToAddress2').val());
										  $('#EstimateShipToCity').val($('#EstimateBillToCity').val());
										  $('#EstimateShipToState').val($('#EstimateBillToState').val());
										  $('#EstimateShipToZip').val($('#EstimateBillToZip').val());

									  }
								  });
								</script>
							</div>
						</div>

						<div class="col-sm-6">
							<h4>Shipping Address (Physical Address)</h4>
							<div class="form-group">
								<label for="EstimateShipToAddress1">Address 1</label>
								<input type="text" class="form-control required" autocomplete="false" name="EstimateShipToAddress1" id="EstimateShipToAddress1" >
							</div>
							<div class="form-group">
								<label for="EstimateShipToAddress2">Address 2</label>
								<input type="text" class="form-control allcaps" autocomplete="false" name="EstimateShipToAddress2" id="EstimateShipToAddress2" >
							</div>
							<div class="row">
								<div class="col-sm-6">
									<div class="form-group">
										<label for="EstimateShipToCity">City</label>
										<input type="text" class="form-control required allcaps" autocomplete="false" name="EstimateShipToCity" id="EstimateShipToCity">
									</div>
								</div>
								<div class="col-sm-2">
									<div class="form-group">
										<label for="EstimateShipToState">State</label>
										<input type="text" class="form-control required allcaps" autocomplete="false" name="EstimateShipToState" id="EstimateShipToState">
									</div>
								</div>
								<div class="col-sm-4">
									<div class="form-group">
										<label for="EstimateShipToZip">Zip Code</label>
										<input type="text" class="form-control" autocomplete="false" name="EstimateShipToZip" id="EstimateShipToZip">
									</div>
								</div>
							</div>
						</div>
					</div>

					<hr>
					<?php
				  }
					?>
					<div class="col-sm-12">
					  <div class="form-group form-inline"  style="display: inline-block;">

						  <input class="form-control"  style="display: inline-block;"  type="checkbox" name="estimateProductImage" id="estimateProductImage">
						  <label for="estimateProductImage" class="radio-inline">Include Product Images</label>
						  <div style="color: red; position: relative; left: 20px; bottom: 30px;" class="visible-xs-inline">
							  <!--<span style="background-color: yellow;">NEW!</span>-->
						  </div>
					  </div>

						<label for="estimateImage">Select Program Image</label>
						<select class="form-control" name="estimateImageSelect" id="estimateImageSelect">
							<option value="0">None</option>
							<?php
								$query = "SELECT * FROM PROGRAM_PICTURE ORDER BY ProgramName ASC";
								$result = mysqli_query($con, $query);
								while($row = mysqli_fetch_array($result)){
							?>
							<option value="<?= $row['id'] ?>"><?= $row['ProgramName'] ?></option>
							<?php
								}
							?>
						</select>
						<script type="text/javascript">
							$('#estimateImageSelect').on('change', function(){
								$('#estimateImage').val($('#estimateImageSelect').val());
							});
							function validateNewCustomerEmail(){
								if($('#EstimateEmail').val()){
									var email = $('#EstimateEmail').val().trim();
									if(email !== "" && email != "no tiene"){
										$.get("functions.php?action=verifyEmail&email=" + email, function(data){
												if(data == "false"){
													alert("The email address is not valid!");

													$('#EstimateEmail').focus();
													return false;
												}else{
													return true;
												}
										});
									}else{
										return true;
									}
								}else{
									return true;
								}
							}
							$('#EstimateEmail').on('change', function(){
								validateNewCustomerEmail();
							});
						</script>
					</div>


			  </div>
			</div>
			<div class="modal-footer">
				<br>
				<button type="button" id="closeModalSave" class="btn btn-default" data-dismiss="modal">Back</button>
			  <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
			  <button type="button" name="SubmitEstimate" class="btn btn-primary">Submit</button>
			</div>
		  </div><!-- /.modal-content -->
		</div><!-- /.modal-dialog -->
	  </div><!-- /.modal -->


	  <!-- Choose estimate or order modal -->
	  <div class="modal fade" tabindex="-1" id="approveOrderModal" role="dialog" aria-labelledby="">
		<div class="modal-dialog modal-sm" role="document">
		  <div class="modal-content">
			<div class="modal-header">
				<h4>Select Transaction Type</h4>
			</div>
			<div class="modal-body">
				<center>
					<button onclick="setEstimateTypeAndSubmit('0');" class="btn btn-warning">Estimate</button>
					<button onclick="setEstimateTypeAndSubmit('1');" class="btn btn-primary">Order</button>
				</center>
			</div>
		  </div>
		</div>
	  </div>

 </form>
		<!--<div style="margin-top: 120px; width: 60%; margin-left: 20px;" class="well well-sm"></div>-->
<hr />



 <script type="text/javascript">

	$('#closeModalSave').on('click', function(){
		var data = {};
		$('#NewCustomerInformationForm input').each(function(e){
			data[$(this).attr('id')] = $(this).val();
		});
		$('#NewCustomerInformationForm select').each(function(e){
			data[$(this).attr('id')] = $(this).val();
		});
		$('#NewCustomerInformationForm input[type="checkbox"]').each(function(e){
			//alert($(this).prop('checked'));
			if($(this).prop('checked') === true){
					data[$(this).attr('id')] = "on";
			}else{
				data[$(this).attr('id')] = "off";
			}


		});
		//data["PONumber"] = $("#PONumber").val();
		$.post("functions.php?action=saveToSession", {
			"key"	: "newEstimateData",
			"data"	: data
		}, function(data){
			console.log(data);
		});
		//console.log(data);
	});
	$('#PONumber').on('keydown', function(e){
		if(e.keyCode == 13 || e.keyCode === 0){
			return false;
		}

		});
 	$('#cartForm').submit(function(event) {
		if($('#PONumber').val() === ""){
			event.preventDefault();
			alert('Entre un numero de PO o nombre del comprador');
			$('#PONumber').focus();
			return;
		}

 		if($('#customerSelect').val() == "-1" || $('#customerSelect').val() === null){
 			event.preventDefault();
 			alert("Please select a customer");
 			$('#customerSelect').focus();
 		}else{
 			$('#customerNumber').val($('#customerSelect').val());
 			$('#cartForm').submit();
 		}
 	});
	$('.required').each(function(index){
			var item = $('.required')[index];
			$($(item).siblings()[0]).append("<span style=\"color: red;\"> *</span>");

		});
	$('[name=SubmitEstimate]').on('click', function(event){
		$('#cartForm').attr('action', 'estimateCheckout.php');
		var submit = true;
		<?php
		if($customer->AccountNumber == "00000-00" || $customer->AccountNumber == "00000-01"){

		?>
		$('.required').each(function(index){
			var item = $('.required')[index];
			if(submit){
				if($(item).val().trim() == ""){
					var label = $($(item).siblings()[0]).text();
					alert('Required Field.\n\n' + label);
					$(item).parent().addClass('has-error');
					$(item).focus();
					submit = false;
					return;
				}else{
					$(item).parent().removeClass('has-error');
					$(item).parent().addClass('has-success');
				}
			}
		});

		if($('#approveOrder').val() === "" && submit){
			$('#approveOrderModal').modal('toggle');
			submit = false;
			return;
		}

		<?php
		}
		?>
		submit = validateNewCustomerEmail();

		if(submit){
			$('[name=Submit]').click();
		}

	});
	$('#deliveryMethod').change(function(){
		CalculateDeliveryDate(this);
	});
	function setEstimateTypeAndSubmit(estimateType){
		$('#approveOrder').val(estimateType);

		$('[name=SubmitEstimate]').click();
	}
	function CalculateDeliveryDate(object){
		var expectedBy = $(object).find(':selected').data('expected');
		var fee = $(object).find(':selected').data('fee');
		var sku = $(object).find(':selected').data('sku');
		if(expectedBy === undefined){
			expectedBy = "";
		}
		$('#expectedBy').val(expectedBy);
		$('#serviceFee').val(fee);
		$('#deliverySKU').val(sku);
	}
 	$('#PONumber').change(function() {
 		saveFields();
 	});
 	$('#orderNotes').change(function() {
		saveFields();
 	});
 	function saveFields() {
 		var request = $.get( "functions.php", {
 			action: "saveFields",
 			OrderNotes: $('#orderNotes').val(),
 			PONumber: $('#PONumber').val()
 			}).done(function( data ) {

 			});
 	}
 	jQuery.fn.filterByText = function(textbox) {
 	    return this.each(function() {
 	        var select = this;
 	        var options = [];
 	        $(select).find('option').each(function() {
 	            options.push({value: $(this).val(), text: $(this).text()});
 	        });
 	        $(select).data('options', options);
 	        $(textbox).bind('change keyup', function() {
 	            var options = $(select).empty().data('options');
 	            var search = $.trim($(this).val());
 	            var regex = new RegExp(search,"gi");
 	            $.each(options, function(i) {
 	                var option = options[i];
 	                if(option.text.match(regex) !== null || option.value.match(regex) !== null) {
 	                    $(select).append(
 	                        $('<option>').text(option.text).val(option.value)
 	                    );
 	                }
 	            });
 	        });
 	    });
 	};
 	$('#customerSelect').filterByText($('#custFilter'));
 	$('#customerSelect').width($('#customerSelect').width());
 	function setCustomer(param) {
 		if (param == undefined) {
 			param = $('#customerSelect').val();
 		}
 		if (param == -1 || param == "-1") {
 			$.get('functions.php?action=clearSetCustomer', function(data) {
 				data = JSON.parse(data);
 				if (data.result) {
 					location.reload();
 				}else {
 					alert("ERROR");
 				}


 			});
 		}else {
 			$.get('functions.php?action=setCustomer&id=' + param, function(data) {
 				data = JSON.parse(data);
 				if (data.result) {
 					location.reload();
 				}else {
 					alert("ERROR");
 				}
 			});
 		}

 	}

 </script>
   </body>
 </html>
