<?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('E-m-s/_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){


	if(ch($row['ANULOWANA'])=='PRAWDA')continue;
	include("../../config.php");

	$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->set_charset("utf8")) {
	    printf("Error loading character set utf8: %s\n", $mysqli->error);
	} else {
	    printf("Current character set: %s\n", $mysqli->character_set_name());
	}


	$id=create_guid();
	$stmt=$mysqli->prepare("INSERT INTO ecmstockdoccorrects (id,name,pdf_text,date_entered,date_modified,number,document_no,type,register_date,total,stock_id) 
	        VALUES (?,?,?,?,?,?,?,?,?,?,?)"); 
	$stmt->bind_param("sssssssssss", $id,$name,$pdf_text,date("Y-m-d"),date("Y-m-d"),$number,$document_no,$type,$register_date,$total,$stock_id);
	$name=ch($row['UWAGI']);
	$pdf_text=ch($row['UWAGI1']);
	$number=str_replace('/','',ch($row['NR_PL'])).date('dmY',strtotime(ch($row['DATA'])));
	$document_no=$row['NR_PL'];
	$type='';
	$register_date=date('Y-m-d',strtotime(ch($row['DATA'])));
	$total=str_replace(',','.',ch($row['WARTOSC']));
	$stock_id=$stock_id;
	if (!$stmt->execute()) {
	    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
	}
	$stmt->close();
	
	return $id;
}

function addProductLine($id,$i,$r,$bc){
    include("../../config.php");
    $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->set_charset("utf8")) {
        printf("Error loading character set utf8: %s\n", $mysqli->error);
    } else {
        printf("Current character set: %s\n", $mysqli->character_set_name());
    }
    
    $stmt2=$mysqli->prepare("select id from ecmproducts where code=?");
    $stmt2->bind_param("s", ch($r['INDEKS']));
    /* execute statement */
    $stmt2->execute();
     
    /* bind result variables */
    $stmt2->bind_result($idprod);
     
    /* fetch values */
    while ($stmt2->fetch()) {
    
        if($idprod!=''){
            $pid=$idprod;
        }
    }
    $stmt2->close();

	$iid=create_guid();	
	
	$jednostki =
	array (
	        1 => 'kg',
	        2 => 'szt',
	        3 => 'kpl',
	        4 => 'mb',
	        5 => 'm',
	        6 => 't',
	        7 => 'm2',
	        8 => 'doba',
	        9 => 'kmpl',
	        '6275f1de-dbd1-7c7f-f722-556daf14780d' => 'l'
	);
	
	$stmt=$mysqli->prepare("INSERT INTO ecmstockdoccorrectitems (id,date_entered,date_modified,ecmstockdoccorrect_id,ecmproduct_id,position,code,name,quantity,price,total,dd_unit_id,dd_unit_name)
	        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
	$stmt->bind_param("sssssssssssss", $iid,date("Y-m-d"),date("Y-m-d"),$id,$pid,$i,$code,$name,$quantity,$price,$total,$unit_id,$unit_name);
	//repair prices (remove ',')
	$code=ch($r['INDEKS']);
	$name=ch($r['NAZWA']);
	if($r['ILOSC']==''){
	$quantity=str_replace(',','.',$r['ILE_PRZEC']);
	$price=str_replace(',','.',$r['CENA_KONC']);
	$total=$quantity*$price;
	} else {
	$quantity=str_replace(',','.',$r['ILOSC']);
	$price=str_replace(',','.',$r['CENA_EWID']);
	$total=$quantity*$price;
	}
	$jed=strtolower (str_replace('.','',$r['NAZWA_J_M']));
	$unit_id=array_search($jed, $jednostki);
	$unit_name=$jed;
	if (!$stmt->execute()) {
	    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
	}
	
	$stmt->close();
	$bc++;
	return $iid;
	
	
}

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

$start = getmicrotime();
$db=mysql_query('select id,dir from crm.ecmstocks where dir="0"');
while($magi=mysql_fetch_array($db)){
    if($magi['dir']=='0'){
       $path = dirname(__FILE__).'/E-m-s/_pl_list.dbf';
       $path2 = dirname(__FILE__).'/E-m-s/_pl.dbf';
    } else {
       $path = dirname(__FILE__).'/E-m-s/'.$magi['dir'].'/_pl_list.dbf';
       $path2 = dirname(__FILE__).'/E-m-s/'.$magi['dir'].'/_pl.dbf';
    }
	$dbfp = new dbf_class($path);
	$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($path2);
	$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_PL'])=='') 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 crm.ecmstockdoccorrects WHERE document_no ='KS ".trim($docs[$i]['NR_PL'])."'");
		//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,$magi['id'],$magi['dir']);
		$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);
?>
