<?
	/*
	 * author: Michał Zieliński, mz@bim-it.pl
	 * created: 17.08.2015
	 * last modified date: 10.09.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 id, name FROM ecmstocks WHERE deleted='0' ORDER BY name");
	$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);
	//document categories
	$categories = "";
	if ($_REQUEST['categories']) $categories = $_REQUEST['categories'];
	$s_categories = "";
	global $app_list_strings;
	$categories_def = $app_list_strings['ecminvoiceouts_category_dom'];
	if ($_REQUEST['categories']) $categories = $_REQUEST['categories'];
	$categories_tpl = '<select multiple id="categories" name="categories[]">';
	foreach ($categories_def as $k=>$v) {
			$categories_tpl .= '<option value="'.$k.'"';
			if ($categories == "" || in_array($k, $categories)) {
				$categories_tpl .= ' selected';
				$s_categories.= $v.", ";
			}
			$categories_tpl .= '>'.$v.'</option>';
		}
	$categories_tpl .= '</select>';
	$s_categories = substr($s_categories,0,-2);
	if (is_array($categories) && sizeof($categories) == sizeof($categories_def))
		$s_categories = "Wszystkie";
	$ss->assign("CATEGORIES", $categories_tpl);
	//document kinds
	$kinds_def = array (
		'K' => 'Kraj',
		'U' => 'Unia',
		'E' => 'Import',
	);	
	$kinds = "";
	if ($_REQUEST['kinds']) $kinds = $_REQUEST['kinds'];
	$s_kinds = "";
	$kinds_tpl = '<select multiple id="kinds" name="kinds[]">';
	foreach ($kinds_def as $k=>$v) {
			$kinds_tpl .= '<option value="'.$k.'"';
			if ($kinds == "" || in_array($k, $kinds)) {
				$kinds_tpl .= ' selected';
				$s_kinds.=$v.", ";
			}
			$kinds_tpl .= '>'.$v.'</option>';
		}
	$kinds_tpl .= '</select>';
	$s_kinds = substr($s_kinds,0,-2);
	if (is_array($kinds) && sizeof($kinds) == sizeof($kinds_def))
		$s_kinds = "Wszystkie";
	$ss->assign("KINDS", $kinds_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);	

	if (!$process == true) {
		$ss->display ( 'modules/EcmReports/mz_tpl/VatPurchases/VatPurchasesSearch.tpl' );
		return;
	}
	
	//Do your job!
	$main_query = "SELECT id, value, currency_id, currency_value, document_number, active_date, register_date FROM documents WHERE deleted='0' AND value IS NOT NULL ";
	$main_query.= "AND register_date >= '$date_from_db' AND register_date <= '$date_to_db' ";
	if($_REQUEST['categories'][0]==' '){
	    $s_categories = "Wszystkie";
	} else {
	    if (is_array($categories))
	        $main_query .= " AND (category IN ('".implode("','", $categories)."') OR category IS NULL)";
	}

	//if ($group_accounts == true)
		$main_query .= " ORDER BY register_date, date_entered";
	$doc_res = $db->query($main_query);
	//get vats names
	$main_query = str_replace(", value, currency_id, currency_value, document_number, active_date, register_date", "", $main_query); //leave only id field
	$vats_query = "SELECT DISTINCT vat_value as ecmvat_name, vat_id as value FROM documents_vat
						 WHERE netto != 0 AND document_id IN ($main_query) ORDER BY ecmvat_name";
	$v_res = $db->query($vats_query);
	$vats = array();
	$vatsCount = 0;
	while ($v_row = $db->fetchByAssoc($v_res)) {
		//check if value is 0
		if ($v_row['value'] == 0) {
			$vats[$v_row['ecmvat_name']] = 1; //var is 0 - we didn't have to draw column
			$vatsCount++;
		} else {
			$vats[$v_row['ecmvat_name']] = 2;
			$vatsCount+=2;
		}
	}
	
	$data = array();
	$c = 1; //counter
	while ($row = $db->fetchByAssoc($doc_res)) {
		$tmp = array();
		$tmp['document_no'] = $row['document_number'];
		$tmp['register_date'] = implode('.', array_reverse(explode('-', $row['register_date'])));
		$tmp['publish_date'] = implode('.', array_reverse(explode('-', $row['active_date'])));
		
		//get Account info
		$a_res = $db->fetchByAssoc($db->query("SELECT parent_id FROM documents_accounts WHERE parent_type='Account' AND deleted='0' AND document_id='".$row['id']."' LIMIT 0,1"));
		$a = new Account();
		$a->retrieve($a_res['parent_id']);
				
		$pi = $a->to_vatid;
		if (strlen($pi.", ".$a->name) <= 70)
			$pi.=", ".$a->name;
		if (strlen($pi.", ".$a->register_address_street) <= 70)
			$pi.=", ".$a->register_address_street;
		if (strlen($pi.", ".$a->register_address_postalcode) <= 70)
			$pi.=", ".$a->register_address_postalcode;
		if (strlen($pi.", ".$a->register_address_city) <= 70)
			$pi.=", ".$a->register_address_city;
		$tmp['parent_info'] = $pi;
		$tmp['parent_index'] = $a->index_dbf;
		$tmp['parent_id'] = $a->id;
		$tmp['parent_type'] = $a->invoice_type;
		unset($a);
		if (!in_array($tmp['parent_type'], $kinds)) continue;
				
		//get PZ info if existst
		$pz_res = $db->query("SELECT parent_id FROM documents_accounts WHERE parent_type='EcmStockDocIn' AND deleted='0' AND document_id='".$row['id']."'");
		$tmp['rel_doc'] = "";
		$tmp['rel_doc_total'] = 0;
		$stock_ok = true;
		if ($pz_res->num_rows > 0) {
			while ($pz_row = $db->fetchByAssoc($pz_res)) {
				$pz = new EcmStockDocIn();
				$pz->retrieve($pz_row['parent_id']);
				if (!in_array($pz->stock_id, $stocks)) $stock_ok = false;
				$tmp['rel_doc'].= $pz->document_no.", ";
				$tmp['rel_doc_total'] += $pz->total;
				unset($pz);
			}
		} else continue;
		if ($stock_ok == false) continue;
		$tmp['lp'] = $c; $c++;
		$tmp['rel_doc'] = substr($tmp['rel_doc'],0,-2);
		//if ($inv->currency_id == 'PLN') $currency = 1; else $currency = $inv->currency_value_nbp;
		//TODO: check currency_value on documents
		$currency = 1;
		$tmp['brutto'] = $row['value'] * $currency;
		$tmp['netto'] = 0;
		$tmp['vat'] = 0;
		//prepare vats
		$dv_res = $db->query("SELECT DISTINCT vat_value as ecmvat_name, vat_id as value, netto, vat FROM documents_vat
									    WHERE netto != 0 AND document_id = '".$row['id']."' ORDER BY ecmvat_name");
		$doc_vat = array();
		//insert zeros
		foreach ($vats as $k=>$v) {
			$doc_vat[$k][0] = 0;
			$doc_vat[$k][1] = 0;
		}
		while ($dv_row = $db->fetchByAssoc($dv_res)) {
				$doc_vat[$dv_row['ecmvat_name']][0] = round($dv_row['netto']*$currency,2);
				$doc_vat[$dv_row['ecmvat_name']][1] = round($dv_row['vat']*$currency,2);
				$tmp['netto'] += round($dv_row['netto']*$currency,2);
				$tmp['vat'] += round($dv_row['vat']*$currency,2);
		}
		$tmp['vats'] = $doc_vat;
		unset($doc_vat);
		$data[] = $tmp;
		unset($tmp);
	}
	
	if ($group_accounts == true) {
		usort($data, "cmp");
		//creaate Accounts summary
		$tmp_data = array();
		$summary = array();
		$sum = array();
		$sum_vat = array();
		for ($i = 0; $i < sizeof($data); $i++) {
			$row = $data[$i];
			$row['lp'] = $i+1;
			$tmp_data[] = $row;
			if (array_key_exists("total_netto",$sum))
				$sum['total_netto'] += $row['netto']; else $sum['total_netto'] = $row['netto'];
			if (array_key_exists("total_brutto",$sum))
				$sum['total_brutto'] += $row['brutto']; else $sum['total_brutto'] = $row['brutto'];
			if (array_key_exists("total_vat",$sum))
				$sum['total_vat'] += $row['vat']; else $sum['total_vat'] = $row['vat'];
			if (array_key_exists("total_rel",$sum))
				$sum['total_rel'] += $row['rel_doc_total']; else $sum['total_rel'] = $row['rel_doc_total'];
			foreach ($row['vats'] as $k=>$v) {
				if (!array_key_exists($k,$sum_vat)) {
					$sum_vat[$k][0] = 0;
					$sum_vat[$k][1] = 0;
				}
				$sum_vat[$k][0] += $v[0];
				$sum_vat[$k][1] += $v[1];
			}
			if ($data[$i]['parent_id'] != $data[$i+1]['parent_id'] || $i == sizeof($data)) {
				//insert summary row			
				$sum['is_summary'] = 1;
				$sum['index'] = $row['parent_index'];
				$sum['parent_info'] = 'Podsumowanie dla kontrahenta';
				$sum['vats'] = $sum_vat;
				$tmp_data[] = $sum;
				unset($sum); $sum = array(); 
				unset($sum_vat); $sum_vat = array();
			}
		}
		$data = $tmp_data;
	}

	
	$rop = 26; // rows on page
	$nop = ceil(sizeof($data)/$rop); // number of pages
	$pages_data = array_chunk($data, $rop);
	$pages = array();
	unset($data);
	$prev_page = array();
	$c = 1; //counter
	foreach ($pages_data as $data) {
	
			$tmp = array();
			$tmp['site_netto'] = 0; $tmp['site_brutto'] = 0; $tmp['site_vat'] = 0; $tmp['site_pz'] = 0;
			$tmp['moved_netto'] = 0; $tmp['moved_brutto'] = 0; $tmp['moved_vat'] = 0; $tmp['moded_pz'] = 0; 
			//prepare vats array
			$site_vats = array();
			$moved_vats = array();
			$total_vats = array();
			foreach ($vats  as $k => $v) {
				$site_vats[$k][0] = 0;
				$site_vats[$k][1] = 0;
				$moved_vats[$k][0] = 0;
				$moved_vats[$k][1] = 0;
				$total_vats[$k][0] = 0;
				$total_vats[$k][1] = 0;
			}
			foreach ($data as $i) {
				if ($i['is_summary'] == 1) continue;
				$tmp['site_netto'] += $i['netto'];
				$tmp['site_brutto'] += $i['brutto'];
				$tmp['site_vat'] += $i['vat'];
				$tmp['site_pz'] += $i['rel_doc_total'];
				foreach ($i['vats'] as $k => $v) {
					$site_vats[$k][0] += $v[0];
					$site_vats[$k][1] += $v[1];
				}
			}
			if ($c!=1) { //not first page
				$tmp['moved_netto'] = $prev_page['total_netto'];
				$tmp['moved_brutto'] = $prev_page['total_brutto'];
				$tmp['moved_vat'] = $prev_page['total_vat'];
				$tmp['moved_pz'] = $prev_page['total_pz'];

				foreach ($vats as  $k=>$v) {
					$moved_vats[$k][0] += $prev_page['total_vats'][$k][0];
					$moved_vats[$k][1] += $prev_page['total_vats'][$k][1];
				}
			}
			$tmp['total_netto'] = $tmp['site_netto'] + $tmp['moved_netto'];
			$tmp['total_brutto'] = $tmp['site_brutto'] + $tmp['moved_brutto'];
			$tmp['total_vat'] = $tmp['site_vat'] + $tmp['moved_vat'];
			$tmp['total_pz'] = $tmp['site_pz'] + $tmp['moved_pz'];
			foreach ($vats as $k=>$v) {
					$total_vats[$k][0] += $site_vats[$k][0] + $moved_vats[$k][0];
					$total_vats[$k][1] += $site_vats[$k][1] + $moved_vats[$k][1];
				}
			//insert page data
			$tmp['rows'] = $data;
			$tmp['page_no'] = $c;
			$tmp['site_vats'] = $site_vats;
			$tmp['moved_vats'] = $moved_vats;
			$tmp['total_vats'] = $total_vats;
			
			$pages[] = $tmp;
			$prev_page = $tmp;
			$c++;
	}

	//create document and show it
	$ss_pdf = new Sugar_Smarty();
	$ss_pdf->assign("PAGES", $pages);
	$ss_pdf->assign("VATS", $vats);
	$ss_pdf->assign("vatsCount", $vatsCount);
	//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_CATEGORY", $s_categories);
	$ss_pdf->assign("S_KIND", $s_kinds);
	$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/VatPurchases/VatPurchasesPDF.tpl' );
	include_once ("include/MPDF57/mpdf.php");
	$p = new mPDF ( '', 'A4', null, 'helvetica', 5, 5, 30, 5, 5, 5 );
	$p->writeHTML ($content) ;
	$p->setTitle ( "Rejestr zakupu VAT" );
	$p->output("rej_zak.pdf", "I");
	
	//helper
	function cmp($a, $b) {
		if ($a['parent_info'] == $b['parent_info']) {
			return ( $a['register_date'] > $b['register_date'] ) ? 1 : -1;
		}
		return ( $a['parent_info'] > $b['parent_info'] ) ? 1 : -1;
	}
		
		
		
		
		
		