<?php

set_time_limit(9999999999);
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 names utf8");
//mysql_query("truncate table ecmstockdocins");
//mysql_query("truncate table ecmstockdocinitems");



function getmicrotime(){ 
list($usec, $sec) = explode(" ",microtime()); 
return ((float)$usec + (float)$sec); 
}
function getnr($nr_sys){
	//echo $nr_sys;
	$dbfi = new dbf_class('ekomer/_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'"));
	//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="RW";
	$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['DO_ZAPLATY']-$row['PODATEK'];
	$total = $row['WARTOSC'];
	$kurs = 0;
	if ($row['KURS']!=0) {
		$kurs = $row['KURS']; 
		$waluta = "EUR";
	}
		if($r['RODZ_PL']==1){
	$kind='other';
	} else {
	$kind='import';
	}
	//$row['NR_RW'][1]='W';
	$n = substr($row['NR_RW'], 0, -3);
	if($n<100 && $n>9){$ad=0;} else { $ad='';}
	if($n<10){$ad='00';} 
	$nrdoc=$rd[0].$rd[1].$rd[2].$rd[3]."".$rd[4].$rd[5]."".$rd[6].$rd[7].$ad.$n;
	$arr=array(
		"id"=>$id,
		"name"=>ch($row['UWAGI']." ".$row['UWAGI1']." ".$row['UWAGI2']),
		"description"=>ch($row['UWAGI']." ".$row['UWAGI1']." ".$row['UWAGI2']),
		"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"=>$nrdoc,
		"document_no"=>$pre." ".trim($row['NR_RW']),
		"parent_id"=>$parent_id,
		"type"=>"normal",
		//"ecminvoiceout_id"=>"",
		//"ecminvoiceout_name"=>"",
		"status"=>"accepted",
		"register_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],
		"subtotal"=>$subtotal,
		"total"=>$total,
		"discount"=>0,
		"to_vatid"=>"",
		"to_is_vat_free"=>"",
		"header_text"=>"",
		"footer_text"=>"",
		"ads_text"=>"",
		"template_id"=>"97700b0d-fbe9-e366-4016-4b260f058a47",
		"template_name"=>"EKOMER K. Wróblewska Spółka Jawna",
		"accepted"=>"",
		"email_id"=>"",
		"ecmlanguage"=>"pl_pl",
		"ecmpaymentcondition_id"=>"",
		"ecmpaymentcondition_text"=>"",
		"stock_id"=>"c7afd71a-4c3a-bde4-138d-4acaee1644e4",
		"parent_contact_name"=>"",
		"parent_contact_title"=>"",
		"contact_id"=>"",	
		"imp"=>1,
		"currency_id"=>$waluta,
		"deleted"=>$type,
	);
	foreach($arr as $k=>$v){
		$in[]=$k."='".$v."'";
	}
	mysql_query("set character set utf8;"); 
    $query = "insert into ekomer.ecmstockdocinsideouts set ".implode(",",$in).";\n";
	echo $query;
	//echo $query.';\n';
	return $id;
}

function addProductLine($id,$i,$r,$bc){
	$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'];

	$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,
		"ecmstockdocinsideout_id"=>$id,
		"ecmproduct_id"=>$pid,
		"position"=>$i,
		"code"=>ch(str_replace("'","",$r['INDEKS'])),
		"name"=>ch(str_replace("'","",$r['NAZWA'])),
		"quantity"=>$r['ILOSC'],
		"price"=>$r['CENA_EWID'],
		"total"=>$r['CENA_EWID']*$r['ILOSC'],
		"discount"=>$r['RABAT'],
		"dd_unit_name"=>$r['NAZWA_J_M'],
		"dd_unit_id"=>$r['NAZWA_J_M'],
		"ecmvat_id"=>$vat_tmp,
		"ecmvat_value"=>$r['VAT'],
		"ecmvat_name"=>$r['VAT']."%",
		"ecmproductcategory_id"=>"",
		"currency_id"=>"PLN",
		"currency_name"=>"PLN",
	);
	foreach($arr as $k=>$v){
		$in[]=$k."='".$v."'";
	}
	mysql_query("set character set utf8;"); 
	$query="insert into ekomer.ecmstockdocinsideoutitems set ".implode(",",$in).";\n";
   // $a="insert into ekomer.ecminvoiceoutitems set ".implode(",",$in);
	//echo $a.';\n';
	echo $query;
	$bc++;
	return $iid;
	
	
}

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

$start = getmicrotime();

	$dbfp = new dbf_class('ekomer/_rw_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('ekomer/_rw.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';
	//print_r($docs);
$ac=0;
$bc=0;
	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_RW'])=='') 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.ecmstockdocinsideouts WHERE document_no ='RW ".trim($docs[$i]['NR_RW'])."'");
		//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=0;
		//echo 'tutaj';
		//print_r($products);
		foreach($products[$docs[$i]['NR_SYSTEM']] as $prod){
			addProductLine($id,$j,$prod,$bc);
	
			$j++;
			$ac++;
		}
	}
//echo $ac.' '.$bc;
mysql_close($sql);

?>
