<?php 
$db = $GLOBALS['db'];
global $app_list_strings;

$db->query("TRUNCATE TABLE ecmstockdoccorrects");

$res = $db->query("SELECT * FROM ecmstockdoccorrectscp ORDER BY register_date DESC");

while ($r = $db->fetchByAssoc($res)) {
$q="INSERT INTO ecmstockdoccorrects VALUES (
	'".$r['id']."',	
	'".$r['name']."',	
	'".$r['description']."',	
	'".$r['date_entered']."',	
	'".$r['date_modified']."',	
	'".$r['modified_user_id']."',	
	'".$r['assigned_user_id']."',	
	'".$r['created_by']."',	
	'".$r['deleted']."',	
	'".$r['number']."',	
	'".$r['document_no']."',			
	'".$r['register_date']."',		
	'".$r['total']."',		
	'',
	'".$r['stock_to_id']."',
	'".$r['stock_from_id']."'						
);
";	
$db->query($q);

$all_total = 0;

//get products
//remove old
$db->query("DELETE FROM ecmstockdoccorrectitems WHERE ecmstockdoccorrect_id='".$r['id']."'");

$pres = $db->query("SELECT * FROM ecmstockdomoveitemscp WHERE ecmstockdoccorrect_id='".$r['id']."'");

while ($p = $db->fetchByAssoc($pres)) {
	//calculate totals
	$total = $p['price']*$p['quantity'];
	$all_total+=$total;
		
	$unit_name = $app_list_strings['ecmproducts_unit_dom'][$p['dd_unit_id']];
	
	$pq = "INSERT INTO ecmstockdoccorrectitems VALUES(
		'".$p['id']."',	
		'".$p['date_entered']."',	
		'".$p['date_modified']."',	
		'".$p['modified_user_id']."',	
		'".$p['assigned_user_id']."',	
		'".$p['created_by']."',	
		'".$p['deleted']."',	
		'".$p['ecmstockdoccorrect_id']."',	
		'".$p['ecmproduct_id']."',	
		'".$p['position']."',	
		'".$p['code']."',	
		'".$p['name']."',	
		'".$p['quantity']."',	
		'".$p['price']."',
		'$total',
		'".$p['dd_unit_id']."',
		'$unit_name',					
		'".$p['ecmproductcategory_id']."'							
	);";
	$db->query($pq);
}

//update totals
foreach ($vats as $k=>$v) {
	$vats_all = $k.':'.$v.',';
}

$db->query("UPDATE ecmstockdoccorrects SET total='$all_total' WHERE id='".$r['id']."'");
}
echo 'koniec';
