<?php
$wh[]="1=1";
if($_GET['product_category_id'])$wh[]="product_category_id='".$_GET['product_category_id']."'";
if($_GET['product_name'])$wh[]="name like '".$_GET['product_name']."%'";
if($_GET['product_code'])$wh[]="code like '".$_GET['product_code']."%'";
if($_GET['active']){
	if($_GET['active']=="yes")$wh[]="product_active='1'";
	if($_GET['active']=="no")$wh[]="product_active='0'";
}
if($_GET['production']){
	if($_GET['production']=="yes")$wh[]="production='1'";
	if($_GET['production']=="no")$wh[]="production='0'";
}
if($_GET['end_of_line']){
	if($_GET['end_of_line']=="yes")$wh[]="end_of_line='1'";
	if($_GET['end_of_line']=="no")$wh[]="end_of_line='0'";
}
include_once("modules/EcmProductReports/vtigerConnector.php");
include_once('modules/EcmCharts/chartHelper.php');
$s=sum(2009);
include_once('modules/EcmCharts/chartHelper.php');
$s=sum(2009);
if($_GET['product_category_id'])$wh_cat=" and product_category_id='".$_GET['product_category_id']."'";
else $wh_cat="";
$w=mysql_query("select id,code,name from ecmproducts where deleted='0' and product_category_id is not null and product_active='1' ".$wh_cat);
$i=0;
$sum=0;
while($r=mysql_fetch_array($w)){
	$ss=$s[2009];

	if($ss['product_sum_'.$r['id']]-$ss['product_pur_sum_'.$r['id']]<0)$value=0;
	else $value=$ss['product_sum_'.$r['id']]-$ss['product_pur_sum_'.$r['id']];
	
	$sum+=$value;
	$ii++;
	
	$arr[]=array(
		"name"=>$r['code'],
		"name1"=>$r['name'],
		"value"=>$value,
	);
}
$arr=multisort($arr,array(array('key'=>'value','sort'=>'desc')));
$i=0;
foreach($arr as $best){
	if($best['value']>$sum/$ii)$bests[]=$best['name'];
	$i++;
}
function getSales($code){
	$sale0=0;
	$sale30=0;
	$sale90=0;
	$sale180=0;
	$qty0=0;
	$qty30=0;
	$qty90=0;
	$qty180=0;
	$ddate=date("Y-m-d",mktime()-365*24*3600);
	//echo "select l.price as price,l.quantity as quantity,e.register_date as date from ecminvoiceoutitems as l inner join ecminvoiceouts as e on l.ecminvoiceout_id=e.id where l.code='".$code."' and e.type!='correct' and e.register_date>'".$ddate."' limit 100";
	$w=mysql_query("select ecminvoiceoutitems.price as price,ecminvoiceoutitems.quantity as quantity,ecminvoiceouts.register_date as date from ecminvoiceoutitems inner join ecminvoiceouts on ecminvoiceoutitems.ecminvoiceout_id=ecminvoiceouts.id where ecminvoiceoutitems.ecmproduct_id='".$code."' and ecminvoiceouts.type!='correct' and ecminvoiceouts.register_date>'".$ddate."'");
	//$w=mysql_query("select ecmproducts_fk_list.price as price,ecmproducts_fk_list.quantity as quantity,ecmproducts_fk_list.no as no,ecmproducts_fk_list.date as date from ecmproducts_fk_list where ecmproducts_fk_list.code like '".$code."'");
	while($r=mysql_fetch_array($w)){
		$date=date("Y-m");
		$m=(int)date("m"); 
		
		$date1=date("Y-m",mktime(0,0,0,($m-1),1,date("Y")));
		$date2=date("Y-m",mktime(0,0,0,($m-2),1,date("Y")));
		$date3=date("Y-m",mktime(0,0,0,($m-3),1,date("Y")));

		$d=explode("-",$r['date']);
			
		$dd=$d[0]."-".$d[1];

		if($dd==$date){
	  		$sale0+=$r['price']*$r['quantity'];
			$qty0+=$r['quantity'];
			$aq0[$r['no']]+=$r['quantity'];
		}
		if($dd==$date1 || $dd==$date2 || $dd==$date3){
	  		$sale90+=$r['price']*$r['quantity'];
			$qty90+=$r['quantity'];
			$aq90[$r['no']]+=$r['quantity'];
		}
		//if($dd==$date1 || $dd==$date2 || $dd==$date3){
	  		$sale1+=$r['price']*$r['quantity'];
			$qty1+=$r['quantity'];
			$aq1[$r['no']]+=$r['quantity'];
		//}
	}
	 
	if($qty0>0)$SALE_AVG_PRICE0=round($sale0/$qty0,2);
	if($qty90>0)$SALE_AVG_PRICE90=round($sale90/$qty90,2);
	
	return array(
		"qty0"=>$qty0,
		"qty90"=>($qty90/3),
		"qty1"=>($qty1/12),
		"sale0"=>$sale0,
		"sale90"=>$sale90,
		"sale1"=>$sale1,
		"avg0"=>$SALE_AVG_PRICE0,
		"avg90"=>$SALE_AVG_PRICE90,
	);
}
$vc=new vtigerConnector();
if($_GET['where'])$vc->where=$_GET['where'];
if(!$_GET['start'])$vc->limit="0,".$vc->pp;
else $vc->limit=$_POST['start'].",".$vc->pp;
if($_GET['order_by'])$order_by=$_GET['order_by'];
else $order_by="name";
if($_GET['sorder'])$sorder=$_GET['sorder'];
else $sorder="desc";

$vc->getData();
$vc->getCount();
$data=$vc->data=$_SESSION['EcmProductReportsData'];

set_include_path('include/PHPExcel/');

include 'PHPExcel.php';
include 'PHPExcel/Writer/Excel2007.php';
include 'PHPExcel/IOFactory.php';

$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("E5 CRM");
$objPHPExcel->getProperties()->setLastModifiedBy("E5 CRM");
$objPHPExcel->getProperties()->setTitle("Office 2007 PRODUCTS");
$objPHPExcel->getProperties()->setSubject("Office 2007 PRODUCTS");
$objPHPExcel->getProperties()->setDescription("PRODUCTS");

$objPHPExcel->getActiveSheet()->duplicateStyleArray(
	array(
		'fill' => array(
			'type'	=> PHPExcel_Style_Fill::FILL_SOLID,
			'color'	=> array('argb' => 'FFCCFFCC')
		),
		'borders' => array(	
			'bottom'	=> array('style' => PHPExcel_Style_Border::BORDER_THIN),
			'right'		=> array('style' => PHPExcel_Style_Border::BORDER_MEDIUM)
		)
	),
	"A1:L1"
);

$alf="ABCDEFGHIJKLMNOPQRSTUVWXYZ";

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(20);

$objPHPExcel->getActiveSheet()->SetCellValue('A1','Product');
$objPHPExcel->getActiveSheet()->SetCellValue('B1','Code');
$objPHPExcel->getActiveSheet()->SetCellValue('C1','Category');
$objPHPExcel->getActiveSheet()->SetCellValue('D1','Inventory');
$objPHPExcel->getActiveSheet()->SetCellValue('E1','Ordered');
$objPHPExcel->getActiveSheet()->SetCellValue('F1','Delivery Date');
$objPHPExcel->getActiveSheet()->SetCellValue('G1','Inv+Ord');
$objPHPExcel->getActiveSheet()->SetCellValue('H1','Qty 12m');
$objPHPExcel->getActiveSheet()->SetCellValue('I1','Qty this m');
$objPHPExcel->getActiveSheet()->SetCellValue('J1','Stock m');
$objPHPExcel->getActiveSheet()->SetCellValue('K1','Pricebook');
$objPHPExcel->getActiveSheet()->SetCellValue('L1','Bestsell');

$j=0;
$w=mysql_query("select * from ecmproducts where deleted='0' and product_category_id is not null and product_active='1' and ".implode(" and ",$wh)." order by ".$order_by." ".$sorder);
while($r=mysql_fetch_array($w)){
	//if(!$_REQUEST['check'][$i])continue;
	$id=$r['id'];
	$gs=getSales($id);
	
	$inv_value=$r['ems_qty_in_stock'];
	$inv_qty=$r['ems_qty_in_stock'];
	$inv_price=$r['ems_price'];
	
	
	$deliverydate=$data[$r['code']]['deliverydate'];
	
	$_ord=0;
	$_ord+=$data[$r['code']."_S"]['quantity'];
	$_ord+=$data[$r['code']."_s"]['quantity'];
	$_ord+=$data[$r['code']]['quantity'];
	
	$objPHPExcel->getActiveSheet()->SetCellValue('A'.($j+2),$r['name']);
	$objPHPExcel->getActiveSheet()->SetCellValue('B'.($j+2),$r['code']);
	$objPHPExcel->getActiveSheet()->SetCellValue('C'.($j+2),$r['product_category_name']);
	if(in_array($r['code'],$bests))$b="B";
	else $b="";
	$objPHPExcel->getActiveSheet()->SetCellValue('D'.($j+2),$inv_value);
	$objPHPExcel->getActiveSheet()->SetCellValue('E'.($j+2),$_ord);
	$objPHPExcel->getActiveSheet()->SetCellValue('F'.($j+2),$deliverydate);
	$objPHPExcel->getActiveSheet()->SetCellValue('G'.($j+2),($inv_qty+$_ord));
	$objPHPExcel->getActiveSheet()->SetCellValue('H'.($j+2),((int)$gs['qty1']));
	$objPHPExcel->getActiveSheet()->SetCellValue('I'.($j+2),((int)$gs['qty0']));
	
	if($gs['qty1']>$gs['qty0'])$avg=$gs['qty1'];
	else $avg=$gs['qty0'];
	
	if($avg>0)$stock_m=(($inv_value+$r['ordered'])/$avg);
	else $stock_m="err";
	$objPHPExcel->getActiveSheet()->SetCellValue('J'.($j+2),$stock_m);
	//pricebook
	$accounts=array("Auchan","Carrefour","Euro","Real");
	$dig=array();
	foreach($accounts as $account){
		$www=mysql_query("select p.id from ecmpricebooks_ecmproducts as p inner join ecmpricebooks as e on e.id=p.ecmpricebook_id where p.ecmproduct_id='".$id."' and e.name='".$account."' and e.deleted='0' and p.deleted='0'");
		if(mysql_num_rows($www)>0)$dig[]=$account[0];
	}
	$objPHPExcel->getActiveSheet()->SetCellValue('K'.($j+2),implode(",",$dig));
	$objPHPExcel->getActiveSheet()->SetCellValue('L'.($j+2),$b);
	$j++;
}
	
$objPHPExcel->getActiveSheet()->setTitle('Simple');
$objPHPExcel->setActiveSheetIndex(0);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
chmod("cache/upload",0777);
$microtime=str_replace(".","",str_replace(" ","",microtime()));
$name="cache/upload/ProductReport".$microtime.".xlsx";
$objWriter->save($name);
chmod($name,0777);

header("Location: ".$name);
?>