<?php
include_once("class.dbf.php");
include_once("/var/www/crm/config.php");
include_once("helper.php");
global $sugar_config;
$sql=mysql_connect($sugar_config['dbconfig']['db_host_name'],$sugar_config['dbconfig']['db_user_name'],$sugar_config['dbconfig']['db_password']);
mysql_select_db($sugar_config['dbconfig']['db_name']);

mysql_query("truncate table accounts_discounts");
mysql_query("set character set utf8;"); 

$path = dirname(__FILE__).'/_odb_rab.dbf';
$dbfp = new dbf_class($path);

$num_recp=$dbfp->dbf_num_rec;

$j = 0;

$discounts = array();

for ($i=0; $i<$num_recp;$i++) {
	$rowp=$dbfp->getRowAssoc($i);


	if (intval($rowp['UPUST'])==0 && ($rowp['KOD_CENY']=='' || $rowp['KOD_CENY']=='0')) continue;
	if (trim($rowp['WSKAZ'])=='*') $is_group=0; else $is_group=1; 


	if (!isset($discounts[$rowp['NR_EWIDENC']]))
		$discounts[$rowp['NR_EWIDENC']] = array();
		
	$discounts[$rowp['NR_EWIDENC']][$rowp['GRUPA']] = array();
	$discounts[$rowp['NR_EWIDENC']][$rowp['GRUPA']][0] = floatval($rowp['UPUST']);
	$discounts[$rowp['NR_EWIDENC']][$rowp['GRUPA']][1] = $is_group;
	
	//get pricebook_id
	$pp = mysql_fetch_assoc(mysql_query("SELECT id FROM ecmpricebooks WHERE index_dbf='".trim($rowp['KOD_CENY'])."'"));
	if ($pp)
		$pricebook_id = $pp['id'];
	else
		$pricebook_id='';
		
	$discounts[$rowp['NR_EWIDENC']][$rowp['GRUPA']][2] = $pricebook_id;
	
}

foreach ($discounts as $k=>$v) {
	foreach ($v as $kk=>$vv) {
		$id = create_guid();
		$query="INSERT INTO accounts_discounts VALUES ('$id','".$k."','".addslashes($kk)."','".$vv[1]."', '".$vv[0]."','".$vv[2]."')";

		mysql_query(ch($query));
		if (mysql_error()) echo 'Database error: '.mysql_error();
	}
}
return;
	//insert
	$id = create_guid();
	$query="INSERT INTO accounts_discounts VALUES ('$id','".$rowp['NR_EWIDENC']."','".addslashes($rowp['GRUPA'])."','$is_group', '".intval($rowp['UPUST'])."')";
	mysql_query(ch($query));
	if (mysql_error()) echo 'Database error: '.mysql_error();

?>