<?php
set_time_limit(9999999999);
$sql=mysql_connect("localhost","root","sgpmk777");
mysql_select_db("crm");
mysql_query("set names utf8");

function getmicrotime(){ 
list($usec, $sec) = explode(" ",microtime()); 
return ((float)$usec + (float)$sec); 
}

function getnr($nr_sys){
	echo $nr_sys;
	$dbfi = new dbf_class('_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 from accounts where index_dbf = '".$row['INDEKS_KON']."' and deleted='0'"));
	$parent_id=$r['id'];
	$rd=$row['DATA'];
	$sd=$row['DATA'];
	$a1=explode(" ",$row['ADRES2']);
	$r=mysql_fetch_array(mysql_query("select id from ecminvoiceouts where document_no like 'FK ".trim($row['NR_FK'])."' and deleted='0'"));
	$invoice_id=$r['id'];
	$pre="FKKOR";
	$id=create_guid();
	//update normal invoice - add correct id
	if (($invoice_id!='') && (isset($invoice_id)))
		mysql_query("update ecminvoiceouts set ecminvoiceout_id='".$id."' where id='".$invoice_id."'");
	
	if($row['ANULOWANA']!="F")
		$type = 'canceled'; 
			else
			$type = 'correct';
			
	$year = substr($row['DATA'], 0, 4);
		if (($year=='2012') || ($year=='2011') || ($year=='2010'))
			$type = 'correct';
	
	$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"=>"",
		"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"=>ch(str_replace("'","",$row['PLATNIK'])),
		"parent_id"=>$parent_id,
		"type"=>" ",
		"ecminvoiceout_id"=>$invoice_id,
		"ecminvoiceout_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"=>$row['ROZN_NETTO'],
		"total"=>$row['ROZN_BRUT'],
		"discount"=>0,
		"to_vatid"=>"",
		"to_is_vat_free"=>"",
		"header_text"=>"",
		"footer_text"=>"",
		"ads_text"=>"",
		"template_id"=>"e3342f88-bc5d-848e-4bea-4e80240eed51",
		"template_name"=>"POLPACK Sp. z o. o.",
		"accepted"=>"",
		"email_id"=>"",
		"ecmlanguage"=>"pl_pl",
		"ecmpaymentcondition_id"=>"",
		"ecmpaymentcondition_text"=>"",
		"wz_id"=>"",
		"parent_contact_name"=>"",
		"parent_contact_title"=>"",
		"contact_id"=>"",	
		"currency_value"=>$kurs,
		"currency_id"=>$waluta,
		"type"=>$type,
		"correct_reason" => $row['TYT1'],
	);
	foreach($arr as $k=>$v){
		$in[]=$k."='".$v."'";
	}
    $query = "insert into ecminvoiceouts set ".implode(",",$in);
	mysql_query($query);
	return $id;
}

function addProductLine($id,$i,$r){
	$vats=array(
		0=>"d010f48f-0ca8-dbfa-be98-4e6e4b663b54",
		22=>"9ec174d1-db5e-8db6-9195-4e6e4a041e40",
		7=>"8bc1a7f7-2faa-e6b8-f14a-4e6e4b9e86dd",
	);
	$rr=mysql_fetch_array(mysql_query("select id from ecmproducts where index_dbf = '".$r['INDEKS']."' and deleted='0'"));
	$pid=$rr['id'];
	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];
	
	
	$r['CENA_SPRZ'] = trim(str_replace(",", ".", $r['CENA_SPRZ']));;
	$wartosc = floatval(trim(str_replace(",", ".", $r['WARTOSC']))) -floatval(trim(str_replace(",", ".", $r['OLD_WART'])));
	
	$ilosc = floatval(trim(str_replace(",", ".", $r['ILOSC']))) -floatval(trim(str_replace(",", ".", $r['OLD_ILOSC'])));
	
	$r['WART_ZWROT'] = trim(str_replace(",", ".", $r['WART_ZWROT']));
	
	
	$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"=>$ilosc,
		"price"=>$r['CENA_SPRZ'],
		"purchase_price"=>-1*$r['WART_ZWROT'],
		"discount"=>"",
		"total"=>$wartosc,
		"dd_unit_name"=>$r['NAZWA_J_M'],
		"dd_unit_id"=>1,
		"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("insert into ecminvoiceoutitems set ".implode(",",$in));
	return $iid;
}

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

$start = getmicrotime();


	$dbfp = new dbf_class('_KF_LIST.DBF');
	$num_recp=$dbfp->dbf_num_rec;

	for($i=0;$i<$num_recp;$i++){
		$rowp=$dbfp->getRowAssoc($i);
		$products[$rowp['NR_SYSTEM']][]=$rowp;
	}

	$dbf = new dbf_class('_KF.DBF');
	$num_rec=$dbf->dbf_num_rec;
	

	for($i=0;$i<$num_rec;$i++){
		$docs[$i]=$dbf->getRowAssoc($i);
	}
	$add = 0;

	$stop=0;
	for($i=$num_rec-1;$i>0;$i--){
	//for ($i=0; $i<$num_rec; $i++) {
		if ((trim($docs[$i]['NR_KF'])=='') or ($docs[$i]['ANULOWANA'] == 'T')) 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, 2008);
		//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 trim($docs[$i]['NR_KF']).'
';
		$result = mysql_query("SELECT id FROM ecminvoiceouts WHERE document_no ='FKKOR ".trim($docs[$i]['NR_KF'])."'");		
		if (mysql_num_rows($result)!=0) {
		$stop++; 
		if ($stop==5) break;
		continue;
		}
		
		$add++;
		$id=addFk($docs[$i],$i,'');
		$j=1;
		foreach($products[$docs[$i]['NR_SYSTEM']] as $prod){
			addProductLine($id,$j,$prod);
			$j++;
		}
	}
echo "Podsumowanie:\nW dbf: ".$num_rec."\nDodano: ".$add; 
$koniec = getmicrotime();
echo "Czas trawania:".(($koniec - $start)/60)." minut\n";
mysql_close($sql);
?>