<?php

ini_set('display_errors', 0);
set_time_limit(-1);
ini_set('memory_limit', '-1');

include_once("class.dbf.php");
include_once("helper.php");
$sugar_config = array(
		
		
		'dbconfig' =>
		array(
				'db_host_name' => 'localhost',
				'db_user_name' => 'root',
				'db_password' => '%g7!@fG',
				'db_name' => 'preDb_45ab7160e7af49269e17044eaed9e0ba',
				'db_type' => 'mysql',
		),
);

//Tworzenie polaczenia z baza 
echo '************************************************<br>Ustawianie polaczenia z baza...<br>';
$mysqli = new mysqli($sugar_config['dbconfig']['db_host_name'], $sugar_config['dbconfig']['db_user_name'], $sugar_config['dbconfig']['db_password'], $sugar_config['dbconfig']['db_name']);
if(mysqli_connect_errno()){
	echo 'Nie nawiazano polaczenia z baza...<br>';
	exit($mysqli->error);
}else{
	echo 'Ustawiono polaczenie z baza na serwerze ' . $sugar_config['dbconfig']['db_host_name'] . ' uzywajac loginu: '. $sugar_config['dbconfig']['db_user_name'] . ' i domyslna baza to: '.$sugar_config['dbconfig']['db_name'] . '<br>';
}

if ($mysqli->set_charset("utf8")) {
    echo 'Ustawiono kodowanie: ' . $mysqli->get_charset()->charset . '<br>';
} else {
	echo "Blad w ustawianiu kodowania utf8<br>";
	$mysqli->close();
    exit($mysqli->error);
}

if($mysqli->query('TRUNCATE TABLE ecminvoiceoutitems')){
	echo 'Wyczyszczono tabele ecminvoiceoutitems<br>';
}else{
	echo 'Nie usunieto danych z ecminvoiceoutitems<br>';
	$mysqli->close();
	exit($mysqli->error);
}

if($mysqli->query('TRUNCATE TABLE ecminvoiceouts')){
	echo 'Wyczyszczono tabele ecminvoiceouts<br>';
}else{
	echo 'Nie usunieto danych z ecminvoiceouts<br>';
	$mysqli->close();
	exit($mysqli->error);
}
echo 'Zakonczono ustanawianie polaczenia z baza<br>************************************************<br><br>';


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

function getnr($nr_sys, $path) {
    //echo $nr_sys;
	if($path==NULL){
		$dbfi = new dbf_class(dirname(__FILE__).'/bsl/_indeksy.dbf');
	}else{
		$dbfi = new dbf_class(dirname(__FILE__).'/bsl/_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 dodajFaktury($dokumenty, $idmagazynu, $nrmagazynu=NULL) {
	
	global $mysqli;
	
	if(!isset($dokumenty) || count($dokumenty)==0){
		return NULL;
	}
	$tmpplatnosc = array();
	foreach($dokumenty as $key => $row){
		$result = $mysqli->query("SELECT id, name, to_vatid FROM accounts WHERE index_dbf = '" . ch(trim($row['INDEKS_KON'])) . "'");
		if($result->num_rows>0){
			$r = $result->fetch_array(MYSQLI_ASSOC);
		} else {
			$result = $mysqli->query('SELECT id, name, to_vatid FROM accounts WHERE index_dbf = "' . ch(trim($row['INDEKS_KON'])) . '"');
			if($result->num_rows>0){
				$r = $result->fetch_array(MYSQLI_ASSOC);
			}
		}
		
		if(!isset($r)){
			$result = $mysqli->query("SELECT id, name, to_vatid FROM accounts WHERE to_vatid = '" . trim($row['NR_IDENT']) . "'");
			$r = $result->fetch_array(MYSQLI_ASSOC);
			if(!isset($r)){
				$result = $mysqli->query("SELECT id, name, to_vatid FROM accounts WHERE to_vatid = '" . str_replace('-', '', trim($row['NR_IDENT'])) . "'");
				$r = $result->fetch_array(MYSQLI_ASSOC);
				if(!isset($r)){
					//var_dump($row);
				
					continue;
				}
			}
		}

		$rd = $row['DATA'];
		$sd = $row['DATA_SPRZ'];
		$a1 = explode(" ", $row['ADRES1']);
		$pre = "FK";
		if(isset($nrmagazynu)){
			
		}
		$id = create_guid();

		if ($row['ANULOWANA'] == "F" || $row['ANULOWANA'] == "")
			$canceled = '0';
		else
			$canceled = '1';

		$year = substr($row['DATA_SPRZ'], 0, 4);
			$waluta = "PLN";
		$subtotal = $row['WARTOSC'] - $row['PODATEK'];
		
		$kurs = 0;
		if ($row['KURS'] != 0) {
			$kurs = strtolower (str_replace(',','.',$row['KURS']));
			$waluta = "EUR";
		}
		$n = substr($row['NR_FK'], 0, -3);
		if ($n < 100 && $n > 9) {
			$ad = 0;
		} else {
			$ad = '';
		}
		if ($n < 10) {
			$ad = '00';
		}
		$date = $rd[0] . $rd[1] . $rd[2] . $rd[3] . "" . $rd[4] . $rd[5] . "" . $rd[6] . $rd[7] . $ad . $n;
		$date2 = $rd[0] . $rd[1] . $rd[2] . $rd[3] . "-" . $rd[4] . $rd[5] . "-" . $rd[6] . $rd[7];
		$n = (int) $row['TERMIN'];
		date_default_timezone_set('Europe/Warsaw');
		$date3 = new DateTime($date2);
		$date3->add(new DateInterval('P' . $n . 'D'));
		
		$payment_method_dom=array (
			'PRZELEW' => 'Przelew',
			'' => 'Inny',
			'PRZEDPLATA' => 'Przedpłata',
			'ZA POBRANIEM' => 'Za pobraniem',
			'PRZY ODBIORZE' => 'Przy odbiorze',
			'GOTÓWKĄ' => 'Gotówka',
			'*PRZELEW*' => '*Przelew*',
		);
		$payment_method_dom = array(
			"PRZELEW"=>'PRZELEW',
			"PRZEDPŁATA"=>'PRZEDPLATA',
			"PRZELEWEM"=>'PRZELEW',
			"GOTÓWKA"=>'GOTÓWKĄ',
			"POBRANIE T.K."=>'ZA POBRANIEM',
			"POBRANIE"=>'ZA POBRANIEM',
			"GOTÓWKĄ"=>'GOTÓWKĄ',
			"POBRANIE GOTÓWKA"=>'ZA POBRANIEM',
			"POPRANIE"=>'ZA POBRANIEM',
			"GOTWKA"=>'GOTÓWKĄ',
			"KOMPENSATA"=>'',
		);

		$payment_date_days = $n;
		$id = create_guid();
		$name = $pre . " " . trim($row['NR_FK']);
		$description = ch($row['ADRES2'] . " " . $row['ADRES1'] . " " . $row['UWAGI'] . " " . $row['UWAGI1']);
		$date_entered = date("Y-m-d H:i:s");
		$date_modified = $date_entered;
		$modified_user_id = "eaa650d6-5a48-8a29-cd7c-554207f71255";
		$assigned_user_id = $modified_user_id;
		$created_by = $modified_user_id;
		$stock_id = $idmagazynu;
		$number = $date;
		$document_no = $pre . " " . trim($row['NR_FK']);
		$parent_type = "Accounts";
		$parent_name = empty($r['name']) ? '' : str_replace("'", "",$r['name']);
		$parent_id = empty($r['id']) ? '' : $r['id'];
		$type = "normal";
		$ecminvoiceout_id = 't';
		$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 = $date3->format('Y-m-d');
		$parent_address_street = ch(str_replace("'", "", $row['ADRES2']));
		$parent_address_city = empty(ch($a1[1])) ? '' : ch($a1[1]);
		$parent_address_postalcode = empty($a1[0]) ? '' : $a1[0];
		$prepaid = empty($row['PRZEDPLATA']) ? '' : $row['PRZEDPLATA'];
		$paid_val = empty($row['GOTOWKA']) ? '' : $row['GOTOWKA'];
		$total_brutto = empty($row['WARTOSC']) ? '' : $row['WARTOSC'];
		$total_netto = $row['WARTOSC'] - $row['PODATEK'];
		$total_vat = $row['PODATEK'];
		if ($row['KURS'] != 0) {
			$total_brutto = round($total_brutto * $kurs,2);
			$total_netto = round($total_netto * $kurs,2);
			$total_vat = round($total_vat * $kurs,2);
		}
		$paid_val = $row['GOTOWKA'];
		$payment_method = $payment_method_dom[ch($row['SPOS_ZAP'])];
		$discount = 0;
		$pdf_type = 'K';
		$ecmlanguage = "pl_pl";
		$currency_id = empty($waluta) ? '' : $waluta;
		$currency_value = empty($kurs) ? '' : $kurs;
		$deleted = empty($type) ? '' : $type;
		$nr_system = $row['NR_SYSTEM'];

		
		$query = "INSERT ecminvoiceouts (";
		$query .= " id, ";
		$query .= " name, ";
		$query .= " deleted, ";
		$query .= " date_entered, ";
		$query .= " date_modified, ";
		$query .= " modified_user_id, ";
		$query .= " assigned_user_id, ";
		$query .= " created_by, ";
		$query .= " number, ";
		$query .= " document_no, ";
		$query .= " parent_type, ";
		$query .= " parent_name, ";
		$query .= " parent_id, ";
		$query .= " type, ";
		$query .= " register_date, ";
		$query .= " sell_date, ";
		$query .= " total_netto, ";
		$query .= " total_brutto, ";
		$query .= " total_vat, ";
		$query .= " parent_address_street, ";
		$query .= " parent_address_city, ";
		$query .= " parent_address_postalcode, ";
		$query .= " parent_nip_unformated, ";
		$query .= " parent_nip, ";
		$query .= " currency_id, ";
		$query .= " currency_value, ";
		$query .= " currency_value_nbp, ";
		$query .= " payment_date_days, ";
		$query .= " payment_date, ";
		$query .= " paid_val, ";
		$query .= " payment_method, ";
		$query .= " sys_number, ";
		$query .= " pdf_type, ";
		$query .= " canceled, ";
		$query .= " stock_id, ";
		$query .= " ecmlanguage, ";
		$query .= " document_autoincrement ";
		$query .= " ) VALUES (";
		$query .= "'" . $id . "',"; // id
		$query .= "'" . $name . "',"; // name
		$query .= "0,"; // deleted
		$query .= "NOW(),"; //date_entered
		$query .= "NOW(),"; //date_modified
		$query .= "'". $modified_user_id ."',"; //modified_user_id
		$query .= "'". $assigned_user_id ."',"; //assigned_user_id
		$query .= "'". $created_by ."',"; //created_by
		$query .= "'" . $number . "' ,"; // number
		$query .= "'" . $document_no . "' ,"; // document_no
		$query .= "'Accounts',"; // parent_type
		$query .= "'" . $parent_name . "',"; // parent_name
		$query .= "'" . $parent_id . "' ,"; // parent_id
		$query .= "'normal',"; // type
		$query .= "'" . $register_date . "',"; // register_date
		$query .= "'" . $sell_date . "',"; // sell_date
		$query .= "'" . $total_netto . "',"; // total_netto
		$query .= "'" . $total_brutto . "',"; // total_brutto
		$query .= "'" . $total_vat . "',"; // total_vat
		$query .= "'" . $parent_address_street . "',"; // parent_address_street
		$query .= "'" . $parent_address_city . "',"; // parent_address_city
		$query .= "'" . $parent_address_postalcode . "',"; // parent_address_postalcode
		$query .= "'" . $r['to_vatid'] . "',"; // parent_nip
		$query .= "'" . str_replace("-", '', $r['to_vatid']) . "',"; // parent_nip_unformated
		$query .= "'" . $currency_id . "',"; // currency_id
		$query .= "'" . $currency_value . "',"; // currency_value
		$query .= "'" . $currency_value . "',"; // currency_value
		$query .= "'" . $payment_date_days . "',"; // payment_date_days
		$query .= "'" . $payment_date . "',"; // payment_date$paid_val
		$query .= "'" . $paid_val . "',"; // paid_val
		$query .= "'" . $payment_method . "',"; // payment_method
		$query .= "'" . $nr_system . "',"; // sys_number
		$query .= "'" . $pdf_type . "',"; // sys_number
		$query .= "'" . $canceled . "',"; // canceled
		$query .= "'" . $idmagazynu . "',"; // payment_date
		$aa=explode('/',$document_no);
		preg_match('|\d+|',$aa[0],$matches);

		$document_auto=date("Ymd",strtotime($register_date)).''.sprintf('%05d',(string)((int)$matches[0]));
		$query .= " 'pl_pl',"; // ecmlanguage
		$query .= "'" . $document_auto . "'"; // payment_date
		$query .= ");";
		
		$result = $mysqli->query($query);
		if (!$result) {
			echo $query . '<Br><br>';
			echo $mysqli->error;
		}
		foreach($row['LISTA_POZYCJI'] as $klucz => $wartosc){
			if(isset($nrmagazynu)){
				addProductLine($id, $klucz, $wartosc, $nrmagazynu);
			}else{
				addProductLine($id, $klucz, $wartosc);
			}
		}
		
	}
}

function addProductLine($id, $i, $r, $nrmagazynu=NULL) {

	$jed=strtolower (str_replace('.','',$r['NAZWA_J_M']));
	$unit_id=array_search($jed, $jednostki);
	global $mysqli;
	$result = $mysqli->query("SELECT id FROM ecmproducts WHERE code ='" . ch($r['INDEKS']) . "' and deleted='0'");
    $rr = $result->fetch_array(MYSQLI_ASSOC);
    $pid = $rr['id'];
	if ($rr['id'] == ''){
		$result = $mysqli->query('SELECT id FROM ecmproducts WHERE code ="' . ch($r['INDEKS']). '" and deleted="0"');
		$rr = $result->fetch_array(MYSQLI_ASSOC);
		$pid = $rr['id'];
		if ($rr['id'] == ''){
		$pid=getnr($r['INDEKS'], $nrmagazynu);
		}
	}
    $iid = create_guid();

    //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" => "eaa650d6-5a48-8a29-cd7c-554207f71255",
        "assigned_user_id" => "eaa650d6-5a48-8a29-cd7c-554207f71255",
        "created_by" => "eaa650d6-5a48-8a29-cd7c-554207f71255",
        "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'],
		"price_start" => $r['CENA_POCZ'],
        "price_netto" => $r['CENA_SPRZ'],
		"price_brutto" => round($r['CENA_SPRZ']*strtolower (str_replace('.','',$r['VAT'])),2) + $r['CENA_SPRZ'],
		"discount" => $r['RABAT'],
		"total_netto" => $r['WARTOSC'],
        "total_brutto" => $r['WARTOSC'] + $r['POD_WART'],
		"total_vat" => $r['POD_WART'],
        "price_purchase" => round($r['CENA_EWID'] / $r['ILOSC'],2),
        "dd_unit_name" => $r['NAZWA_J_M'],
        "dd_unit_id" => md5($r['NAZWA_J_M']),
        "ecmvat_id" => md5($r['VAT'].'asd'),
        "ecmvat_value" => strtolower (str_replace('.','',$r['VAT'])),
        "ecmvat_name" => $r['VAT'] . "%",
    );
    foreach ($arr as $k => $v) {
        $in[] = $k . "='" . $v . "'";
    }
    $query = "insert into ecminvoiceoutitems set " . implode(",", $in) . ";\n";
	$result = $mysqli->query($query);
	if (!$result) {
		echo $mysqli->error;
		echo $query . '<Br><br>';
	}
}

function wczytajFaktury($path, $path2){
	//Naglowki faktur
	$dbf = new dbf_class($path);
	$num_rec = $dbf->dbf_num_rec;
	$dokumenty = array();
	echo $num_rec. '<br>';
	for ($i = 0; $i < $num_rec; $i++) {
		$row = $dbf->getRowAssoc($i);
		if(!$row){
		//	echo 'Pominieto wiersz naglowka'.$i.' z '. $num_rec. ' '.$path.'<br>';
			continue;
		}
		if(strlen($row['NR_SYSTEM'])>0){
			$dokumenty[$row['NR_SYSTEM']] = array();
			//$dokumenty[$row['NR_SYSTEM']] = $row;
			foreach($row as $key => $value){
				if(strlen($value)>0){
					$dokumenty[$row['NR_SYSTEM']][$key] = $value;
				}else{
					continue;
				}
			}
		}else{
			echo 'BRAK NUMERU FAKTURY!<br>';
		//	var_dump($row);
			echo '<br><br>';
		}
	}

	//Pozycje faktur
	$dbfp = new dbf_class($path2);
	$num_recp = $dbfp->dbf_num_rec;
	for ($i = 0; $i < $num_recp; $i++) {
		$row = $dbfp->getRowAssoc($i);
		if(!$row){
		//	echo 'Pominieto wiersz pozycji'.$i.' z '. $num_rec. ' ' .$path2. '<br>';
			continue;
		}
		if(isset($dokumenty[$row['NR_SYSTEM']])){
			if(isset($dokumenty[$row['NR_SYSTEM']]['LISTA_POZYCJI'])){
				$tmprow = array();
				foreach($row as $key => $value){
					if(strlen($value)>0){
						$tmprow[$key] = $value;
					}
				}
				$dokumenty[$row['NR_SYSTEM']]['LISTA_POZYCJI'][] = $tmprow;
			}else{
				$dokumenty[$row['NR_SYSTEM']]['LISTA_POZYCJI'] = array();
				$tmprow = array();
				foreach($row as $key => $value){
					if(strlen($value)>0){
						$tmprow[$key] = $value;
					}
				}
				$dokumenty[$row['NR_SYSTEM']]['LISTA_POZYCJI'][] = $tmprow;
			}
		}else{
		//	var_dump($row);
			echo '<br><br>';
		}
	}
	return $dokumenty;
}

// Obsluga importu
$start = microtime_float();

echo 'Wczytywanie dokumentow...<br>';
$re = $mysqli->query('SELECT id, dir, name FROM ecmstocks');
while($magazyn = $re->fetch_array(MYSQLI_ASSOC)){

	echo 'Magazyn: ' . $magazyn['name'] . '<br>';
	if($magazyn['dir']=='mg'){
		$path2 = dirname(__FILE__).'/bsl/_fk_list.dbf';
		$path = dirname(__FILE__).'/bsl/_fk.dbf';;
		$dokumenty = wczytajFaktury($path , $path2);
		dodajFaktury($dokumenty, $magazyn['id']);
	} else {
$path2 = dirname(__FILE__).'/bsl/_fk_list.dbf';
		$path = dirname(__FILE__).'/bsl/_fk.dbf';;
		$dokumenty = wczytajFaktury($path , $path2);
		dodajFaktury($dokumenty, $magazyn['id'], $magazyn['dir']);
	}
}
echo 'Zakonczono wczytywanie dokumentow<br>';
//echo 'Dodawanie faktur...<br>';
//
//echo 'Zakonczono dodawanie faktur<br>';


	$res2 = $mysqli->query("select * from ecminvoiceouts where type='normal'");
	
	while($r = $res2->fetch_array(MYSQLI_ASSOC)){
	
	$vats_summary = '';
	$total_netto = 0;
	$total_brutto = 0;
	$total_vat = 0;

	$res = $mysqli->query(  "select ROUND(sum(total_netto),2) AS total_netto,ROUND(sum((total_netto*ecmvat_value)/100),2) AS total_vat,
ROUND(sum(((total_netto*ecmvat_value)/100)+total_netto),2) AS total_brutto,ecmvat_value,ecmvat_name
from ecminvoiceoutitems where ecminvoiceout_id='" . $r['id'] . "' group by ecmvat_id" );
	while ( $cc=$res->fetch_array(MYSQLI_ASSOC) ) {
		$total_netto += $cc ['total_netto'];
		$total_brutto += $cc ['total_brutto'];
		$total_vat += $cc ['total_vat'];
		if($cc ['ecmvat_name']=='OO'){
			$cc ['ecmvat_value']=$cc ['ecmvat_name'];
		} else {
			$cc ['ecmvat_value']=$cc ['ecmvat_name'];
		}
		$vats_summary .= $cc ['ecmvat_value'] . ':' . $cc ['total_netto'] . ':' . $cc ['total_vat'] . ':' . $cc ['total_brutto'] . ',';
	}
	$res = $mysqli->query(  "update ecminvoiceouts set vats_summary='" . $vats_summary . "',total_netto='" . $total_netto . "',total_vat='" . $total_vat . "',
	           total_brutto='" . $total_brutto . "' where id='" .$r['id']. "'" );
	
	}

$koniec = microtime_float();
echo "<br><br>Czas trawania:".(($koniec - $start)/60)." minut<br>";
$mysqli->close();

?>
