<?
error_reporting(0);
set_time_limit(999999);
include_once("modules/EcmReports/cache.php");
include_once("modules/EcmReports/form.php");
include_once("modules/EcmProductReports/vtigerConnector.php");

$vc=new vtigerConnector();
//$wc[]="purchaseorder.tracking_no!=''";
$vc->pp=99999;
$vc->where="(purchaseorder.postatus='Created' or purchaseorder.postatus='Approved' or purchaseorder.postatus='Delivered')";

$vc->getData();
$cnt=$vc->getCount();
$data=$vc->data;

$vd=$data;
function getValueByCode($data,$code,$status=""){
	$r=mysql_fetch_array(mysql_query("select conversion_rate from currencies where name like 'USD'"));
	for($i=0;$i<count($data);$i++){
		if($data[$i]['productcode']==$code || $data[$i]['productcode']==$code."_S"){
			if($status){
				if($status==$data[$i]['postatus'])$value+=$r['conversion_rate']*$data[$i]['quantity']*$data[$i]['listprice']/0.8;
			}
			else $value+=$r['conversion_rate']*$data[$i]['quantity']*$data[$i]['listprice']/0.8;
		}
	}
	return $value;
}
function getSumLast($account_id,$product_active){
	$wh[]="e.register_date>'".date("Y-m-d",mktime()-12*30*24*3600)."'";
	$wh[]="e.deleted='0'";
	$wh[]="i.deleted='0'";
	$wh[]="p.deleted='0'";
	$wh[]="e.status='accepted'";
	if($account_id)$wh[]="(e.parent_id='".$account_id."' or w.parent_id='".$account_id."')";
	if($product_active && $product_active=="active")$wh[]="p.product_active='1'";
	elseif($product_active && $product_active=="inactive")$wh[]="p.product_active='0'";
	elseif($product_active && $product_active=="inactive")$wh=" and p.product_active='0'";
	
	$w=mysql_query("select i.purchase_price,i.quantity,i.ecmproduct_id,p.product_category_id from ecminvoiceoutitems as i inner join ecminvoiceouts as e on e.id=i.ecminvoiceout_id inner join ecmproducts as p on i.ecmproduct_id=p.id where ".implode(" and ",$wh));
	while($r=mysql_fetch_array($w)){
		$arr[$r['product_category_id']]+=$r['purchase_price']*$r['quantity'];
		$arr[$r['ecmproduct_id']]+=$r['purchase_price']*$r['quantity'];
	}
	return $arr;
}

echo '<script language="javascript" src="modules/EcmProducts/helper.js"></script>';
echo '<script language="javascript" src="modules/EcmProducts/mintajax.js"></script>';

echo $tbs1;
echo $trs;
echo '<td valign="top">';

echo $tbs2;
echo $trs;
echo $tds11."Name".$tde1;
echo $tds12."Inv qty".$tde1;
echo $tds13."Inv value".$tde1;
echo $tds13."Ord value".$tde1;
echo $tds13."Ord on sea value".$tde1;
echo $tds13."Ord approved value".$tde1;
echo $tds13."Ord created value".$tde1;
echo $tds13."Pur 12m".$tde1;
echo $tds13."Stock m".$tde1;
echo $tds13."Stock m + ord".$tde1;
echo $tds13."CBM".$tde1;
echo $tre;

if($_GET['category'])$cw=" and id='".$_GET['category']."'";
else $cw="";
$z="select name,id from ecmproductcategories where deleted='0'".$cw." order by name";
$w=$GLOBALS['db']->query($z);


$as=sum($year,$_REQUEST['account'],"","",$_REQUEST['active']);
$last=getSumLast($_REQUEST['account'],$_REQUEST['active']);

while($r=$GLOBALS['db']->fetchByAssoc($w)){
	
	$ems_qty_in_stock=0;
	$stock_value=0;
	$order_value=0;
	$order_created_value=0;
	$order_approved_value=0;
	$order_delivered_value=0;
	$cbm=0;
	if($_GET['category']==$r['id']){
		$catd="";
		$imgd="basic";
	}
	else {
		$catd="none;";
		$imgd="advanced";
	}
	

	echo $trs.$tds_cat.'<strong>'.$r['name'].'&nbsp;<a style="cursor:pointer;color: #000000;text-decoration:none;" onclick="openCat1(\''.$r['id'].'\',\''.$_REQUEST['account'].'\','.$mmm.',\''.$year.'\',\''.$_REQUEST['active'].'\')"><img id="img'.$r['id'].'" src="themes/Sugar/images/'.$imgd.'_search.gif" border="0"/></a></strong>'.$tde_cat;
	
	$act="";
	if($_REQUEST['active']=="active")$act=" and product_active='1'";
	elseif($_REQUEST['active']=="active")$act=" and product_active='0'";
	$zz="select ems_qty_in_stock,ems_price,carton_volume_meter as cvm,pieces_per_carton as ppc,code from ecmproducts where product_category_id='".$r['id']."' and deleted='0'".$act;
	$ww=$GLOBALS['db']->query($zz);
	while($rr=$GLOBALS['db']->fetchByAssoc($ww)){
		$ems_qty_in_stock+=$rr['ems_qty_in_stock'];
		$stock_value+=$rr['ems_qty_in_stock']*$rr['ems_price'];
		@$cbm+=$rr['ems_qty_in_stock']*($rr['cvm']/$rr['ppc']);
		$order_value+=getValueByCode($vd,$rr['code']);
		$order_created_value+=getValueByCode($vd,$rr['code'],"Created");
		$order_approved_value+=getValueByCode($vd,$rr['code'],"Approved");
		$order_delivered_value+=getValueByCode($vd,$rr['code'],"Delivered");
	}
	
	$cbm_total+=$cbm;
	$ems_qty_in_stock_total+=$ems_qty_in_stock;
	$stock_value_total+=$stock_value;
	$order_value_total+=$order_value;
	$order_created_value_total+=$order_created_value;
	$order_approved_value_total+=$order_approved_value;
	$order_delivered_value_total+=$order_delivered_value;
	
	
	
	$sumy=getSum($as,$year,"",$r['id']);
	
	$tot_pur+=$sumy['total_purchase'];
	$stock_m=0;
	$stock_m_order=0;
	if($sumy['total_purchase'])$stock_m=@$stock_value/($last[$r['id']]/12);
	if($sumy['total_purchase'])$stock_m_order=@($stock_value+$order_value)/($last[$r['id']]/12);
	
	$stock_m_total+=$stock_m;
	$stock_m_order_total+=$stock_m_order;
	$pur12m+=$last[$r['id']];
	echo $tds_cat.'<strong>'.$ems_qty_in_stock.'</strong>'.$tde_cat;
	echo $tds_cat.'<strong>'.number_format($stock_value,0,",",".").'</strong>'.$tde_cat;
	echo $tds_cat.'<strong>'.number_format($order_value,0,",",".").'</strong>'.$tde_cat;
	echo $tds_cat.'<strong>'.number_format($order_delivered_value,0,",",".").'</strong>'.$tde_cat;
	echo $tds_cat.'<strong>'.number_format($order_approved_value,0,",",".").'</strong>'.$tde_cat;
	echo $tds_cat.'<strong>'.number_format($order_created_value,0,",",".").'</strong>'.$tde_cat;
	echo $tds_cat.'<strong>'.number_format($last[$r['id']]/12,0,",",".").'</strong>'.$tde_cat;
	echo $tds_cat.'<strong>'.number_format($stock_m,0,",",".").'</strong>'.$tde_cat;
	echo $tds_cat.'<strong>'.number_format($stock_m_order,0,",",".").'</strong>'.$tde_cat;
	echo $tds_cat.'<strong>'.number_format($cbm,0,",",".").'</strong>'.$tde_cat;
	echo $tre;
	
	echo '<tbody id="cat'.$r['id'].'" style="display:'.$catd.'">';
	$zz="select id,name,code,ems_qty_in_stock,ems_price,carton_volume_meter as cvm,pieces_per_carton as ppc from ecmproducts where product_category_id='".$r['id']."' and deleted='0'".$act." order by code asc";
	$ww=$GLOBALS['db']->query($zz);
	while($rr=$GLOBALS['db']->fetchByAssoc($ww)){
		$sumy=getSum($as,$year,$rr['id'],"");
		$stock_m=0;
		$stock_m_order=0;
		$o_value=0;
		$o_value+=getValueByCode($vd,$rr['code']);
		$o_c_value=0;
		$o_c_value+=getValueByCode($vd,$rr['code'],"Created");
		$o_a_value=0;
		$o_a_value+=getValueByCode($vd,$rr['code'],"Approved");
		$o_d_value=0;
		$o_d_value+=getValueByCode($vd,$rr['code'],"Delivered");
		if($sumy['total_purchase'])$stock_m=@($rr['ems_qty_in_stock']*$rr['ems_price'])/($last[$rr['id']]/12);
		if($sumy['total_purchase'])$stock_m_order=@(($rr['ems_qty_in_stock']*$rr['ems_price'])+$o_value)/($last[$rr['id']]/12);
		echo $trs;
		echo '<td class="oddListRowS1" nowrap><div style="width:180px;overflow:hidden;">'.'<a href="index.php?module=EcmProducts&action=DetailView&record='.$rr['id'].'">'.$rr['code'].' '.$rr['name'].'</div>'.$tde;
		echo '<td class="oddListRowS1" nowrap>'.$rr['ems_qty_in_stock'].$tde;
		echo '<td class="oddListRowS1" nowrap>'.number_format(($rr['ems_qty_in_stock']*$rr['ems_price']),0,",",".").$tde;
		echo '<td class="oddListRowS1" nowrap>'.number_format($o_value,0,",",".").$tde;
		echo '<td class="oddListRowS1" nowrap>'.number_format($o_c_value,0,",",".").$tde;
		echo '<td class="oddListRowS1" nowrap>'.number_format($o_a_value,0,",",".").$tde;
		echo '<td class="oddListRowS1" nowrap>'.number_format($o_d_value,0,",",".").$tde;
		echo '<td class="oddListRowS1" nowrap>'.number_format($last[$rr['id']]/12,0,",",".").$tde;
		echo '<td class="oddListRowS1" nowrap>'.number_format($stock_m,0,",",".").$tde;
		echo '<td class="oddListRowS1" nowrap>'.number_format($stock_m_order,0,",",".").$tde;
		echo '<td class="oddListRowS1" nowrap>'.@number_format(($rr['ems_qty_in_stock']*($rr['cvm']/$rr['ppc'])),0,",",".").$tde;
		echo $tre;
	}
	echo '</tbody>';
}
echo $trs;
echo '<td class="oddListRowS1" nowrap>'.$tde;
echo '<td class="oddListRowS1" nowrap>'.$ems_qty_in_stock_total.$tde;
echo '<td class="oddListRowS1" nowrap>'.number_format(($stock_value_total),0,",",".").$tde;
echo '<td class="oddListRowS1" nowrap>'.number_format(($order_value_total),0,",",".").$tde;
echo '<td class="oddListRowS1" nowrap>'.number_format(($order_delivered_value_total),0,",",".").$tde;
echo '<td class="oddListRowS1" nowrap>'.number_format(($order_approved_value_total),0,",",".").$tde;
echo '<td class="oddListRowS1" nowrap>'.number_format(($order_created_value_total),0,",",".").$tde;
echo '<td class="oddListRowS1" nowrap>'.number_format($pur12m/12,0,",",".").$tde;
echo '<td class="oddListRowS1" nowrap>'.number_format(($stock_value_total/($pur12m/12)),0,",",".").$tde;
echo '<td class="oddListRowS1" nowrap>'.number_format((($stock_value_total+$order_value_total)/($pur12m/12)),0,",",".").$tde;
echo '<td class="oddListRowS1" nowrap>'.@number_format(($cbm_total),0,",",".").$tde;
echo $tre;
echo $tbe;
//end 1 column
echo $tde;
echo '<td valign="top"><div id="plist" style="overflow: auto; width: 700px;">';

//start 2 column
echo $tbs;
echo $trs;
for($i=0;$i<count($months);$i++){
	echo $tds4.$months_names[$months[$i]]." ".$year.$tde;
}
echo $tds4.$year.$tde4;
echo $trs;
for($i=0;$i<count($months);$i++){
	echo $tds22."Qty".$tde;
	echo $tds22."Avg qty".$tde;
	echo $tds22."Sales".$tde;
	echo $tds22."Avg sales".$tde;
	echo $tds22."Purchase".$tde;
	echo $tds22."Avg purchase".$tde;
	echo $tds22."Margin".$tde;
	echo $tds22."CBM".$tde;
	echo $tds22."Pred. sales".$tde;
	echo $tds22."Pred. qty".$tde;
}
echo $tds22."Qty".$tde;
echo $tds22."Avg qty".$tde;
echo $tds22."Sales".$tde;
echo $tds22."Avg sales".$tde;
echo $tds22."Purchase".$tde;
echo $tds22."Avg purchase".$tde;
echo $tds22."Margin".$tde;
echo $tds22."CBM".$tde;
echo $tds22."Pred. sales".$tde;
echo $tds22."Pred. qty".$tde;
echo $tre;

$z="select name,id from ecmproductcategories where deleted='0'".$cw." order by name";
$w=$GLOBALS['db']->query($z);
while($r=$GLOBALS['db']->fetchByAssoc($w)){
	echo $trs_cat;
	
	$avg_cat=0;
	$avg_cat_qty=0;
	$avg_cat_pur=0;
	$sumy=getSum($as,$year,"",$r['id']);
	
	$avg_cat+=$sumy["total"];
	$summary_avg_cat+=$sumy['total'];
	$avg_cat_pur+=$sumy["total_purchase"];
	$summary_avg_cat_pur+=$sumy['total_purchase'];
	$avg_cat_qty+=$sumy["qty"];
	$summary_avg_cat_qty+=$sumy['qty'];

	for($i=0;$i<count($months);$i++){
		$sum=getSum($as,$year."-".$months[$i],"",$r['id']);		
		$cat=$sum["total"];
		$cat_pur=$sum["total_purchase"];
		$cat_qty=$sum["qty"];
		$cbm=$sum["cbm"];
		
		if($cat)$margin=100*($cat-$cat_pur)/$cat;
		else $margin=0;
		
		if(!$cat)$cat=number_format(0,2,"",".");
		
		$rvs=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select value from ecmsalesreports_predictions_cat where account_id='".$_REQUEST['account']."' and year='".$year."' and month='".$i."' and bean_id='".$r['id']."' and type='sale'"));
		$rvq=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select value from ecmsalesreports_predictions_cat where account_id='".$_REQUEST['account']."' and year='".$year."' and month='".$i."' and bean_id='".$r['id']."' and type='qty'"));
		
		if($rvs['value']<=0)$rvs['value']=$avg_cat/$mmm;
		if($rvq['value']<=0)$rvq['value']=$avg_cat_qty/$mmm;
		
		$ajax_cat=ajaxWindow($r['id'],$i,$rvs['value'],$_REQUEST['account'],"sale",$year);
		@$ajax_cat_qty=ajaxWindow($r['id'],$i,$rvq['value'],$_REQUEST['account'],"qty",$year,($avg_cat/$avg_cat_qty));
		
		$summary['total'][$year."-".$months[$i]]+=$cat;
		$summary['total_purchase'][$year."-".$months[$i]]+=$cat_pur;
		$summary['total_qty'][$year."-".$months[$i]]+=$cat_qty;
		$summary['total_cbm'][$year."-".$months[$i]]+=$cbm;
		
		$summary['total'][$year]+=$cat;
		$summary['total_purchase'][$year]+=$cat_pur;
		$summary['total_qty'][$year]+=$cat_qty;
		$summary['total_cbm'][$year]+=$cbm;
		
		echo $tdsf1.'<strong>'.number_format($cat_qty,0,"","").'</strong>'.$tde;
		echo $tdsf2.'<strong>'.number_format($avg_cat_qty/$mmm,0,"","").'</strong>'.$tde;
		echo $tdsf2.'<strong>'.number_format($cat,0,",",".").'</strong>'.$tde;
		echo $tdsf2.'<strong>'.number_format($avg_cat/$mmm,0,",",".").'</strong>'.$tde;
		echo $tdsf2.'<strong>'.number_format($cat_pur,0,",",".").'</strong>'.$tde;
		echo $tdsf2.'<strong>'.number_format($avg_cat_pur/$mmm,2,",",".").'</strong>'.$tde;
		echo $tdsf2.'<strong>'.number_format($margin,0,",",".")."%".'</strong>'.$tde;
		echo $tdsf2.'<strong>'.number_format($cbm,0,",",".").'</strong>'.$tde;
		echo $tdsf2.'<strong>'.$ajax_cat.'</strong>'.$tde;
		echo $tdsf3.'<strong>'.$ajax_cat_qty.'</strong>'.$tde;
	}
	
	if($sumy["total_purchase"])$margin=100*($sumy["total"]-$sumy["total_purchase"])/$sumy["total"];
	else $margin=0;
	
	$cbm=$sumy["cbm"];
	
	echo $tdsfs1.'<strong>'.number_format(($sumy["qty"]),0,"","").'</strong>'.$tde;
	echo $tdsfs2.'<strong>'.number_format($avg_cat_qty/$mmm,0,"","").'</strong>'.$tde;
	echo $tdsfs2.'<strong>'.number_format($sumy["total"],0,",",".").'</strong>'.$tde;
	echo $tdsfs2.'<strong>'.number_format($avg_cat/$mmm,0,",",".").'</strong>'.$tde;
	echo $tdsfs2.'<strong>'.number_format($sumy["total_purchase"],0,",",".").'</strong>'.$tde;
	echo $tdsfs2.'<strong>'.number_format($avg_cat_pur/$mmm,0,",",".").'</strong>'.$tde;
	echo $tdsfs2.'<strong>'.number_format($margin,0,",",".").'%</strong>'.$tde;
	echo $tdsfs2.'<strong>'.number_format($cbm,0,",",".").'</strong>'.$tde;
	echo $tdsfs2.'<strong>'.number_format($avg_cat/$mmm,0,",",".").'</strong>'.$tde;
	echo $tdsfs2.'<strong>'.number_format($avg_cat_qty/$mmm,0,"","").'</strong>'.$tde;
	
	echo $tre;
	
	if($_GET['category']==$r['id'])$catd="";
	else $catd="none;";
	echo '<tbody id="catp'.$r['id'].'" style="display:'.$catd.'">';
	echo '</tbody>';
}
echo $trs_cat;
	

$avg_cat=0;
$avg_cat_qty=0;
	


for($i=0;$i<count($months);$i++){		
	$cat=$summary['total'][$year."-".$months[$i]];
	$cat_pur=$summary['total_purchase'][$year."-".$months[$i]];
	$cat_qty=$summary['total_qty'][$year."-".$months[$i]];
	$cbm=$summary['total_cbm'][$year."-".$months[$i]];
	
	if($cat_pur)$margin=100*($cat-$cat_pur)/$cat;
	else $margin=0;
	
	$pred_cat=sumCat($year,$i,$_REQUEST['account'],"sale");
	$pred_cat_qty=sumCat($year,$i,$_REQUEST['account'],"qty");
	if(!$pred_cat)$pred_cat=$summary_avg_cat/$mmm;
	if(!$pred_cat_qty)$pred_cat_qty=$summary_avg_cat_qty/$mmm;
	
	$summary_pred_cat+=$pred_cat;
	$summary_pred_cat_qty+=$pred_cat_qty;
	
	if(!$cat)$cat=number_format(0,2,",",".");
	
	echo $tdsfs1.number_format($cat_qty,0,"","").$tde;
	echo $tdsfs2.number_format($summary_avg_cat_qty/$mmm,0,"","").$tde;
	echo $tdsfs2.number_format($cat,0,",",".").$tde;
	echo $tdsfs2.number_format($summary_avg_cat/$mmm,0,",",".").$tde;
	echo $tdsfs2.number_format($cat_pur,0,",",".").$tde;
	echo $tdsfs2.number_format($summary_avg_cat_pur/$mmm,0,",",".").$tde;
	echo $tdsfs2.number_format($margin,0,",",".")."%".$tde;
	echo $tdsfs2.number_format($cbm,0,",",".").$tde;
	echo $tdsfs2.number_format($pred_cat,0,",",".").$tde;
	echo $tdsfs2.number_format($pred_cat_qty,0,"","").$tde;
}
	
$sa=$summary['total'][$year];
$sa_pur=$summary['total_purchase'][$year];

if($sa_pur)$margin=100*($sa-$sa_pur)/$sa;
else $margin=0;
		
if(!$sa)$sa=number_format(0,2,",",".");
		
echo $tdsfs1.number_format(($summary['total_qty'][$year]/$mmm),0,"","").$tde;
echo $tdsfs2.number_format($summary['total_qty'][$year]/$mmm,0,"","").$tde;
echo $tdsfs2.number_format($sa,0,",",".").$tde;
echo $tdsfs2.number_format($sa/$mmm,0,",",".").$tde;
echo $tdsfs2.number_format($sa_pur,0,",",".").$tde;
echo $tdsfs2.number_format($sa_pur/$mmm,0,",",".").$tde;
echo $tdsfs2.number_format($margin,0,",",".")."%".$tde;
echo $tdsfs2.number_format($summary['total_cbm'][$year],0,",",".").$tde;
echo $tdsfs2.number_format($summary_pred_cat,0,",",".").$tde;
echo $tdsfs2.number_format($summary_pred_cat_qty,0,"","").$tde;

echo $tbe;
//end 2 column
echo '</div>'.$tde;
echo $tre;
echo $tbe;
?>