<?php

ini_set('display_errors', 0);
set_time_limit(-1);
ini_set('memory_limit', '-1');
$sql=mysql_connect("localhost","root","%g7!@fG");
mysql_select_db("preDb_7561b7965a2f9cebf2cbca60a9a07064");
mysql_query("set names utf8");



function getnr24($nr_sys,$path=NULL){

	if($path == NULL){
		$dbfi = new dbf_class(dirname(__FILE__).'/przemyslowka/glowny/_INDEKSY.DBF');
	}else{
 		$dbfi = new dbf_class(dirname(__FILE__).'/przemyslowka/glowny/_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) 
		{
		return ch($indeks['NR_SYSTEM']);
		}
	}
		return 'BRAK INDEKSU';
}

function addFk44($row,$i,$stock_id){
	
	
	$r=mysql_fetch_array(mysql_query("select id from accounts where index_dbf = '".ch($row['INDEKS_KON'])."' and deleted='0'"));
	$parent_id=$r['id'];
if($parent_id==''){
	$r=mysql_fetch_array(mysql_query('select id from accounts where index_dbf = "'.ch($row['INDEKS_KON']).'" and deleted="0"'));
	$parent_id=$r['id'];
}
	$rd=$row['DATA'];
	$sd=$row['DATA'];
	$a1=explode(" ",$row['ADRES1']);
	$r=mysql_fetch_array(mysql_query("select id, name, parent_nip, stock_id from ecmreceipts where document_no = 'PR ".trim($row['DO_PR'])."' and deleted='0'"));
	$invoice_id=$r['id'];
	$invoice_name =$r['name'];
	$pre="PRKOR";
	$id=create_guid();
	//update normal invoice - add correct id
	if (($invoice_id!='') && (isset($invoice_id))){
		$rrr = mysql_query("update ecmreceipts set ecminvoiceout_id='".$id."' where id='".$invoice_id."'");
		if (!$rrr) {
			echo mysql_error() . '<br>';
			echo $query . '<Br><br>';
		}
	}

	$type = 'correct';
	if($row['ANULOWANA']=='T'){
		$anulowana = 1;
	}else{
		$anulowana = 0;
	}		
	$year = substr($row['DATA'], 0, 4);
	$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"=>'',
	);
	
	//$type = 'correct';
	//print_r($row);print_r('<br><br>');
	$paid_val = empty($row['GOTOWKA']) ? '' : $row['GOTOWKA'];
	$payment_date_days = (int) $row['TERMIN'];
	$waluta = "PLN";
	$subtotal = $row['ROZN_NETTO'];
	$total = $row['ROZN_BRUT'];
	$kurs = null;
	if ($row['KURS']!=0) {
		$kurs = $row['KURS']; 
		$waluta = "EUR";
		}
		$aa=explode('/',$pre." ".trim($row['NR_PL']));
		preg_match('|\d+|',$aa[0],$matches);
		$document_autot=date("Ymd",strtotime($rd[0].$rd[1].$rd[2].$rd[3]."-".$rd[4].$rd[5]."-".$rd[6].$rd[7])).''.sprintf('%05d',(string)((int)$matches[0]));
	$arr=array(
		"id"=>$id,
		"name"=>$pre." ".trim($row['NR_PL']),
		"description"=>ch($row['TYT1']),
		"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,
		"number"=>($i+1),
		"document_no"=>$pre." ".trim($row['NR_PL']),
		"parent_type"=>"Accounts",
		"parent_name"=>ch(str_replace("'","",$row['PLATNIK'])),
		"parent_id"=>$parent_id,
		"ecminvoiceout_id"=>$invoice_id,
		"ecminvoiceout_name"=>$invoice_name,
		
		"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],
		"parent_nip"=>$r['parent_nip'],
		"total_netto"=>$row['ROZN_NETTO'],
		"total_brutto"=>$row['ROZN_BRUT'],
		"total_vat" =>$row['ROZN_VAT'],
		"payment_method" => $payment_method_dom[ch($row['SPOS_ZAP'])],
		"pdf_type" => 'K',
		"paid_val" => $paid_val,
		"discount"=>0,
		"payment_date_days" => $payment_date_days,
		"stock_id" => $r['stock_id'],
		"ecmlanguage"=>"pl_pl",
		"currency_value"=>$kurs,
		
		"currency_id"=>$waluta,
			"document_autoincrement"=>$document_autot,
		"type"=>$type,
			
		"sys_number"=>$row['NR_SYSTEM'],
		"canceled"=>$anulowana,
	);
	
	
	foreach($arr as $k=>$v){
		$in[]=$k."='".$v."'";
	}
    $query = "insert into ecmreceipts set ".implode(",",$in);
    //print_r(implode(",",$in));print_r('<br><br>');
	$result = mysql_query($query);
	if (!$result) {
		echo mysql_error() . '<br>';
		echo $query . '<Br><br>';
	}
	return array(0=>$id,1=>$invoice_id);
}

function addProductLine24($id,$i,$r, $path=null,$invoice_id){


	$jed=strtolower (str_replace('.','',$r['NAZWA_J_M']));
	$unit_id=array_search($jed, $jednostki);
	
$result = mysql_query("SELECT id FROM ecmproducts WHERE code ='" . ch($r['INDEKS']) . "' and deleted='0'");
    $rr = mysql_fetch_array($result);
    $pid = $rr['id'];
	if ($rr['id'] == ''){
		$result = mysql_query('SELECT id FROM ecmproducts WHERE code ="' . ch($r['INDEKS']). '" and deleted="0"');
		$rr = mysql_fetch_array(MYSQLI_ASSOC);
		$pid = $rr['id'];
		if ($rr['id'] == ''){
		$pid=getnr($r['INDEKS'], $nrmagazynu);
		}
	}
	$iid=create_guid();	
	
	$qq = "select id from ecmreceiptitems WHERE  code='" . ch($r['INDEKS']) ."' AND quantity = ". ch($r['ILOSC_OLD']) ." AND ecmreceipt_id = '". $invoice_id ."' ";
	
	$oldid = mysql_fetch_array(mysql_query($qq));
	
	$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['ILOSC_OLD'])));
	
	$r['WART_ZWROT'] = trim(str_replace(",", ".", $r['WART_ZWROT']));
	
	$q12='select * from ecmvats where id= "'.md5($r['VAT'].'asd').'" ';
	$q1122=mysql_fetch_array(mysql_query($q12));
	
	$vat_value=1+($q1122['value']/100);
	
	$ilosc=$r['ILOSC'];
	$wartosc = $wart_zwrot;
	//$ilosc = $r ["ZWROT"];

	//print_r($r);print_r('<br><br>');
	$cena_brutto_new=round($r['ILOSC_NEW']*$r['CENA_NEW'],2);
	$cena_brutto_old=round($r['ILOSC_OLD']*$r['CENA_OLD'],2);
	$roznica_brutto=$cena_brutto_new-$cena_brutto_old;
	$vat_new=$cena_brutto_new-round(($cena_brutto_new/($vat_value)),2);
	$vat_old=$cena_brutto_old-round(($cena_brutto_old/($vat_value)),2);
	$vat_diff=$vat_new-$vat_old;
	
	print_r($cena_brutto_new);print_r('<br><br>');
	print_r($cena_brutto_old);print_r('<br><br>');
	print_r($roznica_brutto);print_r('<br><br>');
	
	if($r['ILOSC']==0){
		$_ilosc=$r['ILOSC_NEW'];
	
	}else{
		$_ilosc=$r['ILOSC_NEW']-$r['ILOSC_OLD'];
		}
		$wart_zwrot=$r['CENA_EWID']*($r['ILOSC_NEW']);
		$cenaJednostkowa = $r['CENA_EWID'];
	print_r($r['CENA_NEW']);print_r('<br><br>');
	print_r($cena_brutto_new);print_r('<br><br>');
	$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,
		"ecmreceipt_id"=>$id,
		"ecmproduct_id"=>$pid,
		"position"=>$i,
		"code"=>str_replace("'","",$r['INDEKS']),
		"name"=>str_replace("'","",$r['NAZWA']),
		"ecminvoiceoutitem_id" => $oldid['id'],
		"old_ecminvoiceoutitem_id" => $oldid['id'],
		"quantity"=>$_ilosc,
		"price_start"=>$r['CENA_NEW'],
		"price_netto"=>round($r['CENA_NEW']/$vat_value,2) ,
		"price_brutto"=>$r['CENA_NEW'],
		"discount"=>"0",
		"total_netto"=>$roznica_brutto-$vat_diff,
		"total_brutto" => $roznica_brutto,
		"total_vat" => $vat_diff,
		"old_total_netto" => $cena_brutto_old-$vat_old,
		"old_total_brutto" => $cena_brutto_old,
		"old_total_vat" => $vat_old,
		"old_quantity" => $r['ILOSC_OLD'],
		"price_purchase" => $cenaJednostkowa,
		
		"total_netto_corrected" => $roznica_brutto-$vat_diff,
		"total_brutto_corrected" => $roznica_brutto,
		"quantity_corrected"=>-1*floatval($ilosc),
		"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."'";
	}
	$result = mysql_query("insert into ecmreceiptitems set ".implode(",",$in));
	//print_r(implode(",",$in));print_r('<br><br>');
	if (!$result) {
		echo mysql_error() . '<br>';
		echo $query . '<Br><br>';
	}

	return $iid;
}

function getKfId3($doc,$products){
	
	
	//echo $query;
		$result = mysql_query($query);
	if (!$result) {
		//echo mysql_error() . '<br>';
		//echo $query . '<Br><br>';
	}
	
	foreach($products[$doc["NR_SYSTEM"]] as $key => $value){
		//print_r($value);
		$wartosc = $value ["WART_ZWROT"];
		if($wartosc=='0.00'){
			continue;
		}
		$wartosc = $value ["WART_ZWROT"];
		$ilosc = $value ["ZWROT"];
		$cenaJednostkowa = round($wartosc / $ilosc,2);
		$query = "UPDATE ecmreceipts doc, ecmreceiptitems item SET item.price_purchase='".$cenaJednostkowa ."', item.total_purchase='".$wartosc."' WHERE item.ecminvoiceout_id = doc.id AND doc.sys_number = '" . $doc["NR_SYSTEM"] ."' AND item.code='" . $value ["INDEKS"] . "' AND item.name='" . $value["NAZWA"]. "' AND item.old_total_netto='". $value ["OLD_WART"]."'";
		//$result = mysql_query($query);
			//echo 'Wartosc: ' .$wartosc .'<br>';
			//echo 'Ilosc: ' .$ilosc .'<br>';
		//	echo 'cenaJednostkowa: ' .$cenaJednostkowa .'<br>';
			//echo $query . '<br>';

			//echo '<br><br>';
		
		
		 
	}
	
}

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

function mainloop44($path=NULL){
	//$start = getmicrotime();
		if($path==null){
			$tmppath = dirname(__FILE__).'/przemyslowka/';
		}else{
			$tmppath = $path;
		}
	$dbfp = new dbf_class($tmppath.'_ZW_LIST.DBF');
	$num_recp=$dbfp->dbf_num_rec;

	for($i=0;$i<$num_recp;$i++){
		$rowp=$dbfp->getRowAssoc($i);
		$new=array();
		foreach ($rowp as $key=>$val){
		
			$new[$key]=ch($val);
		}
		$products[$rowp['NR_SYSTEM']][]=$new;
	}
	$dbf = new dbf_class($tmppath.'_ZW.DBF');
	$num_rec=$dbf->dbf_num_rec;
	$new2=array();
	for($i=0;$i<$num_rec;$i++){
		$docs[$i]=$dbf->getRowAssoc($i);
		
		foreach ($docs[$i] as $key=>$val){
		
			$new2[$i][$key]=ch($val);
		}
	}
	$add = 0;

	$stop=0;
	foreach($new2 as $i => $value){
		//print_r($value);print_r('<br><br>');
	//	if ((trim($docs[$i]['NR_KF'])=='') or ($docs[$i]['ANULOWANA'] == 'T')) continue;
		if ((trim($new2[$i]['DO_PR'])=='')) continue;
				$add++;
		$id=addFk44($docs[$i],$i,'');
	//	
	
		$j=0;
		foreach($products[$docs[$i]['NR_SYSTEM']] as $prod){
			addProductLine24($id[0],$j,$prod,$path,$id[1]);
			$j++;
		}
		$id=getKfId3($new2[$i],$products);
	}
	echo "Podsumowanie:<br>W dbf: ".$num_rec."<br>Dodano: ".$add; 
	//$koniec = getmicrotime();
	echo "<br>Czas trawania:".(($koniec - $start)/60)." minut<br><br>";
}

$re = mysql_query('SELECT id, dir FROM ecmstocks');
while($magazyn = mysql_fetch_array($re)){
	

	if($magazyn['dir']=='1'){
		$path = dirname(__FILE__).'/przemyslowka/1/';
		mainloop44($path);
	} else {

		$path = dirname(__FILE__).'/przemyslowka/glowny/';
		mainloop44($path);
	}
}


$res2 = mysql_query("select * from ecmreceipts where type='correct'");

while($r = mysql_fetch_array($res2, MYSQL_ASSOC)){

	$vats_summary = '';
    $total_netto = 0;
    $total_brutto = 0;
    $total_vat = 0;
    $vats=array();
    $res = mysql_query ( "select
	total_netto,ecmvat_id,ecmvat_value,ecmvat_name
 from ecmreceiptitems n
where
    n.ecmreceipt_id = '".$r['id']."'" );

    while ( $cc = mysql_fetch_array($res, MYSQL_ASSOC) ) {
        $vats[$cc['ecmvat_id']]['jest']['total_netto']+=$cc['total_netto'];
        $vats[$cc['ecmvat_id']]['ecmvat_value']=$cc['ecmvat_value'];
        $vats[$cc['ecmvat_id']]['ecmvat_name']=$cc['ecmvat_name'];
    }
    $res = mysql_query (" select
	n.total_netto,n.ecmvat_id,n.ecmvat_value,n.ecmvat_name
 from ecmreceiptsitems n
inner join ecmreceiptitems o on o.old_ecminvoiceoutitem_id=n.id
where
    o.ecminvoiceout_id = '".$r['id']."'" );
    print_r('res2');print_r('<br><br>');
    print_r(mysql_fetch_array($res));print_r('<br><br>');
    while ( $cc = mysql_fetch_array($res, MYSQL_ASSOC) ) {
        $vats[$cc['ecmvat_id']]['bylo']['total_netto']+=$cc['total_netto'];
        $vats[$cc['ecmvat_id']]['ecmvat_value']=$cc['ecmvat_value'];
        $vats[$cc['ecmvat_id']]['ecmvat_name']=$cc['ecmvat_name'];
    }
    $vats_now=array();

    foreach ($vats as $key=>$val){
        if($vats[$key]['jest']['total_netto']==''){
            $vats[$key]['jest']['total_netto']=0;
        }
        if($vats[$key]['bylo']['total_netto']==''){
            $vats[$key]['bylo']['total_netto']=0;
        }
        $total_netto+=$vats[$key]['jest']['total_netto']-$vats[$key]['bylo']['total_netto'];
        $total_vat+=(($vats[$key]['jest']['total_netto']-$vats[$key]['bylo']['total_netto'])*$vats[$key]['ecmvat_value'])/100;
        $total_brutto+=((($vats[$key]['jest']['total_netto']-$vats[$key]['bylo']['total_netto'])*$vats[$key]['ecmvat_value'])/100)+($vats[$key]['jest']['total_netto']-$vats[$key]['bylo']['total_netto']);
        $vats_summary .= $vats[$key]['ecmvat_name'] . ':' .round($vats[$key]['jest']['total_netto']-$vats[$key]['bylo']['total_netto'],2)
        . ':' . round((($vats[$key]['jest']['total_netto']-$vats[$key]['bylo']['total_netto'])*$vats[$key]['ecmvat_value'])/100,2). ':'
                . round(((($vats[$key]['jest']['total_netto']-$vats[$key]['bylo']['total_netto'])*$vats[$key]['ecmvat_value'])/100)+($vats[$key]['jest']['total_netto']-$vats[$key]['bylo']['total_netto']),2) . ',';

    }
    echo $vats_summary;
    $res = mysql_query ( "update ecmreceipts set vats_summary='" . $vats_summary . "',total_netto='" . round($total_netto,2) . "',total_vat='" . round($total_vat,2) . "',
	           total_brutto='" . round($total_brutto,2) . "' where id='" . $r['id'] . "'" );

} 
/*

$query = "SELECT * FROM ecminvoiceoutitems WHERE ecmproduct_id ='BRAK INDEKSU'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
	$query = "SELECT id from ecmproducts where code='" .$row['code']. "' AND name='".$row['name']."'";
	$re = mysql_query($query);
	$count=0;
	$r = mysql_fetch_array($re);
	$updateQuery = "UPDATE ecminvoiceoutitems SET ecmproduct_id='" . $r['id'] . "' where id='" . $row['id'] ."'";
	echo $updateQuery . '<br>';
	mysql_query($updateQuery);
}
echo 'done';
mysql_close($sql);
*/
?>
