<?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'
);
/* 
 *  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");
$docs               = array();
$i                  = 0;
$skip               = array();
$total_quantity_old = 0;
$total_value_old    = 0;

if($_GET['submit']=='Wykonaj'){
	

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;
        
    } else {
        $skip[$tmp2['id']]['start'] = 1;
    }
    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 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;
        
    } else {
        $skip[$tmp2['id']]['mid'] = 1;
    }
    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;
$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]['rozchod_q']  = 0;
        $docs[$i]['rozchod_w']  = 0;
        $docs[$i]['przychod_q'] = 0;
        $docs[$i]['przychod_w'] = 0;
    } else {
        $skip[$tmp2['id']]['end'] = 1;
    }
    while ($tmp = $db->fetchByAssoc($r)) {
    	$module=substr($tmp['parent_type'], 0, -1);
    	 
    	$doc = new $module();
    	$doc->retrieve($tmp['parent_id']);
    	if($doc->type=='correct'){
    		$docs[$i]['rozchod_w'] += (-1*$tmp['quantity'] * $tmp['price']);
    		$docs[$i]['rozchod_q'] += ($tmp['quantity']*-1);
    		$rozchod_w += ($tmp['quantity'] * $tmp['price']*-1);
    		$rozchod_q += ($tmp['quantity']*-1);
    	} else {
    		$docs[$i]['przychod_w'] += ($tmp['quantity'] * $tmp['price']);
    		$docs[$i]['przychod_q'] += ($tmp['quantity']);
    		$przychod_w += ($tmp['quantity'] * $tmp['price']);
    		;
    		$przychod_q += ($tmp['quantity']);
    	}
     
        
    }
    $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 ($tmp3 = $db->fetchByAssoc($ii)) {
            $docs[$i]['rozchod_w'] += ($tmp3['quantity'] * $tmp3['price']);
            $docs[$i]['rozchod_q'] += ($tmp3['quantity']);
            $rozchod_w += ($tmp3['quantity'] * $tmp3['price']);
            $rozchod_q += ($tmp3['quantity']);
            
        }
        
    }
    $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'];
}
foreach ($skip as $key => $id) {
    if ($skip[$key]['end'] == 1 && $skip[$key]['mid'] == 1 && $skip[$key]['start'] == 1) {
        unset($docs[$key]);
    }
}

}
// create & execute smarty
$smarty = new Sugar_Smarty();
global $mod_strings;
$smarty->assign("MOD", $mod_strings);
$smarty->assign("DATA", $docs);
$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/ReportStockNewDoc.tpl');
    
    include_once("include/MPDF57/mpdf.php");
    unset($smarty);
    if( $_GET ["selectStock"]!=''){
    	$s = new EcmStock();
    	$s->retrieve($_GET ["selectStock"]);
    	$magazyn_nazwa = $s->name;
    }else{
		$magazyn_nazwa = 'Wszystkie';
	}
    $p = new mPDF('', 'A4', null, 'helvetica', 5, 5, 23, 5, 5, 5);
    $p->setFooter('Strona {PAGENO}  z {nbpg}');
    $EcmSysInfos = new EcmSysInfo();
    $p->SetHTMLHeader('<p style="text-align:left;font-size: 10px;">' . $EcmSysInfos->getName() . '<br> 	
Raport magazynowy - Stany magazynowe za okres ' . $_GET['date_from'] . ' - ' . $_GET['date_to'] . '<br>Data wydruku: ' . date("d.m.Y") . '<br>Magazyn: ' . $magazyn_nazwa . '</p>');
    //$p->setTitle($mod_strings["LBL_REPORT_STOCKS_DOCS"]);
    //echo $output;
    
    $p->writeHTML($output);
    
    $p->Output();
} else {
    $smarty->display('modules/EcmReports/tpls/ReportStockNewDoc.tpl');
}

?>