<?php

class Order {
	public $OrderID, $PONumber, $Customer, $OrderDate, $Items, $OrderNotes, $DeliveryMethod, $OrderTotal, $SalesmanOrder, $AccountNumber, $InProcess, $InProcessDate, $Done, $DoneDate, $ProcessUser, $Delete, $OnHold, $OnHoldDate, $DeleteDate, $OnHoldDeleteReason, $OnHoldDeleteUser, $SpecialOrder, $KYBOrder, $NIPOrder, $DHIOrder;
	public function __construct($OrderID) {
		$query = "SELECT * FROM ORDER_HEAD WHERE OrderID = $OrderID";
		global $con;
		$result = mysqli_query($con, $query);
		$row = mysqli_fetch_array($result);
		$this->OrderID = $row['OrderID'];
		$this->OfflineID = $row['OfflineID'];
		$this->PONumber = $row['PONumber'];
		$this->AccountNumber = $row['AccountNumber'];
		$this->Customer = new Customer($row['AccountNumber']);
		$this->OrderDate = $row['OrderDate'];
		$this->OrderNotes = $row['OrderNotes'];
		$this->DeliveryMethod = $row['DeliveryMethod'];
		$this->SalesmanOrder = $row['SalesmanOrder'];
		$this->Salesman = new Salesman($row['Salesman']);
		$this->InProcess = $row['InProcess'];
		$this->InProcessDate = $row['InProcessDate'];
		$this->Processed = $row['Processed'];
		$this->ProcessedDate = $row['ProcessedDate'];
		$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->Items = array();
		$query = "SELECT *, IF(Line = 'MIS', 2, 1) PartOrder FROM ORDER_DETAIL WHERE OrderID = '$OrderID' ORDER BY Line, `Group`, SKU";
		$result = mysqli_query($con, $query);
		$total = 0;
		while($row = mysqli_fetch_array($result)){
			$item = new OrderItem($row['Group'], $row['Line'], $row['SKU']);
			$item->AvailableQty = $row['AvailableQty'];
			$item->OrderQty = $row['OrderQty'];
			$item->ID = $row['ID'];
			$item->Price = $row['Price'];
			$total += $row['OrderQty'] * $row['Price'];
			$total += $row['OrderQty'] * $row['Core'];

			array_push($this->Items, $item);
			unset($item);
		}
		$this->OrderTotal = $total;
	}
	public function getCSV($Divided = false){
		if($Divided){

		}else{
			$path = "csv/" . $this->OrderID . "-" . $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 voidOrder(){
		global $con;
		$query = "UPDATE ORDER_HEAD SET DeleteOrder = 1 WHERE OrderID = " . $this->OrderID;
		return mysqli_query($con, $query);

	}
	public function generateInvoice(){
		if($this->Processed){
			die("Error. Order Already processed.");
			return false;


		}else{
			global $con;
			$terms = $this->Customer->Terms;
			$termDays = $terms;
			if(!$terms){
				$terms = 0;
				$termDays = 0;
			}else if(strtoupper($terms) == "2/15 NET 16"){
				$termDays = 15;
			}
			$query = "INSERT INTO INVOICE_HEAD (OrderID, AccountNumber, CreationDate, Salesman, SalesmanOrder,WarehouseID, Notes, PONumber,
			DeliveryMethod, InvoiceUser, SentPicking, Tax1Rate, Tax2Rate, Terms, DueDate,
			ShipToName, ShipToAddress1, ShipToAddress2, ShipToCity,  ShipToState, ShipToZip,  BillToName,
			BillToAddress1, BillToAddress2, BillToCity, BillToState, BillToZip) VALUES (
			{$this->OrderID},
			'{$this->AccountNumber}',
			DATE_ADD(NOW(), INTERVAL -4 HOUR),
			'{$this->Salesman->ID}', {$this->SalesmanOrder} , '{$this->WarehouseID}' ,'{$this->OrderNotes}',
			'{$this->PONumber}', '{$this->DeliveryMethod}',
			'{$_SESSION['Username']}', DATE_ADD(NOW(), INTERVAL -4 HOUR),
			" . getSetting("Tax1Percent")['value'] . " ,
			" . getSetting("Tax2Percent")['value'] . ",
			'$terms',
			DATE_ADD(NOW(), INTERVAL $termDays DAY),
			'{$this->Customer->Name}',
			'{$this->Customer->ShipToAddress1}',
			'{$this->Customer->ShipToAddress2}',
			'{$this->Customer->ShipToCity}',
			'{$this->Customer->ShipToState}','{$this->Customer->ShipToZip}',
			'{$this->Customer->Name}','{$this->Customer->Address1}',
			'{$this->Customer->Address2}','{$this->Customer->City}',
			'{$this->Customer->State}','{$this->Customer->ZipCode}')";
			$result = mysqli_query($con, $query);
			if(!$result){
				die('Error generating invoice header.<br>' . mysqli_error($con) . "<br>Query: " . $query);
			}
			$invNum = mysqli_insert_id($con);
			foreach($this->Items as $key => $item){
				error_log(print_r($item,true));
				$query = "INSERT INTO INVOICE_DETAIL (InvoiceID, Line, `Group`, SKU, Description, Notes, OrderQty, ShippedQty, AvgCost, Core, Price, Taxable1, Taxable2) VALUES
				($invNum, '{$item->Line}','{$item->Group}','{$item->SKU}','{$item->Description}','{$item->Notes}',{$item->OrderQty},{$item->OrderQty},{$item->AvgCost}, {$item->Core}, {$item->Price}, {$item->Taxable1}, {$item->Taxable2})";
				$result = mysqli_query($con, $query);

				if(!$result){
					error_log("Error inserting order line. Query:" . $query );
				}
			}

			$query = "UPDATE ORDER_HEAD SET Processed = 1, ProcessedDate = DATE_ADD(NOW(), INTERVAL -4 HOUR), ProcessUser = '{$_SESSION['Username']}' WHERE OrderID = " . $this->OrderID;
			mysqli_query($con, $query);
			return $invNum;
		}
	}
}

class OrderItem extends Item {
	public $OrderQty;
	public $ID;
}
function fputcsv_eol($fp, $array, $eol) {
  fputcsv($fp, $array);
  if("\n" != $eol && 0 === fseek($fp, -1, SEEK_CUR)) {
    fwrite($fp, $eol);
  }
}

?>
