<?php

class Estimate {
	public $EstimateID, $PONumber, $Customer, $EstimateDate, $Items, $EstimateNotes, $DeliveryMethod, $EstimateTotal, $SalesmanEstimate, $AccountNumber, $InProcess, $InProcessDate, $Done, $DoneDate, $ProcessUser, $Delete, $OnHold, $OnHoldDate, $DeleteDate, $OnHoldDeleteReason, $OnHoldDeleteUser, $SpecialOrder;
	public function __construct($EstimateID) {
		$query = "SELECT * FROM ESTIMATE_HEAD WHERE EstimateID = $EstimateID";
		global $con;
		$result = mysqli_query($con, $query);
		$row = mysqli_fetch_array($result);
		
		foreach($row as $key => $value){
				$this->$key = $value;
				//array_push($this->ItemsOriginalColumns, $key);
		}
		
		$this->EstimateID = $row['EstimateID'];
		$this->OfflineID = $row['OfflineID'];
		$this->PONumber = $row['PONumber'];
		$this->AccountNumber = $row['AccountNumber'];
		
		$this->Customer = new Customer($row['AccountNumber']);
		if($this->AccountNumber == "00000-00" || $this->AccountNumber == "00000-01"){
			$query = "SELECT * FROM ESTIMATE_CUSTOMER WHERE EstimateID = " . $this->EstimateID;
			$result2 = mysqli_query($con, $query);
			$customerRow = mysqli_fetch_array($result2, MYSQLI_ASSOC);
			$this->Customer->Name = $customerRow['Name'];
			$this->Customer->Contact = $customerRow['Contact'];
			$this->Customer->ContactTitle = $customerRow['ContactTitle'];
			$this->Customer->Email = $customerRow['Email'];
			$this->Customer->Phone = $customerRow['Phone'];
			$this->Customer->Address1 = $customerRow['BillToAddress1'];
			$this->Customer->Address2 = $customerRow['BillToAddress2'];
			$this->Customer->City = $customerRow['BillToCity'];
			$this->Customer->State = $customerRow['BillToState'];
			$this->Customer->ZipCode = $customerRow['BillToZip'];
			
			$this->Customer->TaxID1 = $customerRow['TaxID1'];
			$this->Customer->TaxIDExpiration1 = $customerRow['TaxIDExpiration1'];
			
			$this->Customer->TaxID2 = $customerRow['TaxID2'];
			$this->Customer->TaxIDExpiration2 = $customerRow['TaxIDExpiration2'];
			
			$this->Customer->ShipToAddress1 = $customerRow['ShipToAddress1'];
			$this->Customer->ShipToAddress2 = $customerRow['ShipToAddress2'];
			$this->Customer->ShipToCity = $customerRow['ShipToCity'];
			$this->Customer->ShipToState = $customerRow['ShipToState'];
			$this->Customer->ShipToZip = $customerRow['ShipToZip'];
		}
		$this->EstimateDate = $row['EstimateDate'];
		$this->EstimateNotes = $row['EstimateNotes'];
		$this->DeliveryMethod = $row['DeliveryMethod'];
		$this->SalesmanEstimate = $row['SalesmanEstimate'];
		$this->Salesman = new Salesman($row['Salesman']);
		$this->InProcess = $row['InProcess'];
		$this->InProcessDate = $row['InProcessDate'];
		$this->Processed = $row['Processed'];
		$this->ProcessedDate = $row['ProcessedDate'];
		$this->ImageURL = $row['ImageURL'];
		$this->ProcessUser = $row['ProcessUser'];
		$this->Delete = $row['DeleteOrder'];
		$this->OnHold = $row['OnHold'];
		$this->OnHoldDate = $row['OnHoldDate'];
		$this->DeleteDate = $row['DeleteOrderDate'];
		$this->OnHoldDeleteReason = $row['HoldDeleteReason'];
		$this->OnHoldDeleteUser = $row['OnHoldDeleteUser'];
		$this->SpecialOrder = false;
		$this->IncludeProductImage = $row['IncludeProductImage'];
		
		$this->Items = array();
		$query = "SELECT *, IF(Line = 'MIS', 2, 1) PartOrder FROM ESTIMATE_DETAIL WHERE EstimateID = '$EstimateID' ORDER BY PartOrder, Line, `Group`, SKU";
		$result = mysqli_query($con, $query);
		$total = 0;
		while($row = mysqli_fetch_array($result)){
			$item = new EstimateItem($row['Group'], $row['Line'], $row['SKU']);
			$item->AvailableQty = $row['AvailableQty'];
			$item->EstimateQty = $row['EstimateQty'];
			$item->ID = $row['ID'];
			$total += $row['EstimateQty'] * $row['Price'];
			$total += $row['EstimateQty'] * $row['Core'];
			array_push($this->Items, $item);
			unset($item);
		}
		$this->EstimateTotal = $total;
	}
	public function getCSV($Divided = false){
		
		$path = "csv/" . $this->EstimateID . "-" . $this->AccountNumber . '-' . $this->Salesman->ID . '.csv';
		$fp = fopen($path, 'w');
		foreach ($this->Items as $fields) {
			$data = array(3,$fields->Line, $fields->SKU, $fields->OrderQty);
			fputcsv_eol($fp, $data, "\r\n");
		}
		fclose($fp);
		return $path;
		
	}
	public function sendToShoppingCart(){
		global $con;
		
		if($this->AccountNumber == "00000-00" || $this->AccountNumber == "00000-01"){
				$this->AccountNumber = $this->createCustomerAccount();
				$query = "UPDATE ESTIMATE_HEAD SET AccountNumber = '" . $this->AccountNumber . "' WHERE EstimateID = " . $this->EstimateID;
				mysqli_query($con,$query);
		}
		$query = "INSERT INTO SHOPPING_CART (AccountNumber,`Group`, `Line`, `SKU`, `Qty`, `SalesmanCart`) (SELECT '" . $this->Salesman->ID . "' AccountNumber, `Group`, `Line`, `SKU`, `EstimateQty` Qty, 1 SalesmanCart FROM ESTIMATE_DETAIL WHERE EstimateID = '" . $this->EstimateID . "')";
		echo $query;
		if(mysqli_query($con, $query)){
			$query = "UPDATE ESTIMATE_HEAD SET Processed = 1, ProcessedDate = DATE_ADD(NOW(), INTERVAL -4 HOUR), ProcessUser = '{$_SESSION['Username']}' WHERE EstimateID = " . $this->EstimateID;
			
			return mysqli_query($con, $query);
			
		}else{
			return false;
		}
	}
	public function setAsUnprocessed(){
		global $con;
		$query = "UPDATE ESTIMATE_HEAD SET `Processed` = 0 WHERE EstimateID = " . $this->EstimateID . ";";
		if($result = mysqli_query($con, $query)){
			event_log($_SESSION['Username'], "SET ESTIMATE AS UNPROCESSED", "EstimateID = " . $this->EstimateID );
			return $result;
		}
		
	}
	public function setAsProcessed(){
		global $con;
		$query = "UPDATE ESTIMATE_HEAD SET `Processed` = 1 WHERE EstimateID = " . $this->EstimateID . ";";
		if($result = mysqli_query($con, $query)){
			event_log($_SESSION['Username'], "SET ESTIMATE AS PROCESSED", "EstimateID = " . $this->EstimateID );
			return $result;
		}
		
	}
	public function deleteEstimate(){
		global $con;
		$query = "UPDATE ESTIMATE_HEAD SET `DeleteEstimate` = 1 WHERE EstimateID = " . $this->EstimateID . ";";
		if($result = mysqli_query($con, $query)){
			event_log($_SESSION['Username'], "SET ESTIMATE AS DELETED", "EstimateID = " . $this->EstimateID );
			return $result;
		}
		
	}
	public function archiveEstimate(){
		global $con;
		$query = "UPDATE ESTIMATE_HEAD SET `Archive` = 1 WHERE EstimateID = " . $this->EstimateID . ";";
		if($result = mysqli_query($con, $query)){
			event_log($_SESSION['Username'], "SET ESTIMATE AS ARCHIVED","EstimateID = " . $this->EstimateID );
			return $result;
		}
	}
	public function createCustomerAccount(){
		global $con;
		
		if($this->AccountNumber != "00000-00" && $this->AccountNumber != "00000-01"){
			die('Error, this estimate has already a defined customer');
		}else{
			$query = "SELECT MAX(SUBSTRING(AccountNumber, 1,5))+1 NewAccountNumber FROM `CUSTOMER` WHERE AccountNumber < 90000";
			$result = mysqli_query($con, $query);
			
			$row = mysqli_fetch_array($result);
			$newCustomerNumber = $row[0];
			if($this->AccountNumber == "00000-00"){
				$priceLevel = "B";
			}elseif($this->AccountNumber == "00000-01"){
				$priceLevel = "A";
			}else{
				$priceLevel = "C";
			}
			$query = "INSERT INTO CUSTOMER (`Name`, `AccountNumber`, `Email`, `Contact`, `ContactTitle`,`Phone`, `Address1`, `Address2`,
					`City`, `State`, ZipCode, ShipToAddress1, ShipToAddress2, ShipToCity, ShipToState, ShipToZip,
					Salesman, `Terms`, `TaxID2`, `TaxIDExpiration2`, `TaxID1`, `TaxIDExpiration1`, PriceLevel) VALUES
			(
				'" . $this->Customer->Name . "',
				'" . $newCustomerNumber . "',
				'" . $this->Customer->Email . "',
				'" . $this->Customer->Contact . "',
				'" . $this->Customer->ContactTitle . "',
				'" . $this->Customer->Phone . "',
				'" . $this->Customer->Address1 . "',
				'" . $this->Customer->Address2 . "',
				'" . $this->Customer->City . "',
				'" . $this->Customer->State . "',
				'" . $this->Customer->ZipCode . "',
				'" . $this->Customer->ShipToAddress1 . "',
				'" . $this->Customer->ShipToAddress2 . "',
				'" . $this->Customer->ShipToCity . "',
				'" . $this->Customer->ShipToState . "',
				'" . $this->Customer->ShipToZip . "',
				'" . $this->Salesman->ID . "',
				0,
				'" . $this->Customer->TaxID2 . "',
				'" . $this->Customer->TaxIDExpiration2 . "',
				'" . $this->Customer->TaxID1 . "',
				'" . $this->Customer->TaxIDExpiration1 . "',
				'" . $priceLevel . "'
				
			)";
			
			if(mysqli_query($con, $query)){
				return $newCustomerNumber;
			}else{
				echo mysqli_error($con);
			}
			
			
		}
	}
	public function generateOrder(){
		if($this->Processed){
			//die("Error. Estimate Already processed.");
			return false;
			
			
		}else{
			global $con;
			
			
			$terms = 0;
			if($this->AccountNumber == "00000-00" || $this->AccountNumber == "00000-01"){
				$this->AccountNumber = $this->createCustomerAccount();
				$query = "UPDATE ESTIMATE_HEAD SET AccountNumber = '" . $this->AccountNumber . "' WHERE EstimateID = " . $this->EstimateID;
				mysqli_query($con,$query);
			}
			
			$query = "INSERT INTO ORDER_HEAD (AccountNumber, OrderDate, Salesman, SalesmanOrder, OrderNotes, DeliveryMethod, PONumber) VALUES (
			'{$this->AccountNumber}', DATE_ADD(NOW(), INTERVAL -4 HOUR), '{$this->Salesman->ID}', 1,'{$this->EstimateNotes}', '{$this->DeliveryMethod}', '{$this->PONumber}')";
			$result = mysqli_query($con, $query);
			if(!$result){
				die('Error generating order header.<br>' . mysqli_error($con) . "<br>Query: " . $query);
			}
			$orderID = mysqli_insert_id($con);
			foreach($this->Items as $key => $item){
				$query = "INSERT INTO ORDER_DETAIL (OrderID, Line, `Group`, SKU, Description, Notes, OrderQty, AvailableQty, Core, Price) VALUES
				($orderID, '{$item->Line}','{$item->Group}','{$item->SKU}','{$item->Description}','{$item->Notes}',{$item->EstimateQty},{$item->AvailableQty}, {$item->Core}, {$item->Price})";
				$result = mysqli_query($con, $query);
				
				if(!$result){
					error_log("Error inserting order line. Query:" . $query );
				}
			}
			
			$query = "UPDATE ESTIMATE_HEAD SET Processed = 1, ProcessedDate = DATE_ADD(NOW(), INTERVAL -4 HOUR), ProcessUser = '{$_SESSION['Username']}' WHERE EstimateID = " . $this->EstimateID;
			mysqli_query($con, $query);
			return $orderID;
		}
	}
	public function getLinkKey(){
		$key = md5($this->EstimateID . "WestingPR");
		$key = substr($key, -16);
		return $key;
	}
	public function getViewLink($include_root = true){
		
		if($include_root){
			$return = "$root";
		}else{
			$return = "";
		}
		return $return . "/viewEstimate.php?id=" . $this->EstimateID . "&key=" . $this->getLinkKey();
	}
}

class EstimateItem extends Item {
	public $EstimateQty;
	public $ID;
}


?>