<?php
set_time_limit(9999999999);

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

$sql=mysql_connect("localhost","root","sgpmk777");
mysql_select_db("ekomer");
mysql_query("set names utf8");
mysql_query("truncate table ecmstockoperations");
mysql_query("truncate table ecmstockdocins");
mysql_query("truncate table ecmstockdocinitems");

$re="RE00018";

$w=mysql_query("select id,name,dir from ecmstocks where deleted='0' and id='c7afd71a-4c3a-bde4-138d-4acaee1644e4'");
while($r=mysql_fetch_array($w)){
	addPzBilans("PZ 201403176001",$r['id']);
	
	$dbf = new dbf_class("ekomer/_stany.dbf");
	$num_rec=$dbf->dbf_num_rec;
	
	$dbfp = new dbf_class("ekomer/_struk.dbf");
	$num_recp=$dbfp->dbf_num_rec;
	$products=array();
	for($j=0;$j<$num_recp;$j++){
    	$rowp = $dbfp->getRowAssoc($j);
		$products[$rowp['NR_SYSTEM']][]=$rowp;
	}
	
	$n=1;
	for($i=0;$i<$num_rec;$i++){
   		$row = $dbf->getRowAssoc($i);
		//if($re!=$row['INDEKS'])continue;
		$scena=$row['CENA'];
		$silosc=$row['STAN'];
		$index=$row['INDEKS'];
		$rr=mysql_fetch_array(mysql_query("select name from ecmproducts where code like '".ch($index)."' and deleted='0'"));
		$name=$rr['name'];
		$cena=0;
		$ilosc=0;
		if(count($products[$row['NR_SYSTEM']])>0){
		foreach($products[$row['NR_SYSTEM']] as $prod){
			if($prod['ILOSC']>0){
				addOperation("bilans_otwarcia".$r['id'],"PZ 20091006001","EcmStockDocIn",1,ch($index),ch($name),$prod['ILOSC'],$prod['CENA_ZAK'],0,$r['id'],$r['name']);
				addProductLinePZ("bilans_otwarcia".$r['id'],$n,$prod,ch($index),ch($name));
				$n++;
				$cena+=(int)$prod['ILOSC']*$prod['CENA_ZAK'];
				$ilosc+=(int)$prod['ILOSC'];
				$sum+=$ilosc*$cena;
			}
		}
		}
		//echo $i."/".$num_rec." ".$r['dir']." ".$ilosc." = ".round($silosc,0)."\n";
	}
	//mysql_query("update ecmstockdocins set total='".$sum."',subtotal='".$sum."'");
	$a="update ecmstockdocins set total='".$sum."',subtotal='".$sum."';\n";
	echo $a;
}
//echo round(($cena/$ilosc),2)." = ".$scena."\n".$ilosc." = ".$silosc;
mysql_close($sql);
?>