<?php
function getState($id,$date){
	$who[]="deleted='0'";
	$who[]="date_entered<='".$date." 23:59:59'";
	$arr=array();
	$pp1=0;
	$q1=0;
	$ww=mysql_query("select quantity as qty,id,price from ecmstockoperations where deleted='0' and type='0' and (in_id IS NULL or in_id='') and product_id='".$id."' and (".implode(" and ",$who).")");
	while($rrr=mysql_fetch_array(($ww)){
		$www=mysql_query("select quantity from ecmstockoperations where in_id='".$rrr['id']."' and type='1' and in_id IS NOT NULL  and in_id!='' and product_id='".$id."' and (".implode(" and ",$who).") and deleted='0'");
		$rqty=0;
		while($rrp=mysql_fetch_array(($www)){
			$rqty+=$rrp['quantity'];
		}
		$qty=$rrr['qty']-$rqty;
		if($qty>0){
			$arr[]=array("qty"=>$qty,"id"=>$rrr['id'],"price"=>$rrr['price']);
		}
	}
	if(count($arr)>0){
		foreach($arr as $v){
			$q1+=$v['qty'];
			$pp1+=$v['qty']*$v['price'];
		}
	}
	$qty=$q1;
	$value=$pp1;
	@$price=$value/$qty;
	return array("qty"=>$qty,"price"=>$price);
}

$z="select id,name,code from ecmproducts where deleted='0' order by code asc";
$w=mysql_query($z);
while($r=mysql_fetch_array(($w)){
	$s=getState($r['id'],$_REQUEST['date']);
	if($s['qty']>0){
		$t.=$r['code'].','.$r['name'].','.$s['qty'].','.$s['price'].',
';
	}
}
$filename = "states.cvs";
$handle = fopen($filename, "wb");
$numbytes = fwrite($handle,$t);
fclose($handle);
?>