<?php
ini_set('display_errors', 0);
set_time_limit(999999999);
ini_set('memory_limit', '-1');

include_once("class.dbf.php");
include_once("../../config.php");
include_once("helper.php");
global $sugar_config;

//Tworzenie polaczenia z baza 
echo '************************************************<br>Ustawianie polaczenia z baza...<br>';
$mysqli = new mysqli($sugar_config['dbconfig']['db_host_name'], $sugar_config['dbconfig']['db_user_name'], $sugar_config['dbconfig']['db_password'], $sugar_config['dbconfig']['db_name']);
if(mysqli_connect_errno()){
	echo 'Nie nawiazano polaczenia z baza...<br>';
	exit($mysqli->error);
}else{
	echo 'Ustawiono polaczenie z baza na serwerze ' . $sugar_config['dbconfig']['db_host_name'] . ' uzywajac loginu: '. $sugar_config['dbconfig']['db_user_name'] . ' i domyslna baza to: '.$sugar_config['dbconfig']['db_name'] . '<br>';
}

if ($mysqli->set_charset("utf8")) {
    echo 'Ustawiono kodowanie: ' . $mysqli->get_charset()->charset . '<br>';
} else {
	echo "Blad w ustawianiu kodowania utf8<br>";
	$mysqli->close();
    exit($mysqli->error);
}
echo 'Zakonczono ustanawianie polaczenia z baza<br>************************************************<br><br>';

function microtime_float(){
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}


$result = $mysqli->query('SELECT id FROM ecminvoiceouts WHERE sys_number IS NOT NULL');

while($row = $result->fetch_array(MYSQLI_ASSOC)){
	$query = 'SELECT ecmvat_name, ecmvat_value, ROUND(SUM(total_netto),2) as netto, ROUND(SUM(total_brutto),2) as brutto, ROUND(SUM(total_vat),2) as vat FROM ecminvoiceoutitems WHERE ecminvoiceout_id = "'. $row['id'].'" GROUP BY ecmvat_name';
	
	$vats_summary = '';
	$re = $mysqli->query($query);
	while($r = $re->fetch_array(MYSQLI_ASSOC)){
		$vats_summary .= $r['ecmvat_name'] .':'. $r['netto'] . ':'. $r['vat']. ':'. $r['brutto'] .',';
	}
	$updatequery = 'UPDATE ecminvoiceouts SET vats_summary="' . $vats_summary .'" where id="'.$row['id'] .'"';
	
	$mysqli->query($updatequery);
}
$mysqli->close();
exit();