<?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 FORM DATA ON CACHE...
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'] = "";
if($_SESSION['TruckMode']){
	$WarehouseID = $_SESSION['WarehouseID'];
}else{
	$WarehouseID = "100";
}
$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 {
	
	$priceRate = getPricePlanCalculatedRate($customer->AccountNumber);
	$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']), 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){
	
	if($_SESSION['TruckMode']){
		$orderID = $estimate->generateOrder();
		$order = new Order($orderID);
		$invoiceNumber = $order->generateInvoice();
		$invoice = new Invoice($invoiceNumber);
		$invoice->WarehouseID = $WarehouseID;
		$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);
		
		
	}
}


sendEstimate($estimateID);


$_REQUEST['id'] = $estimateID;
$estimate = new Estimate($estimateID);
$_REQUEST['key'] = $estimate->getLinkKey();
include_once("viewEstimate.php");
 ?>
