<?php
// Singular control
include("../lib/ado/adodb.inc.php");
include("../lib/generic.inc.php");
include("../lib/visual.inc.php");
define('MY_SESSION_NAME', 'iAdmin');
implement_session();
?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<BASE HREF="http://<?php echo @$_SERVER['HTTP_HOST']; ?>/">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
<LINK REL="stylesheet" type="text/css" href="script/themes/redmond/jquery-ui.custom.css" />
<LINK REL="stylesheet" type="text/css" href="ishop/adm.css">
<script SRC="script/jquery.js"></script>
<script SRC="script/jquery-ui.js"></script>
<SCRIPT SRC="ishop/xadm.js.php"></SCRIPT>
<script language="javascript" src="/script/datepicker/popcalendar.js"></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 onbeforeunload="save_awcols()">

<table width=100%>
<tr>
   <td class=bgHeader>Modern iShopping cart Setup (for Singular Control)</td>
</tr>
</table>

<?php
require_once("ishop_all.inc.php");
require_once("ishop.inc.php");
include('ishop_x_115a.php');

$dbin = &db_open();

$x2=new cX2($dbin);

// Parse command line arguments
parse_cmd_line();

// confirm_login() needs LPATH, PASSWD or RESELID, REPASS.
if ( !$x2->quick_login() && !$x2->validate_session() ) { // err
   $dbin->Close();
   die("Authentication error");
}
else { // ok
   $_REQUEST['AGENTID']=$x2->agentid;
	$x2->read_agent_main();
}

$fu=(int)@$_REQUEST['FUNC2'];

// Normalize
$pa=array('EXT115_DATASOURCE', 'EXT115_CATALOG', 'EXT115_USERID', 'EXT115_PWD');
foreach ($pa as $pa1) {
   if (isset($x2->Agp[$pa1]))
      $_REQUEST[$pa1]=$x2->Agp[$pa1];
   else
      $_REQUEST[$pa1]='';
}

$dbex = &ADONewConnection('ado_mssql');
if (!$dbex->Connect( $_REQUEST['EXT115_DATASOURCE'], $_REQUEST['EXT115_USERID'], $_REQUEST['EXT115_PWD'], $_REQUEST['EXT115_CATALOG'])) {
	echo "<h6>External database connection failed! ".$dbex->ErrorMsg()."</h6>\n";
	$dbex=false;
}
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;

switch ($fu)
{
case 0:
   main_menu();
   break;
case 1:
   load_customers($dbex,$dbin,0);
   main_menu();
   break;
case 2:
   ask_load_items();
   main_menu();
   break;
case 115:
   load_items($dbex,$dbin);
   main_menu();
   break;
case 4:
   export_ord_ask($dbin);
   main_menu();
   break;
case 5:
   ascii_exp_orders($dbin,true); // do export orders (ascii) real
   main_menu();
   break;
case 6:
   ascii_exp_orders($dbin,false); // export orders (ascii) test
   main_menu();
   break;
case 7:
   load_salesmen($dbex,$dbin);
   load_dlvmethod($dbex, $dbin);
   //load_paymethod($dbex, $dbin);
   //load_warehouse($dbex, $dbin);
   main_menu();
   break;
case 8:
   show_items_sub($dbex, $dbin);
   echo "<a href=\"".$_SERVER['PHP_SELF']."\">Επιστροφή</a>";
   break;
case 9:
   load_items_sub($dbex,$dbin);
   main_menu();
   break;
case 10:
   db_exp_orders($dbex,$dbin,true); // do export orders (DB)
   main_menu();
   break;
case 11:
   db_exp_orders($dbex,$dbin,false); // export orders (DB) test
   main_menu();
   break;
case 13:
   import_orders($dbex, $dbin);
   main_menu();
   break;
case 14:
   db_exp_apogra($dbex, $dbin, false);
   break;
case 15:
   reread_orders($dbex, $dbin);
   main_menu();
   break;
case 16:
   parameter_ask($dbex,$dbin);
   break;
case 17:
   parameter_save($dbin);
   main_menu();
   break;
case 113: // called from a batch file
   real_import_orders($dbex, $dbin);
   break;
case 115: // called from a batch
   real_reread_orders($dbex, $dbin);
   break;
case 200:
   show_files($dbex);
   main_menu();
   break;
case 201:
   show_file_list($dbex);
   break;
case 202:
   show_file_data($dbex);
   echo "<a href=\"javascript:goMovePageEx(202,1)\">Ανανέωση</a> | <a href=\"".$_SERVER['PHP_SELF']."\">Επιστροφή</a>";
   break;
case 203:
   cre_stored_proc();
   main_menu();
   break;
case 209:
   load_items_script($dbin);
   main_menu();
   break;
case 210:
   db_test($dbin);
   main_menu();
   break;
}

if ($dbex) $dbex->Close();
$dbin->Close();

echo "</body></html>";
//======================================
// Functions
//======================================
function main_menu()
{
   global $x2;

   $idata=(int)@$x2->Agp['EXT115_IDATA'];
?>
<b>Επιλογές</b>
<ul>
<li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=16">Παράμετροι</a>
   <br>&nbsp;
<li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=1">Εισαγωγή πελατών</a>
<li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=3"></a>Εισαγωγή κατηγοριών
<?php
   if ($idata==0) {
      echo "<li><a href=\"".$_SERVER['PHP_SELF']."?FUNC2=2\">Εισαγωγή ειδών</a>";
   }
?>
<li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=7">Εισαγωγή πωλητών/ Τρόπων αποστολής <!--/ Πληρωμής/ Αποθηκών--></a>
<?php
   echo "<li>Export παραγγελιών: <a href=\"".$_SERVER['PHP_SELF']."?FUNC2=10\">Export</a> |\n".
         "<a href=\"".$_SERVER['PHP_SELF']."?FUNC2=11\">Δοκιμή</a>\n";
?>
<!--
<li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=14">Export απογραφής</a>
-->
<li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=200">Show files</a>
<!--
<li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=210">Test DB</a>
-->
</ul>
<button type=button onClick="self.close()">Close Window</button>
<?php
}
//--------------------------------------
function load_salesmen($dbin, $dbout)
{
   global $x2;
   $prof=new cPROFILER1();

	if ($dbin===false) {
		echo "<h6>External connection not established!</h6>\n";
		return;
	}

   $nrec=0;
   $prim=array('AGENTID', 'RESELID');

   $query="SELECT NAME, ABBREVIATION, PWD, ID 
      FROM EliteUser.USR";
   $data=false;
   if (!$rs=$dbin->Execute($query,$data)) {
      echo "<h6>".$query.": ".$dbin->ErrorMsg()."</h6>\n";
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $data=array(
			'AGENTID'=>$x2->agentid,
			'RE_NAME'=>ToUTF8($o1->ABBREVIATION),
			'RE_COMMENTS'=>ToUTF8($o1->NAME),
			'PASSWD'=>ToUTF8($o1->PWD),
			'RESELID'=>$o1->ID
		);

      if (ReplaceEx2($dbout,'reseller', $data, $prim ))
         $nrec++;
      else {
         echo "<h6>".__LINE__.$dbout->ErrorMsg()."</h6>\n";
         pre($data);
         //break;
      }
   }
   $rs->Close();

   echo "<h5>".$nrec." records replaced in ".$prof->elapsed()." seconds</h5>";
}
//--------------------------------------
function load_dlvmethod($dbin, $dbout)
{
   global $x2;
   $prof=new cPROFILER1();

	if ($dbin===false) {
		echo "<h6>External connection not established!</h6>\n";
		return;
	}

   $nrec=0;
   $prim=array('AGENTID', 'MENUTYPE', 'MENUID');

   $query="SELECT ID, NAME FROM EliteUser.SHV ";
   $data=false;
   if (!$rs=$dbin->Execute($query,$data)) {
      echo "<h6>".$query.": ".$dbin->ErrorMsg()."</h6>\n";
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $data=array(
			'AGENTID'=>$x2->agentid,
			'MENUTYPE'=>6,
			'MENUID'=>(int)$o1->ID,
			'MENUDES'=>ToUTF8($o1->NAME)
		);
      if (ReplaceEx2($dbout,'menurep', $data, $prim ))
         $nrec++;
      else {
         echo "<h6>".$query.": ".$dbout->ErrorMsg()."</h6>\n";
         //break;
      }
   }
   $rs->Close();

   echo "<h5>Delivery methods: ".$nrec." records replaced in ".$prof->elapsed()." seconds</h5>";
}
//--------------------------------------
function load_warehouse($dbin, $dbout)
{
   global $x2;
   $prof=new cPROFILER1();

	if ($dbin===false) {
		echo "<h6>External connection not established!</h6>\n";
		return;
	}

	$nrec=0;
   $prim=array('AGENTID', 'MENUTYPE', 'MENUID');

   $query="SELECT WHOUSE, NAME FROM WHOUSE WHERE COMPANY=? AND ISACTIVE=1";
   $company=get_company($dbout,$x2->agentid);
   $data=array($company);
   if (!$rs=$dbin->Execute($query,$data)) {
      echo "<h6>".$query.": ".$dbin->ErrorMsg()."</h6>\n";
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $data=array(
			'AGENTID'=>$x2->agentid,
			'MENUTYPE'=>1,
			'MENUID'=>(int)$o1->WHOUSE,
			'MENUDES'=>ToUTF8($o1->NAME)
		);
      if (ReplaceEx2($dbout,'menurep', $data, $prim ))
         $nrec++;
      else {
         echo "<h6>".$query.": ".$dbout->ErrorMsg()."</h6>\n";
         //break;
      }
   }
   $rs->Close();

   echo "<h5>Warehouses: ".$nrec." records replaced in ".$prof->elapsed()." seconds</h5>";
}
//--------------------------------------
function load_paymethod($dbin, $dbout)
{
   global $x2;
   $prof=new cPROFILER1();

	if ($dbin===false) {
		echo "<h6>External connection not established!</h6>\n";
		return;
	}

   $nrec=0;
   $prim=array('AGENTID', 'MENUTYPE', 'MENUID');

   $query="SELECT CODE,NAME FROM PAYMENT WHERE SODTYPE=13 AND COMPANY=?";
   $company=get_company($dbout,$x2->agentid);
   $data=array($company);
   if (!$rs=$dbin->Execute($query,$data)) {
      echo "<h6>".$query.": ".$dbin->ErrorMsg()."</h6>\n";
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $data=array(
			'AGENTID'=>$x2->agentid,
			'MENUTYPE'=>7,
			'MENUID'=>(int)$o1->CODE,
			'MENUDES'=>ToUTF8($o1->NAME)
		);
      if (ReplaceEx2($dbout,'menurep', $data, $prim ))
         $nrec++;
      else {
         echo "<h6>".$query.": ".$dbout->ErrorMsg()."</h6>\n";
         //break;
      }
   }
   $rs->Close();

   echo "<h5>Pay methods: ".$nrec." records replaced in ".$prof->elapsed()." seconds</h5>";
}
//--------------------------------------
function load_customers($dbin, $dbout, $ct)
// $ct=0/1: Πελατες/Προμηθευτες
{
   global $x2;

   $prof=new cPROFILER1();

	if ($dbin===false) {
		echo "<h6>External connection not established!</h6>\n";
		return;
	}

	if (empty($x2->Agp['EXT115_VATENCODE'])) {
	   $code='$y=$x';
	}
	else {
	   $code=$x2->Agp['EXT115_VATENCODE'];
	}
	$code .= ';return $y;';
	$fx=create_function('$x',$code);

   $nrec=0;
   $nerr=0;
   $prim=array('AGENTID', 'LOGIN');
   $t1=($ct==0?'ishop_mbr':'ishop_sup');

   // Mark records for deletion
   $query="UPDATE $t1 SET XDBID = -1 WHERE AGENTID=?";
   $data=array($x2->agentid);
   if (!$dbout->Execute($query,$data)) {
      echo "<h6>".$query.": ".$dbout->ErrorMsg()."</h6>\n";
      return;
   }

   $query="SELECT T1.ID, T1.ABBREVIATION, T1.NAME, T1.AFM, T2.NAME DOY, T1.STREET, T1.STRNUMBER, 
      T1.CITY, T1.PHONE1, T1.FAX, T1.PHONE2, T1.EMAIL, T1.ZIPCODE, T3.NAME COUNTRY, T4.NAME JOB FROM EliteUser.TRD T1 
      LEFT JOIN EliteUser.DOY T2 ON (T2.ID=T1.DOYID)
      LEFT JOIN EliteUser.CNT T3 ON (T3.ID=T1.CNTID)
      LEFT JOIN EliteUser.OCP T4 ON (T4.ID=T1.OCPID) ";
   //$company=get_company($dbout,$x2->agentid);
   $data=false; //array( $company );
   if (!$rs=$dbin->Execute($query,$data)) {
      echo "<h6>".$query.": ".$dbin->ErrorMsg()."</h6>\n";
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $data=array(
			'AGENTID'=>$x2->agentid,
			'LOGIN'=>ToUTF8($o1->ABBREVIATION),
			'XDBID'=>$o1->ID,
			'COMPANY'=>ToUTF8($o1->NAME),
			'VATNO'=>ToUTF8($o1->AFM),
			'JOB'=>ToUTF8($o1->JOB),
			'ADDR1'=>ToUTF8($o1->STREET.' '.$o1->STRNUMBER),
			'CITY'=>ToUTF8($o1->CITY),
			/*'STATE'=>ToUTF8($o1->DISTRICT),*/
			'ZIP'=>ToUTF8($o1->ZIPCODE),
			'PHONE'=>ToUTF8($o1->PHONE1),
			'PHONE2'=>ToUTF8($o1->PHONE2),
			'FAX'=>ToUTF8($o1->FAX),
			'DOY'=>ToUTF8($o1->DOY),
			'EMAIL'=>ToUTF8($o1->EMAIL),
			/*'VATCODE'=>$fx($o1->VATSTS),*/
			'TRKEY'=>ToEnglish( ToUTF8($o1->ABBREVIATION.' '.$o1->NAME) ),
			'CRERESELID'=>0
		);
      if (ReplaceEx2($dbout,$t1, $data, $prim )) {
         echo (++$nrec)." ";
      }
      else {
         echo "<h6>".__LINE__.$dbout->ErrorMsg()."</h6>\n";
         pre($data);
         ++$nerr;
         
         $doy=$data['DOY'];
         $l=strlen($doy);
         for ($i=0;$i<$l;$i++) {
            printf('x%02X', ord($doy{$i}));
         }
         
         break;
      }
   }
   $rs->Close();

   // Cleanup
   $query="DELETE FROM $t1 WHERE AGENTID=? AND XDBID=-1";
   $data=array($x2->agentid);
   if (!$dbout->Execute($query,$data)) {
      echo "<h6>".$query.": ".$dbout->ErrorMsg()."</h6>\n";
      return;
   }

   echo "<h5>".$nrec." records replaced in ".$prof->elapsed()." seconds, $nerr errors</h5>";
}
//--------------------------------------
function load_items($dbin, $dbout)
{
   global $x2;
   $prof=new cPROFILER1();

   if ($dbin===false) {
		echo "<h6>External connection not established!</h6>\n";
		return;
	}

   $nrec=0;
   $nerr=0;
   $prim=array('AGENTID', 'CODE');

   /*
   $query="SELECT T1.ABBREVIATION, T1.NAME, T2.NAME UNIT
      FROM EliteUser.INI T1
      LEFT JOIN EliteUser.MEU T2 ON (T2.ID=T1.MEUIDBASIC)
      WHERE  COMID=? ";
   */
   $query="SELECT     T1.ABBREVIATION AS CODE, T1.NAME, T2.NAME AS UNIT, T3.ALTERNATECODE AS BARCODE
      FROM EliteUser.INI AS T1 
      LEFT OUTER JOIN EliteUser.MEU AS T2 ON T2.ID = T1.MEUIDBASIC 
      LEFT OUTER JOIN EliteUser.AIC AS T3 ON T3.INIID = T1.ID AND T3.ISBARCODE = 1 AND T3.COMID=T1.COMID
      WHERE  T1.COMID=? ";
   $company=get_company($dbout, $x2->agentid);
   $data=array($company); // empty array
	if (!empty($_REQUEST['CODEFILTER'])) {
		$query .= " AND T1.ABBREVIATION LIKE ?";
		$data[]=$_REQUEST['CODEFILTER'];
	}
   if (!$rs=$dbin->Execute($query,$data)) {
      echo "<h6>".$dbin->ErrorMsg()."</h6>\n";
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $data=array(
			'AGENTID'=>$x2->agentid,
			'CODE'=>ToUTF8($o1->CODE),
			'NAME'=>ToUTF8($o1->NAME),
			'UNIT'=>ToUTF8($o1->UNIT),
			'BARCODE'=>(string)ToUTF8($o1->BARCODE),
         'TRKEY'=>ToEnglish(ToUTF8($o1->CODE.' '.$o1->NAME))
		);
      if (ReplaceEx2($dbout, 'ishop_item', $data, $prim)) {
         echo (++$nrec)." ";
      }
      else {
         echo "<h6>".$dbout->ErrorMsg()."</h6>\n";
         pre($data);
         ++$nerr;
         break;
      }
   }
   $rs->Close();

   echo "<h5>".$nrec." records replaced in ".$prof->elapsed()." seconds, $nerr errors</h5>";
}
//--------------------------------------
function ask_load_items()
{
?>
<h5>Εισαγωγή ειδών</h5>
<table>
<form method=POST action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type=HIDDEN name="FUNC2" value="115">
<tr>
	<td>Φίλτρο ειδών</td>
	<td><input type=TEXT name="CODEFILTER">
      Παράδειγμα: &quot;1%&quot;. Το σημείο <kbd style="color:blue;font-weight:bold;">%</kbd> = ο,τιδήποτε.
         Το σημείο <kbd style="color:blue;font-weight:bold;">_</kbd> = 1 χαρακτήρας ακριβώς.</td>
</tr>
<!--
<tr>
	<td>Τιμοκατάλογος</td>
	<td><select name="PRICENO">
      <option value="0">Ελλάδος
      <option value="1">Ευρώπης
      </select></td>
</tr>
-->
<tr>
	<td></td>
	<td>
		<input type=SUBMIT name="ok" value="Ενημέρωση">
	</td>
</tr>
</form>
</table>
<hr>
<?php
}
//--------------------------------------
function export_ord_ask($db)
{
?>
<h5>Export παραγγελιών</h5>
<table>
<form method=POST action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type=HIDDEN name="FUNC2" value="5">
<tr>
	<td>Αρχείο εξαγωγής</td>
	<td><input type=FILE name="OUTFILE"></td>
</tr>
<tr>
	<td></td>
	<td>
		<input type=BUTTON name="ok" value="Εξαγωγή" onclick="this.form.FUNC2.value='5';this.form.submit()">
		<input type=BUTTON name="ok" value="Δοκιμή" onclick="this.form.FUNC2.value='6';this.form.submit()">
	</td>
</tr>
</form>
</table>
<hr>
<?php
}
//--------------------------------------
function reload_odata($db,&$odata)
{
   global $x2;
   static $keys=array('DLVDATE', 'DLVMETHOD', 'PAYMETHOD');

   foreach ($keys as $k1)
      $odata[$k1]='';

   $query="SELECT PNAME, PVALUE FROM order_prop WHERE ORDERID=?";
   $data=array( (int)$odata['ORDERID'] );
   if (($rs=$db->Execute($query,$data))===false) {
      echo "<h6>".$db->ErrorMsg()."</h6>\n";
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      if (in_array($o1->PNAME,$keys))
         $odata[$o1->PNAME]=$o1->PVALUE;
   }
   $rs->Close();

   $v=$odata['DLVMETHOD'];
   $odata['DLVMETHOD']=0;
   if (!empty($v)) {
      $query="SELECT MENUID FROM menurep WHERE AGENTID=? AND MENUTYPE=6 AND MENUDES=?";
      $data=array($x2->agentid,$v);
      if (($rs=$db->Execute($query,$data))===false) {
         echo "<h6>".$db->ErrorMsg()."</h6>\n";
      }
      else {
         if ($row=$rs->FetchRow()) {
            $odata['DLVMETHOD']=$row[0];
         }
         $rs->Close();
      }
   }

   $v=$odata['PAYMETHOD'];
   $odata['PAYMETHOD']=0;
   if (!empty($v)) {
      $query="SELECT MENUID FROM menurep WHERE AGENTID=? AND MENUTYPE=7 AND MENUDES=?";
      $data=array($x2->agentid,$v);
      if (($rs=$db->Execute($query,$data))===false) {
         echo "<h6>".$db->ErrorMsg()."</h6>\n";
      }
      else {
         if ($row=$rs->FetchRow()) {
            $odata['PAYMETHOD']=$row[0];
         }
         $rs->Close();
      }
   }
}
//--------------------------------------
function ascii_exp_orders($db,$do_update)
{
   global $x2;
   $prof=new cPROFILER1();

	// Transformation function for ishop_mbr.VATCODE
   if (empty($x2->Agp['EXT115_VATDECODE'])) {
	   $code='$y=$x';
	}
	else {
	   $code=$x2->Agp['EXT115_VATDECODE'];
	}
	$code .= ';return $y;';
	$fx=create_function('$x',$code);

   // Transformation function for order_line.VATPER
	if (empty($x2->Agp['EXT115_VCADECODE'])) {
	   $code='$y=$x';
	}
	else {
	   $code=$x2->Agp['EXT115_VCADECODE'];
	}
	$code .= ';return $y;';
	$fx2=create_function('$x',$code);

   $nrec=0;

   if (($fp=@fopen($_REQUEST['OUTFILE'],"w"))===false) {
   	echo "<h6>Δεν ανοίγει το αρχείο για γράψιμο: ".myhtml($_REQUEST['OUTFILE'])."</h6>";
   	return;
	}

	$odata=array('ORDERID'=>0);

   // Process orders collection
	$query="SELECT T1.LOGTIME, T1.ORDERID, T1.MBR_LOGIN, T1.RE_RESELID,
		T2.ICODE, T2.QUANTITY, T2.PRICE, T2.VATPER, T3.VATCODE
		FROM order_main T1
		LEFT JOIN order_line T2 ON (T2.ORDERID=T1.ORDERID)
		LEFT JOIN ishop_mbr T3 ON (T3.AGENTID=T1.AGENTID AND T3.LOGIN=T1.MBR_LOGIN)
		WHERE T1.AGENTID=? AND T1.STATE=4
		ORDER BY ORDERID, ORDLINE";
	$data=array($x2->agentid);
	if (!$rs=$db->Execute($query,$data)) {
		echo "<h6>".$db->ErrorMsg()."</h6>\n";
		fclose($fp);
		return;
	}
	while ($o1=$rs->FetchNextObject()) {
      if ((int)$o1->ORDERID!=(int)$odata['ORDERID']) {
         $odata['ORDERID']=$o1->ORDERID;
         reload_odata($db,$odata);
      }
		$buf=sprintf("%4s#-#%s#%s#%s#%s#%s#%s#%s#%s#%s#%s#%d#%d#%d\r\n",
			substr($o1->LOGTIME,0,4),
			$o1->ORDERID,
			substr($o1->LOGTIME,8,2)."/".substr($o1->LOGTIME,5,2)."/".substr($o1->LOGTIME,0,4),
			$o1->MBR_LOGIN,
			$o1->ICODE,
			strtr($o1->QUANTITY,'.',','),
			strtr($o1->PRICE,'.',','),
			( empty($odata['DLVDATE']) ? '00/00/0000' : substr($odata['DLVDATE'],8,2)."/".substr($odata['DLVDATE'],5,2)."/".substr($odata['DLVDATE'],0,4) ),
			$odata['DLVMETHOD'],
			$odata['PAYMETHOD'],
			$o1->RE_RESELID,
			(int)@$x2->Agp['THISORDERSEQUENCE'],
			$fx($o1->VATCODE),
			$fx2($o1->VATPER)
		);
		$l=strlen($buf);
		fwrite($fp,$buf,$l);
		$nrec++;
	}
	$rs->Close();
	fclose($fp);

	if ($do_update && $nrec>0) {
		$query="UPDATE order_main SET STATE=9 WHERE AGENTID=? AND STATE=4";
		$data=array($x2->agentid);
		if ($db->Execute($query,$data))
			echo "<h6>".$db->ErrorMsg()."</h6>\n";
	}

   echo "<h5>".$nrec." orders processed in ".$prof->elapsed()." seconds</h5>";
}
//--------------------------------------
function cre_stored_proc()
{
?>
<pre>
-- =============================================
-- =============================================

-- Να υπάρχει η παρακάτω Stored Procedure στην βάση του Panorama.

-- =============================================
-- =============================================


-- =============================================
-- Author:		TEAM, SOFTONE SA
-- Create date: 21/07/2006
-- Description:	Extract CDIMLEVEL
-- =============================================
CREATE PROCEDURE [dbo].[EXTR_CDIMLEVEL]
	@COMPANY int=null
AS
BEGIN

set nocount on

if not exists(select name from  sysobjects where name=N'CUST_MTRL_XM' and type='U') begin
	create table CUST_MTRL_XM
	(
		MTRL      int,
		CDIMLINES1 int,
		CDIMLINES2 int,
		CDIMLINES3 int,
		DIFFPRICEW float,
		DIFFPRICER float
	)
end
else
	truncate table CUST_MTRL_XM


declare AA cursor for
select 
	MTRL,
	substring(CDIMLEVEL,1,8000) as CDIMLEVEL,
	PRICEW,
	PRICER
from 
	MTRL
where
	COMPANY=@COMPANY
	and
	SODTYPE=51

declare 
	@MTRL int,
	@CDIMLEVEL varchar(8000),
	@PRICEW float,
	@PRICER float,
	@STR varchar(8000),
	@STR1 varchar(500),
	@CDIMLINES1 int,
	@CDIMLINES2 int,
	@CDIMLINES3 int,
	@DIFFPRICEW float,
	@DIFFPRICER float

open AA
fetch next from AA into @MTRL,@CDIMLEVEL,@PRICEW,@PRICER
while @@fetch_status=0 begin
	if @CDIMLEVEL is not null begin
		set @STR=@CDIMLEVEL
		while LEN(@STR)>0 begin

			set @CDIMLINES1=0
			set @CDIMLINES2=0
			set @CDIMLINES3=0
			set @DIFFPRICEW=0
			set @DIFFPRICER=0
			
			set @STR1=SUBSTRING(@STR,1,CHARINDEX('~',@STR)-1)

			set @CDIMLINES1=CAST(isnull(SUBSTRING(@STR1,1,CHARINDEX('|',@STR1)-1),'0') as int)
			set @STR1=SUBSTRING(@STR1,CHARINDEX('|',@STR1)+1,LEN(@STR1)-CHARINDEX('|',@STR1))
			set @CDIMLINES2=CAST(isnull(SUBSTRING(@STR1,1,CHARINDEX('|',@STR1)-1),'0') as int)
			set @STR1=SUBSTRING(@STR1,CHARINDEX('|',@STR1)+1,LEN(@STR1)-CHARINDEX('|',@STR1))
			set @CDIMLINES3=CAST(isnull(SUBSTRING(@STR1,1,CHARINDEX('|',@STR1)-1),'0') as int)
			set @STR1=SUBSTRING(@STR1,CHARINDEX('|',@STR1)+1,LEN(@STR1)-CHARINDEX('|',@STR1))

			set @DIFFPRICEW=CAST(isnull(SUBSTRING(@STR1,1,CHARINDEX('|',@STR1)-1),'0') as float)
			set @STR1=SUBSTRING(@STR1,CHARINDEX('|',@STR1)+1,LEN(@STR1)-CHARINDEX('|',@STR1))
			set @DIFFPRICER=CAST(isnull(SUBSTRING(@STR1,1,CHARINDEX('|',@STR1)-1),'0') as float)

			insert CUST_MTRL_XM 
			(MTRL,CDIMLINES1,CDIMLINES2,CDIMLINES3,DIFFPRICEW,DIFFPRICER)
			values
			(
				@MTRL,@CDIMLINES1,@CDIMLINES2,@CDIMLINES3,@DIFFPRICEW,@DIFFPRICER
			)

			if CHARINDEX('~',@STR)=LEN(@STR)
				set @STR=''
			else
				set @STR=SUBSTRING(@STR,CHARINDEX('~',@STR)+1,LEN(@STR)-CHARINDEX('~',@STR))
		end
	end
	fetch next from AA into @MTRL,@CDIMLEVEL,@PRICEW,@PRICER
end
close AA
deallocate AA


END


GO
</pre>
<hr>
<?php
}
//--------------------------------------
function db_test(&$db)
{
   global $x2;
   $src="ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ";
   
   $query="DELETE FROM ishop_mbr WHERE AGENTID=? AND LOGIN >='01' AND LOGIN <='24' ";
   $data=array($x2->agentid);
   if (!$db->Execute($query,$data)) {
      echo $db->ErrorMsg();
      return;
   }
   
   $query="INSERT INTO ishop_mbr (AGENTID, LOGIN, COMPANY) VALUES(?,?,?)";
   for ($i=0;$i<24;$i++) {
      $data=array($x2->agentid, sprintf("%02d", $i+1), mb_substr($src, $i, 1) );
      if (!$db->Execute($query,$data)) {
         echo $db->ErrorMsg();
         pre($data);
      } 
   }
   
}
//--------------------------------------
function show_files($dbin)
{
   if ($dbin===false) {
		echo "<h6>External connection not established!</h6>\n";
		return;
	}

	$ar1=$dbin->MetaTables('TABLES');
	if ($ar1===false) {
      echo $dbin->ErrorMsg();
      return;
   }
   echo "<ul>";
   sort($ar1);
   foreach ($ar1 as $f1) {
      echo "<li><a href=\"".$_SERVER['PHP_SELF']."?FUNC2=202&F1=".urlencode(ToUTF8($f1))."\" target=rightpane>".ToUTF8($f1)."</a>\n";
   }
   echo "</ul>";
}
//--------------------------------------
function show_file_list($dbex)
{
   if ($dbin===false) {
		echo "<h6>External connection not established!</h6>\n";
		return;
	}

	$ar1=$dbin->MetaTables('TABLES');
	if ($ar1===false) {
      echo $dbin->ErrorMsg();
      return;
   }
   echo "<ul>";
   sort($ar1);
   foreach ($ar1 as $f1) {
      echo "<li><a href=\"".$_SERVER['PHP_SELF']."?FUNC2=202&F1=".urlencode(ToUTF8($f1))."\" target=rightpane>".ToUTF8($f1)."</a>\n";
   }
   echo "</ul>";
}
//--------------------------------------
function show_file_data($dbext)
{
   if ($dbext===false) {
		echo "<h6>External connection not established!</h6>\n";
		return;
	}

	// BODY
	$pg=getPage();
	$pgsz=getPageSize('grid1');

	$query="SELECT * FROM EliteUser.".UTF8decode($_REQUEST['F1']);
	if (!($rs=$dbext->PageExecute($query,$pgsz,$pg))) {
		echo "<h6>".$dbext->ErrorMsg()."</h6>\n";
		return;
	}
	echo "<div class=bgLine><b>".myhtml($_REQUEST['F1'])."</b></div>";
?>
<form method=POST action="<?php echo $_SERVER['PHP_SELF']; ?>" name="goForm">
<input type=HIDDEN name="RSPAGE">
<input type=HIDDEN name="F1" value="<?php echo myhtml($_REQUEST['F1']); ?>">
<input type=hidden name="FUNC2" value="202">
<input type=hidden name="FUNCTION" value="">
<?php
	$gr1=new cXRID('grid1');
	
	//	define column labels (need define all columns, even empty ones)
	$n=$rs->FieldCount();
	for ($i=0;$i<$n;$i++) {
      $fo=$rs->FetchField($i);
	   $gr1->cols[]=array(ToUTF8($fo->name),60);
	}

	while ($row=$rs->FetchRow()) {
      $row1=array();

      for ($i=0;$i<$n;$i++) {
         $row1[]=myhtml8($row[$i]);
      }

      $gr1->rows[]=$row1;
   }
   $epage=$rs->LastPageNo();
	$rs->Close();

	// Increase default margin
	$gr1->bottom_margin=80;
	// Disable sort feature
	$gr1->sort=false;
	// Execute
   $gr1->play();

	echo "<table width=100%><tr class=bgButton2><td>";
	print_page_navEx($pg,$epage,202);
	echo "</td></tr></form></table>";
}
//--------------------------------------
function get_item_query($dblocal, &$query, &$data)
{
   global $x2;
   $company=get_company($dblocal,$x2->agentid);

	$query="EXECUTE EXTR_CDIMLEVEL ?; select
	A.MTRL,
	A.LINENUM,
	A.CODE,
	A.NAME,
	A.QTY1,
	A.QTY2,
	A.MTRDIM1,
	A.MTRDIM2,
	A.MTRDIM3,
	(isnull((select PRICEW from MTRL Z1 where Z1.MTRL=A.MTRL),0)+isnull((select DIFFPRICEW from CUST_MTRL_XM ZZ where ZZ.MTRL=A.MTRL and ZZ.CDIMLINES1=isnull(A.MTRDIM1,0) and ZZ.CDIMLINES2=isnull(A.MTRDIM2,0) and ZZ.CDIMLINES3=isnull(A.MTRDIM3,0)),0)) as PRICEW,
	(isnull((select PRICER from MTRL Z1 where Z1.MTRL=A.MTRL),0)+isnull((select DIFFPRICER from CUST_MTRL_XM ZZ where ZZ.MTRL=A.MTRL and ZZ.CDIMLINES1=isnull(A.MTRDIM1,0) and ZZ.CDIMLINES2=isnull(A.MTRDIM2,0) and ZZ.CDIMLINES3=isnull(A.MTRDIM3,0)),0)) as PRICER,
   B.CODE ICODE,
   B.CDIM1,
   B.CDIM2,
   C.NAME NM1,
   D.NAME NM2,
   E.SHORTCUT
from
	MTRSUBSTITUTE A
	LEFT JOIN MTRL B ON (B.MTRL=A.MTRL)
	LEFT JOIN CDIMLINES C ON (C.COMPANY=A.COMPANY AND C.CDIM=B.CDIM1 AND C.CDIMLINES=A.MTRDIM1)
	LEFT JOIN CDIMLINES D ON (D.COMPANY=A.COMPANY AND D.CDIM=B.CDIM2 AND D.CDIMLINES=A.MTRDIM2)
	LEFT JOIN MTRUNIT E ON (E.COMPANY=B.COMPANY AND E.MTRUNIT=B.MTRUNIT1)
where
	A.ISACTIVE=1
	and
	A.COMPANY=?
	and
	A.MTRL in (select MTRL from MTRL where COMPANY=? and SODTYPE=51 and ISACTIVE=1)
ORDER BY
   A.MTRL";
   $data=array($company,$company,$company);
}
//--------------------------------------
function load_items_sub($dbin,$dbout)
{
   global $x2;
   $prof=new cPROFILER1();

   if ($dbin===false) {
		echo "<h6>External connection not established!</h6>\n";
		return;
	}

	$nrec=$nrec2=$nrec3=0;
   $prim_m=array('AGENTID', 'CODE');
   $prim_sub=array('AGENTID', 'CODE', 'SUBCODE');

   $query="UPDATE ishop_item SET XDBID=-1 WHERE AGENTID=?";
   $data=array($x2->agentid);
   if (!$dbout->Execute($query,$data)) {
      echo "<h6>".$query.": ".$dbout->ErrorMsg()."</h6>\n";
      return;
   }

   $query="DELETE FROM ishop_subitem WHERE AGENTID=?";
   $data=array($x2->agentid);
   if (!$dbout->Execute($query,$data)) {
      echo "<h6>".$query.": ".$dbout->ErrorMsg()."</h6>\n";
      return;
   }

	$query='';
   $data=array();
   get_item_query($dbout, $query, $data);
   $prof2=new cPROFILER1();
   if (!$rs=$dbin->Execute($query,$data)) {
      echo "<h6>".$dbin->ErrorMsg()."</h6>\n";
      return;
   }
   echo "<h5>External query executed in ".$prof2->elapsed()." seconds</h5>";
   $last_icode=false;
   while ($o1=$rs->FetchNextObject()) {
      if ($o1->ICODE!=$last_icode) {
         // Update master
         $data=array(
			   'AGENTID'=>$x2->agentid,
			   'CODE'=>ToUTF8($o1->ICODE),
			   'XDBID'=>ToUTF8($o1->MTRL),
			   'NAME'=>ToUTF8($o1->NAME),
			   'UNIT'=>ToUTF8($o1->SHORTCUT),
			   'PRICE2'=>toFloat($o1->PRICEW),
			   'PRICE1'=>toFloat($o1->PRICER),
            'TRKEY'=>ToEnglish(ToUTF8($o1->ICODE.' '.$o1->NAME))
		   );
         if (ReplaceEx2($dbout, 'ishop_item', $data, $prim_m)) {
            echo (++$nrec)." ";
         }
         else {
            echo "<h6>".$dbout->ErrorMsg()."</h6>\n";
            break;
         }

         $last_icode=$o1->ICODE;
      }

      // Update subcodes
      $data=array(
         'AGENTID'=>$x2->agentid,
         'CODE'=>ToUTF8($o1->ICODE),
         'UCODE'=>ToUTF8($o1->CODE),
         'SUBCODE'=>ToUTF8($o1->CDIM1.'.'.$o1->MTRDIM1.'.'.$o1->CDIM2.'.'.$o1->MTRDIM2),
         'SUBCOLOR'=>ToUTF8($o1->NM1),
         'SUBSIZE'=>ToUTF8($o1->NM2)
      );
      if (InsertEx($dbout, 'ishop_subitem', $data)) {
         echo "#".(++$nrec2)." ";
      }
      else {
         echo "<h6>".$dbout->ErrorMsg()."</h6>\n";
         break;
      }
   }
   $rs->Close();

   // Cleanup
   $query="DELETE FROM ishop_item WHERE AGENTID=? AND XDBID=-1";
   $data=array($x2->agentid);
   if (!$dbout->Execute($query,$data)) {
      echo "<h6>".$query.": ".$dbout->ErrorMsg()."</h6>\n";
      return;
   }

   // Update s81
   $query="INSERT IGNORE INTO ishop_s81 (AGENTID,s81warehouse,s81cod1,s81subcod)
		SELECT T1.AGENTID, 0, T1.CODE, T1.SUBCODE FROM ishop_subitem T1
      LEFT JOIN ishop_s81 T2 ON (T2.AGENTID=T1.AGENTID AND T2.s81cod1=T1.CODE AND T2.s81subcod=T1.SUBCODE AND T2.s81warehouse=0)
      WHERE T1.AGENTID=? AND T2.AGENTID IS NULL";
   $data=array($x2->agentid);
   if (!$dbout->Execute($query,$data)) {
      echo "<h6>".$dbout->ErrorMsg()."</h6>\n";
   }
   else {
		$nrec3=$dbout->Affected_Rows();
	}

	echo "<h5>$nrec + $nrec2 + $nrec3 records replaced in ".$prof->elapsed()." seconds</h5>";
}
//--------------------------------------
function show_items_sub($dbext,$dbin)
{

   if ($dbext===false) {
		echo "<h6>External connection not established!</h6>\n";
		return;
	}

	// BODY
	$pg=getPage();
	$pgsz=getPageSize('grid2');

   $query='';
   $data=array();
   get_item_query($dbin,$query, $data);
	if (!($rs=$dbext->PageExecute($query,$pgsz,$pg,$data))) {
		echo "<h6>".$dbext->ErrorMsg()."</h6>\n";
		return;
	}
	echo "<b>Κωδικοί/Υποκωδικοί</b>\n";
?>
<table border=0 cellpadding=0 cellspacing=0 class=delta>
<form method=POST action="<?php echo $_SERVER['PHP_SELF']; ?>" name="goForm">
<input type=HIDDEN name="RSPAGE">
<input type=hidden name="FUNC2" value="8">
<input type=hidden name="FUNCTION" value="">
</table>
<?php
	$gr1=new cXRID('grid2');

	//	define column labels (need define all columns, even empty ones)
	$n=$rs->FieldCount();
	for ($i=0;$i<$n;$i++) {
      $fo=$rs->FetchField($i);
	   $gr1->cols[]=array($fo->name,60);
	}

	while ($row=$rs->FetchRow()) {
      $row1=array();

      for ($i=0;$i<$n;$i++) {
         $row1[]=myhtml($row[$i]);
      }

      $gr1->rows[]=$row1;
   }
   $epage=$rs->LastPageNo();
	$rs->Close();

	// Increase default margin
	$gr1->bottom_margin=80;
	// Disable sort feature
	$gr1->sort=false;
	// Execute
   $gr1->play();

	echo "<table width=100%><tr class=bgButton2><td>";
	print_page_navEx($pg,$epage,1000);
	echo "</td></tr></form></table>";
}
//--------------------------------------
function load_items_script($dbin)
{
   make_batch($dbin,9);
   echo "<hr>";
}
//--------------------------------------
function reread_orders($dbex, $dbin)
{
   make_batch($dbin,115);

   $query=get_final_query($dbin);
?>
<script language=javascript>
var s=0;
function onOff()
{
   showHide(document.all.qry, s==0?1:0);
   s=1-s;
}
</script>
<table cellspacing=0>
<tr class=bgHeader>
   <td><a href="javascript:onOff()">[+]</a> Query 2</td>
</tr>
<tr>
   <td style="background-color:#d0d0d0;"><pre id=qry style="visibility:hidden;display:none;"><?php echo myhtml($query); ?></pre></td>
</tr>
</table>
<hr>
<?php
}
//--------------------------------------
function real_reread_orders($dbex, $dbin)
{
   global $x2;

   if ($dbex===false) {
		echo "<h6>External connection not established!</h6>\n";
		return;
	}

	db_imp_orders($dbex, $dbin, $show_info=true);
}
//--------------------------------------
function import_orders(&$dbex, &$dbin)
{
   make_batch($dbin,113);

   $query=get_import_query($dbin);
?>
<script language=javascript>
var s=0;
function onOff()
{
   showHide(document.all.qry, s==0?1:0);
   s=1-s;
}
</script>
<table cellspacing=0>
<tr class=bgHeader>
   <td><a href="javascript:onOff()">[+]</a> Query 1</td>
</tr>
<tr>
   <td style="background-color:#d0d0d0;"><pre id=qry style="visibility:hidden;display:none;"><?php echo myhtml($query); ?></pre></td>
</tr>
</table>
<hr>
<?php
}
//--------------------------------------
function make_batch(&$dbin,$f2)
{
   global $x2;

   $query="SELECT RESELID, PASSWD FROM reseller WHERE AGENTID=? LIMIT 1";
   $data=array($x2->agentid);
   if (($rs=$dbin->Execute($query,$data))===false) {
      echo "<h6>".$dbin->ErrorMsg()."</h6>\n";
      return;
   }
   $o1=$rs->FetchNextObject();
   $rs->Close();
   if ($o1===false) {
      echo "<h5>Δεν έχετε ορίσει ακόμη 'Πωλητές'!</h5>";
      return;
   }

   // We use strtr() for Apache on Windows
   $pt1=strtr($_SERVER["PATH_TRANSLATED"],"/","\\");
   $ppath=explode('\\', $pt1 );
   if (($l=count($ppath))<4) {
      echo "<h6>Small exe path array!</h6>";
      return;
   }
   $ppath2=array_slice($ppath,0,$l-3);
   $ppath2[]="php\\php-cli.exe";
   $xcli=implode("\\",$ppath2);
?>
<p></p>
Παρακαλούμε αντιγράψτε τον παρακάτω κώδικα σε ένα αρχείο batch στον server σας, π.χ. στο <i>myjob.bat</i> και
'τρέξτε' το
από την γραμμή διαταγής (DOS) ή μέσω του scheduler:
<div style="border:solid black 1px"><pre style="background-color:#d0d0d0" id=bat1>
@echo OFF
set phpexe=c:\php\php.exe

REM If still not exist, abort:
if not exist %phpexe% exit

%phpexe% -f "<?php
   // We use strtr() for Apache on Windows
   echo strtr($_SERVER["PATH_TRANSLATED"],"/","\\");
   ?>" FUNC2=<?php
   echo $f2;
   ?> RESELID=<?php
   echo $o1->RESELID;
   ?> "REPASS=<?php
   echo $o1->PASSWD;
   ?>" <?php
   if (isset($_REQUEST['FROMDAYS']))
      echo "FROMDAYS=".((int)$_REQUEST['FROMDAYS']);
   ?>
</pre>
<button type=button onclick="window.clipboardData.setData('Text',document.all.bat1.innerText);">Copy to clipboard</button></div>
<p></p>
<?php
}
//--------------------------------------
function get_import_query($dbin)
{
   global $x2;

   $company=get_company($dbin,$x2->agentid);
	$from_date=date('Y-m-d', time() - ((int)$_REQUEST['FROMDAYS']) * 86400 );
	
	if (!empty($x2->Agp['EXT115_SALESERIES']))
	   $series=$x2->Agp['EXT115_SALESERIES'];
	else
	   $series="0"; // dummy value, so that query does not generate error

	$query="if not exists(select name
                from  sysobjects
               where name=N'FINDOCBARCODE' and type='U')
begin
	create table FINDOCBARCODE
	(	 FINDOC    int
		,MTRLINES  int
		,COLORNO   int
		,SIZENO    int
		,BARCODE   varchar(64)
		,FINCODE   varchar(64)
		,TRNDATE   datetime
		,TRDCODE   varchar(64)
		,WHOUSE    int
		,MCODE     varchar(64)
		,QTY1      float
		,PRICE     float
		,DISCNT    float
		,SALESMAN  int
		,MTRL      int
	)
end
else
	truncate table FINDOCBARCODE

declare  	@vcdimlines1 	int
		,@vcdimlines2 	int
		,@vcdimlines3 	int
		,@vpending 	int
		,@vqty1 	float
		,@vqty1cov 	float
		,@vqty 		float
		,@vprice 	float
		,@vqty1canc 	float
		,@vqty2 	float
		,@vqty1fcov 	float
		,@vfindoc 	int
		,@vmtrlines 	int
		,@vsoanal 	varchar(8000)
		,@cnt 		int
		,@tsoanal 	varchar(8000)
		,@rsoanal 	varchar(1000)
		,@color   	varchar(200)
		,@size   	varchar(200)
		,@vfincode 	varchar(64)
		,@vtrndate 	datetime
		,@vtrdcode 	varchar(64)
		,@vwhouse  	int
		,@vmcode   	varchar(64)
		,@vdisc1   	float
		,@vsalesman 	int
		,@vmtrl     	int
		,@company	int

select @company=$company  	--Id Εταιρίας στο panorama
declare cr1 cursor for
select    m.findoc
		, m.mtrlines
		, CAST(m.soanal AS VarChar(8000))
		, f.fincode
		, f.trndate
		, t.code
		, m.whouse
		, l.code
		, m.price1
		, m.disc1prc
		, f.salesman
		, m.mtrl
from mtrlines m, findoc f, trdr t, mtrl l
where m.company=@company
--  AND t.code=<κωδικός πελάτη>
AND F.TRNDATE>='$from_date' -- <απο ημερομηνια>
--  AND F.TRNDATE<=<εως ημερομηνια>
--  AND CHARINDEX(','+CAST(F.FPRMS AS VARCHAR)+',' , ','+<τύποι παραστατικών>+',') > 0
  and f.findoc=m.findoc
  and f.series in ($series)
  and t.trdr=f.trdr
  and f.sosource=1351
  and l.mtrl=m.mtrl
  and m.soanal is not null
begin
open cr1
  set @cnt=0
  fetch next from cr1 into @vfindoc, @vmtrlines, @vsoanal ,@vfincode, @vtrndate, @vtrdcode, @vwhouse, @vmcode, @vprice, @vdisc1, @vsalesman, @vmtrl
  while (@@fetch_status<>-1)
  begin
    if @cnt=0
      begin tran
      /**/
      SELECT @tsoanal=CAST(@vsoanal as VarChar(8000))
	  SELECT @tsoanal=SubString(@tsoanal,CharIndex(';',@tsoanal)+1,len(@tsoanal))
	  SELECT @tsoanal=SubString(@tsoanal,CharIndex(';',@tsoanal)+1,len(@tsoanal))
	  SELECT @tsoanal=SubString(@tsoanal,CharIndex(';',@tsoanal)+1,len(@tsoanal))
	  SELECT @rsoanal=SubString(@tsoanal,1,CharIndex('~',@tsoanal)-1)
	  while (len(@rsoanal)>0)
	  begin
		SELECT @color=SubString(@rsoanal,1,CharIndex('|',@rsoanal)-1)
		SELECT @rsoanal=SubString(@rsoanal,CharIndex('|',@rsoanal)+1,len(@rsoanal))
		SELECT @size=SubString(@rsoanal,1,CharIndex('|',@rsoanal)-1)
		SELECT @rsoanal=SubString(@rsoanal,CharIndex('|',@rsoanal)+1,len(@rsoanal))
		SELECT @rsoanal=SubString(@rsoanal,CharIndex('|',@rsoanal)+1,len(@rsoanal))
		SELECT @vpending=CONVERT( int, SubString(@rsoanal,1,CharIndex('|',@rsoanal)-1) )
		SELECT @rsoanal=SubString(@rsoanal,CharIndex('|',@rsoanal)+1,len(@rsoanal))
		SELECT @vqty1=CONVERT( float, SubString(@rsoanal,1,CharIndex('|',@rsoanal)-1) )
		SELECT @rsoanal=SubString(@rsoanal,CharIndex('|',@rsoanal)+1,len(@rsoanal))
		SELECT @vqty1cov=CONVERT( float, SubString(@rsoanal,1,CharIndex('|',@rsoanal)-1) )
		SELECT @rsoanal=SubString(@rsoanal,CharIndex('|',@rsoanal)+1,len(@rsoanal))
		SELECT @rsoanal=SubString(@rsoanal,CharIndex('|',@rsoanal)+1,len(@rsoanal))
		SELECT @rsoanal=SubString(@rsoanal,CharIndex('|',@rsoanal)+1,len(@rsoanal))
		SELECT @vqty1canc=CONVERT( float, SubString(@rsoanal,1,CharIndex('|',@rsoanal)-1) )
		INSERT INTO FINDOCBARCODE
		(FINDOC
		,MTRLINES
		,COLORNO
		,SIZENO
		,BARCODE
		,FINCODE
		,TRNDATE
		,TRDCODE
		,WHOUSE
		,MCODE
		,QTY1
		,PRICE
		,DISCNT
		,SALESMAN
		,MTRL)
		SELECT		  @VFINDOC
					, @VMTRLINES
					, CONVERT( int, @COLOR )
					, CONVERT( int, @SIZE )
					, NULL     AS BARCODE
					, @vFINCODE
					, @vTRNDATE
					, @vTRDCODE
					, @vWHOUSE
					, @vMCODE
					, (case @vpending when 1 then (@vqty1-@vqty1cov-@vqty1canc) else 0 end)
					, @VPRICE
					, @VDISC1
					, @VSALESMAN
					, @VMTRL
		SELECT @tsoanal=SubString(@tsoanal,CharIndex('~',@tsoanal)+1,len(@tsoanal))
		if len(@tsoanal)>0
			SELECT @rsoanal=SubString(@tsoanal,1,CharIndex('~',@tsoanal)-1)
			if len(@tsoanal)=0
				SELECT @rsoanal=''
	  end
     /**/
      set @cnt=@cnt+1
	  if @cnt>=300
	  begin
		commit tran
	  set @cnt=0
	end
fetch next from cr1 into @vfindoc, @vmtrlines, @vsoanal ,@vfincode, @vtrndate, @vtrdcode, @vwhouse, @vmcode, @vprice, @vdisc1, @vsalesman, @vmtrl
end
if @cnt>0 commit tran
close cr1
deallocate cr1
end
update findocbarcode
set barcode=(select top 1 ms.code
	     from mtrsubstitute ms
	     where ms.mtrl=findocbarcode.mtrl
		and ms.mtrdim1=findocbarcode.colorno
		and ms.mtrdim2=findocbarcode.sizeno order by ms.qty1)

   ,qty1=(qty1/isnull((select top 1 ms.qty1
			from mtrsubstitute ms
			where ms.mtrl=findocbarcode.mtrl
			and ms.mtrdim1=findocbarcode.colorno
			and ms.mtrdim2=findocbarcode.sizeno order by ms.qty1),1))

	SELECT    B.SERIES    AS SERIES           	-- Κωδικός σειράς
		, A.TRNDATE   AS TRNDATE          	-- ημερομηνία (old=TRNDATE)
		, B.SERIESNUM AS SERIESNUM              -- Αριθμός Παραστατικού
		, A.FINCODE   AS FINCODE          	-- Κωδικός παραστατικού
		, A.TRDCODE   AS TRDCODE          	-- κωδικός πελάτη
		, A.WHOUSE    AS WHOUSE           	-- id αποθηκευτικού χώρου
		, A.MCODE     AS MCODE            	-- κωδικός είδους
		, A.QTY1      AS QTY1             	-- συνολική εκκρεμής ποσότητα είδους
        	, L1.NAME     AS COLOR            	-- χρώμα
        	, L2.NAME     AS SIZE             	-- μέγεθος
		, A.PRICE     AS PRICE            	-- τιμή
		, A.DISCNT    AS DISCNT           	-- εκπτωση γραμμής
		, ISNULL( A.BARCODE, '' ) AS BARCODE   	-- κωδικός barcode
		, A.SALESMAN  AS SALESMAN         	-- πωλητής
		, A.FINDOC   AS FINDOC            	-- id παραστατικού
		, A.MTRLINES  AS MTRLINES         	-- id γραμμής παραστατικού
		, B.TRDR   AS TRDR                	-- id πελάτη
		, A.MTRL  AS MTRL                 	-- id είδους
	FROM FINDOCBARCODE A, FINDOC B, mtrl m, cdim d1, cdim d2, cdimlines l1, cdimlines l2
	WHERE A.FINDOC=B.FINDOC
	and a.mtrl=m.mtrl
	and m.cdim1=d1.cdim
	and m.cdim2=d2.cdim
	and l1.cdim=d1.cdim
	and l2.cdim=d2.cdim
	and l1.cdimlines=a.colorno
	and l2.cdimlines=a.sizeno";

	return $query;
}
//--------------------------------------
function real_import_orders($dbex, $dbin)
{
   global $x2;

   if ($dbex===false) {
		echo "<h6>External connection not established!</h6>\n";
		return;
	}

   $query=get_import_query($dbin);
   if (!$dbex->Execute($query)) {
      echo "<h6>".$dbex->ErrorMsg()."</h6>";
      return;
   }

   db_imp_orders($dbex, $dbin, $show_info=true);
}
//--------------------------------------
function parameter_ask($db_remote,$db_local)
{
   global $x2;

   // ANAPTIXI
   $ar1=array();
   if ($db_remote===false) {
		echo "<h6>External connection not established!</h6>\n";
	}
	else {
      $query="SELECT ID, NAME FROM EliteUser.COM ORDER BY ID";
      if (($rs=$db_remote->Execute($query))===false) {
         echo "<h6>$query: ".$db_remote->ErrorMsg()."</h6>";
      }
      else {
         while ($o1=$rs->FetchNextObject()) {
            $ar1[ $o1->ID ] = '#'.$o1->ID.' '.ToUTF8($o1->NAME);
         }
         $rs->Close();
      }
   }

   if (isset($x2->Agp['EXT115_COMPANY']))
      $company=(int)$x2->Agp['EXT115_COMPANY'];
   else
      $company=1;
      
   if (!array_key_exists($company, $ar1)) {
      $ar1[$company]='Company #'.$company;
   }

   $ar2=array('Κωδικοί (μόνο)', 'Κωδικοί/υποκωδικοί');
   if (isset($x2->Agp['EXT115_IDATA']))
      $idata=(int)$x2->Agp['EXT115_IDATA'];
   else
      $idata=0;

   if (isset($x2->Agp['EXT115_AUTO_ORD']))
      $auto_ord=(int)$x2->Agp['EXT115_AUTO_ORD'];
   else
      $auto_ord=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><select name="EXT115_COMPANY"><?php
      prAssocSelect($ar1,$company);
      ?></select></td>
</tr>
<tr>
   <td>Data</td>
   <td><select name="EXT115_IDATA"><?php
      prAssocSelect($ar2,$idata);
      ?></select></td>
</tr>
<tr>
   <td>Αυτόματη ενημέρωση παραγγελιών</td>
   <td><input type=CHECKBOX name="EXT115_AUTO_ORD" <?php
      if ($auto_ord!=0) echo "CHECKED";
      ?> value="1"> Ναί</td>
</tr>
<tr>
   <td>Σειρές πωλήσεων για εισαγωγή
      <br><small>(comma separated)</small></td>
   <td><input type=TEXT name="EXT115_SALESERIES" value="<?php
      echo myhtml((string)@$x2->Agp['EXT115_SALESERIES']);
      ?>" MAXLENGTH=255 size=40></td>
</tr>
<tr>
   <td>Αντιστοίχιση καθεστώτος ΦΠΑ (τιμή iShop βάσει Panorama)
      <br><small>Source=$x, result=$y. Example $y=$x+1</small></td>
   <td><input type=TEXT name="EXT115_VATENCODE" value="<?php
      echo @$x2->Agp['EXT115_VATENCODE'];
      ?>" MAXLENGTH=255 size=40></td>
</tr>
<tr>
   <td>Αντιστοίχιση καθεστώτος ΦΠΑ (τιμή Panorama βάσει iShop)
      <br><small>Source=$x, result=$y. Example $y=$x-1</small></td>
   <td><input type=TEXT name="EXT115_VATDECODE" value="<?php
      echo @$x2->Agp['EXT115_VATDECODE'];
      ?>" MAXLENGTH=255 size=40></td>
</tr>
<tr>
   <td>Αντιστοίχιση κατηγορίας ΦΠΑ (τιμή iShop βάσει Panorama)
      <br><small>Source=$x, result=$y. Example $y=$x+1</small></td>
   <td><input type=TEXT name="EXT115_VCAENCODE" value="<?php
      echo @$x2->Agp['EXT115_VCAENCODE'];
      ?>" MAXLENGTH=255 size=40></td>
</tr>
<tr>
   <td>Αντιστοίχιση ποσοστού ΦΠΑ σε κωδικό (τιμή Panorama βάσει iShop)
      <br><small>Source=$x, result=$y. Example $y=$x-1</small></td>
   <td><input type=TEXT name="EXT115_VCADECODE" value="<?php
      echo @$x2->Agp['EXT115_VCADECODE'];
      ?>" MAXLENGTH=255 size=40></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($db_local)
{
   global $x2;

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

   $pars=array('EXT115_COMPANY', 'EXT115_IDATA', 'EXT115_AUTO_ORD', 'EXT115_SALESERIES',
      'EXT115_VATENCODE', 'EXT115_VATDECODE', 'EXT115_VCAENCODE', 'EXT115_VCADECODE' );
   $prim=array('AGENTID', 'PNAME');

   foreach ($pars as $par1) {
      $data=array( 'PNAME'=>$par1, 'PVALUE'=>$_REQUEST[$par1], 'AGENTID'=>$x2->agentid );
      if (ReplaceEx2($db_local, 'agent_main', $data, $prim)) // o.k.
         $x2->Agp[$par1]=$_REQUEST[$par1];
      else // error
         echo "<h6>".$db_local->ErrorMsg()."</h6>";
   }
}
//--------------------------------------
?>
