<?php
include_once('/var/www/html/e5crm/vserver/e5crm.more7.com/www/modules/EcmCharts/chartHelper.php');
if((int)date("m")==1){
	$mmm=12;
	$year=date("Y")-1;
}
else{
	$mmm=(int)date("m")-1;
	$year=date("Y");
}
function getRotation($id){
	$ww=$GLOBALS['db']->query("select sum(value) as sum from ecmproducts_history_states where ecmproduct_id='".$id."' and ecmstock_id='c7afd71a-4c3a-bde4-138d-4acaee1644e4'");
	$rr=$GLOBALS['db']->fetchByAssoc($ww);
	$i=mysql_num_rows($GLOBALS['db']->query("select distinct date from ecmproducts_history_states"));
	$v=$rr['sum'];
	return @$v/$i;
}
function getPurchase($id){
	$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select sum(i.quantity*i.purchase_price) as sum from ecminvoiceoutitems as i inner join ecminvoiceouts as e on e.id=i.ecminvoiceout_id where e.deleted='0' and e.status='accepted' and i.deleted='0' and i.ecmproduct_id='".$id."' and e.register_date like '".date("Y")."%'"));
	return $r['sum'];
}
$w=$GLOBALS['db']->query("select id,code,name from ecmproducts where product_active='1' and deleted='0'");
while($r=$GLOBALS['db']->fetchByAssoc($w)){
	@$r['rotation']=12*(getPurchase($r['id'])/$mmm)/getRotation($r['id']);
	$row[]=$r;
}

$row=multisort($row,array(array('key'=>'rotation','sort'=>'desc')));
echo '<table>';
foreach($row as $rr){
	echo '<tr><td>'.$rr['code']."</td><td>".$rr['name']."</td><td>".number_format($rr['rotation'],2,",",".")."</td></tr>";
}
echo '</table>';
?>