<?php 

$id='84c9b4cd-feb9-3470-d9b5-5655a6b272c6';
function calculateCorrectTotals($id) {
    $vats_summary = '';
    $total_netto = 0;
    $total_brutto = 0;
    $total_vat = 0;
    $vats=array();
    $res = $GLOBALS ['db']->query ( "select
	total_netto,ecmvat_id,ecmvat_value,ecmvat_name
 from ecminvoiceoutitems n
where
    n.ecminvoiceout_id = '".$id."'" );
    while ( $cc = $GLOBALS ['db']->fetchByAssoc ( $res ) ) {
        $vats[$cc['ecmvat_id']]['jest']['total_netto']+=$cc['total_netto'];
        $vats[$cc['ecmvat_id']]['ecmvat_value']=$cc['ecmvat_value'];
        $vats[$cc['ecmvat_id']]['ecmvat_name']=$cc['ecmvat_name'];
    }
    $res = $GLOBALS ['db']->query (" select
	n.total_netto,n.ecmvat_id,n.ecmvat_value,n.ecmvat_name
 from ecminvoiceoutitems n
inner join ecminvoiceoutitems o on o.old_ecminvoiceoutitem_id=n.id
where
    o.ecminvoiceout_id = '".$id."'" );

    while ( $cc = $GLOBALS ['db']->fetchByAssoc ( $res ) ) {
        $vats[$cc['ecmvat_id']]['bylo']['total_netto']+=$cc['total_netto'];
        $vats[$cc['ecmvat_id']]['ecmvat_value']=$cc['ecmvat_value'];
        $vats[$cc['ecmvat_id']]['ecmvat_name']=$cc['ecmvat_name'];
    }
    $vats_now=array();

    foreach ($vats as $key=>$val){
        if($vats[$key]['jest']['total_netto']==''){
            $vats[$key]['jest']['total_netto']=0;
        }
        if($vats[$key]['bylo']['total_netto']==''){
            $vats[$key]['bylo']['total_netto']=0;
        }
        $total_netto+=$vats[$key]['jest']['total_netto']-$vats[$key]['bylo']['total_netto'];
        $total_vat+=(($vats[$key]['jest']['total_netto']-$vats[$key]['bylo']['total_netto'])*$vats[$key]['ecmvat_value'])/100;
        $total_brutto+=((($vats[$key]['jest']['total_netto']-$vats[$key]['bylo']['total_netto'])*$vats[$key]['ecmvat_value'])/100)+($vats[$key]['jest']['total_netto']-$vats[$key]['bylo']['total_netto']);
        $vats_summary .= $vats[$key]['ecmvat_name'] . ':' .round($vats[$key]['jest']['total_netto']-$vats[$key]['bylo']['total_netto'],2)
        . ':' . round((($vats[$key]['jest']['total_netto']-$vats[$key]['bylo']['total_netto'])*$vats[$key]['ecmvat_value'])/100,2). ':'
                . round(((($vats[$key]['jest']['total_netto']-$vats[$key]['bylo']['total_netto'])*$vats[$key]['ecmvat_value'])/100)+($vats[$key]['jest']['total_netto']-$vats[$key]['bylo']['total_netto']),2) . ',';

    }
    echo $vats_summary;
    $res = $GLOBALS ['db']->query ( "update ecminvoiceouts set vats_summary='" . $vats_summary . "',total_netto='" . round($total_netto,2) . "',total_vat='" . round($total_vat,2) . "',
	           total_brutto='" . round($total_brutto,2) . "' where id='" . $id . "'" );
    return round($total_brutto,2);

}
calculateCorrectTotals($id);

?>