<?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']);
}

deleteDataFromServer('newEstimateData');

//clean up post entries
$approveOrder = 0;
$approveOrder = isset($_POST['approveOrder'])&&$_POST['approveOrder']?$_POST['approveOrder']:0;
$estimateNotes = 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'] = "";
$ProductImage = isset($_POST['estimateProductImage'])?"1":"0";
$ImageURL = "";
$query = "SELECT * FROM PROGRAM_PICTURE WHERE ID = " . $_POST['estimateImage'];
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
$ImageURL = $row['PictureURL'];
//creating new entry in orders db
if ($isCustomer) {
	$query = "INSERT INTO ESTIMATE_HEAD (AccountNumber, EstimateDate, Salesman, EstimateNotes, PONumber, DeliveryMethod, IncludeProductImage, ApproveOrder) VALUES ('$customer->AccountNumber', DATE_ADD(NOW(), INTERVAL -4 HOUR), '" . $salesman->ID . "', '$estimateNotes', '$PONumber', '$deliveryMethod', $ProductImage, $approveOrder)";
}else {
	$query = "INSERT INTO ESTIMATE_HEAD (AccountNumber, EstimateDate, Salesman, SalesmanEstimate, EstimateNotes, PONumber, DeliveryMethod, ImageURL, IncludeProductImage, ApproveOrder) VALUES ('$customer->AccountNumber', DATE_ADD(NOW(), INTERVAL -4 HOUR), '" . $salesman->ID . "', True, '$estimateNotes', '$PONumber', '$deliveryMethod', '$ImageURL', $ProductImage, $approveOrder)";

}
mysqli_query($con, $query);
if(mysqli_error($con)){
	error_log(mysqli_error($con) . $query);
}
$estimateID = mysqli_insert_id($con);
if($customer->AccountNumber == "00000-00" || $customer->AccountNumber == "00000-01"){
	$query = "INSERT INTO ESTIMATE_CUSTOMER (EstimateID, `Name`, `Email`,`ContactTitle`, `Contact`, `Phone`, `BillToAddress1`, `BillToAddress2`, `BillToCity`, `BillToState`,  `BillToZip`,
		`ShipToAddress1`,`ShipToAddress2`,`ShipToCity`,`ShipToState`,`ShipToZip`, `TaxID2`, `TaxIDExpiration2`, `TaxID1`, `TaxIDExpiration1`) VALUES (
		$estimateID,
		'" . strtoupper(mysqli_real_escape_string($con, $_POST['EstimateCompanyName'])) . "',
		'" . mysqli_real_escape_string($con, $_POST['EstimateEmail']) . "',
		'" . ucwords(mysqli_real_escape_string($con, $_POST['EstimateContactTitle'])) . "',
		'" . ucwords(mysqli_real_escape_string($con, $_POST['EstimateContactName'])) . "',
		'" . mysqli_real_escape_string($con, $_POST['EstimatePhone']) . "',
		'" . strtoupper(mysqli_real_escape_string($con, $_POST['EstimateBillToAddress1'])) . "',
		'" . strtoupper(mysqli_real_escape_string($con, $_POST['EstimateBillToAddress2'])) . "',
		'" . strtoupper(mysqli_real_escape_string($con, $_POST['EstimateBillToCity'])) . "',
		'" . strtoupper(mysqli_real_escape_string($con, $_POST['EstimateBillToState'])) . "',
		'" . mysqli_real_escape_string($con, $_POST['EstimateBillToZip']) . "',
		'" . strtoupper(mysqli_real_escape_string($con, $_POST['EstimateShipToAddress1'])) . "',
		'" . strtoupper(mysqli_real_escape_string($con, $_POST['EstimateShipToAddress2'])) . "',
		'" . strtoupper(mysqli_real_escape_string($con, $_POST['EstimateShipToCity'])) . "',
		'" . strtoupper(mysqli_real_escape_string($con, $_POST['EstimateShipToState'])) . "',
		'" . strtoupper(mysqli_real_escape_string($con, $_POST['EstimateShipToZip'])) . "',
		'" . mysqli_real_escape_string($con, $_POST['EstimateTaxID2']) . "',
		'" . mysqli_real_escape_string($con, $_POST['EstimateTaxIDExpiration2']) . "',
		'" . mysqli_real_escape_string($con, $_POST['EstimateTaxID']) . "',
		'" . mysqli_real_escape_string($con, $_POST['EstimateTaxIDExpiration']) . "')
		";
		$result = mysqli_query($con,$query);
		//var_dump($query);
		if(!$result){
			error_log($query);
		}
}

//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 $estimateID as EstimateID, `SHOPPING_CART`.`Group`, `SHOPPING_CART`.`Line`, `SHOPPING_CART`.`SKU`, `INVENTORY`.`Description`, `INVENTORY`.`Notes`, `SHOPPING_CART`.`Qty` As EstimateQty, `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;
	//error_log("isCustomer == true");
	//error_log($query);
}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 $estimateID as EstimateID, `SHOPPING_CART`.`Group`, `SHOPPING_CART`.`Line`, `SHOPPING_CART`.`SKU`, `INVENTORY`.`Description`, `INVENTORY`.`Notes`, `SHOPPING_CART`.`Qty` As EstimateQty, `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";
	//error_log("isCustomer == false");
	//error_log($query);
	//$query .= $select;
}
//echo $query;
$result = mysqli_query($con, $query);
if(!$result){
	error_log(mysqli_error($con));
}
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
	$row['Price'] = getCustomerPrice($row['Group'], $row['Line'], $row['SKU']) * $priceRate;
	$row = updateQtyBreaks($row);
	$query = "INSERT INTO ESTIMATE_DETAIL (`EstimateID`, `Group`, `Line`, `SKU`, `Description`, `Notes`, `EstimateQty`, `AvailableQty`, `Interchange`, `Price`, `Core`)
	VALUES (
	'" . mysqli_real_escape_string($con, $row['EstimateID']) . "',
	'" . 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['EstimateQty']) . ",
	" . 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']) . ")";
	//echo $query;
	if(!mysqli_query($con, $query)){

		error_log(mysqli_error($con));
		mysqli_query("INSERT INTO ERROR_LOG `Content` VALUES ('Query: " . $query . "\n Data: \n" . print_r($row, true) . "')");
	}

}
$serviceFee = floatval($_REQUEST['serviceFee']);
if($serviceFee){

	//mysqli_query($con, "INSERT INTO ESTIMATE_DETAIL (`OrderID`, `Group`, `Line`, `SKU`, `Description`, `Notes`, `OrderQty`, `AvailableQty`, `Interchange`, `Price`, `Core`) VALUES ($orderID, '0', 'MIS', 'FEE', 'SERVICE FEE', '', 1, 0, '', $serviceFee, 0)");
}


//$deliveryDescription = $deliveryMethod;

//mysqli_query($con, "INSERT INTO ESTIMATE_DETAIL (`EstimateID`, `Group`, `Line`, `SKU`, `Description`, `Notes`, `EstimateQty`, `AvailableQty`, `Interchange`, `Price`, `Core`) VALUES ($estimateID, '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['EstimateQty'] . " 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("ESTIMATE FOR: " . $customer->AccountNumber, "", "", "", 0);
//setup order object
$estimate = new Estimate($estimateID);
if($approveOrder){
	//$estimate->generateOrder();
}
 ?>

 <!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(){
              // $('.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: 200px;" src="<?= $root ?>img/<?= $config['Logo'] ?>" alt="" />
	  	<p>
	  		<b>Customer Name: </b><?= $estimate->Customer->Name; ?><br>
			<b>Address: </b><?= $estimate->Customer->Address1; ?><br>
			<b></b><?= $estimate->Customer->Address2; ?><br>
	  		<b>City: </b><?= $estimate->Customer->City . ", " .  $estimate->Customer->State ; ?><br>
	  		<b>Customer #: </b><?= $estimate->Customer->AccountNumber ?><br />


	  </p>

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

		  	<b>Estimate By: </b> <?= $estimate->Salesman->Name ?><br>
		  <b>Date: </b><?= date("m/d/Y",strtotime($estimate->EstimateDate)) ?><br>
		  <b>Time: </b><?= date("g:i a",strtotime($estimate->EstimateDate)) ?><br>

		  </p>
	  </div>
	</div>
	<div class="row">
		<br>

			<span style="font-size: large;">Saludos <?= $estimate->Customer->ContactTitle ?> <?= $estimate->Customer->Contact ?>,<br>
			<br>
			Gracias por la oportunidad que nos brinda de poder cotizarle nuestros productos Westinghouse. A continuación encontrará el listado de los productos que ofrecemos.
			Si le surge alguna duda, puede comunicarse de inmediato al correo electr&oacute;nico: info@westingpr.com.
			<br>Quedamos a sus &oacute;rdenes.
			<br>
			<br>

			Westing PR, Inc<br>
			http://www.westingpr.com</span>
<br>
<br>
<br>
	  <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%">Estimate Quantity</th>
	        <th style="width: 5%">Price</th>
	        <th style="width: 5%">Extension</th>
	      </tr>
	    </thead>
	  	<tbody>
	  	<?php
	  		$query = "SELECT * FROM ESTIMATE_DETAIL WHERE EstimateID = '$estimateID'";
	  		$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['EstimateQty'] ?>
	        		</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['EstimateQty'] * $row['Price']) ?>
	        			<?php
	        				if(floatval($row['Core'])>0){
	        					echo "<br><i><b>Core:</b> ". moneyFormat($row['EstimateQty'] * $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($estimate->EstimateTotal) ?></span></td>
	      	</tr>
	      </tr>
	    </tbody>
	  </table>

	</div>


</div>
       <div class="panel panel-default">
         <div class="panel-body">
           <span><b>Estimate Notes</b></span><br />
           <?= $estimate->EstimateNotes ?>
		   <span>*Este estimado no incluye impuestos (IVU).</span>
         </div>
       </div>
     <?php
	 if($estimate->ImageURL){
	?>
		<center>
		<img src="<?= $estimate->ImageURL  ?>" style="width: 60%;"/>
		</center>
	<?php

	 }
	 ?>
   </body>
 </html>
 <?php
 sendEstimate($estimateID);
  ?>
