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

$res = $db->query("SELECT p.purchase_price as price, p.vat_value, pp.id, p.srp_price, p.srp_price_eur, pr.exchange_rate_id FROM ecmpricebooks_ecmproducts as pp INNER JOIN ecmproducts AS p ON p.id=pp.ecmproduct_id INNER JOIN ecmpricebooks as pr ON pp.ecmpricebook_id=pr.id WHERE pp.ecmpricebook_id='".$_REQUEST['record']."' and pp.deleted='0'");

//echo "SELECT p.purchase_price as price, p.vat_value, pp.id, p.srp_price, p.srp_price_eur, pp.exchange_rate_id FROM ecmpricebooks_ecmproducts as pp INNER JOIN ecmproducts AS p ON p.id=pp.ecmproduct_id WHERE pp.ecmpricebook_id='".$_REQUEST['record']."' and pp.deleted='0'";


while ($row = $db->fetchByAssoc($res)) {
	if ($_REQUEST['type']=="1") {
	$price = $row['price'] * (1 + $_REQUEST['margin']/100);
	
	if (intval($_REQUEST['discount'])>0) 
		$price = $price - ($price * ($_REQUEST['discount']/100));
	
	if (isset($_REQUEST['with_tax']) && $_REQUEST['with_tax']=='on')
		$price = $price * (1 + $row['vat_value']/100);
	} 
	if ($_REQUEST['type']=="2") {
		if ($row['exchange_rate_id']=='-99')
			$price = $row['srp_price'];
		else $price = $row['srp_price_eur'];
		
		if (!isset($_REQUEST['with_tax']))
			$price = round($price * 100 / (100 + $row['vat_value']),2);
		
		if (intval($_REQUEST['discount'])>0)
			$price = $price - ($price * ($_REQUEST['discount']/100));
		
		$db->query("update ecmpricebooks set currency_value='1' where id='".$_REQUEST['record']."'");
		//echo "update ecmpricebooks set currency_value='1' where id='".$_REQUEST['record']."'"; die();
		
	}
	$db->query("UPDATE ecmpricebooks_ecmproducts SET price='".$price."' WHERE id='".$row['id']."'");
}
header("Location: index.php?module=EcmPriceBooks&action=DetailView&record=".$_REQUEST['record']."&tab=items");