<?php
function getTotal($id){
	$w=$GLOBALS['db']->query("select price,ecmvat_value,quantity from ecminvoiceoutitems where ecminvoiceout_id='".$id."' and deleted='0'");
	while($r=$GLOBALS['db']->fetchByAssoc($w))$total+=round($r['price']*$r['quantity']*(1+$r['ecmvat_value']/100),2);
	return $total;
}
function getTotalCorrect($id){
	$w=$GLOBALS['db']->query("select price,ecmvat_value,quantity,ecminvoiceoutitem_id from ecminvoiceoutitems where ecminvoiceout_id='".$id."'");
	while($r=$GLOBALS['db']->fetchByAssoc($w)){
		$total+=round($r['price']*$r['quantity'],2)+round($r['price']*$r['quantity']*$r['ecmvat_value']/100,2);
		$rr=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select price,ecmvat_value,quantity from ecminvoiceoutitems where id='".$r['ecminvoiceoutitem_id']."'"));
		$total-=(round($rr['price']*$rr['quantity'],2)+round($rr['price']*$rr['quantity']*$rr['ecmvat_value']/100,2));
	}
	return $total;
}

$arr="2432,2196,2170,2169,2168,2167,2166";
$e=explode(",",$arr);
foreach($e as $ee){
	$wh[]="document_no like 'FVKOR ".$ee."/11'";
}
$where=implode(" or ",$wh);
//$where="register_date>'2011-01-01' and paid='0' and account_id='134' and document_no like 'FVKOR %/11'";
$z="select ecminvoiceout_id,id,total,account_id,document_no from ecmpayments_ecminvoiceouts where (".$where.") and deleted='0'";
echo $z;
$w=$GLOBALS['db']->query($z);
echo mysql_error();
while($r=$GLOBALS['db']->fetchByAssoc($w)){
	$rr=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select id,type,ecminvoiceout_id,document_no,parent_id from ecminvoiceouts where document_no='".$r['document_no']."'"));
	
	if($rr['type']=="correct"){
		$total=round(getTotalCorrect($r['ecminvoiceout_id']),2);
	}
	else{
		$total=round(getTotal($r['ecminvoiceout_id']),2);
	}
	//if($rr['parent_id']==$r['account_id'] && $total==$r['total'] && $rr['id']==$r['ecminvoiceout_id'])continue;
	if($total==$r['total'] && $r['total']!=0)continue;
	echo "#".$rr['document_no']." ".$r['total']." ".$rr['id']."=".$r['ecminvoiceout_id']."<br>";
	echo "update ecmpayments_ecminvoiceouts set total='".$total."' where id='".$r['id']."';<br>";
}

?>
