﻿<?php
// alfados (����� ��������)
session_name('iAdmin'); session_start(); 
?><html>

<head>
<BASE HREF="http://<?php echo $_SERVER['HTTP_HOST']; ?>/">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1253">
<LINK REL="stylesheet" type="text/css" href="ishop/adm.css">
<SCRIPT SRC="ishop/xadm.js.php"></SCRIPT>
<title>Modern iShopping cart Setup</title>
<style>
.openTable {
   border-top: 1px solid #404040;
   border-left: 1px solid #404040;
   border-right: 1px solid #404040;
   table-layout:fixed;
}
</style>
</head>

<body>
<?php
include("../lib/ado/adodb.inc.php");
include("../lib/generic.inc.php");
require_once("ishop_all.inc.php");
include("ishop/ishop.inc.php");

$db_local = &db_open();

$x2=new cX2($db_local);

// confirm_login() needs LPATH, PASSWD or RESELID, REPASS; Reseller needs allowence for desktop login
if ( !$x2->quick_login() && !$x2->validate_session() ) // err
	die("Authentication error");

$x2->read_agent_main();
print_header();

$fu=0;
if (isset($_REQUEST['FUNC2']))
   $fu=(int)$_REQUEST['FUNC2'];

switch ($fu)
{
case 0:
   main_menu();
   break;
case 1:
	pre_load_ascii();
	echo "<hr>";
	main_menu();
	break;
case 2:
   load_files();
   echo "<hr>";
   main_menu();
   break;
case 4:
	load_customer();
   main_menu();
   break;
case 5:
   pre_export_orders($upd=false);
   break;
case 6:
   pre_export_orders($upd=true);
   break;
case 7:
   do_export_orders();
   echo "<hr>";
   main_menu();
   break;
case 16:
   parameter_ask();
   break;
case 17:
   parameter_save();
   break;
}

$db_local->Close();

//======================================
// Functions
//======================================
function print_header()
{
   global $x2;
?>
<table width=100%>
<tr>
   <td class=bgHeader>Modern iShopping cart Setup (for <?php echo $x2->extIds[108]; ?>) agentid=<?php
      echo $x2->agentid.'# '.myhtml($x2->lpath);
   ?></td>
</tr>
</table>
<?php
}
//======================================
function main_menu()
{
?>
<h5>��������</h5>
<ul>
<!-- 
<li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=16">����������</a> 
-->
<li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=1">�������� ascii</a>
<!--
<li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=5">������� ����������� (������ ����)</a>
<li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=6">������� �����������</a>
-->
</ul>
<button type=button onClick="self.close()">Close Window</button>
<!--
<p style="background-color:#D0D0D0;">
Auto-scheduler:
<BR>
<kbd><?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=...&amp;LPATH=...&amp;PASSWD=...</kbd>
<BR>�
<BR><kbd><?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=...&amp;RESELID=...&amp;REPASS=...</kbd>
</kbd>
</p>
-->
<?php
}
//--------------------------------------
function trim_leading_zero($src)
{
	$i=0;
	$l=strlen($src);
	while ($i<$l && $src{$i}=='0')
		$i++;
		
	if ($i>0)
		return substr($src,$i);
	else
		return $src;
}
//--------------------------------------
function trim_2spaces($src)
{
	while (strpos($src,'  ')!==false)
		$src=str_replace('  ',' ',$src);

	return $src;
}
//--------------------------------------
function load_menurep($typ,$src)
{
   global $x2;
   $db=&$x2->db;

   $prof=new cPROFILER1();

   $fname=$GLOBALS['cfx']->ascii.'\\'.$src;
	if (($fp=fopen($fname,"r"))===false) {
		echo "<h6>Could not open file ".myhtml($fname)."</h6>";
		return;
	}

   // Delete old values
	$query="DELETE FROM menurep WHERE AGENTID=? AND MENUTYPE=?";
	$data=array($x2->agentid, $typ);
	if (!$db->Execute($query,$data)) {
      echo "<h6>".$db->ErrorMsg()."</h6>";
      fclose($fp);
      return;
   }

	$query="INSERT INTO menurep (AGENTID,MENUTYPE,MENUID,MENUDES) VALUES(?,?,?,?)";

	$nrec=0;
	$nerr=0;
	while (!feof($fp)) {
		$buf=fgets($fp,1024);
		$var=explode('#',$buf);
		if (empty($var) || count($var)<2)
			continue;

		$id=trim_leading_zero(trim($var[0]));
		$des=trim($var[1]);

		$data=array( $x2->agentid, $typ, $id, $des );
		if (!$db->Execute($query,$data)) {
			echo "<h6>".$db->ErrorMsg()."</h6>";
			$nerr++;
		}
		else {
			$nrec++;
		}
	}
	fclose($fp);

	echo "<h5>$nrec records replaced in ".$prof->elapsed()." seconds, $nerr errors.</h5>";
}
//--------------------------------------
function load_supplier()
{
   global $x2;
   $db=&$x2->db;

   $prof=new cPROFILER1();

   $fname=$GLOBALS['cfx']->ascii.'\\SUPPLIERS.TXT';
	if (($fp=fopen($fname,"r"))===false) {
		echo "<h6>Could not open file ".myhtml($fname)."</h6>";
		return;
	}

   // Delete old values
	$query="DELETE FROM ishop_sup WHERE AGENTID=?";
	$data=array($x2->agentid);
	if (!$db->Execute($query,$data)) {
      echo "<h6>".$db->ErrorMsg()."</h6>";
      fclose($fp);
      return;
   }

	$query="INSERT INTO ishop_sup (AGENTID,LOGIN,COMPANY,TRKEY) VALUES(?,?,?,?)";

	$nrec=0;
	$nerr=0;
	while (!feof($fp)) {
		$buf=fgets($fp,1024);
		$var=explode('#',$buf);
		if (empty($var) || count($var)<2)
			continue;

     	$trkey=ToEnglish( trim($var[0])." ".trim($var[1]) );
		$data=array( $x2->agentid, trim($var[0]), trim($var[1]), $trkey );
		if (!$db->Execute($query,$data)) {
			echo "<h6>".$db->ErrorMsg()."</h6>";
			$nerr++;
		}
		else {
			$nrec++;
		}
	}
	fclose($fp);

	echo "<h5>$nrec records replaced in ".$prof->elapsed()." seconds, $nerr errors.</h5>";
}
//--------------------------------------
function pre_load_ascii()
{
   global $x2;
?>
<table>
<form method=POST action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<input type=HIDDEN name="FUNC2" value="2">
<input type=hidden name="MAX_FILE_SIZE" value="10000000">
<tr>
   <td colspan=2><b>�������� ascii</b></td>
</tr>
<tr>
   <td>������</td>
   <td><input type=FILE name="ASCIIFILE"></td>
<tr>
   <td>��������</td>
   <td><select name="WHAT">
      <option value="2">�������
      <option value="1">����
      </select></td>
</tr>
<tr>
   <td></td>
   <td><input type=SUBMIT name="ok" value="��������"></td>
</tr>
</form>
</table>
<?php
}
//--------------------------------------
function load_files()
{
   switch ( (int)$_REQUEST['WHAT'] )
   {
   case 1: // items
      load_items();
      break;
   case 2:
      load_customer();
      break;
   }
}
//--------------------------------------
function load_customer()
{  // New
   global $x2;
   $db=&$x2->db;

   $prof=new cPROFILER1();
   
   $t1='ishop_mbr';
   $prim=array('AGENTID', 'LOGIN');

   $t2='ishop_delivery';
   $pri2=array('AGENTID', 'MBR_LOGIN', 'DLVID');

   $nrec=$nrec2=0;
   $nerr=0;
   $datafile=$_FILES['ASCIIFILE']['tmp_name'];
   do {
      if (($fp=@fopen($datafile,"r"))===false) {
         echo "<h6>������� �� ������� ��� �������!</h6>\n";
         break;
      }

      // ������� ��� �� ��������� records �� -1. ���� �������� ��� loading ���� 0.
      // ��� ����� �� ����� �� �������� (���������).
   	$q2="UPDATE ishop_mbr SET XDBID=-1 WHERE AGENTID=?";
	   $data=array($x2->agentid);
   	if (!$db->Execute($q2,$data)) {
         echo "<h6>".$db->ErrorMsg()."</h6>";
         fclose($fp);
         return;
      }

      $last_login=false;
      while (!feof($fp)) {
         $buf0=fgets($fp,2048);

         $buf=tr437_928($buf0,true);

         $login=trim(substr($buf,0,7));
         if (strlen($login)==0)
            continue;

         if ($last_login!==false && strcmp($login,$last_login)==0) {
            // �������� ���������������
            $data2=array('AGENTID'=>$x2->agentid, 'MBR_LOGIN'=>$login,
               'DLVID'=>(int)substr($buf,7,5), 'ADDR1'=>trim(substr($buf,53,26)),
               'CITY'=>trim(substr($buf,79,21)), 'PHONE'=>trim(substr($buf,186,32)) );
            if (ReplaceEx($db,$t2,$data2,$pri2)==0) {
               echo "<h6>".$db->ErrorMsg()."</h6>";
               ++$nerr;
            }
            else {
               echo ++$nrec2."\n";
            }

            continue;
         }

         $last_login=$login; // save login

         // Reassigning the whole table is faster then reassigning each key=>value pair individually
         $data=array('AGENTID'=>$x2->agentid, 'XDBID'=>0,
            'LOGIN'=>$login, 'COMPANY'=>trim(substr($buf,12,41)),
            'ADDR1'=>trim(substr($buf,53,26)), 'CITY'=>trim(substr($buf,79,21)),
            'JOB'=>trim(substr($buf,100,21)), 'VATCODE'=>trim(substr($buf,121,13)),
            'DOY'=>trim(substr($buf,134,21)), 'PHONE'=>trim(substr($buf,186,32)) );

         $trkey=ToEnglish($data['LOGIN']." ".$data['COMPANY']);
         $data['TRKEY']=$trkey;

         if (ReplaceEx($db,$t1,$data,$prim)==0) {
            echo "<h6>".$db->ErrorMsg()."</h6>";
            ++$nerr;
         }
         else {
            echo ++$nrec."\n";
         }
      }
      fclose($fp);

      // ����� �� �������� (���������).
   	$q2="DELETE FROM ishop_mbr WHERE AGENTID=? AND XDBID=-1";
	   $data=array($x2->agentid);
   	if (!$db->Execute($q2,$data)) {
         echo "<h6>".$db->ErrorMsg()."</h6>";
         break;
      }

   } while (false);

   echo "<h5>$nrec +$nrec2 records processed in ".$prof->elapsed()." seconds, $nerr errors.</h5>";
}
//--------------------------------------
function load_items()
{
   global $x2;
   $db=&$x2->db;

   $prof=new cPROFILER1();

   $t1='ishop_ctg';
   $prim=array('AGENTID', 'PAGENO');

   $t2='ishop_item';
   $pri2=array('AGENTID', 'CODE');

   $query="INSERT INTO ishop_item
      (AGENTID, CODE, NAME, PAGENO, UNIT, VATCAT, TRKEY)
      VALUES (?,?,?,?,  ?,?,?) ";

   $nrec=$nrec2=0;
   $nerr=0;
   $datafile=$_FILES['ASCIIFILE']['tmp_name'];
   do {
      if (($fp=@fopen($datafile,"r"))===false) {
         echo "<h6>������� �� ������� ��� �������!</h6>\n";
         break;
      }

      // ������� ��� �� ��������� records �� -1. ���� �������� ��� loading ���� 0.
      // ��� ����� �� ����� �� �������� (���������).
   	$q2="UPDATE ishop_item SET XDBID=-1 WHERE AGENTID=?";
	   $data=array($x2->agentid);
   	if (!$db->Execute($q2,$data)) {
         echo "<h6>".$db->ErrorMsg()."</h6>";
         fclose($fp);
         return;
      }

      while (!feof($fp)) {
         $nrec++;
         if ($nrec==1)
            continue;

         $buf0=fgets($fp,2048);
         $buf=tr437_928($buf0,true); // 437->928

         $code=trim(substr($buf,0,14));
         if (strlen($code)==0)
            continue;

         $name=trim(substr($buf,14,51));

         $ar1=explode(' ',trim(substr($buf,65,16)),2);
         if (count($ar1)==2 && strlen($ar1[1])>0)
            $unit=$ar1[1];
         else
            $unit=$ar1[0];

         $ar1=explode(' ',trim(substr($buf,81,16)),2);
         $ctg=$ar1[0];
         if (count($ar1)==2 && strlen($ar1[1])>0) {
            $data=array('AGENTID'=>$x2->agentid, 'PAGENO'=>$ctg, 'ABBREV'=>$ar1[1], 'TITLE'=>$ar1[1]);
            if (ReplaceEx($db,$t1,$data,$prim)==0)
               echo "<h6>".$db->ErrorMsg()."</h6>";
         }

         $vc1=toFloat(substr($buf,97));
         if ($vc1==9.0)
            $vatcat=1;
         else if ($vc1==19.0)
            $vatcat=2;
         else
            $vatcat=3;

         $trkey=ToEnglish($code.' '.$name);

         // Reassigning the whole table is faster then reassigning each key=>value pair individually
         $data2=array( 'AGENTID'=>$x2->agentid, 'XDBID'=>0, 'CODE'=>$code, 'NAME'=>$name,
            'PAGENO'=>$ctg, 'UNIT'=>$unit, 'VATCAT'=>$vatcat, 'TRKEY'=>$trkey );
         if (ReplaceEx($db,$t2,$data2,$pri2)==0) {
            echo "<h6>".$db->ErrorMsg()."</h6>";
            ++$nerr;
         }
         else {
            echo ++$nrec."\n";
         }

         //
         // Process quantity
         //
         /*
         $qua=toFloat(substr($buf,139,18));
         $whid=(int)substr($buf,159,3);

         $n=0;
         $data=array( $x2->agentid, $whid, $code );
         if (($rs=$db->Execute($q81c,$data))===false) {
            echo "<h6>".$db->ErrorMsg()."</h6>";
            break;
         }
         if ($row=$rs->FetchRow()) {
            $n=(int)$row[0];
         }
         $rs->Close();

         if ($n==0) {
            // Record not found, insert quantity
            $data=array( $x2->agentid, $whid, $code, $qua );
            if (!$db->Execute($q81ins,$data)) {
               echo "<h6>".$db->ErrorMsg()."</h6>";
               break;
            }
            else
               echo ++$nrec2."\n";
         }
         else {
            // Record found, add quantity
            $data=array( $qua, $x2->agentid, $whid, $code );
            if (!$db->Execute($q81upd,$data)) {
               echo "<h6>".$db->ErrorMsg()."</h6>";
               break;
            }
            else
               echo ++$nrec2."\n";
         }
         */
      }

      fclose($fp);

      // ����� �� �������� (���������).
   	$q2="DELETE FROM ishop_item WHERE AGENTID=? AND XDBID=-1";
	   $data=array($x2->agentid);
   	if (!$db->Execute($q2,$data)) {
         echo "<h6>".$db->ErrorMsg()."</h6>";
         break;
      }

   } while (false);

	echo "<h5>$nrec +$nrec2 records processed in ".$prof->elapsed()." seconds, $nerr errors.</h5>";
}
//--------------------------------------
function parameter_ask()
{
   global $x2;
   $db=&$x2->db;

   if (isset($x2->Agp['EXT108_USEPAYMETHOD']))
      $upm=(int)$x2->Agp['EXT108_USEPAYMETHOD'];
   else
      $upm=0;
?>
<h5>����������</h5>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method=POST>
<input type=HIDDEN name="FUNC2" value="17">

<table width=500 class=openTable style="border-bottom: 1px solid #404040;">
<tr>
   <td width=200><b>������� ��������</b></td>
   <td width=300>&nbsp;</td>
</tr>
<tr>
   <td>����� ������� ��������</td>
   <td><input type=CHECKBOX name="EXT108_USEPAYMETHOD" <?php
      if ($upm!=0) echo "CHECKED";
      ?> value="1"> ���</td>
</tr>
</table>

<table width=500 style="table-layout:fixed;">
<tr>
   <td width=200>&nbsp;</td>
   <td width=300><input type=SUBMIT name="ok" value="��������">
      <input type=button onclick="location.href='<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=0';"
      value="�����"></td>
</tr>
</table>

</form>
<?php
}
//--------------------------------------
function parameter_save()
{
   global $x2;
   $db=&$x2->db;

   if (!isset($_REQUEST['EXT108_USEPAYMETHOD']))
      $_REQUEST['EXT108_USEPAYMETHOD']=0;

   $pars=array('EXT108_USEPAYMETHOD');
   $prim=array('AGENTID', 'PNAME');

   foreach ($pars as $par1) {
      $data=array( 'PNAME'=>$par1, 'PVALUE'=>$_REQUEST[$par1], 'AGENTID'=>$x2->agentid );
      if (ReplaceEx($db_local, 'agent_main', $data, $prim)) // o.k.
         $x2->Agp[$par1]=$_REQUEST[$par1];
      else // error
         echo "<h6>".$db_local->ErrorMsg()."</h6>";
   }
}
//--------------------------------------
function pre_export_orders($upd=false)
{
   global $x2;
?>
<script language=javascript>
function verify_file()
{
   var f1=document.forms[0];
   if (f1.OUTFILE.value.length==0) {
      window.alert('��� ���������� OUTFILE!')
      return;
   }
   var i=f1.OUTFILE.value.lastIndexOf('.');
   if (i<0) {
      file1=f1.OUTFILE.value+'1';
      file2=f1.OUTFILE.value+'2';
   }
   else if (i==0) {
      file1='1.'+f1.OUTFILE.value.substr(1);
      file2='2.'+f1.OUTFILE.value.substr(1);
   }
   else { // i>0
      file1=f1.OUTFILE.value.substr(0,i)+'1.'+f1.OUTFILE.value.substr(i+1);
      file2=f1.OUTFILE.value.substr(0,i)+'2.'+f1.OUTFILE.value.substr(i+1);
   }
   var msg='������� ��� ������ '+file1+', '+file2+'?';
   if (window.confirm(msg))
      f1.submit();
}
</script>
<h5>������� �����������</h5>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method=POST>
<input type=HIDDEN name="FUNC2" value="7">

<table width=500 class=openTable style="border-bottom: 1px solid #404040;">
<tr>
   <td>���������</td>
   <td><input type=CHECKBOX name="UPD" <?php
      if ($upd) echo "CHECKED";
      ?> value="1"> ���</td>
</tr>
<tr>
   <td>������ ������</td>
   <td><input type=TEXT name="OUTFILE" value="<?php echo myhtml(@$x2->Agp['EXT108_OUTFILE']); ?>" size=40></td>
</tr>
</table>

<table width=500 style="table-layout:fixed;">
<tr>
   <td>&nbsp;</td>
   <td><input type=BUTTON name="ok" value="��������" onclick="verify_file()">
      <input type=button onclick="location.href='<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=0';"
      value="�����"></td>
</tr>
</table>

</form>
<?php
}
//--------------------------------------
function do_export_orders()
{
   global $x2;
   $db=&$x2->db;

   // Save outfile
   $prim=array('AGENTID', 'PNAME');
   $data=array('AGENTID'=>$x2->agentid, 'PNAME'=>'EXT108_OUTFILE', 'PVALUE'=>$_REQUEST['OUTFILE'] );
   if (ReplaceEx($db, 'agent_main', $data, $prim)) // o.k.
      $x2->Agp['EXT108_OUTFILE']=$_REQUEST['OUTFILE'];
   else // error
      echo "<h6>".$db_local->ErrorMsg()."</h6>";

   // Prepare for export
   $i=strrpos( $_REQUEST['OUTFILE'], '.' );
   if ($i===false) {
      $file1=$_REQUEST['OUTFILE'].'1';
      $file2=$_REQUEST['OUTFILE'].'2';
   }
   else if ($i==0) {
      $file1='1.'.substr($_REQUEST['OUTFILE'], 1);
      $file2='2.'.substr($_REQUEST['OUTFILE'], 1);
   }
   else { // $i>0
      $file1=substr($_REQUEST['OUTFILE'], 0, $i).'1.'.substr($_REQUEST['OUTFILE'], $i+1);
      $file2=substr($_REQUEST['OUTFILE'], 0, $i).'2.'.substr($_REQUEST['OUTFILE'], $i+1);
   }

   // Export data
   $upd=(int)@$_REQUEST['UPD'];
   $fp1=$fp2=false;
   $oids=array();
   do {
      if (($fp1=@fopen($file1,"w"))===false) {
         echo "<h6>Failed to open file ".myhtml($file1)."!</h6>";
         break;
      }

      if (($fp2=@fopen($file2,"w"))===false) {
         echo "<h6>Failed to open file ".myhtml($file2)."!</h6>";
         break;
      }

      // Export orders
      $seline=str_pad('',120,'123456789+');
      $query="SELECT T1.ORDERID, T1.LOGTIME, T1.MBR_LOGIN, T1.DOCID, T1.DISCOUNT DM, T1.DISCOUNTCALC, T1.COMMENT,
         T2.DISCOUNT DLI, T2.ICODE, T2.QUANTITY, T2.PRICE, T5.PVALUE F1, T3.PVALUE ISS, T4.WAREHOUSEID,
         T6.PVALUE CANDOCID
         FROM order_main T1
         LEFT JOIN order_line T2 ON (T2.ORDERID=T1.ORDERID)
         LEFT JOIN order_prop T3 ON (T3.ORDERID=T1.ORDERID AND T3.PNAME='ORD_ISSUESEQ')
         LEFT JOIN reseller T4 ON (T4.AGENTID=T1.AGENTID AND T4.RESELID=T1.RE_RESELID)
         LEFT JOIN order_prop T5 ON (T5.ORDERID=T1.ORDERID AND T5.PNAME='ORD_ISSUENR')
         LEFT JOIN order_prop T6 ON (T6.ORDERID=T1.ORDERID AND T6.PNAME='ORD_CANCELED_DOCID')
         WHERE T1.AGENTID=? AND T1.STATE=9
         ORDER BY T1.ORDERID, T2.ORDLINE";
      $data=array($x2->agentid);
      if (($rs=$db->Execute($query,$data))===false) {
         echo "<h6>".$db->ErrorMsg()."</h6>";
         break;
      }
      $err=false;
      $last_oid=-1;
      echo "<pre>";
      while ($o1=$rs->FetchNextObject()) {
         if ($o1->DOCID==5) { // ���������
            $docid=(int)$o1->CANDOCID;
            $qdoc="SELECT XDBCATYP XDB_TYPE, XDBCADES XDB_DESC FROM ISSUEDOC
               WHERE AGENTID=? AND DOCID=? AND (ISSUESEQ=? OR ISSUESEQ=?)";
         }
         else {
            $docid=(int)$o1->DOCID;
            $qdoc="SELECT XDBRTYPE XDB_TYPE, XDBRDESC XDB_DESC FROM ISSUEDOC
               WHERE AGENTID=? AND DOCID=? AND (ISSUESEQ=? OR ISSUESEQ=?)";
         }

         $ar2=array('XDB_TYPE'=>'', 'XDB_DESC'=>'');
         $data2=array($x2->agentid, $docid, $o1->ISS, convertEngToGr($o1->ISS,1));
         if ($rs2=$db->Execute($qdoc,$data2)) {
            if ($o2=$rs2->FetchNextObject()) {
               $ar2['XDB_TYPE']=$o2->XDB_TYPE;
               $ar2['XDB_DESC']=$o2->XDB_DESC;
            }
            $rs2->Close();
         }
         else {
            echo "<h6>".$db->ErrorMsg()."</h6>";
         }

         $dti=explode(' ',$o1->LOGTIME); // YYYY-MM-DD HH:MM:SS
         $dd=explode('-',$dti[0]); // YYYY-MM-DD
         $line = $dd[2].'/'.$dd[1].'/'.$dd[0];

         $line .= substr( str_pad($ar2['XDB_DESC'],3), 0, 3);
         $line .= substr( str_pad($o1->F1,6,"0",STR_PAD_LEFT), 0, 6);
         $line .= substr( str_pad($ar2['XDB_TYPE'],2,"0",STR_PAD_LEFT), 0, 2).str_pad('',3);
         $line .= substr( str_pad($o1->MBR_LOGIN,14), 0, 14);
         $line .= substr( str_pad($o1->ICODE,10), 0, 10).str_pad('',10);
         $line .= substr( str_pad($o1->WAREHOUSEID,2), 0, 2);
         $line .= str_pad(sprintf("%01.3f",abs($o1->QUANTITY)),10,' ',STR_PAD_LEFT); // 6+1+3=10
         $line .= str_pad(sprintf("%01.3f",$o1->PRICE),14,' ',STR_PAD_LEFT); // 10+1+3=14
         $line = str_pad($line,90);

         if ((int)$o1->DISCOUNTCALC==0) { // ����������
            $discount = $o1->DM + $o1->DLI;
         }
         else { // ����������������
      	   $discount = 100 - (1.0 - $o1->DLI/100.0) * (1.0 - $o1->DM/100.0) * 100.0;
         }
         $line .= str_pad(sprintf("%01.1f",$discount),6,' ',STR_PAD_LEFT); // 4+1+1=6

         $val = abs($o1->QUANTITY) * $o1->PRICE * (1.0 - $discount/100.0);
         $line .= str_pad(sprintf("%01.2f",$val),10,' ',STR_PAD_LEFT); // 7+1+2=10

         $line .= strtr($o1->COMMENT,"\r\n", "  "); // 'TEXT' field

         // Fill collection
         if (!in_array($o1->ORDERID,$oids))
            $oids[]=$o1->ORDERID;
          
         if ($o1->ORDERID!=$last_oid && $last_oid>=0) {
            // Write data
            if (!fwrite($fp1,"\r\n")) {
               echo "<h6>Failed to write file!</h6>";
               $err=true;
               break;
            }

            // Debug
            if ($upd==0)
               echo "\n$seline\n";
         }

         // Write data
         if (!fwrite($fp1,tr437_928($line,false)."\r\n")) {
            echo "<h6>Failed to write file!</h6>";
            $err=true;
            break;
         }

         // Debug
         if ($upd==0)
            echo "$line\n$seline\n";
            
         $last_oid=$o1->ORDERID;
      }
      echo "</pre>";
      $rs->Close();

      if ($err)
         break;

      echo "<hr>";

      // Export cash
      $qdoc="SELECT XDBMOTYP, XDBMODES FROM ISSUEDOC
         WHERE AGENTID=? AND DOCID=? AND (ISSUESEQ=? OR ISSUESEQ=?)";
      $cdocs=array(2,4,6); // Doc. ids with cash (2=>'��������� - �/���������', 4=>'��������� - �/���������', 6=>'���������')
      $query="SELECT T1.ORDERID, T1.LOGTIME, T1.MBR_LOGIN, T1.GRANDTOTAL, T1.DOCID, T1.COMMENT,
         T5.PVALUE F1, T3.PVALUE ISS, T2.PVALUE CANDOCID
         FROM order_main T1
         LEFT JOIN order_prop T2 ON (T2.ORDERID=T1.ORDERID AND T2.PNAME='ORD_CANCELED_DOCID')
         LEFT JOIN order_prop T3 ON (T3.ORDERID=T1.ORDERID AND T3.PNAME='ORD_ISSUESEQ')
         LEFT JOIN order_prop T5 ON (T5.ORDERID=T1.ORDERID AND T5.PNAME='ORD_ISSUENR')
         WHERE T1.AGENTID=? AND T1.ORDERID IN (".implode(',',$oids).") AND T1.STATE=9
         ORDER BY T1.ORDERID ";
      $data=array($x2->agentid);
      if (($rs=$db->Execute($query,$data))===false) {
         echo "<h6>".$db->ErrorMsg()."</h6>";
         break;
      }
      $err=false;
      echo "<pre>";
      while ($o1=$rs->FetchNextObject()) {
         if ($o1->DOCID==5) { // ���������
            $docid=(int)$o1->CANDOCID;
         }
         else {
            $docid=(int)$o1->DOCID;
         }
         if (!in_array($docid,$cdocs))
            continue;

         $ar2=array('XDB_TYPE'=>'', 'XDB_DESC'=>'');
         $data2=array($x2->agentid, $docid, $o1->ISS, convertEngToGr($o1->ISS,1));
         if ($rs2=$db->Execute($qdoc,$data2)) {
            if ($o2=$rs2->FetchNextObject()) {
               $ar2['XDB_TYPE']=$o2->XDBMOTYP;
               $ar2['XDB_DESC']=$o2->XDBMODES;
            }
            $rs2->Close();
         }
         else {
            echo "<h6>".$db->ErrorMsg()."</h6>";
         }

         $line = substr( str_pad($ar2['XDB_TYPE'],2,"0",STR_PAD_LEFT), 0, 2);

         $line .= substr( str_pad($ar2['XDB_DESC'],3), 0, 3);
         $line .= substr( str_pad($o1->F1,6,"0",STR_PAD_LEFT), 0, 6);

         $dti=explode(' ',$o1->LOGTIME); // YYYY-MM-DD HH:MM:SS
         $dd=explode('-',$dti[0]); // YYYY-MM-DD
         $line .= $dd[2].'/'.$dd[1].'/'.$dd[0];

         $line .= substr( str_pad($o1->MBR_LOGIN,14), 0, 14);
         $line .= str_pad(sprintf("%01.3f",$o1->GRANDTOTAL),13,' ',STR_PAD_LEFT); // 10+1+2=13
         $line .= strtr($o1->COMMENT,"\r\n", "  "); // 'TEXT' field

         // Write data
         if (!fwrite($fp2,tr437_928($line,false)."\r\n")) {
            echo "<h6>Failed to write file!</h6>";
            $err=true;
            break;
         }

         // Debug
         if ($upd==0)
            echo "$line\n$seline\n";
      }
      echo "</pre>";
      $rs->Close();

      if ($err)
         break;

      // UPDATE
      if ($upd>0) {
         $query="UPDATE order_main SET STATE=110
            WHERE AGENTID=? AND ORDERID IN (".implode(',',$oids).") AND STATE=9";
         $data=array($x2->agentid);
         if (!$db->Execute($query,$data))
            echo "<h6>".$db->ErrorMsg()."</h6>";
      }

   } while (false);

   if ($fp1!==false)
      fclose($fp1);

   if ($fp2!==false)
      fclose($fp2);
}
//--------------------------------------
?>
</body>
</html>

