<?php
ini_set('display_errors',0); 
set_time_limit(9999999999);
ini_set('memory_limit', '-1');
include_once("class.dbf.php");
include_once("../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_query("set character set utf8;"); 
mysql_query("truncate table ecminvoiceouts");
mysql_query("truncate table ecminvoiceoutitems");



function getmicrotime(){ 
list($usec, $sec) = explode(" ",microtime()); 
return ((float)$usec + (float)$sec); 
}
function getnr($nr_sys){
	//echo $nr_sys;
	$dbfi = new dbf_class('dbf/_INDEKSY.DBF');
	$num_rec=$dbfi->dbf_num_rec;
	for($i=0;$i<$num_rec;$i++){
		$indeks=$dbfi->getRowAssoc($i);
		
		//echo $indeks['INDEKS']."\r\n";
		if ($indeks['INDEKS']==$nr_sys) 
		{
		//echo $indeks['INDEKS'];
		return ch($indeks['NR_SYSTEM']);
		}
	}
		return 'BRAK INDEKSU';
}

function addFk($row,$i,$stock_id){

	$r=mysql_fetch_array(mysql_query("select id,name from ekomer.accounts where index_dbf2 = '".trim($row['INDEKS_KON'])."' and deleted='0'"));
	$r2=mysql_fetch_array(mysql_query("select id,name from ekomer.ecminvoiceouts where name like 'FK ".trim($row['NR_FK'])."'"));
	//echo "<br>select id,name from ekomer.ecminvoiceouts where name like 'FK ".trim($row['NR_FK'])."'<br>";
	//echo $r['id']."\n\r";
	$parent_id=$r['id'];
	$parent_name=$r['name'];
	$rd=$row['DATA'];
	$sd=$row['DATA_SPRZ'];
	$a1=explode(" ",$row['ADRES2']);
	$pre="KF";
	$id=create_guid();
		
	if($row['ANULOWANA']=="F" || $row['ANULOWANA']=="")
		$type = '0'; 
			else
		$type = '1';
			
	$year = substr($row['DATA_SPRZ'], 0, 4);
		if (($year=='2012') || ($year=='2011') || ($year=='2010'))
			//$type = 'normal';
		
	$waluta = "PLN";
	$subtotal = $row['ROZN_NETTO'];
	$total = $row['ROZN_BRUT'];
	$kurs = 0;
	if ($row['KURS']!=0) {
		$kurs = $row['KURS']; 
		$waluta = "EUR";
	}
	$arr=array(
		"id"=>$id,
		"name"=>$pre." ".trim($row['NR_KF']),
		"description"=>ch($row['TYT1'])." ".ch($row['TYT2']),
		"date_entered"=>date("Y-m-d H:i:s"),
		"date_modified"=>date("Y-m-d H:i:s"),
		"modified_user_id"=>"d9c0007b-1247-5e82-31b6-4f168a01d290",
		"assigned_user_id"=>"d9c0007b-1247-5e82-31b6-4f168a01d290",
		"created_by"=>"d9c0007b-1247-5e82-31b6-4f168a01d290",
		"deleted"=>0,
		"number"=>($i+1),
		"document_no"=>$pre." ".trim($row['NR_KF']),
		"parent_type"=>"Accounts",
		"parent_name"=>$parent_name,
		"parent_id"=>$parent_id,
		"type"=>"correct",
		"ecminvoiceout_id"=>$r2['id'],
		"ecminvoiceout_name"=>$r2['name'],
		"status"=>"accepted",
		"register_date"=>$rd[0].$rd[1].$rd[2].$rd[3]."-".$rd[4].$rd[5]."-".$rd[6].$rd[7],
		"sell_date"=>$sd[0].$sd[1].$sd[2].$sd[3]."-".$sd[4].$sd[5]."-".$sd[6].$sd[7],
		"payment_date"=>$rd[0].$rd[1].$rd[2].$rd[3]."-".$rd[4].$rd[5]."-".$rd[6].$rd[7],
		"parent_address_street"=>ch(str_replace("'","",$row['ADRES2'])),
		"parent_address_city"=>ch($a1[1]),
		"parent_address_postalcode"=>$a1[0],
		"to_nip"=>"",
		"subtotal"=>$subtotal,
		"total"=>$total,
		"discount"=>0,
		"to_vatid"=>"",
		"to_is_vat_free"=>"",
		"header_text"=>"",
		"footer_text"=>"",
		"ads_text"=>"",
		"template_id"=>"ef0c4dea-ddf3-de51-9d08-512257d4b675",
		"template_name"=>"BSL Truck",
		"accepted"=>"",
		"email_id"=>"",
		"ecmlanguage"=>"pl_pl",
		"ecmpaymentcondition_id"=>"",
		"ecmpaymentcondition_text"=>"",
		"wz_id"=>"",
		"parent_contact_name"=>"",
		"parent_contact_title"=>"",
		"contact_id"=>"",	
		"currency_id"=>$waluta,
		"currency_value"=>$kurs,
		"deleted"=>$type,
	);
	foreach($arr as $k=>$v){
		$in[]=$k."='".$v."'";
	}
	
	mysql_query("set character set utf8;"); 
    $query = "insert into ekomer.ecminvoiceouts set ".implode(",",$in).";\n";
	echo $query;
	//echo $query.';\n';
	return $id;
}

function addProductLine($id,$i,$r){
	$vats=array(
		0=>"9b783d21-5548-6653-e1d6-49610eb3f9dd",
		22=>"9c592a4a-2de0-1fa3-e082-494aeceb122c",
		7=>"bf3a5fec-435f-af22-024a-4958b51863c8",
		'OO'=>"d7a2073e-44ca-7d52-cc02-5301eedef40f",
		23=>"93295ab1-bc7d-74a3-5644-4d21770fa33b",
		
	);
	mysql_query("SET NAMES 'utf8'");
	mysql_query("set character set utf8;"); 
	//$text = str_replace ("(l|ł)","l" , $r['INDEKS']);
	//$text = str_replace ("(L|Ł)","L" , $r['INDEKS']);
	//$rr=mysql_fetch_array(mysql_query("select id from ecmproducts where index_dbf like '%".$text."%' and deleted='0'"));
	//$rr=mysql_fetch_array(mysql_query("select id from ecmproducts where index_dbf like '%".$r['INDEKS']."%' and deleted='0'"));
	//$pid=$rr['id'];
	$rr=mysql_fetch_array(mysql_query("select id from ekomer.ecmproducts where code ='".$r['INDEKS']."' and deleted='0'"));
	$pid=$rr['id'];
	//echo 'id do produ: '.$pid;
	//if ($rr['id'] == '')	$pid=getnr($r['INDEKS']);
	$iid=create_guid();	
	if (($r['VAT']=='7') || ($r['VAT']=='8')) $vat_tmp = $vats[7];
	elseif (($r['VAT']=='22') || ($r['VAT']=='23')) $vat_tmp = $vats[22];
	else $vat_tmp = $vats[0];
	
	//repair prices (remove ',')
	$r['CENA_SPRZ'] = trim(str_replace(",", ".", $r['CENA_SPRZ']));
	$r['CENA_POCZ'] = trim(str_replace(",", ".", $r['CENA_POCZ']));
	$r['WARTOSC'] = trim(str_replace(",", ".", $r['WARTOSC']));
	$r['RABAT'] = trim(str_replace(",", ".", $r['RABAT']));
	$r['CENA_EWID'] = trim(str_replace(",", ".", $r['CENA_EWID']));
	$subtotal = $r['WARTOSC']-$r['POD_WART'];
	$arr=array(
		"id"=>$iid,
		"date_entered"=>date("Y-m-d H:i:s"),
		"date_modified"=>date("Y-m-d H:i:s"),
		"modified_user_id"=>"d9c0007b-1247-5e82-31b6-4f168a01d290",
		"assigned_user_id"=>"d9c0007b-1247-5e82-31b6-4f168a01d290",
		"created_by"=>"d9c0007b-1247-5e82-31b6-4f168a01d290",
		"deleted"=>0,
		"ecminvoiceout_id"=>$id,
		"ecmproduct_id"=>$pid,
		"position"=>$i,
		"code"=>ch(str_replace("'","",$r['INDEKS'])),
		"name"=>ch(str_replace("'","",$r['NAZWA'])),
		"quantity"=>$r['ILOSC'],
		"subprice"=>$r['CENA_SPRZ'],
		"total"=>$r['WARTOSC'],
		"startprice"=>$r['CENA_POCZ'],
		"purchase_price"=>$r['CENA_EWID'],
		"discount"=>$r['RABAT'],
		"subtotal"=>$subtotal,
		"dd_unit_name"=>$r['NAZWA_J_M'],
		"dd_unit_id"=>'KG',
		"ecmvat_id"=>$vat_tmp,
		"ecmvat_value"=>$r['VAT'],
		"ecmvat_name"=>$r['VAT']."%",
		"ecmproductcategory_id"=>"",
		"currency_id"=>"PLN",
		"currency_name"=>"PLN",
		"tax_code"=>"",
	);
	foreach($arr as $k=>$v){
		$in[]=$k."='".$v."'";
	}
	mysql_query("set character set utf8;"); 
	$query="insert into ekomer.ecminvoiceoutitems set ".implode(",",$in).";\n";
   // $a="insert into ekomer.ecminvoiceoutitems set ".implode(",",$in);
	// echo $a.';\n';
	echo $query;
	return $iid;
	
	
}

include_once("class.dbf.php");
include_once("helper.php");

$start = getmicrotime();

	$dbfp = new dbf_class('dbf/_kf_list.dbf');
	$num_recp=$dbfp->dbf_num_rec;	
	
	$products = array();
	for($i=0;$i<$num_recp;$i++){
		$rowp=$dbfp->getRowAssoc($i);
		$products[$rowp['NR_SYSTEM']][] = $rowp;
	}

	$dbf = new dbf_class('dbf/_kf.dbf');
	$num_rec=$dbf->dbf_num_rec;
	
	//$num_rec=1000;
	for($i=0;$i<$num_rec;$i++){
		$docs[$i]=$dbf->getRowAssoc($i);
	}
	$add = 0;

	$stop =0;
	//echo 'tutaj';

	for($i=$num_rec-1;$i>-1;$i--){
		//echo $docs[$i]['ANULOWANA']=ch($docs[$i]['ANULOWANA']);
		//echo 'cz: '.$docs[$i]['ANULOWANA'].'<br>';
		//echo $docs[$i]['NR_FK'].' a '.$docs[$i]['ANULOWANA'];
		
		 //echo "pole: ".$docs[$i]['ANULOWANA']."\n";
		if ((trim($docs[$i]['NR_FK'])=='') or ($docs[$i]['ANULOWANA'])=='P') continue;
		$data1 = mktime(0, 0, 0, substr($docs[$i]['DATA'],4,2),substr($docs[$i]['DATA'],6,2),substr($docs[$i]['DATA'],0,4));
		$data2 = mktime(0, 0, 0, 1, 1, 2004);
		//echo substr($docs[$i]['DATA'],4,2)."\n\r";
		//echo substr($docs[$i]['DATA'],6,2)."\n\r";
		//echo substr($docs[$i]['DATA'],0,4)."\n\r";
		//echo $data1."\n\r";
		//echo $data2."\n\r";
		if ($data1 < $data2) break; 

		//echo 'to: '.trim($docs[$i]['NR_FK']).'';
		$result = mysql_query("SELECT id FROM ekomer.ecminvoiceouts WHERE document_no ='FVCOR ".trim($docs[$i]['NR_KF'])."'");
		//echo 'sadasdasdas';
		//stop - zabezpieczenie w przypadku braku kolejności w numerach

		if (mysql_num_rows($result)!=0) {
		$stop++; 
		if ($stop==5) break;
		continue;
		}
		
		//echo '2342332';
		$add++;
		
		$id=addFk($docs[$i],$i,'');
		$j=1;
		
		//echo 'tutaj';
		foreach($products[$docs[$i]['NR_SYSTEM']] as $prod){
			addProductLine($id,$j,$prod);
			$j++;
		}
	}
//echo "Podsumowanie:\nW dbf: ".$num_rec."\nDodano: ".$add."\n"; 
$koniec = getmicrotime();
//echo "Czas trawania:".(($koniec - $start)/60)." minut\n";
mysql_close($sql);

?>
