<?php
global $mod_strings, $app_list_strings, $db;
// kontrahent 
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');
};

//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 ecminvoiceouts.canceled = 0 AND users.id =  ecminvoiceouts.assigned_user_id group by user_id ORDER BY user_name";
$trader_result = $db->query($query_trader);
$trader_array = array(""=>"");
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'];
}

//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'] != ""){
	$whereInvoice['ecminvoiceouts'][] = 'assigned_user_id="' . $_REQUEST['trader'] . '"';
	$whereRecipe['ecmrecipes'][] = 'assigned_user_id="' . $_REQUEST['trader'] . '"';
}
//Kontrahent
if($_REQUEST['account_id'] != ""){
	$whereInvoice['ecminvoiceouts'][] = 'parent_id="' . $_REQUEST['account_id'] . '"';
	$whereRecipe['ecmrecipes'][] = 'parent_id="' . $_REQUEST['account_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) . '")';
	}
}

//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) . '")';
	}
}

// Typ PDF
$pdf_type = $_REQUEST['pdf_type'];
if(count($pdf_type)>0){
	if(in_array("",$pdf_type)){
		$indeks = array_search("",$pdf_type);
		unset($pdf_type[$indeks]);
	}
	if(count($pdf_type)>0){
		$product_group_list = array();
		$value = array_values ( $pdf_type );
		$whereInvoice['ecmproducts'][] = 'pdf_type IN ("' . implode('","',$value) . '")';
	//	$whereRecipe['ecmproducts'][] = 'pdf_type 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;
		foreach($document_sales_type as $key => $value){
			switch($value){
				case 'invoice': 
					$tmpInvoiceType[] = 'normal';
					$invoceDo = true;
					break;
				case 'invoice_correct': 
					$invoceDo = true;
					$tmpInvoiceType[] = 'correct';
					break;
				case 'recipe': 
					$receiptDo = true;
					$tmpRecipeType[] = 'normal';
					break;
				case 'recipe_correct': 
					$receiptDo = true;
					$tmpRecipeType[] = 'correct';
					break;
			}
		}
		if(count($tmpInvoiceType)>0){
			$value = array_values ( $tmpInvoiceType );
			$whereInvoice['ecminvoiceouts'][] = 'type IN ("' . implode('","',$value) . '")';
			$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
		}
		
		if(count($tmpRecipeType)>0){
			$value = array_values ( $tmpRecipeType );
			$whereRecipe['ecmrecipes'][] = 'type IN ("' . implode('","',$value) . '")';
			$dataRecipe = EcmReceipt::getReceiptsList($whereRecipe);
		}
		
	}else{
		$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
		$dataRecipe = EcmReceipt::getReceiptsList($whereRecipe);
	}
}else{
	$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
	$dataRecipe = EcmReceipt::getReceiptsList($whereRecipe);
}

// Przetwarzanie danych
$data = array();
foreach($dataInvoice as $indeks => $invoice){
	if($invoice['document_type'] == 'EcmInvoiceOuts'){
		$docname = 'Faktura';
	}elseif($invoice['document_type'] == 'EcmReceipts'){
		$docname .= 'Paragon';
	}
	if($invoice['type'] == 'correct'){
		$docname .= ' Korekta';
	}
	$docname .= " " . $invoice['document_no'];
	$data[$invoice['id']]['name'] = '<a target="_blank"  href="index.php?module=' . $invoice['document_type'] . '&action=DetailView&parentTab=Sprzedaż&record=' . $invoice['parent_id'] . '">' . $docname . '</a>';
	$data[$invoice['id']]['register_date'] = getFormatedDateForView($invoice['register_date']);
	$data[$invoice['id']]['total_netto'] += $invoice['total_netto'];
	$data[$invoice['id']]['total_brutto'] += $invoice['total_brutto'];
	$data[$invoice['id']]['price_purchase'] += $invoice['purchase_price'];
	$data[$invoice['id']]['parent_name'] = '<a target="_blank"  href="index.php?module=Accounts&return_module=Account&action=DetailView&parentTab=Kontakty&record=' . $invoice['parent_id'] . '">' . $invoice['parent_name'] . '</a>';
              if($_REQUEST['to_xls']=='1'){
            $data[$invoice['id']]['parent_name']= $invoice['parent_name'];
            $data[$invoice['id']]['name'] =$docname;
        }
}

foreach($dataRecipe as $indeks => $invoice){
	if($invoice['document_type'] == 'EcmInvoiceOuts'){
		$docname = 'Faktura';
	}elseif($invoice['document_type'] == 'EcmReceipts'){
		$docname = 'Paragon';
	}
	if($invoice['type'] == 'correct'){
		$docname .= ' Korekta';
	}
	$docname .= " " . $invoice['document_no'];
	$data[$invoice['id']]['name'] = '<a target="_blank"  href="index.php?module=' . $invoice['document_type']. '&action=DetailView&parentTab=Sprzedaż&record=' . $invoice['parent_id'] . '">' . $docname . '</a>';
	$data[$invoice['id']]['register_date'] = getFormatedDateForView($invoice['register_date']);
	$data[$invoice['id']]['total_netto'] += $invoice['total_netto'];
	$data[$invoice['id']]['total_brutto'] += $invoice['total_brutto'];
	$data[$invoice['id']]['price_purchase'] += $invoice['purchase_price'];
	$data[$invoice['id']]['parent_name'] = '<a target="_blank"  href="index.php?module=Accounts&return_module=Account&action=DetailView&parentTab=Kontakty&record=' . $invoice['parent_id'] . '">' . $invoice['parent_name'] . '</a>';
        if($_REQUEST['to_xls']=='1'){
            $data[$invoice['id']]['parent_name']= $invoice['parent_name'];
            $data[$invoice['id']]['name'] =$docname;
        }
}

//
//Szykowanie wyświetlania
$smarty = new Sugar_Smarty ();
$smarty->assign("MOD", $mod_strings);
$smarty->assign("APP_LIST_STRINGS", $app_list_strings);
$smarty->assign("DATA", $data);
$smarty->assign("TRADERS_LIST", $trader_array);
$smarty->assign("STOCK_LIST", $stock_array);


//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_invoice_type_dom", $app_list_strings['account_invoice_type_dom']);
$smarty->assign("STOCK_SELECTED", $_REQUEST['stocks']);
$smarty->assign("PRODUCT_GROUP_SELECTED", $_REQUEST['product_group']);
$smarty->assign("DOCUMENT_SALES_SELECTED", $_REQUEST['document_sales_type']);
$smarty->assign("PDF_TYPE_SELECTED", $_REQUEST['pdf_type']);
$smarty->assign("ACCOUNT_ID", $_REQUEST['account_id']);
$smarty->assign("ACCOUNT_NAME", $_REQUEST['account_name']);

if($_REQUEST['to_pdf']!='1'){
	echo $smarty->display('modules/EcmReports/tpls/ReportSalesByDocument.tpl');
}else{
        if($_REQUEST['to_xls']=='1'){
        $header=array();
        $header[]='dokument';
        $header[]='data dokumentu';
        $header[]='kontrahent';
        $header[]='sprzedaż netto';
        $header[]='sprzedaż brutto';
        $header[]='koszt zakupu';
        $header[]='dochód';
            $filename='modules/Home/Files/raport_sprzedazy_wartosciowy_'.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[]=$val['name'];
            $line[]=$val['register_date'];
            $line[]=preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['parent_name'])));
                        $line[]=str_replace(".",",",$val['total_netto']);
                           $line[]=str_replace(".",",",$val['total_brutto']);
            $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");
	$EcmSysInfos = new EcmSysInfo();

	$content = $smarty->fetch('modules/EcmReports/tpls/ReportSalesByDocumentPDF.tpl');
	$mPDF = new mPDF ( '', 'A4', null, 'helvetica',  10, 10, 10, 10, 5, 5 );
	$mPDF->mirrorMargins = 1;
	$mPDF->WriteHTML($content);

	$dir = 'upload/' . $EcmSysInfos->getDatabaseName() . '/pdf/EcmReports/';
	if(!is_dir($dir)){
		mkdir($dir, '755', true);
	}
	$file_name = $dir . str_replace(".","",$date_from) . "_" . str_replace(".","",$date_to) ."_Raport_Sprzedazy_Raport_wartosciowy.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 getFormatedDateForView($data){
	if(strpos($data,"-")>0){
		$split = explode ("-",$data);
		$return_data = $split[2] . "." . $split[1] . "." .$split['0'];
	}
	return $return_data;
}