<?php 
$code = $_REQUEST['code'];

if (!$code || $code=='') die('Brak kodu');

$db = $GLOBALS['db'];

//get id
$prod = $db->fetchByAssoc($db->query("SELECT id FROM ecmproducts WHERE code='$code' AND deleted='0'"));

$product_id = $prod['id'];


if (!$product_id || $product_id=='') die ('Nie znaleziono produktu');

//get operations

$operations = $db->query("SELECT sum(quantity) as op_sum, parent_name, parent_type, type, parent_id FROM ecmstockoperations WHERE product_id='$product_id' GROUP BY parent_id");

$types = array();
while ($o = $db->fetchByAssoc($operations)) {
	//get document info
	$doc = $db->fetchByAssoc($db->query("SELECT sum(quantity) doc_sum FROM ".substr(strtolower($o['parent_type']),0,-1)."items WHERE ".substr(strtolower($o['parent_type']),0,-1)."_id='".$o['parent_id']."' AND ecmproduct_id='$product_id'"));

	if (!$types[$o['parent_type']]) {
		$types[$o['parent_type']]['op'] = $o['op_sum']; 
		$types[$o['parent_type']]['doc'] = $doc['doc_sum']; 
	} else {
		$types[$o['parent_type']]['op'] += $o['op_sum'];
		$types[$o['parent_type']]['doc'] += $doc['doc_sum'];
	}
	if (floatval($doc['doc_sum']) != floatval($o['op_sum']))
	echo $o['parent_name'].'   '.format_number($o['op_sum']).'      '.format_number($doc['doc_sum']).'<br><br>';
}

echo '<br>Sumy:<br>';
foreach ($types as $k=>$v) {
	echo '----<br>';
	echo $k.'<br>';
	echo 'Operacje: '.format_number($v['op']).'<br>';
	echo 'Dokumenty: '.format_number($v['doc']);
	echo '<br><br>';
}



