<?php
	/*
	 * author: Michał Zieliński, mz@bim-it.pl
	 * created: 24.08.2015
	 * last modified date: 31.08.2015 by MZ
	*/
	$process = false;
	if ($_REQUEST['process'] == "1") $process = true;
	
	$db = $GLOBALS['db'];
	//create search form
	$ss = new Sugar_Smarty ();
	//group accounts
	if ($_REQUEST['group_accounts'] == "on") {
			$group_accounts = true;
			$ss->assign("GROUP_ACCOUNTS", "1");
			}
	//get Stocks
	$stocks = "";
	if ($_REQUEST['stocks']) $stocks = $_REQUEST['stocks'];
	$s_res = $db->query("SELECT DISTINCT o.stock_id as id, s.name FROM ecmstockoperations AS o INNER JOIN ecmstocks AS s ON s.id=o.stock_id WHERE o.deleted='0'");
	$stocks_tpl = '<select multiple id="stocks" name="stocks[]">';
	$s_stocks = "";
	while ($s_row = $db->fetchByAssoc($s_res)) {
		$stocks_tpl .= '<option value="'.$s_row['id'].'"';
		if ($stocks=="" || in_array($s_row['id'], $stocks)) {
			$stocks_tpl .= " selected ";
			$s_stocks.= $s_row['name'].", ";
		}
		$stocks_tpl .= '>'.$s_row['name'].'</option>';
	}
	$stocks_tpl .= '</select>';
	$s_stocks = substr($s_stocks,0,-2);
	if (is_array($stocks) && sizeof($stocks) == $s_res->num_rows)
		$s_stocks = "Wszystkie";
	$ss->assign("STOCKS", $stocks_tpl);
	
		//dates
	if ($_REQUEST['date_from']) 
		$date_from = $_REQUEST['date_from'];
	else {
		$date_from = new DateTime("first day of last month");
		$date_from = $date_from->format('d.m.Y');
	}
	$date_from_db = implode('-', array_reverse(explode('.', $date_from)));

	$ss->assign("DATE_FROM", $date_from);
	
	if ($_REQUEST['date_to']) 
		$date_to = $_REQUEST['date_to'];
	else {
		$date_to = new DateTime("last day of last month");
		$date_to = $date_to->format('d.m.Y');
	}
	$date_to_db = implode('-', array_reverse(explode('.', $date_to)));
	$ss->assign("DATE_TO", $date_to);	

	$ss->display ( 'modules/EcmReports/mz_tpl/StockOperationsCheck/StockOperationsCheckSearch.tpl' );
	
	if (!$process == true) {
		return;
	}
	//do your job!
	
	//get documents
	$doc_res = $db->query("SELECT parent_type, type FROM ecmstockoperations WHERE deleted='0' AND stock_id IN ('".implode("','", $stocks)."') GROUP BY parent_type, type");
	$documents = array();
	while ($doc_row = $db->fetchByAssoc($doc_res))
		$documents[$doc_row['parent_type'].'_'.$doc_row['type']] = 0;
	


	$data = array();
	$prod_res = $db->query("SELECT distinct product_id FROM ecmstockoperations WHERE stock_id IN ('".implode("','", $stocks)."') ORDER BY product_code");
	while ($row = $db->fetchByAssoc($prod_res)) {
		$tmp = array();
		$p = new EcmProduct();
		$p->retrieve($row['product_id']);
		$tmp['code'] = $p->code;
		$tmp['id'] = $p->id;
		$tmp['start_state'] = getStockStateByDate($p->id, $date_from_db." 00:00:00", $stocks);
		$tmp['end_state'] = getStockStateByDate($p->id, $date_to_db." 23:59:59", $stocks);
		$tmp['calc_state'] = $tmp['start_state'];
		$doc_tmp = $documents;
		$max = 0;
		$docs_tmp = array();
		foreach ($documents as $k=>$v) {
			$par = explode("_", $k);
			$op_res = $db->query("SELECT sum(quantity) as quantity, parent_id, parent_name, parent_type FROM ecmstockoperations WHERE product_id = '".$p->id."' AND deleted='0' AND parent_type='".$par[0]."' AND type='".$par[1]."' AND date_modified > '$date_from_db 00:00:00' AND date_modified < '$date_to_db 23:59:59' AND stock_id IN ('".implode("','", $stocks)."') GROUP BY parent_id ORDER BY date_entered");
			$op_qty = 0;
			if ($op_res->num_rows > $max)
				$max = $op_res->num_rows;
			
			while ($op = $db->fetchByAssoc($op_res)) {
					$op_qty += $op['quantity'];
					$docs_tmp[$k][] = $op;
			}
			$doc_tmp[$k] = floatval($op_qty);
			if ($par[1] == '0')
				$tmp['calc_state'] += $op_qty;
			if ($par[1] == '1')
				$tmp['calc_state'] -= $op_qty;
		}
		$tmp['doc_details'] = array();
		for ($i = 0; $i<$max; $i++) {
			$tmp2 = array();
			foreach ($documents as $k=>$v) {
				$tmp2[$k] = "";
				if (isset($docs_tmp[$k][$i]))
				$tmp2[$k] = $docs_tmp[$k][$i];
			}
			$tmp['doc_details'][]  = $tmp2;
		}
		//echo '<pre>'; var_dump($tmp['doc_details']); echo '</pre>';
		$tmp['error'] = abs($tmp['end_state'] - $tmp['calc_state']);
		$tmp['op'] = $doc_tmp; 
		$data[] = $tmp;
		unset($tmp);
		unset($p);
	}
	$module_names = array (
		'EcmStockDocIns' => 'PZ',
		'EcmStockDocOuts' => 'WZ',
		'EcmStockDocInsideIns' => 'PW',
		'EcmStockDocInsideOuts' => 'RW',
		'EcmStockDocMoves' => 'MM',
		'EcmStockDocCorrects' => 'KS',
		'EcmInvoiceOuts' => 'FV',
	);
	
	//create document and show it
	$ss_pdf = new Sugar_Smarty();
	$ss_pdf->assign("DATA", $data);
	$ss_pdf->assign("DOCUMENTS", $documents);
	$ss_pdf->assign("MOD_NAMES", $module_names);
	//header stuff
	$cur_date = new DateTime("now");
	$cur_date = $cur_date->format('d.m.Y H:m:s');
	$ss_pdf->assign("CUR_DATE", $cur_date);
	$ss_pdf->assign("DATE_FROM", $date_from);
	$ss_pdf->assign("DATE_TO", $date_to);
	$ss_pdf->assign("S_STOCK", $s_stocks);
	include_once ("modules/EcmSysInfos/EcmSysInfo.php");
    $EcmSysInfo = new EcmSysInfo();
    $ss_pdf->assign("COMPANY_NAME", $EcmSysInfo->getName());
	$content = $ss_pdf->fetch ( 'modules/EcmReports/mz_tpl/StockOperationsCheck/StockOperationsCheck.tpl' );
	echo $content;
	//include_once ("include/MPDF57/mpdf.php");
	//$p = new mPDF ( '', 'A4', null, 'helvetica', 5, 5, 30, 5, 5, 5 );
	//$p->writeHTML ($content) ;
	//$p->setTitle ( "Analiza ruchu magazynowego" );
	//$p->output("mag.pdf", "I");
	

	
	//helper
	function getStockStateByDate($product_id, $date, $stocks) {
		$db = $GLOBALS['db'];
		//get current stock state
		$cur = $db->fetchByAssoc($db->query("SELECT sum(quantity) AS qty FROM ecmstockstates WHERE product_id='$product_id' AND deleted='0' AND  quantity IS NOT NULL AND stock_id IN ('".implode("','", $stocks)."')"));
		$quantity = $cur['qty'];
		//get + operations
		$in = $db->fetchByAssoc($db->query("SELECT sum(quantity) AS qty FROM ecmstockoperations WHERE product_id = '$product_id' AND deleted='0' AND type='0' AND date_modified> '$date' AND stock_id IN ('".implode("','", $stocks)."')"));
		$quantity-=$in['qty'];
		//get - operations
		$out = $db->fetchByAssoc($db->query("SELECT sum(quantity) AS qty FROM ecmstockoperations WHERE product_id = '$product_id' AND deleted='0' AND type='1' AND date_modified > '$date' AND stock_id IN ('".implode("','", $stocks)."')"));
		$quantity+=$out['qty'];
		
		return $quantity;
	}
	
	