<?
$c1 = explode("|",substr($_GET['inv'],0,-1));
$c2 = explode("|",substr($_GET['pay'],0,-1));

$account_id = $_GET['account_id'];
$tot_t=0.00;
$tot_v=0.00;
for($j=0;$j<count($c1);$j++){
	if($c1[$j]){
		$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select total from ecmpayments_ecminvoiceouts where id='".$c1[$j]."'"));
		$tot_t+=$r['total'];
	}
}
for($j=0;$j<count($c2);$j++){
	if($c2[$j]){
		$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select value from ecmpayments where id='".$c2[$j]."'"));
		$tot_v+=$r['value'];
	}
}

if(round($tot_t,2)-round($tot_v,2)> abs(0.5)){
	echo "Error: totals not match, invoices: ".$tot_t.", payments: ".$tot_v;
	die();
}
else{
	for($j=0;$j<count($c1);$j++){
		if($c1[$j]) {
			$GLOBALS['db']->query("update ecmpayments_ecminvoiceouts set paid='1',payment_date='".date("Y-m-d")."' where id='".$c1[$j]."'");
			$GLOBALS['db']->query("update ecminvoiceouts as i inner join ecmpayments_ecminvoiceouts as pi on i.id=pi.ecminvoiceout_id set i.paid=pi.paid where pi.id='".$c1[$j]."'");
		}
	}
	for($j=0;$j<count($c2);$j++){
		if($c2[$j]) {
			$GLOBALS['db']->query("update ecmpayments set paid='1' where id='".$c2[$j]."'");
			$GLOBALS['db']->query("update ecminvoiceouts as i inner join ecmpayments_ecminvoiceouts as pi on i.id=pi.ecminvoiceout_id set i.paid=pi.paid where pi.id='".$c2[$j]."'");
		}
	}
	$str="";
	foreach($_POST as $k => $v){
		$str.="&".$k."=".$v;
	}
	for($j=0;$j<count($c1);$j++){
		for($i=0;$i<count($c2);$i++){
			$GLOBALS['db']->query("insert into ecmpayments_ecminvoiceouts_rel(id,ee_id,ecmpayment_id) values('".create_guid()."','".$c1[$j]."','".$c2[$i]."');");
		}
	}
	header("Location: index.php?module=EcmPaymentStates&action=index&account_id=".$account_id);
}
?>