<?php
if (! defined ( 'sugarEntry' ) || ! sugarEntry)
	die ( 'Not A Valid Entry Point' );

/**
 * **************************************************
 */
/**
 * ********************* PREPARE ********************
 */
/**
 * **************************************************
 */
$db = $GLOBALS ['db'];

$data = array ();
$categoryArray = array ();

$sum = array ();
$sumSub = array ();
$sumSub2 = array ();

if ($_GET ['selectProductActive'] != "") {
	$selectProductActive = $_GET ['selectProductActive'];
} else {
	$selectProductActive = "";
}

if ($_GET ['selectStock'] != "") {
	$selectStock = $_GET ['selectStock'];
} else {
	$selectStock = "";
}

$datastocks = array ();
$users = array ();
$queryStocks = "SELECT
					name,
					id
					FROM ecmstocks
					where deleted= 0";
$rowsStocks = $db->query ( $queryStocks );

while ( $rowStocks = $db->fetchByAssoc ( $rowsStocks ) ) {
	$stocks ["name"] = $rowStocks ["name"];
	$stocks ["id"] = $rowStocks ["id"];
	$datastocks [] = $stocks;
}

$query = "SELECT 
    p.id, p.name, p.code, SUM(ss.quantity) as quantity, SUM(ss.quantity * ss.price) as price
FROM
    ecmproducts as p
INNER JOIN ecmstockstates AS ss
ON ss.product_id = p.id
WHERE
    p.deleted = '0' AND ss.quantity IS NOT NULL";

if ($_GET ['selectStock'] != "")
	$query .= " AND ss.stock_id = '" . $_GET ["selectStock"] . "' ";

if ($_GET ['selectProductActive'] != "")
	$query .= " AND p.product_active = '" . $_GET ["selectProductActive"] . "' ";

$query .= " GROUP BY p.id";

/**
 * **************************************************
 */
/**
 * ************* GET DATA FROM DB********************
 */
/**
 * **************************************************
 */
$rows = $db->query ( $query );

// prepare data for Smarty
while ( $r = $db->fetchByAssoc ( $rows ) ) {
	$row = array ();
	$row ["id"] = $r ["id"];
	$row ["name"] = $r ["name"];
	$row ["code"] = $r ["code"];
	$row ["quantity"] = $r ["quantity"];
	$row ["price"] = $r ["price"] ;
	
	$querySubCategory = "SELECT category.name as 'podkategoria'
											FROM 			
												ecmproductcategories_bean bean
													JOIN
												ecmproductcategories category ON bean.ecmproductcategory_id = category.id
											WHERE bean.bean_id='" . $row ["id"] . "'
											and bean.position = '1'
											and bean.deleted = '0'
											and category.deleted = '0';";
	$rowsSubCategory = $db->query ( $querySubCategory );
	$row["podkategoria"] ="";
	while ( $rowSubCategory = $db->fetchByAssoc ( $rowsSubCategory ) ) {
		$row ["podkategoria"] = $rowSubCategory ["podkategoria"];
	}
	
	$queryCategory = "SELECT category.name as 'kategoria'
											FROM 			
												ecmproductcategories_bean bean
													JOIN
												ecmproductcategories category ON bean.ecmproductcategory_id = category.id
											WHERE bean.bean_id='" . $row ["id"] . "'
											and bean.position = '0'
										    and bean.deleted = '0'
											and category.deleted = '0';";
	$rowscategory = $db->query ( $queryCategory );
	$row["kategoria"] = "";
	while ( $rowcategory = $db->fetchByAssoc ( $rowscategory ) ) {
		$row ["kategoria"] = $rowcategory ["kategoria"];
	}
	$data [] = $row;
}

// //////////////// SUM /////////////////////////////////
foreach ( $data as $key => &$element ) {
		$categoryArray1 [$element ["kategoria"] == "" ? "Inne" : $element ["kategoria"]] [$element ["podkategoria"] == "" ? "Reszta" : $element ["podkategoria"]] [$key] = $element;
}
function cmp($a, $b) {
	if ($a ["name"] == $b ["name"]) {
		return 0;
	}
	return ($a ["name"] < $b ["name"]) ? - 1 : 1;
}

// grupowanie po kategoriach
foreach ( $categoryArray1 as $key1 => &$element1 ) {
	foreach ( $element1 as $key2 => &$element2 ) {
		usort ( $element2, "cmp" );
		$i = 0;
		$tmp2 [$key1] [$key2] [0] = array (
				'name' => null 
		);
		$counter = 0;
		
		foreach ( $element2 as $count => &$element3 ) {
			if ($element3 ["id"] != $tmp2 [$key1] [$key2] [$i] ["id"]) {
				
				if ($tmp2 [$key1] [$key2] [$i] ["id"] != null) {
					$i ++;
				}
				
				$tmp2 [$key1] [$key2] [$i] ["id"] = $element3 ["id"];
				$tmp2 [$key1] [$key2] [$i] ["name"] = $element3 ["name"];
				$tmp2 [$key1] [$key2] [$i] ["code"] = $element3 ["code"];
				$tmp2 [$key1] [$key2] [$i] ["quantity"] = $element3 ["quantity"];
				$tmp2 [$key1] [$key2] [$i] ["price"] = $element3 ["price"];
			}
			
			$counter += 1;
			
			/*
			if ($element2 [$count] ["name"] != $element2 [$count + 1] ["name"]) {
				$tmp2 [$key1] [$key2] [$i] ["marza"] = $tmp2 [$key1] [$key2] [$i] ["marza"] / $counter;
				$tmp2 [$key1] [$key2] [$i] ["srednia"] = $tmp2 [$key1] [$key2] [$i] ["srednia"] / $counter;
				$counter = 0;
			}
			*/
		}
		$categoryArray = $tmp2;
	}
}
foreach ( $categoryArray as $key => &$element ) {
	$count = 0;
	foreach ( $element as $keyy => &$elementt ) {
		foreach ( $elementt as $keyyy => &$elementtt ) {
			$sumSub ["QuantitySum"] [$key] += $elementtt ["quantity"];
			$sumSub ["PriceSum"] [$key] += $elementtt ["price"];
			
			$sumSub2 ["QuantitySum"] [$key] [$keyy] += $elementtt ["quantity"];
			$sumSub2 ["PriceSum"] [$key] [$keyy] += $elementtt ["price"];
		}
		$count += sizeof ( $elementt );
		
		$categoryArray [$key] [$keyy] ["QuantitySum2"] = $sumSub2 ["QuantitySum"] [$key] [$keyy];
		$categoryArray [$key] [$keyy] ["PriceSum2"] = $sumSub2 ["PriceSum"] [$key] [$keyy];
	}
	$categoryArray [$key] ["QuantitySum"] = $sumSub ["QuantitySum"] [$key];
	$categoryArray [$key] ["PriceSum"] = $sumSub ["PriceSum"] [$key];
}

foreach ( $categoryArray as $key => &$element ) {
	$sum ["QuantitySumSum"] += $sumSub ["QuantitySum"] [$key];
	$sum ["PriceSumSum"] += $sumSub ["PriceSum"] [$key];
}

foreach ( $categoryArray as $key1 => &$element ) {
	foreach ( $element as $key2 => &$elements ) {
		foreach ( $element as $key3 => &$element2 ) {
			if ($sumSub2 ["PriceSum"] [$key1] [$key2] > $sumSub2 ["PriceSum"] [$key1] [$key3]) {
				$tmp = $sumSub2 ["PriceSum"] [$key1] [$key2];
				$sumSub2 ["PriceSum"] [$key1] [$key2] = $sumSub2 ["PriceSum"] [$key1] [$key3];
				$sumSub2 ["PriceSum"] [$key1] [$key3] = $tmp;
			}
		}
	}
}

foreach ( $sumSub ["PriceSum"] as $key1 => &$element ) {
	foreach ( $sumSub ["PriceSum"] as $key2 => &$element2 ) {
		if ($sumSub ["PriceSum"] [$key1] > $sumSub ["PriceSum"] [$key2]) {
			$tmp = $sumSub ["PriceSum"] [$key1];
			$sumSub ["PriceSum"] [$key1] = $sumSub ["PriceSum"] [$key2];
			$sumSub ["PriceSum"] [$key2] = $tmp;
		}
	}
}

// //////////////// SORT array /////////////////////////////////
$newArray2;
foreach ( $sumSub ["PriceSum"] as $key1 => &$element1 ) {
	foreach ( $categoryArray as $key2 => &$element2 ) {
		if ($sumSub ["PriceSum"] [$key1] == $categoryArray [$key2] ["PriceSum"]) {
			$newArray2 [$key2] = $categoryArray [$key2];
		}
	}
}
$newArray1;
foreach ( $newArray2 as $key1 => &$element1 ) {
	foreach ( $element1 as $key2 => &$element2 ) {
		foreach ( $element1 as $key3 => &$element3 ) {
			if ($sumSub2 ["PriceSum"] [$key1] [$key2] == $newArray2 [$key1] [$key3] ["PriceSum2"]) {
				$newArray1 [$key1] [$key3] = $newArray2 [$key1] [$key3];
			}
		}
	}
}


/**
 * **************************************************
 */
/**
 * ******************** SMARTY **********************
 */
/**
 * **************************************************
 */
// create & execute smarty
$smarty = new Sugar_Smarty ();
global $mod_strings;
$smarty->assign ( "MOD", $mod_strings );
$smarty->assign ( "DATA", $newArray1 );
$smarty->assign ( "SUM", $sum );
$smarty->assign ( "STOCKS", $datastocks );
$smarty->assign ( "selectStock", $selectStock );
$smarty->assign ( "selectProductActive", $selectProductActive );

echo $smarty->display ( 'modules/EcmReports/tpls/ReportStocks.tpl' );
		
		
	/*****************************************************/
	/***************** EXPORT TO EXCEL *******************/
	/*****************************************************/
		/**
		 * PHPExcel
		 *
		 * Copyright (C) 2006 - 2014 PHPExcel
		 *
		 * This library is free software; you can redistribute it and/or
		 * modify it under the terms of the GNU Lesser General Public
		 * License as published by the Free Software Foundation; either
		 * version 2.1 of the License, or (at your option) any later version.
		 *
		 * This library is distributed in the hope that it will be useful,
		 * but WITHOUT ANY WARRANTY; without even the implied warranty of
		 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
		 * Lesser General Public License for more details.
		 *
		 * You should have received a copy of the GNU Lesser General Public
		 * License along with this library; if not, write to the Free Software
		 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
		 *
		 * @category   PHPExcel
		 * @package    PHPExcel
		 * @copyright  Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
		 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt	LGPL
		 * @version    1.8.0, 2014-03-02
		 */

		/** PHPExcel_IOFactory */
		require_once dirname(__FILE__) . '/PhpExcell/Classes/PHPExcel/IOFactory.php';
		
		// Create new PHPExcel object
		echo date('H:i:s') , " Create new PHPExcel object" , EOL;
		$objPHPExcel = new PHPExcel();
		
		// Set document properties
		echo date('H:i:s') , " Set document properties" , EOL;
		$objPHPExcel->getProperties()->setCreator("E5")
		->setLastModifiedBy("E5")
		->setTitle("E5 - Report Sales")
		->setSubject("E5 - Report Document")
		->setDescription("Report Sales - description")
		->setKeywords("e5, report, report sales")
		->setCategory("Reports");
		
		/*****************************************************/
		/******************* EXCELL Styles *******************/
		/*****************************************************/
		// Set default widths and heights
		$objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(15);
		$objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(20);
		
		$headerStyle = array(
				'alignment' => array(
						'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
						'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
				),
				'font' => array(
						'bold' => true,
						'color' => array('rgb' => 'FFFFFF'),
						'name' => 'Verdana',
				),
				'fill' => array(
						'type' => PHPExcel_Style_Fill::FILL_SOLID,
						'startcolor' => array(
								'rgb' => '272822',
						),
				),
		);
		
		$categoryStyle = array(
				'alignment' => array(
						'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,
						'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
				),
				'font' => array(
						'bold' => true,
						'color' => array('rgb' => 'FFFFFF'),
						'name' => 'Verdana',
				),
				'fill' => array(
						'type' => PHPExcel_Style_Fill::FILL_SOLID,
						'startcolor' => array(
								'rgb' => '4E5044',
						),
				),
		);
		
		$subCategoryStyle = array(
				'alignment' => array(
						'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,
						'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
				),
				'font' => array(
						'bold' => true,
						'color' => array('rgb' => 'FFFFFF'),
						'name' => 'Verdana',
				),
				'fill' => array(
						'type' => PHPExcel_Style_Fill::FILL_SOLID,
						'startcolor' => array(
								'rgb' => '8F937D',
						),
				),
		);
		
		$columnAlignRight = array(
				'alignment' => array(
						'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,
						'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
				),
		);

		$columnAlignLeft = array(
				'alignment' => array(
						'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,
						'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
				),
		);
		
		$objPHPExcel->setActiveSheetIndex(0)->getRowDimension('1')->setRowHeight(25);
		$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(70);
		$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(18);
		$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(20);
		
		$objPHPExcel->setActiveSheetIndex(0)->getStyle("B2:F4000")->applyFromArray($columnAlignRight);
		$objPHPExcel->setActiveSheetIndex(0)->getStyle("C2:F4000")->applyFromArray($columnAlignRight);
		$objPHPExcel->setActiveSheetIndex(0)->getStyle("E2:F4000")->applyFromArray($columnAlignRight);
		$objPHPExcel->setActiveSheetIndex(0)->getStyle("F2:F4000")->applyFromArray($columnAlignRight);
		
		$objPHPExcel->setActiveSheetIndex(0)->getStyle("G2:G4000")->applyFromArray($columnAlignRight);
		$objPHPExcel->setActiveSheetIndex(0)->getStyle("H2:H4000")->applyFromArray($columnAlignRight);
		$objPHPExcel->setActiveSheetIndex(0)->getStyle("A1:D1")->applyFromArray($headerStyle);

		/*****************************************************/
		/********************* EXCELL Data *******************/
		/*****************************************************/
		// Add header
		$objPHPExcel->setActiveSheetIndex(0)
		->setCellValue('A1', $mod_strings['LBL_PRODUCTS'] )
		->setCellValue('B1', $mod_strings['LBL_INDEX'])
		->setCellValue('C1', $mod_strings['LBL_QUANTITY'])
		->setCellValue('D1', $mod_strings['LBL_VALUE']);
		
		
		/*****************************************************/
		/********************* EXCELL Data *******************/
		/*****************************************************/
		// Add all data
		$lastRowNumber = 2;
		$rowNumber = 2;
		foreach ( $newArray1 as $categoryName => $category )
		{
			$objPHPExcel->setActiveSheetIndex(0)
			->setCellValue('A'.($rowNumber), $categoryName)
			->setCellValue('B'.($rowNumber), '')
			->setCellValue('C'.($rowNumber), number_format($category["QuantitySum"], 2, '.', ''))
			->setCellValue('D'.($rowNumber), number_format($category["PriceSum"], 2, '.', ''))
			->getStyle("A".$rowNumber.":D".$rowNumber)->applyFromArray($categoryStyle);

			// Formatowanie walutowe
	        $objPHPExcel->setActiveSheetIndex(0)->getStyle('D'.($rowNumber))->getNumberFormat()->setFormatCode("#,#0.#0 zł");

			// Nazwa kategorii wyrównane do lewej
			$objPHPExcel->setActiveSheetIndex(0)->getStyle("A".$rowNumber)->applyFromArray($columnAlignLeft);
			
			// Wyświetla podkategorie
			foreach ( $category as $subCategoryName => $subCategory )
			{
				if ( $subCategoryName != "QuantitySum" && $subCategoryName != "PriceSum" ) 
				{
					$rowNumber++;
					$lastRowNumber++;
					

					$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue('A'.($rowNumber), "    ".$subCategoryName)
					->setCellValue('B'.($rowNumber), "")
					->setCellValue('C'.($rowNumber), number_format($subCategory["QuantitySum2"], 2, '.', ''))
					->setCellValue('D'.($rowNumber), number_format($subCategory["PriceSum2"], 2, '.', ''))
					->getStyle("A".$rowNumber.":D".$rowNumber)->applyFromArray($subCategoryStyle);
					
					// Formatowanie walutowe
			        $objPHPExcel->setActiveSheetIndex(0)->getStyle('D'.($rowNumber))->getNumberFormat()->setFormatCode("#,#0.#0 zł");

					// Zwijanie wierszy
					$objPHPExcel->setActiveSheetIndex(0)->getRowDimension($rowNumber)->setOutlineLevel(1);
					$objPHPExcel->setActiveSheetIndex(0)->getRowDimension($rowNumber)->setVisible(true);

					
					// Nazwa kategorii wyrównane do lewej
					$objPHPExcel->setActiveSheetIndex(0)->getStyle("A".$rowNumber)->applyFromArray($columnAlignLeft);
					
					// Wyświetla produkty
					foreach ( $subCategory as $productId => $product )
					{				
						if ( $product["name"] != "IloscSum" && $product["name"] != "SoldSum" && $product["name"] != "SredniaSum" 
							 && $product["name"] != "KosztSum" && $product["name"] != "MarzaSum"  && $product["name"] != "" )
						{
							$rowNumber++;
							$lastRowNumber++;
								
							$objPHPExcel->setActiveSheetIndex(0)
							->setCellValue('A'.($rowNumber), "         ".$product["name"])
							->setCellValue('B'.($rowNumber), $product["code"])
							->setCellValue('C'.($rowNumber), number_format($product["quantity"], 2, '.', ''))
							->setCellValue('D'.($rowNumber), number_format($product["price"], 2, '.', ''));
							
							// Formatowanie walutowe
					        $objPHPExcel->setActiveSheetIndex(0)->getStyle('D'.($rowNumber))->getNumberFormat()->setFormatCode("#,#0.#0 zł");
											
							// Zwijanie wierszy
							$objPHPExcel->setActiveSheetIndex(0)->getRowDimension($rowNumber)->setOutlineLevel(2);	
							$objPHPExcel->setActiveSheetIndex(0)->getRowDimension($rowNumber)->setVisible(false);
						}							
						// Nazwa produktu wyrównane do lewej
						$objPHPExcel->setActiveSheetIndex(0)->getStyle("A".$rowNumber)->applyFromArray($columnAlignLeft);
						
					} // end subcategory
					$objPHPExcel->setActiveSheetIndex(0)->getRowDimension($lastRowNumber+1)->setCollapsed(true);
				} 
			} // end category
			$rowNumber++;
			$lastRowNumber++;

		}
		
		// Sumy --------------------------------------------------------------------------------------------------
		$objPHPExcel->setActiveSheetIndex(0)
		->setCellValue('A'.($lastRowNumber), $mod_strings['LBL_SUM'])
		->setCellValue('B'.($lastRowNumber), $sum['IloscSumSum'])
		->setCellValue('C'.($lastRowNumber), number_format($sum['QuantitySumSum'], 2, '.', ''))
		->setCellValue('D'.($lastRowNumber), number_format($sum['PriceSumSum'], 2, '.', ''));

		// Formatowanie walutowe
	    $objPHPExcel->setActiveSheetIndex(0)->getStyle('D'.($lastRowNumber))->getNumberFormat()->setFormatCode("#,#0.#0 zł");
		
		
		// Formatowanie wiersza sum -----------------------------------------------------------------------------
		$objPHPExcel->setActiveSheetIndex(0)->getStyle("A".$lastRowNumber.":D".$lastRowNumber)->applyFromArray($headerStyle);

		$objPHPExcel->setActiveSheetIndex(0)->getStyle("A".$lastRowNumber)->applyFromArray($columnAlignRight);
		$objPHPExcel->setActiveSheetIndex(0)->getStyle("B".$lastRowNumber)->applyFromArray($columnAlignRight);
		$objPHPExcel->setActiveSheetIndex(0)->getStyle("C".$lastRowNumber)->applyFromArray($columnAlignRight);
		$objPHPExcel->setActiveSheetIndex(0)->getStyle("D".$lastRowNumber)->applyFromArray($columnAlignRight);
		
		// Rename worksheet
		$objPHPExcel->getActiveSheet()->setTitle('Raport sprzedaży');
		
		// Set active sheet index to the first sheet, so Excel opens this as the first sheet
		$objPHPExcel->setActiveSheetIndex(0);
		
		// Save Excel 2007 file
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		$objWriter->save( __DIR__ . "/ExcelFiles/ReportStocks.xls");
		
?>
