<?php 

/*
 * Klasa reprezentująca produkt
 */
class Product {
	// Name
	var $name;
	// Total sum
	var $total;
	// Subtotal sum
	var $subtotal;
	// Quantity
	var $quantity;
	// Category
	var $category;
	// Subcategory
	var $subcategory;
	// Item is from correct
	var $fromCorrect;
	// Currency_value
	var $currency_value = 0;

	public function __construct($name, $total, $subtotal, $subprice, $quantity, $currency_value, $old_quantity, $subtotal_corrected, $old_total, $type)
	{
		//echo "W konstruktorze Product: ".$name." ".$total." ".$subtotal." ".$subprice." ".$quantity."<br>";

		$cv = $currency_value == 0 ? 1 : $currency_value;
		$oldSubtotal = ($old_subtotal == 0 || $old_subtotal == null) ? 0 : $old_subtotal;
		$oldTotal = ($old_total == 0 || $old_total == null) ? 0 : $old_total;
		$oldQuantity = ($old_quantity == 0 || $old_quantity == null) ? 0 : $old_quantity;
		$this->name = $name;
		if( $type == 'correct' )
		{
			$this->total = ($total-$oldTotal)*$cv;
			$this->subtotal = ($subtotal_corrected)*$cv;
			$this->quantity = $quantity-$oldQuantity;
			$this->subprice = $subprice*$cv;
			$this->currency_value = $currency_value;

			$this->fromCorrect = true;
		} else {
			$this->total = $total*$cv;
			$this->subtotal = $subtotal*$cv;
			$this->subprice = $subprice*$cv;
			$this->quantity = $quantity;
			$this->currency_value = $cv;

			$this->fromCorrect = false;
		}
	}

}

/*
 * Klasa reprezentująca podkategorię produktową
*/
class Subcategory {
	// Subcategory id
	var $id;
	// Name
	var $name;
	// Total sum
	var $total;
	// Subtotal sum
	var $subtotal;
	// Cost sum in category
	var $cost;
	// Count all products in category
	var $quantity;
	// Products in category
	var $products = array();
	// IsEmpty
	var $isEmpty = true;

	public function __construct($id, $name, $total = 0.00, $subtotal = 0.00, $cost = 0.00, array $products = NULL)
	{
		$this->id = $id;
		$this->name = $name;
		$this->total = $total;
		$this->subtotal = $subtotal;
		$this->cost = $cost;
		$this->products = $products;

		if( $products != null )
			if( count($products) > 0 )
				$this->isEmpty = false;
	}

	public function id()
	{
		return $this->id;
	}

	public function cost()
	{
		return $this->cost;
	}

	public function products()
	{
		return $this->products;
	}

	public function setProducts( array $products )
	{
		$this->products = $products;
		if( count($this->products) > 0 )
			$this->isEmpty = false;
			foreach( $this->products as $product )
			{
					$this->total += $product->total;
					$this->subtotal += $product->subtotal;
					$this->quantity += $product->quantity;	
			}
	}

	public function showProducts()
	{
		if( !$this->isEmpty )
		{
			echo "<br><br>";
			foreach( $this->products as $product) {
				echo $product->name.", ".$product->subtotal."<br>";
			}
		} else {
			echo "<br><br>";
			echo "Brak produktów w kategorii ".$this->name;
		}	
	}

	public function toString()
	{

		echo "<br>";
		echo $this->id." <br>";
		echo $this->name.": <br>";
		echo "Cena netto: ".$this->subtotal."<br>";
		echo "Cena brutto: ".$this->total."<br>";
		echo "Cena ilość produktów: ".$this->quantity."<br>";
	}

}

/*
 * Klasa reprezentująca kategorię produktową
 */
class Category extends Subcategory {
	public function __construct($id, $name = '', $total = 0, $subtotal = 0, $cost = 0, $products = null)
	{ 	
		parent::__construct($id, $name, $total, $subtotal, $cost, $products);
	}

}

/*
 * Klasa pomocnicza przy generowaniu wykresów dla MyChartsSalesDashlet
 */
class ChartSalesHelper {
	
	// Global database connection instance
	var $db_connection;
	// Chart options
	var $options;
	// Product category array
	var $categories = array();
	// Product subcategory array
	var $subcategories = array();
	// Enable log function
	var $logEnabled = false;
		
	// Constructor
	public function __construct($db_connection, $options, $comparativeData = null)
	{
		//$this->log("Parametry dashletu: ", $options );
		$this->db_connection = $db_connection;
		$this->options = $options;
		$this->compData = null;

		$this->getCategories();

		if( $this->options["detail"] == 'category')
		{
			if( $comparativeData != null )
			{
				$this->compData = $comparativeData;
			}
		} else {	
			if( $comparativeData != null )
			{
				$this->compData = $comparativeData;
			} 
		}
	}
	
	public function haveComparativeData()
	{
		if( $this->compData != null )
			return true;
		else
			return false;
	}
	
	public function getAllCategories()
	{
		return $this->categories;
	}
	
	public function getAllSubcategories()
	{
		return $this->subcategories;
	}

	//----------------------------------------
	// Private methods
	//----------------------------------------

	/**
	* Metoda pobiera wszystkie kategorie z bazy
	*/
	private function getCategories($getSubcategories = false)
	{
		// Pobieram kategorie, albo podkategorie
		// w zależności od podanej wartości parametru
		if( $this->options["detail"] == 'subcategory' )
			$depression = 1;
		else
			$depression = 0;

		$query = "
					SELECT 
						category.id, 
						category.name 
					FROM ecmproductcategories category
						JOIN 
					ecmproductcategories_bean bean 
						ON bean.ecmproductcategory_id = category.id
					WHERE 
						category.deleted='0'
						AND bean.position='$depression'
						AND bean.deleted='0'
					GROUP BY 
						category.id
					ORDER BY
						category.name
				 ";
		

		$results = $this->db_connection->query($query);
		$all = array();

		if( $this->options["detail"] == 'subcategory' ) 
		{
			while( $result = $this->db_connection->fetchByAssoc( $results ) )
			{
				$subcategory = new Subcategory($result['id'], $result['name']);
				$all[] = $subcategory;
			}

			$this->subcategories = $all;
			$this->log( "Ilość podkategorii: ".count($this->subcategories));

			foreach( $this->subcategories as $subcategory )
				$this->getCategoryItems($subcategory);
		} else {
			while( $result = $this->db_connection->fetchByAssoc( $results ) )
			{
				$category = new Category($result['id'], $result['name']);
				$all[] = $category;
			}

			$this->categories = $all;
			$this->log( "Ilość kategorii: ".count($this->categories));

			foreach( $this->categories as $category )
				$this->getCategoryItems($category);
		}
		
		// Sort categories
		usort( $this->categories, array($this, 'sortCategoriesAndSubcategoriesFunction') );
		
		// Sort subcategories
		usort( $this->subcategories, array($this, 'sortCategoriesAndSubcategoriesFunction') );
		
	}
	
	private static function sortCategoriesAndSubcategoriesFunction( $a, $b )
	{		
		if( $a->subtotal > $b->subtotal )
			return false;
		else if( $a->subtotal < $b->subtotal )
			return true;
		else
			return 0;
	}
	

	/**
	* Metoda pobiera wszystkie itemy danej kategorii w podanym przedziale czasowym
	*/
	private function getCategoryItems( $obj )
	{
		$date_from = $this->prepareDateToQuery( new DateTime($this->options["date_from"]) );
		$date_to = $this->prepareDateToQuery( new DateTime($this->options["date_to"]) );
		$type = $this->options["type"];
		$category_id = $obj->id();

		if( $obj instanceof Category )
			$position = 0;
		else
			$position = 1;
		
		$query = "
					SELECT
						item.ecmproduct_id AS 'id',
					    item.name AS 'name',
					    item.total_brutto AS 'total',
					    item.total_netto AS 'subtotal',
					    item.price_start AS 'subprice',
					    item.quantity AS 'quantity',
					    item.old_quantity AS 'old_quantity',
					    item.total_netto_corrected AS 'subtotal_corrected',
					    item.old_total_brutto AS 'old_total',
					    item.old_ecminvoiceoutitem_id,
					    faktura.currency_value,
					    faktura.type AS 'type'
					FROM
					    ecminvoiceoutitems item 
					    JOIN ecminvoiceouts faktura
					        ON item.ecminvoiceout_id = faktura.id 
					    JOIN ecmproducts produkt
					        ON item.ecmproduct_id = produkt.id
					    JOIN ecmproductcategories_bean bean
					    	ON bean.bean_id = produkt.id
					    JOIN ecmproductcategories kategoria
					    	ON bean.ecmproductcategory_id = kategoria.id
					WHERE
					    faktura.register_date BETWEEN '$date_from' AND '$date_to'
					    AND faktura.type LIKE '$type'
					    AND kategoria.id = '$category_id'
					    AND bean.position = '$position'
					    AND bean.deleted = '0'
					    AND kategoria.deleted = '0'
					    AND faktura.canceled = '0'
					    AND faktura.deleted = '0'
					    AND item.deleted = '0'
					ORDER BY item.name
					    
				";
		

		$results = $this->db_connection->query( $query );
		$productArray = array();

		while( $result = $this->db_connection->fetchByAssoc( $results ) )
		{
			if( $result["type"] == 'correct')
			{
				if( $result["old_ecminvoiceoutitem_id"] != '' || 
					$result["old_ecminvoiceoutitem_id"] != null ||
					$result["old_ecminvoiceoutitem_id"] != 0)
				{
				$product = new Product($result["name"], 
								   	   $result["total"], 
								   	   $result["subtotal"], 
								   	   $result["subprice"], 
								   	   $result["quantity"], 
								   	   $result["currency_value"],
								   	   $result["old_quantity"], 
								   	   $result["subtotal_corrected"],
								   	   $result["old_total"],
								   	   $result["type"]);
				} else {
					$product = null;
				}
			} else if($result["type"] == 'normal') {
				$product = new Product($result["name"], 
				   	   $result["total"], 
				   	   $result["subtotal"], 
				   	   $result["subprice"], 
				   	   $result["quantity"], 
				   	   $result["currency_value"],
				   	   $result["old_quantity"], 
				   	   $result["subtotal_corrected"],
				   	   $result["old_total"],
				   	   $result["type"]);
			}
		

			if( $product != null )
				$productArray[] = $product;
		}

		$obj->setProducts( $productArray );
/*		if( $obj->name == 'Środki czystości' ){
			$obj->showProducts();
		}*/
	}

	/**
	* Wyświetla kategorie w których są jakieś produkty
	*/
	public function showCategories()
	{
		echo "WYświetlam";
		foreach( $this->categories as $category )
		{
			if( !$category->isEmpty )
			{
				echo $category->id;
				echo "<br>";
				echo $category->name;
				echo "<br>";
			}
		}
		echo "<br>";
	}
	
	/**
	* Wyświetla podkategorie w których są jakieś produkty
	*/
	public function showSubcategories()
	{
		foreach( $this->subcategories as $subcategory )
		{
			if( !$subcategory->isEmpty )
			{
				echo $subcategory->id;
				echo "<br>";
				echo $subcategory->name;
				echo "<br>";
			}
		}
		echo "<br>";
	}

	/**
	* Metoda przygotowuje datę do wstawienia w zapytanie SQL
	*/
	private function prepareDateToQuery( DateTime $d )
	{
		return $d->format('Y-m-d');
	}

	/**
	* Render data to Google Charts options
	*/
	public function renderGoogleChartOptions( $fromCategories = true )
	{
		$data = "";

	    if( $this->options["detail"] == "category" ) {
	    	for( $i = 0; $i < count($this->categories); $i++)
	    	{
	    		if( !$this->categories[$i]->isEmpty ) {
	    			$data .= "['".$this->categories[$i]->name."', ".$this->categories[$i]->subtotal;
	    			if( $this->options["comparativeData"] == 'enabled' )
	    				$data .= ", ".$this->compData[$i]->subtotal."0],";
	    			else 
	    				$data .= "],";
	    			//echo "['".$this->categories[$i]->name."', ".$this->categories[$i]->subtotal.", ".$this->compData[$i]->subtotal."],<br>";
	    		}
	    	}
	    } else {
	    	for( $i = 0; $i < count($this->subcategories); $i++)
	    	{
	    		if( !$this->subcategories[$i]->isEmpty ) {
	    			$data .= "['".$this->subcategories[$i]->name."', ".$this->subcategories[$i]->subtotal;
	    			if( $this->options["comparativeData"] == 'enabled' )
	    				$data .= ", ".$this->compData[$i]->subtotal."0],";
	    			else
	    				$data .= "],";
	    		}
	    	}
	    }
	    $data = rtrim($data, ",");
	    //echo $data;
	    return $data;
	}

	/**
	* Log functions
	*/
	private function log( $msg , $arrayOrObject = '')
	{
		if( $this->logEnabled == true )
		{
			echo "<br>";
			echo $msg;
			if( $arrayOrObject )
				print_r( $arrayOrObject );
			echo "<br>";
		}
	}

} // end class


?>