<?php
global $mod_strings, $app_list_strings, $db;
// partie
$EcmConfig = array (
	'consignments' => true,
	'consignments_label1' => 'Nr',	
);
ini_set('memory_limit','-1');
ini_set('max_execution_time','-1');



$doc_name=array('EcmStockDocInsideIns'=>'PW','EcmStockDocMoves'=>'MM','EcmStockDocCorrects'=>'KS','EcmStockDocIns'=>'PZ');
/* 
 *  Magazyny
 */
$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;
}

/*
 *  Dodatkowe parametry do zapytania
 */
if ($_GET ['selectStock'] != "")
    $add_where .= " and stock_id = '" . $_GET ["selectStock"] . "' ";

if ($_GET ['selectProductActive'] != ""){
    $where= " WHERE product_active = '" . $_GET ["selectProductActive"] . "' ";
} else {
    $where='';
}
$_GET['selectShowEmpty']=1;
$r1 = $db->query("select id,name,code,unit_id from ecmproducts ".$where." order by name asc");
$docs = array();
$i=0;
$total_quantity=0;
$total_value=0;
while ($tmp2 = $db->fetchByAssoc($r1)) {
    $r = $db->query("select * from ecmstockoperations where product_id='" . $tmp2['id'] . "' ".$add_where." and in_id is null and used=0 and type=0 order by counter asc");
    $l = 0;
    if ($r->num_rows > 0) {
        $docs[$i]['unit_id'] = $app_list_strings['ecmproducts_unit_dom'][$tmp2['unit_id']];
		$docs[$i]['unit_precision'] = $app_list_strings['ecmproducts_unit_dom_precision'][$tmp2['unit_id']];
        $docs[$i]['product_id'] = $tmp2['id'];
        $docs[$i]['product_name'] = $tmp2['name']; 
        $docs[$i]['product_code'] = $tmp2['code'];
        $docs[$i]['total_quantity'] = 0;
        $docs[$i]['total_price'] = 0;
        $i++;
    }
    while ($tmp = $db->fetchByAssoc($r)) {

        $ii = $db->query( "select * from ecmstockoperations where in_id='" . $tmp['id'] ."' and type=1");
        if ($ii->num_rows > 0) {
            // licz ilość dla użytych
            $quantity_tmp = $tmp['quantity'];
            while ($tmp2 = $db->fetchByAssoc($ii)) {
                $quantity_tmp -= $tmp2['quantity'];
            }
            if($quantity_tmp==0){
                $db->query("update ecmstockoperations set used=1 where id='".$tmp['id']."'");
                continue;
            }
            $doc['quantity'] = $quantity_tmp;
            $doc['parent_name'] = $tmp['parent_name'];
            $doc['part_no'] = $tmp['part_no'];
            $doc['price'] = $tmp['price'];
            $doc['parent_type'] = $doc_name[$tmp['parent_type']];
            $doc['parent_type2'] = $tmp['parent_type'];
            $doc['parent_id'] = $tmp['parent_id'];
            $doc['product_id'] = $tmp['id'];
            $doc['date_entered'] = $tmp['date_entered'];
            $doc['position_value'] = $doc['quantity']*$tmp['price'];
            $total_quantity+=$doc['quantity'];
            $total_value+=round($doc['quantity']*$tmp['price'],2);
            $docs[$i-1]['add'][] = $doc;
            $docs[$i-1]['total_price']+=($doc['quantity']*$tmp['price'] );
			$docs[$i-1]['part_no'] =$tmp['part_no'];
            $docs[$i-1]['total_quantity']+=($doc['quantity']);
        } else {
            // dla całych
            $doc['quantity'] = $tmp['quantity'];
            $doc['parent_name'] = $tmp['parent_name'];
            $doc['price'] = $tmp['price'];
            $doc['part_no'] = $tmp['part_no'];
            $doc['parent_type'] = $doc_name[$tmp['parent_type']];
            $doc['parent_id'] = $tmp['parent_id'];
            $doc['date_entered'] = $tmp['date_entered'];
            $doc['product_id'] = $tmp2['id'];
            $doc['position_value'] = $doc['quantity']*$tmp['price'];
            $total_quantity+=$doc['quantity'];
            $total_value+=round($doc['quantity']*$tmp['price'],2);
            $docs[$i-1]['add'][] = $doc;
            $docs[$i-1]['total_price']+=($doc['quantity']*$tmp['price'] );
            $docs[$i-1]['total_quantity']+=($doc['quantity']);
			$docs[$i-1]['part_no'] =$tmp['part_no'];
            
        }
        if ($r->num_rows > 1) {
            $docs[$i-1]['price']='';
            $docs[$i-1]['parent_name']='';
			$doc[$i-1]['part_no'] = $tmp['part_no'];
            $docs[$i-1]['parent_type']='';
        } if ($r->num_rows < 2 ){
            $docs[$i-1]['price']=$tmp['price'];
            $doc[$i-1]['part_no'] = $tmp['part_no'];
            $docs[$i-1]['parent_id'] = $tmp['parent_id'];
            $docs[$i-1]['parent_name']=$tmp['parent_name'];
            $docs[$i-1]['date_entered'] = $tmp['date_entered'];
            $docs[$i-1]['parent_type'] = $doc_name[$tmp['parent_type']];
        }else {
        $docs[$i-1]['price']='';
            $docs[$i-1]['parent_name']='';
            $docs[$i-1]['parent_type']='';
        }
        
    }
	if( $docs[$i-1]['total_quantity']==0 && $_GET['selectShowEmpty']!='')unset($docs[$i-1]);
}
// create & execute smarty
$smarty = new Sugar_Smarty ();
global $mod_strings;
$smarty->assign ( "MOD", $mod_strings );
$smarty->assign ( "DATA", $docs );
$smarty->assign ( "TOTAL_VALUE", $total_value );
$smarty->assign ( "TOTAL_QUANTITY", $total_quantity );
$smarty->assign ( "CONSIGNMENTS",$EcmConfig['consignments']);
$smarty->assign ( "STOCKS", $datastocks );
if($_REQUEST['data']=='')$_REQUEST['data'] =date('d.m.Y');
$smarty->assign ( "date", $_REQUEST['data'] );
$smarty->assign ( "selectStock", $_GET ["selectStock"]);
$smarty->assign ( "selectProductActive", $_GET ["selectProductActive"] );
$smarty->assign ( "selectProductEol", $_GET ["selectProductEol"] );
$smarty->assign ( "selectShowEmpty", $_GET ["selectShowEmpty"] );

// Eksport do PDF
if( $_GET['toPDF'] == '1' ) {
    if( $_GET['to_xls'] == '1' ) {
        
    $header=array();
        $header[]='indeks';
        $header[]='nazwa';
        $header[]='dokument';
        $header[]='ilosc';
        $header[]='cena';
        $header[]='suma';
                       $filename='modules/Home/Files/raport_stanow_magazynowych_'.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 ($docs as $key=>$val){
            $line=array();
            $line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['product_code']))).'"""';
        
            $line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['product_name']))).'"""';
     
            $line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['parent_type'].' '.$val['parent_name']))).'"""';
           
            
            $line[]=str_replace(".",",",$val['total_quantity']);
            $line[]=str_replace(".",",",$val['price']);
            $line[]=str_replace(".",",",$val['total_price']);
             foreach ($line as $k=>$v){
             $line[$k]=iconv('UTF-8','windows-1250',$line[$k]);;
        }
            fwrite($fp, implode(";",$line).PHP_EOL);
            if(count($val['add'])>1){
                
                foreach($val['add'] as $k2=>$v2){
                    $line=array();
             $line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['product_code']))).'"""';
        
            $line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['product_name']))).'"""';
     
            $line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['parent_type'].' '.$v2['parent_name']))).'"""';
           
            $line[]=str_replace(".",",",$v2['quantity']);
            $line[]=str_replace(".",",",$v2['price']);
            $line[]=str_replace(".",",",$v2['position_price']);
             foreach ($line as $k=>$v){
               $line[$k]=iconv('UTF-8','windows-1250',$line[$k]);
        }
                    fwrite($fp, implode(";",$line).PHP_EOL);
                }
         
            }
        }
        header("Location: ". $filename);
    } else {
    $output = $smarty->fetch( 'modules/EcmReports/tpls/PDF/ReportStocksDoc.tpl' );
    include_once ("include/MPDF57/mpdf.php");
    unset($smarty);
    $p = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 25, 10, 5, 5 );
    $p->setFooter('Strona {PAGENO}  z {nbpg}');
    if( $_GET ["selectStock"]!=''){
    	$s = new EcmStock();
    	$s->retrieve($_GET ["selectStock"]);
    	$dopisek = $s->name;
    }else{
		$dopisek = 'Wszystkie';
	}
	 $EcmSysInfos = new EcmSysInfo();
    $p->SetHTMLHeader('<p style="text-align:left;font-size: 10px;">' . $EcmSysInfos->getName() . '<br> 	
Raport Magazynowy - Stany magazynowe<br>Data wydruku: '.date("d.m.Y",strtotime($_REQUEST['data'])).'<br>Magazyn: ' . $dopisek .'</p>'); 
    //$p->setTitle($mod_strings["LBL_REPORT_STOCKS_DOCS"]);
    //echo $output;
    $p->writeHTML( $output );
   
    $p->Output ();
    }
} else {
   $smarty->display ( 'modules/EcmReports/tpls/ReportStocksDoc.tpl' );
}
?>