<?php

class ChartAnnualSalesHelper
{
	private $outputOptions = null;
	private $options = null;
	private $db = null;
	private $monthName = null;
	private $comparativeData = null;
	private $months;

	public function ChartAnnualSalesHelper($db, $options, $lang, $comparativeData = null)
	{
		$this->options = $options;
		$this->db = $db;
		$this->comparativeData = $comparativeData;
		$this->monthName = array($lang['LBL_JANUARY'], 
			 					 $lang['LBL_FEBRUARY'], 
			 					 $lang['LBL_MARCH'], 
			 					 $lang['LBL_APRIL'], 
			 					 $lang['LBL_MAY'], 
			 					 $lang['LBL_JUNE'], 
			 					 $lang['LBL_JULY'], 
			 					 $lang['LBL_AUGUST'], 
			 					 $lang['LBL_SEPTEMBER'], 
			 					 $lang['LBL_OCTOBER'], 
			 					 $lang['LBL_NOVEMBER'], 
			 					 $lang['LBL_DECEMBER']);
	}

	// Zwraca ustawienia Google Charts
	public function getChartOptions()
	{
		$months = $this->getMonths();

		$data = "";
		for( $i = 0; $i < count($months); $i++ )
		{
			if( $months[$i] != 0 && $months[$i] != null)
			{
				$value = sprintf("%.2f", (float)$months[$i]);
		    	$data .= "['".$this->monthName[$i]."', ". $value;

		    	if( $this->options["comparativeData"] == "enabled" )
		    		$data .= ", ".$this->comparativeData[$i].'0';

		    	$data .= "],";
	    	}
		}
		$data = rtrim($data, ",");
		return $data;
	}

	// Pobiera tablice z wartościami sum netto dla każdego roku
	private function getMonths()
	{
		$months = array();
		$thisYear = date("Y");
		$thisMonth = date("m");

		for( $i = 1; $i <= 12; $i++ )
		{	
				$result = $this->getSubtotalByMonth(($i <= 9 ? '0'.$i : $i), $this->options['year']);

				array_push($months, $result);
		}

		$this->months = $months;
		return $months;
		
	}

	// Metoda zwraca cenę netto dla danego miesiąca w danym roku
	private function getSubtotalByMonth($month, $year)
	{
		$type = $this->options["type"];
		$query = "
			SELECT
			    SUM(CASE WHEN e.currency_value = '0' OR e.currency_value = '' OR e.currency_value=0 OR e.currency_value is null 
			    	THEN
			    		e.total_netto
			    	ELSE
			    		e.total_netto*e.currency_value
			    	END
			    ) as 'subtotal'
			FROM
			    ecminvoiceouts e
			WHERE e.canceled = '0'
				AND e.deleted = '0'
					AND e.type LIKE '$type'
						AND e.register_date LIKE '$year-$month-%'
		";
		
		//echo $query."<br><br>";

		if( $this->options["contractor_id"] && $this->options["contractor_name"])
		{
			$query .= "AND e.parent_id = '".$this->options["contractor_id"]."'";
		}

		$results = $this->db->query($query);
		$result = $this->db->fetchByAssoc( $results );
		return $result['subtotal'];
	}

	public function getMonthsArray()
	{
		return $this->months;
	}
	
	public function haveComparativeData() 
	{
		if( $this->comparativeData != null )
			return true;
		else 
			return false;	
	}

}

?>