<?
	header("Content-Type: text/html; charset=utf-8");
	
	$g_path = '../../my/';
	
	include $g_path."u_globals.php";
	include $g_path."html/f.php";
	include $g_path."u_spoj_na_bazu.php";
	
	//include $g_path."u_headers.php";
	
	
	
	// proknjizi
	if($_GET['type'] == 2){
		$l_posted = get_item('select posted from medjus where id = '.$_GET['id']);
		if($l_posted == 0){
			
			$l_sql = 'select product_items.article_id, sum(medju_items.kolicina * product_items.amount) as amount '.
					' from medju_items, products, product_items, articles '.
					' where medju_items.product_id = products.id '.
					' and products.id = product_items.product_id '.
					' and product_items.article_id = articles.id '.
					' and medju_items.medju_id = '.$_GET['id'].
					' group by product_items.article_id '.
					' order by product_items.article_id';
					
			$x = get_data($l_sql, 1);
			for($i = 0; $i < sizeof($x['article_id']); $i++){
				$l_sql2 = 'select amount, price_buy from articles where id = '.$x['article_id'][$i];
				$y = get_data($l_sql2, 0);
				
				$l_kol_z = $y['amount'];
				$l_kol_p = $x['amount'][$i];
				
				$l_sql3 = 'update articles '.
					'set amount = '.($l_kol_z - $l_kol_p).' '.
					' where id = '.$x['article_id'][$i];
				sql_exe($l_sql3);
			}
			
			$l_sql = 'update medjus set posted = 1 where id = '.$_GET['id'];
			sql_exe($l_sql);
		}
	}
	
	
	// otknjizi
	if($_GET['type'] == 1){
		$l_posted = get_item('select posted from medjus where id = '.$_GET['id']);
		if($l_posted == 1){
			
			$l_sql = 'select product_items.article_id, sum(medju_items.kolicina * product_items.amount) as amount '.
					' from medju_items, products, product_items, articles '.
					' where medju_items.product_id = products.id '.
					' and products.id = product_items.product_id '.
					' and product_items.article_id = articles.id '.
					' and medju_items.medju_id = '.$_GET['id'].
					' group by product_items.article_id '.
					' order by product_items.article_id';
			$x = get_data($l_sql, 1);
			for($i = 0; $i < sizeof($x['article_id']); $i++){
				$l_sql2 = 'select amount, price_buy from articles where id = '.$x['article_id'][$i];
				$y = get_data($l_sql2, 0);
				
				$l_kol_z = $y['amount'];
				$l_kol_p = $x['amount'][$i];
				
				$l_sql3 = 'update articles '.
					'set amount = '.($l_kol_z + $l_kol_p).
					' where id = '.$x['article_id'][$i];
				sql_exe($l_sql3);
			}
			
			$l_sql = 'update medjus set posted = 0 where id = '.$_GET['id'];
			sql_exe($l_sql);
		}
	}
	
	
	print '1';
?>
