<?php 
// partie
include 'EcmConfig.php';

ini_set('memory_limit','-1');
ini_set('max_execution_time','-1');
if (! defined ( 'sugarEntry' ) || ! sugarEntry)
    die ( 'Not A Valid Entry Point' );

$db = $GLOBALS['db'];
global $app_list_strings;
$doc_name=array('EcmStockDocInsideIns'=>'PW','EcmStockDocMoves'=>'MM','EcmStockDocCorrects'=>'KS','EcmStockDocIns'=>'PZ','EcmStockDocOuts'=>'WZ','EcmStockDocInsideOuts'=>'RW','EcmInvoiceOuts'=>"FK",'EcmInvoiceOuts2'=>"KF");
/* 
 *  Magazyny
 */
$datastocks = array ();
$users = array ();
$queryStocks = "SELECT
					name,
					id
					FROM ecmstocks
					where deleted= 0";
$rowsStocks = $db->query ( $queryStocks );
$s=array();
while ( $rowStocks = $db->fetchByAssoc ( $rowsStocks ) ) {
    $stocks ["name"] = $rowStocks ["name"];
    $stocks ["id"] = $rowStocks ["id"];
    $datastocks [] = $stocks;
    $s[$stocks ["id"]]['name']=$stocks ["name"];
}
if($_GET['date_from']==''){
    $_GET['date_from']=date('01.m.Y');
} else {
    $date_from=date('Y-m-d 00:00:01',strtotime($_GET['date_from']));
}
if( $_GET['date_to']==''){
    $_GET['date_to']=date('t.m.Y');
} else {
    $date_to=date('Y-m-d 23:59:59',strtotime($_GET['date_to']));
}

/*
 *  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");

//var_dump("SELECT id, name, code, unit_id FROM ecmproducts ".$where." ORDER BY name ASC");
$docs = array();
$i=0;
$total_quantity_old=0;
$total_value_old=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 type=0 AND date_entered <='".$date_from."'");
    $l = 0;
    $i=$tmp2['id'];
    if ($r->num_rows > 0) {
        $docs[$i]['unit_id']=$app_list_strings['ecmproducts_unit_dom'][$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_old']=0;
        $docs[$i]['total_price_old']=0;
        
    }
    while ($tmp = $db->fetchByAssoc($r)) {

        $ii = $db->query(
                "select * from ecmstockoperations where in_id='" . $tmp['id'] .
                "' and type=1 and date_entered <='".$date_from."'");
       
        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'] = $tmp2['id'];
           // $doc['date_entered'] = $n->register_date;
            $doc['position_value'] = $doc['quantity']*$tmp['price'];
            $total_quantity_old+=$doc['quantity'];
            $total_value_old+=round($doc['quantity']*$tmp['price'],2);
            //$docs[$i-1]['add'][] = $doc;
            $docs[$i]['total_price_old']+=($doc['quantity']*$tmp['price'] );
            $docs[$i]['total_quantity_old']+=($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'] = $n->register_date;
            $doc['product_id'] = $tmp2['id'];
            $doc['position_value'] = $doc['quantity']*$tmp['price'];
            $total_quantity_old+=$doc['quantity'];
            $total_value_old+=round($doc['quantity']*$tmp['price'],2);
           // $docs[$i-1]['add'][] = $doc;
            $docs[$i]['total_price_old']+=($doc['quantity']*$tmp['price'] );
            $docs[$i]['total_quantity_old']+=($doc['quantity']);
            
        }
       
        if ($r->num_rows > 1) {
            $docs[$i]['price']=$docs[$i]['total_price_old']/$docs[$i]['total_quantity_old'];
            $docs[$i]['parent_name']='';
            $docs[$i]['parent_type']='';
        } if ($r->num_rows < 2 ){
            $docs[$i]['price']=$tmp['price'];

            $doc[$i]['part_no'] = $tmp['part_no'];
             $docs[$i]['parent_id'] = $tmp['parent_id'];
            $docs[$i]['parent_name']=$tmp['parent_name'];
          //  $docs[$i-1]['date_entered'] = $n->register_date;
            $docs[$i]['parent_type'] = $doc_name[$tmp['parent_type']];
        }else {
         $docs[$i]['price']=$docs[$i]['total_price_old']/$docs[$i]['total_quantity_old'];
            $docs[$i]['parent_name']='';
            $docs[$i]['parent_type']='';
        }
        
    }
  if( $docs[$i]['total_quantity_old']==0 && $_GET['selectShowEmpty']!='')unset($docs[$i]);

    

}
$r1 = $db->query("select id,name,code,unit_id from ecmproducts ".$where." order by name asc");

$i=0;
$total_quantity_now=0;
$total_value_now=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 and date_entered <='".$date_to."'");
    $i=$tmp2['id'];
    $l = 0;
    if ($r->num_rows > 0) {
        $docs[$i]['unit_id']=$app_list_strings['ecmproducts_unit_dom'][$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_now']=0;
        $docs[$i]['total_price_now']=0;
        
    }
    while ($tmp = $db->fetchByAssoc($r)) {

        $ii = $db->query(
                "select * from ecmstockoperations where in_id='" . $tmp['id'] .
                "' and type=1 and date_entered <='".$date_to."'");
         
        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'] = $tmp2['id'];
            // $doc['date_entered'] = $n->register_date;
            $doc['position_value'] = $doc['quantity']*$tmp['price'];
            $total_quantity_now+=$doc['quantity'];
            $total_value_now+=round($doc['quantity']*$tmp['price'],2);
            //$docs[$i-1]['add'][] = $doc;
            $docs[$i]['total_price_now']+=($doc['quantity']*$tmp['price'] );
            $docs[$i]['total_quantity_now']+=($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'] = $n->register_date;
            $doc['product_id'] = $tmp2['id'];
            $doc['position_value'] = $doc['quantity']*$tmp['price'];
            $total_quantity_now+=$doc['quantity'];
            $total_value_now+=round($doc['quantity']*$tmp['price'],2);
            // $docs[$i-1]['add'][] = $doc;
            $docs[$i]['total_price_now']+=($doc['quantity']*$tmp['price'] );
            $docs[$i]['total_quantity_now']+=($doc['quantity']);

        }
         
        if ($r->num_rows > 1) {
            $docs[$i]['price']=$docs[$i]['total_price_now']/$docs[$i]['total_quantity_now'];
            $docs[$i]['parent_name']='';
            $docs[$i]['parent_type']='';
        } if ($r->num_rows < 2 ){
            $docs[$i]['price']=$tmp['price'];

            $doc[$i]['part_no'] = $tmp['part_no'];
            $docs[$i]['parent_id'] = $tmp['parent_id'];
            $docs[$i]['parent_name']=$tmp['parent_name'];
            //  $docs[$i-1]['date_entered'] = $n->register_date;
            $docs[$i]['parent_type'] = $doc_name[$tmp['parent_type']];
        }else {
            $docs[$i]['price']=$docs[$i]['total_price_now']/$docs[$i]['total_quantity_now'];
            $docs[$i]['parent_name']='';
            $docs[$i]['parent_type']='';
        }

    }
    if( $docs[$i]['total_quantity_now']==0 && $_GET['selectShowEmpty']!='')unset($docs[$i]);



}

$r1 = $db->query("select id,name,code,unit_id from ecmproducts ".$where." order by name asc");

$i=0;
$przychod_w=0;
$przychod_q=0;
$rozchod_q=0;
$doc=array();
$rozchod_w=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 type=0 and date_entered <='".$date_to."' and date_entered >='".$date_from."'");
    $i=$tmp2['id'];
    $l = 0;
    if ($r->num_rows > 0) {
        $docs[$i]['unit_id']=$app_list_strings['ecmproducts_unit_dom'][$tmp2['unit_id']];
        $docs[$i]['product_id']=$tmp2['id'];
        $docs[$i]['product_name']=$tmp2['name'];
        $docs[$i]['product_code']=$tmp2['code'];
        $docs[$i]['rozchod_q']=0;
        $docs[$i]['rozchod_w']=0;
        $docs[$i]['przychod_q']=0;
        $docs[$i]['przychod_w']=0;
        
    }
    while ($tmp = $db->fetchByAssoc($r)) {
    	$module=substr($tmp['parent_type'], 0, -1);
    	 
    	$doc2 = new $module();
    	$doc2->retrieve($tmp['parent_id']);
    	
        $docs[$i]['przychod_w']+=($tmp['quantity']*$tmp['price'] );
        $docs[$i]['przychod_q']+=($tmp['quantity']);
        $przychod_w+=($tmp['quantity']*$tmp['price'] );;
        $przychod_q+=($tmp['quantity']);
        if($doc2->type=='correct'){
        	$doc[$tmp['type']]['EcmInvoiceOuts2']+=($tmp['quantity']*$tmp['price'] );
        } else {
        	$doc[$tmp['type']][$tmp['parent_type']]+=($tmp['quantity']*$tmp['price'] );
        }
       

    }
    $ii = $db->query(
            "select * from ecmstockoperations where product_id='" . $tmp2['id'] .
            "' and type=1 and date_entered <='".$date_to."' ".$add_where." and date_entered >='".$date_from."'");
     
    if ($ii->num_rows > 0) {
        // licz ilość dla użytych
        $quantity_tmp = $tmp['quantity'];
        while ($tmp2 = $db->fetchByAssoc($ii)) {
            $docs[$i]['rozchod_w']+=($tmp2['quantity']*$tmp2['price'] );
            $docs[$i]['rozchod_q']+=($tmp2['quantity']);
            $rozchod_w+=($tmp2['quantity']*$tmp2['price'] );
            $rozchod_q+=($tmp2['quantity']);
            $doc[$tmp2['type']][$tmp2['parent_type']]+=($tmp2['quantity']*$tmp2['price'] );
        }
    
    }
}

// create & execute smarty
$smarty = new Sugar_Smarty ();
global $mod_strings;
$smarty->assign ( "MOD", $mod_strings );
$smarty->assign ( "DATA", $doc );
$smarty->assign ( "doc_name", $doc_name );
$smarty->assign ( "date_from", $_GET['date_from'] );
$smarty->assign ( "date_to", $_GET['date_to'] );
$smarty->assign ( "TOTAL_VALUE_OLD", $total_value_old );
$smarty->assign ( "TOTAL_QUANTITY_OLD", $total_quantity_old );
$smarty->assign ( "TOTAL_VALUE_NOW", $total_value_now );
$smarty->assign ( "TOTAL_QUANTITY_NOW", $total_quantity_now );
$smarty->assign ( "rozchod_w", $rozchod_w );
$smarty->assign ( "rozchod_q", $rozchod_q );
$smarty->assign ( "przychod_w", $przychod_w );
$smarty->assign ( "przychod_q", $przychod_q );
$smarty->assign ( "CONSIGNMENTS",$EcmConfig['consignments']);
$smarty->assign ( "STOCKS", $datastocks );
$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' ) {
    $output = $smarty->fetch( 'modules/EcmReports/tpls/PDF//Kartoteka.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}');
	$comp = new EcmSysInfo();
	$p->SetHTMLHeader('<p style="text-align:left;font-size: 10px;">'.$comp->name.'<br>
Kartoteka ruchu towarów - Podsumowanie<br>Data wydruku: '.date("d.m.Y").'<br>Stan magazynowy za okres: '.$_GET['date_from'].' - '.$_GET['date_to'].'<br>Magazyn: '.$s[$_GET ["selectStock"]]['name']. '<br>Strona {PAGENO}  z {nbpg}</p>'); 
    //$p->setTitle($mod_strings["LBL_REPORT_STOCKS_DOCS"]);
    //echo $output;
    $p->writeHTML( $output );
   
    $p->Output ();
} else {
   $smarty->display ( 'modules/EcmReports/tpls/Kartoteka.tpl' );
}

?>