<?php
if (!isset($_REQUEST['Submit'])) {
	header("Location: index.php");
}
include_once("session.php");
include_once("connect.php");
global $con, $config;
$isCustomer = $_SESSION['isCustomer'];
if($isCustomer){
	//If there is no items in the shopping cart, redirect to index.php
	$query = "SELECT id FROM SHOPPING_CART WHERE AccountNumber LIKE '" . $_SESSION['AccountNumber'] . "'";
	$result = mysqli_query($con, $query);
	$rows = mysqli_num_rows($result);
	if($rows == 0){
		header("Location: index.php");
		return;
	}
	//setup customer class
	$customer = new Customer($_SESSION['AccountNumber']);
}else {
	//If there is no items in the shopping cart, redirect to index.php
	$query = "SELECT id FROM SHOPPING_CART WHERE AccountNumber LIKE '" . $_SESSION['SalesmanID'] . "'";
	$result = mysqli_query($con, $query);
	$rows = mysqli_num_rows($result);
	if($rows == 0){
		header("Location: index.php");
		return;
	}
	$salesman = new Salesman($_SESSION['SalesmanID']);
	$customer = new Customer($_POST['customerNumber']);
}

//clean up post entries
$orderNotes = mysqli_real_escape_string($con, $_POST['orderNotes']);
$deliveryMethod = mysqli_real_escape_string($con, $_POST['deliveryMethod']);
$deliverySKU = mysqli_real_escape_string($con, $_POST['deliverySKU']);
$PONumber = ucwords(mysqli_real_escape_string($con, $_POST['PONumber']));
$_SESSION['PONumber'] = "";
$_SESSION['OrderNotes'] = "";
if($_SESSION['TruckMode']){
	$WarehouseID = $_SESSION['WarehouseID'];
}else{
	$WarehouseID = "100";
}

$documentID = createDocument("PO", $_FILES);
$documentID = is_null($documentID)?"null":$documentID;

//creating new entry in orders db
if ($isCustomer) {
	$query = "INSERT INTO ORDER_HEAD (AccountNumber, OrderDate, Salesman, OrderNotes, PONumber, DeliveryMethod, DocumentID) VALUES ('$customer->AccountNumber', DATE_ADD(NOW(), INTERVAL -4 HOUR), '" . $customer->Salesman->ID . "', '$orderNotes', '$PONumber', '$deliveryMethod', $documentID)";
}else {
	$query = "INSERT INTO ORDER_HEAD (AccountNumber, OrderDate, Salesman, SalesmanOrder, OrderNotes, PONumber, DeliveryMethod, WarehouseID, DocumentID) VALUES ('$customer->AccountNumber', DATE_ADD(NOW(), INTERVAL -4 HOUR), '" . $customer->Salesman->ID . "', True, '$orderNotes', '$PONumber', '$deliveryMethod', $WarehouseID, $documentID)";
}
error_log( $query);
mysqli_query($con, $query);
$orderID = mysqli_insert_id($con);

//with inserted entry id insert items in order_detail table

if ($isCustomer) {
	$priceRate = getPricePlanCalculatedRate($customer->AccountNumber);
	$column = "PriceA";
	switch ($customer->PriceLevel) {
		case "A":
			$column = "PriceA";
			break;
		case "B":
			$column = "PriceB";
			break;
		case "C":
			$column = "PriceC";
			break;
		case "D":
			$column = "PriceD";
			break;
		case "E":
			$column = "PriceE";
			break;
		default:
			$column = "PriceA";
	}
	$query = "SELECT $orderID as OrderID, `SHOPPING_CART`.`Group`, `SHOPPING_CART`.`Line`, `SHOPPING_CART`.`SKU`, `INVENTORY`.`Description`, `INVENTORY`.`Notes`, `SHOPPING_CART`.`Qty` As OrderQty, `INVENTORY`.`Qty` As AvailableQty, `Interchange`, ROUND(`INVENTORY`.`$column` * $priceRate,2) AS `Price`, `Core` 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 SHOPPING_CART.id";
	//$query .= $select;

}else {
	if ($_SESSION['pricePlanMode']) {
		$priceRate = getPricePlanCalculatedRate($_SESSION['AccountNumber']);
	}else {
		$priceRate = 1;
	}
	$customer->AccountNumber;
	$column = "PriceA";
	switch ($customer->PriceLevel) {
		case "A":
			$column = "PriceA";
			break;
		case "B":
			$column = "PriceB";
			break;
		case "C":
			$column = "PriceC";
			break;
		case "D":
			$column = "PriceD";
			break;
		case "E":
			$column = "PriceE";
			break;
		default:
			$column = "PriceA";
	}
	$query = "SELECT $orderID as OrderID, `SHOPPING_CART`.`Group`, `SHOPPING_CART`.`Line`, `SHOPPING_CART`.`SKU`, `INVENTORY`.`Description`, `INVENTORY`.`Notes`, `SHOPPING_CART`.`Qty` As OrderQty, `INVENTORY`.`Qty` As AvailableQty, `Interchange`, ROUND(`INVENTORY`.`$column` * $priceRate,2) AS `Price`, `Core` 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 SHOPPING_CART.id";
	//$query .= $select;
}
$result = mysqli_query($con, $query);

while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
	$row['Price'] = getCustomerPrice($row['Group'], $row['Line'], $row['SKU']) * $priceRate;
	$row = updateQtyBreaks($row);
	$query = "INSERT INTO ORDER_DETAIL (`OrderID`, `Group`, `Line`, `SKU`, `Description`, `Notes`, `OrderQty`, `AvailableQty`, `Interchange`, `Price`, `Core`)
	VALUES (
	'" . mysqli_real_escape_string($con, $row['OrderID']) . "',
	'" . mysqli_real_escape_string($con, $row['Group']) . "',
	'" . mysqli_real_escape_string($con, $row['Line']) . "',
	'" . mysqli_real_escape_string($con, $row['SKU']) . "',
	'" . mysqli_real_escape_string($con, $row['Description']) . "',
	'" . mysqli_real_escape_string($con, $row['Notes']) . "',
	" . mysqli_real_escape_string($con, $row['OrderQty']) . ",
	" . mysqli_real_escape_string($con, $row['AvailableQty']) . ",
	'" . mysqli_real_escape_string($con, $row['Interchange']) . "',
	" . round(mysqli_real_escape_string($con, $row['Price'])*$priceRate, 2) . ",
	" . mysqli_real_escape_string($con, $row['Core']) . ")";

	if($row['OrderQty'] != 0){
		if(!mysqli_query($con, $query)){
			mysqli_query("INSERT INTO ERROR_LOG `Content` VALUES ('Query: " . $query . "\n Data: \n" . print_r($row, true) . "')");
		}
	}


	//$query = "UPDATE INVENTORY SET Qty = Qty - " . mysqli_real_escape_string($con, $row['OrderQty']) . " WHERE `Group` = '" . mysqli_real_escape_string($con, $row['Group']) . "' AND `Line` = '" . mysqli_real_escape_string($con, $row['Line']) . "' AND `SKU` = '" . mysqli_real_escape_string($con, $row['SKU']) . "'";
	//mysqli_query($con, $query);
}
$serviceFee = floatval($_REQUEST['serviceFee']);
if($serviceFee){


}


$deliveryDescription = $deliveryMethod;

//mysqli_query($con, "INSERT INTO ORDER_DETAIL (`OrderID`, `Group`, `Line`, `SKU`, `Description`, `Notes`, `OrderQty`, `AvailableQty`, `Interchange`, `Price`, `Core`) VALUES ($orderID, '0', 'MIS', '$deliverySKU', '$deliveryDescription', '', 1, 0, '', $serviceFee, 0)");
//mysqli_query($con, $query);
//$result = mysqli_query($con, $select);
//while ($row = mysqli_fetch_array($result)) {
//	$query = "UPDATE INVENTORY SET Qty = Qty - " . $row['OrderQty'] . " WHERE `Group` = '" . $row['Group'] . "' AND `Line` = '" . $row['Line'] . "' AND `SKU` = '" . $row['SKU'] . "'";
//	mysqli_query($con, $query);
//	//error_log($query);
//}
if ($isCustomer) {
	$query = "DELETE FROM SHOPPING_CART WHERE AccountNumber = '$customer->AccountNumber'";
}else {
	$query = "DELETE FROM SHOPPING_CART WHERE AccountNumber = '$salesman->ID'";
}
mysqli_query($con, $query);
//Return to original pricing (default, no customer selected).
clearSetCustomer();
AddCartLogEntry("CHECKOUT FOR: " . $customer->AccountNumber, "", "", "", 0);
//setup order object
$order = new Order($orderID);
if($_SESSION['TruckMode']){
	$invoiceNumber = $order->generateInvoice();
	$invoice = new Invoice($invoiceNumber);
	
	$invoice->Picker = $salesman->FullName;
	$invoice->DeliveryDate = "NOW()";
	$invoice->DeliveryUser = $_SESSION['Username'];
	$invoice->Delivered = 1;
	//$invoice->save();
	$invoice->updateDueDateWithDeliveryDate();
	//$invoice->save();
	$invoice->Finalize();
	$query = "UPDATE MULTIPLE_WH_INVENTORY JOIN INVOICE_DETAIL USING(Line, SKU) SET MULTIPLE_WH_INVENTORY.Qty = MULTIPLE_WH_INVENTORY.Qty-INVOICE_DETAIL.ShippedQty WHERE WarehouseID = " . $_SESSION['WarehouseID'] . " AND InvoiceID = " . $invoiceNumber;
	error_log($query);
	$result = mysqli_query($con, $query);
	
	
}

 ?>

 <!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://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
           <!-- Include all compiled plugins (below), or include individual files as needed -->
           <script src="<?= $root ?>js/bootstrap.min.js"></script>
       	 <script src="<?= $root ?>js/bootstrap-combobox.js"></script>
           <script type="text/javascript">
             $(document).ready(function(){
														<?php
															if($_SESSION['TruckMode']){
														?>
														window.location = "https://<?= $root ?>/mod.php?p=invoice&a=view&id=<?= $invoiceNumber ?>&key=<?= $invoice->getTokenKey() ?>";
														
														<?php
															}
														?>
               //$('.combobox').combobox();
       //        $('.grpline').css("width", "100px");
             });
           </script>

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

       <?php
								
       		include("navbar.php");


       ?>


   <!-- Stack the columns on mobile by making one full-width and the other half-width -->
<div class="container-fluid" style="padding-top: 5px;">
	<div class="row">
	  <div class="col-xs-5">
	  	<img class="img-responsive" style="width: 250px;" src="<?= $root ?>img/<?= $config['Logo'] ?>" alt="" />
	  	<p>
	  		<b>Customer Name: </b><?= $order->Customer->Name; ?><br>
	  		<b>City: </b><?= $order->Customer->City; ?><br>
	  		<b>Customer #: </b><?= $order->Customer->AccountNumber ?><br />
	  		<b>PO Number: </b><?= $order->PONumber ?><br>
	  		<b>Delivery Method: </b><?= $order->DeliveryMethod ?><br>

	  </p>

	  </div>
 	  <div class="col-xs-2"></div>
	  <div class="col-xs-5">
		  <h3>Order Confirmation</h3>
		  <p>
		  	<b>Order Number: </b><span style="font-style: italic;"><?= $order->OrderID ?></span><br>

		  	<b>Order By: </b> <?= ($order->SalesmanOrder == "0")?"Customer":"Salesman" ?><br>
		  <b>Date: </b><?= date("m/d/Y",strtotime($order->OrderDate)) ?><br>
		  <b>Time: </b><?= date("g:i a",strtotime($order->OrderDate)) ?><br>
		  <b>Salesman: </b> <?= $order->Customer->Salesman->ID . " - " . $order->Customer->Salesman->Name ?><br>
		  </p>
	  </div>
	  <table class="table table-condensed">
	    <thead>
	      <tr>
	        <th style="width: 5%">Line<br>Group</th>
	        <th style="width: 70%">Item</th>
	        <th style="width: 5%">Order Quantity</th>
	        <th style="width: 5%">Price</th>
	        <th style="width: 5%">Extension</th>
	      </tr>
	    </thead>
	  	<tbody>
	  	<?php
	  		$query = "SELECT * FROM ORDER_DETAIL WHERE OrderID = '$orderID'";
	  		$result = mysqli_query($con, $query);
	  		$index = 0;
	  		while ($row = mysqli_fetch_array($result)) {
	  	?>
	  		<tr>
	    			<td>
	        			<span class="itemInfo"><?= $row['Line'] ?></span>
	        			<span class="itemInfo"><?= $row['Group'] ?></span>
	        		</td>
	        		<td>
	        			<span class="itemInfo"><b><?= $row['SKU'] ?></b></span><br />
	        			<span class="itemInfo"><?= $row['Description'] ?></span>
	        			<span class="itemInfo"><?= $row['Notes'] ?></span>
	        		</td>
	        		<td class="centered">
	        			<?= $row['OrderQty'] ?>
	        		</td>
	        		<td>
	        			<?= moneyFormat($row['Price']); ?>
	        			<?php
	        				if(floatval($row['Core'])>0){
	        					echo "<br><i><b>Core:</b> ". moneyFormat($row['Core']) . "</i>";
	        				}
	        			?>
	        		</td>
	        		<td style="text-align: right;">
	        			<?= moneyFormat($row['OrderQty'] * $row['Price']) ?>
	        			<?php
	        				if(floatval($row['Core'])>0){
	        					echo "<br><i><b>Core:</b> ". moneyFormat($row['OrderQty'] * $row['Core']) . "</i>";
	        				}
	        			?>
	        		</td>
	      	</tr>
	      	<?php
	      	$index++;
	      	}?>
	      	<tr>
	      		<td></td>
	      		<td></td>
	      		<td></td>
	      		<td><span style="font-weight: bold;">Total</span></td>
	      		<td><span style="font-weight: bold;"><?= moneyFormat($order->OrderTotal) ?></span></td>
	      	</tr>
	      </tr>
	    </tbody>
	  </table>

	</div>


</div>
       <div class="panel panel-default">
         <div class="panel-body">
           <span><b>Order Notes</b></span><br />
           <?= $order->OrderNotes ?>
         </div>
       </div>

   </body>
 </html>
 <?php
 sendOrder($orderID);
  ?>
