<?php
function state1($stock_id,$product_id){
		echo date("Y-m-d H:i:s")."<br>";
		$q=0;
		$p=0;
		$i=0;
		$pp=0;
		$qq=0;


		$w=mysql_query("select quantity as qty,id,price from ecmstockoperations where deleted='0' and type='0' and in_id IS NULL and stock_id='".$stock_id."' and product_id='".$product_id."'");
		while($rrr=mysql_fetch_array($w)){
			$ww=mysql_query("select quantity from ecmstockoperations where in_id='".$rrr['id']."' and type='1' and in_id IS NOT NULL and stock_id='".$stock_id."' and product_id='".$product_id."' and deleted='0'");
			$rqty=0;
			while($rrp=mysql_fetch_array($ww)){
				$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'];
			}
		}
		echo $q1." ".$pp1."<br>".date("Y-m-d H:i:s")."<br><br>";
}
function state2($stock_id,$product_id){
		echo date("Y-m-d H:i:s")."<br>";
		$q=0;
		$p=0;
		$i=0;
		$pp=0;
		$qq=0;

		/*$w=$GLOBALS['db']->query("
select 
(o.quantity-oo.quantity) as qty,
o.id,
o.price 
from ecmstockoperations as o 
right outer join ecmstockoperations as oo on o.id=oo.in_id 
where 
oo.type='1' and 
oo.deleted='0' and 
o.deleted='0' and 
o.type='0' and 
o.in_id is null and 
o.stock_id='".$stock_id."' and 
o.product_id='".$product_id."'");*/
		$w=$GLOBALS['db']->query("select quantity as qty,id,price from ecmstockoperations where deleted='0' and type='0' and used=0 and in_id IS NULL and stock_id='".$stock_id."' and product_id='".$product_id."'");
		while($rrr=$GLOBALS['db']->fetchByAssoc($w)){
			$rrp=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select sum(quantity) as s from ecmstockoperations where in_id='".$rrr['id']."' and type='1' and in_id IS NOT NULL and stock_id='".$stock_id."' and product_id='".$product_id."' and deleted='0'"));
			$rqty=$rrp['s'];
			$qty=$rrr['qty']-$rqty;
			//$qty=$rrr['qty'];
			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'];
			}
		}
		echo $q1." ".$pp1."<br>".date("Y-m-d H:i:s")."<br>";
}
function sales1(){
	// if(i.ecminvoiceoutitem_id is not null,sum(i.price*i.quantity-ii.price*ii.quantity),sum(i.price*i.quantity)) a
	$w=$GLOBALS['db']->query("select 
sum(i.price*i.quantity-ii.price*ii.quantity) as sum
from ecminvoiceouts as e 
inner join (
ecminvoiceoutitems as i on e.id=i.ecminvoiceout_id 
left join ecminvoiceoutitems as ii on ii.id=i.ecminvoiceoutitem_id
)
where 
e.register_date like '2010%'");
	$r=$GLOBALS['db']->fetchByAssoc($w);
	echo $r['sum'];
}
//state1("c7afd71a-4c3a-bde4-138d-4acaee1644e4",450);
//state2("c7afd71a-4c3a-bde4-138d-4acaee1644e4","3e84b9b5-1d1f-8ff4-e187-496bc6ac51e8");
sales1();
?>