<?php

global $mod_strings, $app_list_strings, $db;

if(!$_REQUEST['date_from'])
	$date_from = date("01.m.Y");
else
	$date_from = $_REQUEST["date_from"];

if(!$_REQUEST['date_to'])
	$date_to = date("d.m.Y");
else
	$date_to = $_REQUEST["date_to"];

if(!class_exists('EcmInvoiceOut')){
	include_once('modules/EcmInvoiceouts/EcmInvoiceout.php');
};
if(!class_exists('EcmReceipts')){
	include_once('modules/EcmReceipts/EcmReceipt.php');
};
if(!class_exists('EcmStockDocIn')){
	include_once('modules/EcmStockDocIns/EcmStockDocIn.php');
};

//get trader list
$query_trader = "select ecminvoiceouts.assigned_user_id AS user_id , concat(users.first_name, ' ', users.last_name) AS user_name FROM ecminvoiceouts, users WHERE ecminvoiceouts.deleted = 0 and users.deleted=0 and ecminvoiceouts.canceled = 0 AND users.id =  ecminvoiceouts.assigned_user_id group by user_id ORDER BY user_name";
//$query_trader = "select ecmstockdockins.assigned_user_id AS user_id , concat(users.first_name, ' ', users.last_name) AS user_name FROM ecmstockdockins, users WHERE ecmstockdockins.deleted = 0 and ecmstockdockins.canceled = 0 AND users.id =  ecmstockdockins.assigned_user_id group by user_id ORDER BY user_name";

$trader_result = $db->query($query_trader);
//$trader_array = array(""=>"&nbsp;");
while($row = $db->fetchByAssoc($trader_result)){
	$trader_array[$row['user_id']] = $row['user_name'];
}

//Get Stock List

$query_stock = "Select id, name from ecmstocks where deleted=0";
$stock_result = $db->query($query_stock);
$stock_array = array(""=>"");
while($row = $db->fetchByAssoc($stock_result)){
	$stock_array[$row['id']] = $row['name'];
}

$query_stock = "Select account_type from accounts where deleted=0 group by account_type";
$stock_result = $db->query($query_stock);
$account_array = array(""=>"");


	$account_array[$row['account_type']] =$app_list_strings['account_type_dom'][$row['account_type']];


//Szykowanie zapytań
//Zakres dat
$whereInvoice['ecminvoiceouts'][] = 'register_date>="' . getFormatedDateForDB($date_from) . '"';
$whereInvoice['ecminvoiceouts'][] = 'register_date<="' . getFormatedDateForDB($date_to) . '"';
$whereRecipe['ecmrecipes'][] = 'register_date>="' . getFormatedDateForDB($date_from) . '"';
$whereRecipe['ecmrecipes'][] = 'register_date<="' . getFormatedDateForDB($date_to) . '"';
//Handlowiec
if($_REQUEST['trader'] != ""){
	if($_REQUEST['trader'][0]==""){
		unset($_REQUEST['trader'][0]);
	}
	if(count($_REQUEST['trader'])>0){
		
		$whereInvoice['ecminvoiceouts'][] = 'assigned_user_id in ("' . implode('","',$_REQUEST['trader']). '")';
		$whereRecipe['ecmrecipes'][] = 'assigned_user_id in ("' . implode('","',$_REQUEST['trader']). '")';
	}
	
}

//Kontrahent
if($_REQUEST['account_id'] != ""){
	$whereInvoice['ecminvoiceouts'][] = 'parent_id="' . $_REQUEST['account_id'] . '"';
	$whereRecipe['ecmrecipes'][] = 'parent_id="' . $_REQUEST['account_id'] . '"';
}

if($_REQUEST['product_category_id'] != ""){

	$product_category = $_REQUEST['product_category_id'];
}


//Magazyn
$stocks = $_REQUEST['stocks'];
if(count($stocks)>0){
	if(in_array("",$stocks)){
		$indeks = array_search("",$stocks);
		unset($stocks[$indeks]);
	}
	if(count($stocks)>0){
		$stocksList = array();
		$value = array_values ( $stocks );
		$whereInvoice['ecminvoiceouts'][] = 'stock_id IN ("' . implode('","',$value) . '")';
		$whereRecipe['ecmrecipes'][] = 'stock_id IN ("' . implode('","',$value) . '")';
	}
}

$accounts = $_REQUEST['account_type'];
if(count($accounts)>0){
	if(in_array("",$accounts)){
		$indeks = array_search("",$accounts);
		unset($accounts[$indeks]);
	}
	if(count($accounts)>0){
		$accountsList = array();
		$value = array_values ( $accounts );
		$whereInvoice['accounts'][] = 'accounts.account_type IN ("' . implode('","',$value) . '")';
		
	}
}
//Grupa
$product_group = $_REQUEST['product_group'];
if(count($product_group)>0){
	if(in_array("",$product_group)){
		$indeks = array_search("",$product_group);
		unset($product_group[$indeks]);
	}
	if(count($product_group)>0){
		$product_group_list = array();
		$value = array_values ( $product_group );
		$whereInvoice['ecmproducts'][] = 'ks_group IN ("' . implode('","',$value) . '")';
		$whereRecipe['ecmproducts'][] = 'ks_group IN ("' . implode('","',$value) . '")';
	}
}
$product_group_2 = $_REQUEST['product_group_2'];
if(count($product_group_2)>0){
	if(in_array("",$product_group_2)){
		$indeks = array_search("",$product_group_2);
		unset($product_group_2[$indeks]);
	}
	if(count($product_group_2)>0){
		$product_group_list = array();
		$value = array_values ( $product_group_2 );
		$whereInvoice['ecmproducts'][] = 'ks_group2 IN ("' . implode('","',$value) . '")';
		$whereRecipe['ecmproducts'][] = 'ks_group2 IN ("' . implode('","',$value) . '")';
	}
}


//Typ dokumentu
$document_sales_type = $_REQUEST['document_sales_type'];
if(count($document_sales_type)>0){
	if(in_array("",$document_sales_type)){
		$indeks = array_search("",$document_sales_type);
		unset($document_sales_type[$indeks]);
	}
	
	if(count($document_sales_type)>0){
		$tmpInvoiceType = array();
		$tmpRecipeType = array();
		$receiptDo = false;
		$invoceDo = true;
		
		
		
		if(count($tmpRecipeType)>0){
			$value = array_values ( $tmpRecipeType );
			//var_dump($where);
			$dataRecipe = EcmStockDocIn::getReceiptsList($whereRecipe,$product_category);
		}
		
	}else{
		//$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
		var_dump($where);
		$dataRecipe = EcmStockDocIn::getReceiptsList($whereRecipe,$product_category);
	}
}else{
	//$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
	
	
	$dataRecipe = EcmStockDocIn::getReceiptsList($whereRecipe,$product_category);
}

// Przetwarzanie danych
$data = array();
$total=0;
$total2=0;
$total3=0;
foreach($dataInvoice as $indeks => $invoice){
	foreach($invoice['position_list'] as $position => $item){
		$data[$item['product_id']]['code'] = '<a target="_blank"  href="index.php?module=EcmProducts&return_module=EcmProducts&action=DetailView&parentTab=Produkty&record=' . $item['product_id'] . '">' . $item['position_code'] .  '</a>';
		$data[$item['product_id']]['index'] = $item['position_code'] ;
		$data[$item['product_id']]['nazwa'] =  $item['position_name'];
		
		$data[$item['product_id']]['name'] = '<a target="_blank"  href="index.php?module=EcmProducts&return_module=EcmProducts&action=DetailView&parentTab=Produkty&record=' . $item['product_id'] . '"> ' .  $item['position_name'] . '</a>';
		$data[$item['product_id']]['total_netto'] += $item['position_total_netto'];
		$data[$item['product_id']]['price_purchase'] += $item['position_total_price_purchase'];
		$data[$item['product_id']]['quantity'] += $item['position_quantity'];
		$data[$item['product_id']]['jm_precision'] = $app_list_strings['ecmproducts_unit_dom_precision'][$item['position_unit_id']];
		$data[$item['product_id']]['jm_name'] = $item['position_unit_name'];
		
		if($_REQUEST['to_xls']=='1'){
			$data[$item['product_id']]['name'] =$item['position_code'] . ' ' .  $item['position_name'];
			
		}
		$total3+=$item['position_quantity'];
		$total+=$item['position_total_netto'];

		
		
	}
}
$total4=0;

foreach($dataRecipe as $indeks => $invoice){
	foreach($invoice['position_list'] as $position => $item){
		$data[$item['product_id']]['code'] = '<a target="_blank"  href="index.php?module=EcmProducts&return_module=EcmProducts&action=DetailView&parentTab=Produkty&record=' . $item['product_id'] . '">' . $item['position_code'] .  '</a>';
		$data[$item['product_id']]['index'] = $item['position_code'] ;
		$data[$item['product_id']]['nazwa'] =  $item['position_name'];
		
		$data[$item['product_id']]['name'] = '<a target="_blank"  href="index.php?module=EcmProducts&return_module=EcmProducts&action=DetailView&parentTab=Produkty&record=' . $item['product_id'] . '"> ' . $item['position_name'] . '</a>';
		$data[$item['product_id']]['total_netto'] += $item['position_total_netto'];
		$data[$item['product_id']]['price_purchase'] += $item['position_total_price_purchase'];
		$data[$item['product_id']]['position_weight'] = $item['position_weight'];
		
		$data[$item['product_id']]['position_total_weight'] += $item['position_total_weight'];
		$data[$item['product_id']]['quantity'] += $item['position_quantity'];
		$data[$item['product_id']]['jm_precision'] = $app_list_strings['ecmproducts_unit_dom_precision'][$item['position_unit_id']];
		$data[$item['product_id']]['jm_name'] = $item['position_unit_name'];
		if($_REQUEST['to_xls']=='1'){
			$data[$item['product_id']]['name'] =$item['position_code'] . ' ' .  $item['position_name'];
			
		}
		$total3+=$item['position_quantity'];
		$total+=$item['position_total_netto'];
		$total2+=$item['position_total_price_purchase'];
		$total4+=$item['position_total_weight'];
	}
}

//var_dump($data);
//
//Szykowanie wyświetlania
$smarty = new Sugar_Smarty ();
$smarty->assign("MOD", $mod_strings);
$smarty->assign("APP_LIST_STRINGS", $app_list_strings);

$sort=$_REQUEST['sort'];

if(count($sort)>0){
	foreach($sort as $key=>$val){
		switch (strtolower( $key)) {
			case 'indeks':
				if($val=='ASC'){
					
					usort($data, 'compare_lastname');
				}else{
					
					usort($data, 'compare_lastname_desc');
				}
				break;
			case 'nazwa':
				if($val=='ASC'){
					
					usort($data, 'compare_nazwa');
				}else{
					
					usort($data, 'compare_nazwa_desc');
				}
				break;
			default:
				usort($data, 'compare_lastname');
			
			
		}
	}
}
$smarty->assign("DATA", $data);


$smarty->assign("TRADERS_LIST", $trader_array);
$smarty->assign("STOCK_LIST", $stock_array);
$smarty->assign("ACCOUNT_LIST", $account_array);

$smarty->assign("TOTAL", $total);
$smarty->assign("TOTAL2", $total2);
$smarty->assign("TOTAL3", $total3);
$smarty->assign("TOTAL4", $total4);
//Ustawiamy przeslane dane
//$date_from = $GLOBALS['timedate']->to_display_date($date_from);
//$date_to = $GLOBALS['timedate']->to_display_date($date_to);
$smarty->assign("date_from_value", $date_from );
$smarty->assign("date_to_value", $date_to );
$smarty->assign("TRADER_SELECTED", $_REQUEST['trader']);
$smarty->assign("ACCOUNT_ID", $_REQUEST['account_id']);
$smarty->assign("ACCOUNT_NAME", $_REQUEST['account_name']);

$smarty->assign("PRODUCT_CATEGORY_ID", $_REQUEST['product_category_id']);
$smarty->assign("PRODUCT_CATEGORY_NAME", $_REQUEST['product_category_name']);

if($_REQUEST['to_pdf']!='1'){
	$smarty->assign("STOCK_SELECTED", $_REQUEST['stocks']);
	$smarty->assign("ACCOUNT_SELECTED", $_REQUEST['account_type']);
	$smarty->assign("PRODUCT_GROUP_SELECTED", $_REQUEST['product_group']);
	$smarty->assign("PRODUCT_GROUP_SELECTED_2", $_REQUEST['product_group_2']);
	$smarty->assign("DOCUMENT_SALES_SELECTED", $_REQUEST['document_sales_type']);
	echo $smarty->display('modules/EcmReports/tpls/mzVatPurchases.tpl');
	
}else{
	if($_REQUEST['to_xls']=='1'){
		$header=array();
		$header[]='index';
		$header[]='nazwa';
		$header[]='ilość';
		$header[]='jm';
		$header[]='zakup netto';
		// $header[]='koszt zakupu';
		//$header[]='dochód';
		$filename='modules/Home/Files/raport_zakupu_ilosciowy_'.date('d_m_Y').'.csv';
		$fp=fopen($filename,'w');
		foreach ($header as $k=>$v){
			
			$header[$k]=iconv('UTF-8','windows-1250',$header[$k]);
		}
		fwrite($fp, implode(";",$header).PHP_EOL);
		
		
		
		foreach ($data as $key=>$val){
			$line=array();
			$line[]=html_entity_decode($val['index']);
			
			$line[]=preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['name'])));
			$line[]=str_replace(".",",",$val['quantity']);
			$line[]=$val['jm_name'];
			$line[]=str_replace(".",",",$val['total_netto']);
			//  $line[]=str_replace(".",",",$val['price_purchase']);
			//$line[]=str_replace(".",",",$val['total_netto']-$val['price_purchase']);
			foreach ($line as $k=>$v){
				$line[$k]=iconv('UTF-8','windows-1250',$line[$k]);;
			}
			fwrite($fp, implode(";",$line).PHP_EOL);
		}
		print $filename;
	} else {
		include_once ("include/MPDF57/mpdf.php");
		include_once ("modules/EcmSysInfos/EcmSysInfo.php");
		$smarty->assign("STOCK_SELECTED", $stocks);
		$smarty->assign("PRODUCT_GROUP_SELECTED", $product_group);
		$smarty->assign("DOCUMENT_SALES_SELECTED", $document_sales_type);
		
	//	$EcmSysInfo = new EcmSysInfo();
	//	$smarty->assign("EcmSysInfo", $EcmSysInfo);
		//echo $EcmSysInfo->getName();
		
		$content = $smarty->fetch('modules/EcmReports/tpls/mzVatPurchaesPDF.tpl');
		$mPDF = new mPDF ( '', 'A4', null, 'helvetica',  10, 10, 10, 10, 5, 5 );
		$mPDF->mirrorMargins = 1;
		$mPDF->WriteHTML($content);
		$dir = 'upload/';
		if(!is_dir($dir)){
			mkdir($dir, '755', true);
		}
		$file_name = $dir . str_replace(".","",$date_from) . "_" . str_replace(".","",$date_to) ."_Raport_zakupu_Ilosciowy.pdf";
		$mPDF->Output( $file_name, "F");
		print $file_name;
	}
}

function getFormatedDateForDB($data){
	if(strpos($data,".")>0){
		$split = explode (".",$data);
		$return_data = $split[2] . "-" . $split[1] . "-" .$split['0'];
	}
	return $return_data;
}
function compare_lastname($a, $b)
{
	return strnatcmp($a['index'], $b['index']);
	
}
function compare_lastname_desc($a, $b)
{
	return strnatcmp($b['index'], $a['index']);
}
function compare_nazwa($a, $b)
{
	return strnatcmp($a['nazwa'], $b['nazwa']);
	
}
function compare_nazwa_desc($a, $b)
{
	return strnatcmp($b['nazwa'], $a['nazwa']);
}