<?php
// FLY (Singular) / was OLD Panorama SOFTONE
//--------------------------------------
if (PHP_SAPI==='cli') {
   chdir(dirname($_SERVER['PHP_SELF']));
}
include("../lib/ado/adodb.inc.php");
include("../lib/generic.inc.php");
include("../lib/visual.inc.php");
define('MY_SESSION_NAME', 'iAdmin');
implement_session();
require_once("ishop_all.inc.php");
require_once("ishop.inc.php");
include("ishop_x_102a.php");

if (!function_exists('umessage'))
{
   function umessage($s)
   {
      echo "<div style=\"color:red\">$s</div>";
   }
}


class cWINDOW {
   function __construct()
   {
      echo "<html>
<head>
<BASE HREF=\"http://".(@$_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()\">
<div class=bgHeader>Modern iShopping cart Setup (for FLY)</td>
</div>";
   }

   function __destruct()
   {
      echo "</body></html>";
   }
}

$dbin = &db_open();

$x2=new cX2($dbin);

// Parse command line arguments
parse_cmd_line();
//$_REQUEST['CODEFILTER']=urldecode($_REQUEST['CODEFILTER']);


// 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'];

class cDATAEX
{
   var $db=false;

   function __construct()
   {
      global $x2;

      if (empty($x2->Agp['EXT102_DATASOURCE'])) {
         echo "<h6>Connection string not set!</h6>";
         return;
      }

      $model=false;

      $this->db = &ADONewConnection('ado_mssql');
      //$this->db->debug=true;
      if (!$this->db->Connect( $x2->Agp['EXT102_DATASOURCE'], $x2->Agp['EXT102_USERID'], $x2->Agp['EXT102_PWD'], $x2->Agp['EXT102_CATALOG'])) {

         $this->db = &ADONewConnection('mssql');
         //$this->db->debug=true;
         if (!$this->db->Connect( $x2->Agp['EXT102_DATASOURCE'], $x2->Agp['EXT102_USERID'], $x2->Agp['EXT102_PWD'], $x2->Agp['EXT102_CATALOG'])) {
	         echo "<h6 class=ERROR>External database connection failed! ".$this->db->ErrorMsg()."</h6>\n";
	         $this->db=false;
         }
         else {
            $model='mssql';
         }
      }
      else {
         $model='ado_mssql';
      }

      if ($model!==false) {
         //umessage("External connection model: $model");
      }
   }

   function __destruct()
   {
      if ($this->db!==false)
         $this->db->Close();
   }
}

$ADODB_FETCH_MODE = ADODB_FETCH_NUM;

if ($fu==5 || $fu==6 || $fu==18)
   show_data_header();
else
   $c1=new cWINDOW();


switch ($fu)
{
case 0:
   main_menu();
   break;
case 1:
   $dbex=new cDATAEX();
   load_customers($dbex->db,$dbin,0,false);
   main_menu();
   break;
case 101:
   $dbex=new cDATAEX();
   load_customers($dbex->db,$dbin,0,true); // customers, last only
   break;
case 2:
   ask_load_items();
   main_menu();
   break;
case 102:
   $dbex=new cDATAEX();
   load_items($dbex->db,$dbin,false);
   main_menu();
   break;
case 103:
   $dbex=new cDATAEX();
   load_items($dbex->db,$dbin,true);
   main_menu();
   break;
case 4:
   export_ord_ask($dbin);
   main_menu();
   break;
case 5:
   $dbex=new cDATAEX();
   ascii_exp_orders($dbex->db, true); // do export orders (ascii) real
   //main_menu();
   break;
case 6:
   $dbex=new cDATAEX();
   ascii_exp_orders($dbex->db, false); // export orders (ascii) test
   //main_menu();
   break;
case 7:
   $dbex=new cDATAEX();
   load_salesmen($dbex->db,$dbin); // new
   load_dlvmethod($dbex->db, $dbin); // new
   load_paymethod($dbex->db, $dbin); // new
   load_warehouse($dbex->db, $dbin); // new
   main_menu();
   break;
case 8:
   $dbex=new cDATAEX();
   show_items_sub($dbex->db, $dbin);
   echo "<a href=\"".$_SERVER['PHP_SELF']."\">Επιστροφή</a>";
   break;
case 9:
   $dbex=new cDATAEX();
   load_items_sub($dbex->db,$dbin);
   main_menu();
   break;
case 10:
   $dbex=new cDATAEX();
   db_exp_orders($dbex->db,$dbin,true); // do export orders (DB)
   main_menu();
   break;
case 11:
   $dbex=new cDATAEX();
   db_exp_orders($dbex->db,$dbin,false); // export orders (DB) test
   main_menu();
   break;
case 12:
   // Load suppliers
   $dbex=new cDATAEX();
   load_customers($dbex->db,$dbin,1,false);
   main_menu();
   break;
case 112:
   $dbex=new cDATAEX();
   load_customers($dbex->db,$dbin,1,true); // suppliers, last only
   break;
case 13:
   $dbex=new cDATAEX();
   import_orders($dbex->db, $dbin);
   main_menu();
   break;
case 14:
   $dbex=new cDATAEX();
   db_exp_apogra($dbex->db, $dbin, false);
   break;
case 15:
   $dbex=new cDATAEX();
   reread_orders($dbex->db, $dbin);
   main_menu();
   break;
case 16:
   $dbex=new cDATAEX();
   parameter_ask($dbex->db,$dbin);
   break;
case 17:
   parameter_save($dbin);
   main_menu();
   break;
case 18:
   $dbex=new cDATAEX();
   export_new_customers($dbex->db,$dbin);
   //main_menu();
   break;
case 113: // called from a batch file
   $dbex=new cDATAEX();
   real_import_orders($dbex->db, $dbin);
   break;
case 115: // called from a batch
   $dbex=new cDATAEX();
   real_reread_orders($dbex->db, $dbin);
   break;
case 200:
   $dbex=new cDATAEX();
   show_files($dbex->db);
   main_menu();
   break;
case 202:
   $dbex=new cDATAEX();
   show_file_data($dbex->db);
   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;
default:
   echo "Unknown funtion $fu\n";
   break;
}

$dbin->Close();
//======================================
// Functions
//======================================
function main_menu()
{
   global $x2;

   if (isset($x2->Agp['EXT102_IDATA']))
      $idata=(int)$x2->Agp['EXT102_IDATA'];
   else
      $idata=0;
?>
<b>Επιλογές</b>
<ul>
<li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=16">Παράμετροι</a><br>
   &nbsp;</li>

<li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=1">Εισαγωγή πελατών</a></li>
<!-- li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=12">Εισαγωγή προμηθευτών</a></li -->
<!-- li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=3"></a>Εισαγωγή κατηγοριών</li -->
<?php
   if ($idata==0) {
      echo "<li><a href=\"".$_SERVER['PHP_SELF']."?FUNC2=2\">Εισαγωγή ειδών</a></li>";
   }
   else {
      echo "<li><a href=\"".$_SERVER['PHP_SELF']."?FUNC2=8\">Εμφάνιση κωδικών/υποκωδικών</a></li>
         <li>Εισαγωγή κωδικών/υποκωδικών:
         <a href=\"".$_SERVER['PHP_SELF']."?FUNC2=9\">Εκτέλεση</a> |
         <a href=\"".$_SERVER['PHP_SELF']."?FUNC2=209\">Δημιουργία script</a>
         </li>";
   }
?>
<li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=7">Εισαγωγή πωλητών/ Τρόπων αποστολής/ Πληρωμής/ Αποθηκών</a></li>
<!-- li><form action="<?php echo $_SERVER['PHP_SELF']; ?>" name="goForm">
   <input type=HIDDEN name="FUNC2" value="13">Import παραγελιών από (βάθος χρόνου)
   <input type=TEXT name="FROMDAYS" value="1" size=5> ημέρες
   <input type=submit name="ok" value="Import"></form></li -->
<!-- li><A href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=15">Επανάληψη ανάγνωσης παραγγελιών</a><br>
   &nbsp;</li -->

<?php
   if ($idata==0) {
      echo "<li><a href=\"".$_SERVER['PHP_SELF']."?FUNC2=4\">Export παραγγελιών</a></li>";
   }
   else {
      echo "<li>Export παραγγελιών: <a href=\"".$_SERVER['PHP_SELF']."?FUNC2=10\">Export</a> |\n".
         "<a href=\"".$_SERVER['PHP_SELF']."?FUNC2=11\">Δοκιμή</a></li>";
   }
?>
<!-- li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=14">Export απογραφής</a><br -->
<!-- li><a href="/ishop/ishop_export.php?FUNCTION=1021">Export νέων πελατών</a><br -->
<li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=18">Export νέων πελατών</a><br>
   &nbsp;</li>

<li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNC2=200">Show files</a></li>
<?php
   if ($idata!=0) {
      echo "<li><a href=\"".$_SERVER['PHP_SELF']."?FUNC2=203\">Create Stored Procediour</a></li>";
   }
?>
</ul>
<button type=button onClick="self.close()">Close Window</button>
<?php
}
//--------------------------------------
function show_data_header()
{
   header("Content-Transfer-Encoding: binary");
   header('Content-disposition: attachment; filename="outdata.txt"');
   header("Content-type: application/download");
   header("Cache-Control: no-store, no-cache, must-revalidate");  // HTTP/1.1
   header("Cache-Control: post-check=0, pre-check=0", false);
   header("Pragma: no-cache");
}
//--------------------------------------
function no_external()
{
   echo "<div class=error>External connection not established!</div>\n";
}
//--------------------------------------
function detached_exe($ar1)
{
   global $x2;
   $db=&$x2->db;

   $query="SELECT RESELID, PASSWD FROM reseller WHERE AGENTID=? LIMIT 1";
   $data=array($x2->agentid);
   if (($rs=$db->Execute($query,$data))===false) {
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>";
      return false;
   }
   $o1=$rs->FetchNextObject();
   $rs->Close();
   if ($o1===false) {
      umessage("No reseller(s) exist for Agent!");
      return false;
   }

   $query="SELECT PVALUE FROM agent_main WHERE AGENTID=0 AND PNAME='DETACHED_EXE_CATALOG' ";
   if (($rs=$db->Execute($query))===false) {
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>";
      return false;
   }
   $row=$rs->FetchRow();
   $rs->Close();
   if ($row===false) {
      umessage("Detached execution catalog not set!");
      return false;
   }
   $detached=$row[0];

   if (!is_dir($detached)) { // still does not exist
      echo "<div class=error>Detached execution catalog [$detached] not found!</div>";
      return false;
   }

   $fname=IncludeTrailingPathDlm($detached)."ishop_x_102.bat";
   if (($fp=fopen($fname,"w"))===false) {
      echo "<div class=error>Failed to open file: $fname</div>";
      return false;
   }

   $s1 = "php.exe \"".DOCUMENT_ROOT.$_SERVER['PHP_SELF']."\" \"RESELID=".$o1->RESELID."&REPASS=".urlencode($o1->PASSWD)."&ISDETACHED=1";
   foreach ($ar1 as $k=>$v) {
      $s1 .= "&$k="; //.urlencode($v);
      $s2=urlencode($v);
      for ($i=0;$i<strlen($s2);$i++) {
        if ($s2{$i}==='%')
          $s1 .= '%%';
         else
          $s1 .= $s2{$i};
      }
   }
   $s1 .= "\"";
   fwrite($fp, $s1);
   fclose($fp);

   umessage("Process forwarded as {$fname}!");

   return true;
}
//--------------------------------------
function load_salesmen($dbin)
{
   global $x2;
   $prof=new cPROFILER1();

	if ($dbin===false) {
		no_external();
		return;
	}

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

   /*$query="SELECT NAME2, NAME, PRSN, CODE
      FROM PRSN
      WHERE SODTYPE=20 AND COMPANY=?";*/
   $query="SELECT [ΚΩΔΙΚΟΣ ΠΩΛΗΤΗ] AS PRSN, [ΟΝΟΜΑΤΕΠΩΝΥΜΟ] AS NAME
      FROM [COMM_MPADEKA].[dbo].[Z_PDA_SALESMAN_OUT]";
   //$company=get_company($dbout, $x2->agentid);
   if (!$rs=$dbin->Execute(UTF8Decode($query))) {
      echo "<h6>".$query.": ".$dbin->ErrorMsg()."</h6>\n";
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $data=array(
			'AGENTID'=>$x2->agentid,
			'RE_NAME'=>ToUTF8($o1->NAME),
			'RESELID'=>(int)$o1->PRSN,
			'PASSWD'=>ToUTF8('1234')
		);

      if (ReplaceEx2($dbout,'reseller', $data, $prim ))
         $nrec++;
      else {
         echo "<h6>".$query.": ".$dbout->ErrorMsg()."</h6>\n";
         //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) {
		no_external();
		return;
	}

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

   //$query="SELECT CODE,NAME FROM SHIPMENT WHERE COMPANY=?";
   $query="SELECT [ΚΩΔΙΚΟΣ ΜΕΘΟΔΟΣ ΠΑΡΑΔΟΣΗΣ] AS CODE, [ΠΕΡΙΓΡΑΦΗ] AS NAME
      FROM [COMM_MPADEKA].[dbo].[Z_PDA_SHIPPING_OUT]";
   if (!$rs=$dbin->Execute(UTF8Decode($query))) {
      echo "<h6>".$query.": ".$dbin->ErrorMsg()."</h6>\n";
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $data=array(
			'AGENTID'=>$x2->agentid,
			'MENUTYPE'=>6,
			'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>Delivery methods: ".$nrec." records replaced in ".$prof->elapsed()." seconds</h5>";
}
//--------------------------------------
function load_warehouse($dbin, $dbout)
{
   global $x2;
   $prof=new cPROFILER1();

	if ($dbin===false) {
		no_external();
		return;
	}

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

   //$query="SELECT WHOUSE, NAME FROM WHOUSE WHERE COMPANY=? AND ISACTIVE=1";
   $query="SELECT [ΚΩΔΙΚΟΣ ΑΠΟΘΗΚ.ΧΩΡΟΥ] AS WHOUSE, [ΠΕΡΙΓΡΑΦΗ] AS NAME
      FROM [COMM_MPADEKA].[dbo].[Z_PDA_WAREHOUSE_OUT]";
   if (!$rs=$dbin->Execute(UTF8Decode($query))) {
      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) {
		no_external();
		return;
	}

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

   //$query="SELECT CODE,NAME FROM PAYMENT WHERE SODTYPE=13 AND COMPANY=?";
   $query="SELECT [ΚΩΔΙΚΟΣ ΜΕΘΟΔΟΣ ΠΛΗΡΩΜΗΣ] AS CODE, [ΠΕΡΙΓΡΑΦΗ] AS NAME
      FROM [COMM_MPADEKA].[dbo].[Z_PDA_PAYMENT_OUT]";
   if (!$rs=$dbin->Execute(UTF8Decode($query))) {
      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 convertCharSet(&$val,$key)
{
   $val = strtr( UTF8Decode($val), '#', '+' );
}
//--------------------------------------
function export_new_customers($dbex, $db)
{
   global $x2;

   $prof=new cPROFILER1();

   if ($dbex===false) {
		no_external();
		return;
	}

   $tables=$db->MetaTables();
   // Convert all to lower case
   array_walk($tables,'array_toLower');

   $t1="Z_PDA_customers";
   if (!array($t1,$tables)) {
      $query="CREATE TABLE $t1
      (
      [LOGIN]    VARCHAR(20),  -- customer id
      COMPANY    VARCHAR(40),  -- customer title (name)
      JOB        VARCHAR(40),
      ADDR1      VARCHAR(40),
      ADDR2      VARCHAR(40),
      CITY       VARCHAR(20),
      ZIP        VARCHAR(10),
      PHONE      VARCHAR(20),
      PHONE2     VARCHAR(20),
      FAX        VARCHAR(20),
      VATNO      VARCHAR(20),  -- ΦΠΑ
      DOY        VARCHAR(20),
      EMAIL      VARCHAR(70),
      VATCODE    INT, -- customer vatcode (normal/reduced/zero)
      BASEDISC   NUMERIC(15,2), -- basic discount %
      RESELID    INT, -- reseller id
      ERPIMPORT  INT,
      ERPIMPDATE DATETIME
      )";

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

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

   $qins="INSERT INTO Z_PDA_customers ([LOGIN], COMPANY, JOB, ADDR1, ADDR2, CITY, ZIP, PHONE, PHONE2,
      FAX, VATNO, DOY, EMAIL, VATCODE, BASEDISC, RESELID ) VALUES(?,?,?,?,  ?,?,?,?,  ?,?,?,?,  ?,?,?,?)";

   $query="SELECT LOGIN, COMPANY, JOB, ADDR1, ADDR2, CITY, ZIP, PHONE, PHONE2, FAX, VATNO, DOY, EMAIL, VATCODE, BASEDISC, RESELID
      FROM ishop_mbr
      WHERE AGENTID=? AND CRERESELID <> 0";
   $data=array($x2->agentid);
   $db->SetFetchMode(ADODB_FETCH_NUM);
   if (($rs=$db->Execute($query,$data))===false) {
      echo $db->ErrorMsg();
      return;
   }
   $nrec=0;
   while ($row=$rs->FetchRow()) {
      array_walk($row, 'convertCharSet');

      if ($fx!=null) {
         $row[13] = $fx((int)$row[13]);
      }

      if (!$dbex->Execute($qins, $row)) {
         echo $dbex->ErrorMsg();
         break;
      }

      echo implode(";", $row)."\r\n";

      $nrec++;
   }
   $rs->Close();
   $db->SetFetchMode(ADODB_FETCH_DEFAULT);

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

   if (!empty($x2->Agp['EXT102_DETACHED']) && empty($_REQUEST['ISDETACHED'])) {
      detached_exe( array('FUNC2'=>1) );
      return;
   }

   $prof=new cPROFILER1();

	if ($dbin===false) {
		no_external();
		return;
	}

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

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

   $nrec=0;
   // 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 [Κωδικός] AS CODE
      ,[ΕΠΩΝΥΜΙΑ] AS NAME
      ,[ΑΦΜ] AS AFM
      ,[ΕΚΠΤΩΣΗ] AS DISCOUNT
      ,[ΕΠΑΓΓΕΛΜΑ] AS JOBTYPETRD
      ,[ΔΙΕΥΘΥΝΣΗ] AS ADDRESS
      ,[ΠΟΛΗ] AS CITY
      ,[ΝΟΜΟΣ] AS STATE
      ,[ΤΚ] AS ZIP
      ,[ΤΗΛ.1] AS PHONE01
      ,[ΤΗΛ.2] AS PHONE02
      ,[ΦΑΞ] AS FAX
      ,[ΔΟΥ] AS IRSDATA
      ,[EMAIL] AS EMAIL
      ,[ΚΩΔ.ΦΠΑ] AS VATSTS
      ,[ΠΕΡΙΟΧΗ] AS ADDR2
      ,[ΤΖΙΡΟΣ] AS TZIROS
      ,[ΕΝΕΡΓΟΣ] AS LISTINCAT
      FROM [COMM_MPADEKA].[dbo].[Z_PDA_CUSTOMER_OUT]";
   if (!$rs=$dbin->Execute(UTF8Decode($query))) {
      echo "<h6>".$query.": ".$dbin->ErrorMsg()."</h6>\n";
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $data=array(
			'AGENTID'=>$x2->agentid,
			'LOGIN'=>ToUTF8((string)$o1->CODE),
			'XDBID'=>0,
			'COMPANY'=>ToUTF8((string)$o1->NAME),
			'VATNO'=>ToUTF8((string)$o1->AFM),
			'BASEDISC'=>toFloat($o1->DISCOUNT),
			'JOB'=>ToUTF8((string)$o1->JOBTYPETRD),
			'ADDR1'=>ToUTF8((string)$o1->ADDRESS),
         'ADDR2'=>ToUTF8((string)$o1->ADDR2),
         'COUNTRY'=>('ΤΖΙΡΟΣ: '.toFloat($o1->TZIROS)),
			'CITY'=>ToUTF8((string)$o1->CITY),
			'STATE'=>ToUTF8((string)$o1->STATE), // ΠΕΡΙΟΧΗ
			'ZIP'=>ToUTF8((string)$o1->ZIP),
			'PHONE'=>ToUTF8((string)$o1->PHONE01),
			'PHONE2'=>ToUTF8((string)$o1->PHONE02),
			'FAX'=>ToUTF8((string)$o1->FAX),
			'DOY'=>ToUTF8((string)$o1->IRSDATA),
			'EMAIL'=>ToUTF8((string)$o1->EMAIL),
			'VATCODE'=>$fx((int)$o1->VATSTS),
         'LISTINCAT'=>(int)$o1->LISTINCAT,
			'TRKEY'=>ToEnglish( ToUTF8( ((string)$o1->CODE).' '.((string)$o1->NAME) ) ),
			'CRERESELID'=>0
		);
      if (ReplaceEx2($dbout, $t1, $data, $prim )) {
         echo (++$nrec)." ";
      }
      else {
         echo "<h6>".$query.": ".$dbout->ErrorMsg()."</h6>\n";
         //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</h5>";
}
//--------------------------------------
function load_items($dbin, $dbout, $newer_only=false)
{
   global $x2;
   $prof=new cPROFILER1();

   if (!empty($x2->Agp['EXT102_DETACHED']) && empty($_REQUEST['ISDETACHED'])) {
      detached_exe( array('FUNC2'=>102, 'CODEFILTER'=>$_REQUEST['CODEFILTER'], 'PRICENO'=>$_REQUEST['PRICENO']) );
      return;
   }

   if ($dbin===false) {
		no_external();
		return;
	}

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

   $data=array(); // empty array
   $query="SELECT [ΚΩΔΙΚΟΣ ΕΙΔΟΥΣ] AS CODE,
      [ΠΕΡΙΓΡΑΦΗ] AS NAME,
      [ΜΟΝΑΔΑ ΜΕΤΡΗΣΗΣ] AS UNIT,
      [BARCODE],
      [ΒΑΣΙΚΗ ΤΙΜΗ] AS PRICE2,
      [ΤΙΜΗ ΑΠΟ ΤΙΜΟΚΑΤΑΛΟΓΟ ΕΠΙΛΟΓΗΣ] AS PRICE1
      FROM [COMM_MPADEKA].[dbo].[Z_PDA_ITEM_OUT]
      WHERE 1=1";
	if (!empty($_REQUEST['CODEFILTER'])) {
		$query .= " AND [ΚΩΔΙΚΟΣ ΕΙΔΟΥΣ] LIKE ?";
		$data[] = UTF8Decode($_REQUEST['CODEFILTER']);
	}
   if (!$rs=$dbin->Execute(UTF8Decode($query), $data)) {
      echo "<h6>".$dbin->ErrorMsg()."<br>$query</h6>\n";
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $iname=ToUTF8($o1->NAME);

      $data=array(
			'AGENTID'=>$x2->agentid,
			'CODE'=>ToUTF8((string)$o1->CODE),
			'NAME'=>$iname,
			'UNIT'=>ToUTF8((string)$o1->UNIT),
			'BARCODE'=>ToUTF8((string)$o1->BARCODE),
			'PRICE2'=>toFloat($o1->PRICE2),
			'PRICE1'=>toFloat($o1->PRICE1),
         'TRKEY'=>ToEnglish( ToUTF8((string)$o1->CODE).' '.$iname )
		);

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

   echo "<h5>".$nrec." records processed in ".$prof->elapsed()." seconds</h5>";
}
//--------------------------------------
function ask_load_items()
{
?>
<h5>Εισαγωγή ειδών</h5>
<form method=POST action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type=HIDDEN name="FUNC2" value="102">
<table>
<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">Ευρώπης
      <option value="2">Γενικός
      </select></td>
</tr -->
<tr>
	<td></td>
	<td>
		<input type=SUBMIT name="ok" value="Ενημέρωση">
	</td>
</tr>
</table>
</form>
<hr>
<?php
}
//--------------------------------------
function export_ord_ask($db)
{
   global $x2;
?>
<h5>Export παραγγελιών</h5>
<form method=POST action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type=HIDDEN name="FUNC2">
<label><input type=radio name="EXPORTWHERE" value="1">Στη βάση δεδομένων</label>
<label><input type=radio name="EXPORTWHERE" value="2">Σε αρχείο ascii</label><br><br>
<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()">
</form>
<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($dbx, $do_update)
{
   global $x2;
   $db=&$x2->db;
   $prof=new cPROFILER1();

   if (empty($_REQUEST['EXPORTWHERE'])) {
      echo "<h6>Δεν επιλέξατε που θα γίνει εξαγωγή!</h6>";
      return;
   }
   else {
      $exportInRdbms = $_REQUEST['EXPORTWHERE']==1;
   }

   if ($exportInRdbms) {
      if ($dbx===false) {
		   no_external();
		   return;
      }

      $tables=$dbx->MetaTables();
      // Convert all to lower case
      array_walk($tables,'array_toLower');

      // Create table if not exists
      $t1="Z_PDA_orders";
      if (!array($t1,$tables)) {
         $query="CREATE TABLE $t1
         (
         LOGTIME        DATETIME, -- order taken date time
         ORDERID        INT,
         MBR_LOGIN      VARCHAR(20), -- customer code
         RE_RESELID     INT, -- reseller id
         ICODE          VARCHAR(20), -- item code
         QUANTITY       NUMERIC(15,3),
         PRICE          NUMERIC(15,4),
         VATPER         NUMERIC(6,2),
         VATCODE        INT, -- customer vatcode (normal/reduced/zero)
         DLVDATE        DATETIME, -- delivery date
         DLVMETHOD      INT, -- delivery method
         PAYMETHOD      INT, -- payment method
         ERPIMPORT      INT,
         ERPIMPDATE     DATETIME
         )";

         if (!$dbx->Execute($query)) {
            echo "<h6>".$dbx->ErrorMsg()."</h6>\n";
            return;
         }
      }
   }

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

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

   $nrec=0;

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

   $qins="INSERT INTO Z_PDA_orders (LOGTIME, ORDERID, MBR_LOGIN, RE_RESELID, ICODE, QUANTITY, PRICE,
      VATPER, VATCODE, DLVDATE, DLVMETHOD, PAYMETHOD) VALUES(?,?,?,?,  ?,?,?,?,  ?,?,?,?)";

   // 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 $db->ErrorMsg();
		return;
	}
	while ($o1=$rs->FetchNextObject()) {
      if ((int)$o1->ORDERID!=(int)$odata['ORDERID']) {
         $odata['ORDERID']=$o1->ORDERID;
         reload_odata($db,$odata);
      }

      if ($exportInRdbms)
      {
         $data=array($o1->LOGTIME, $o1->ORDERID, $o1->MBR_LOGIN, $o1->RE_RESELID, $o1->ICODE, $o1->QUANTITY, $o1->PRICE,
            $fx2($o1->VATPER), $fx($o1->VATCODE),
            ( 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'] );
         if (!$dbx->Execute($qins,$data)) {
            echo $dbx->ErrorMsg();
            break;
         }

         echo implode(";",$data)."\r\n";
      }
      else
      { // ascii
		   $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)
		   );
		   echo $buf;
      }

		$nrec++;
	}
	$rs->Close();

	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 $db->ErrorMsg();
	}

   echo "Processed: $nrec records in ".$prof->elapsed()." seconds<";
}
//--------------------------------------
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 show_files($dbin)
{
   if ($dbin===false) {
		no_external();
		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=".$f1."\">".$f1."</a>\n";
   echo "</ul>";
}
//--------------------------------------
function show_file_data($dbext)
{
   if ($dbext===false) {
		no_external();
		return;
	}

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

	$query="SELECT * FROM ".$_REQUEST['F1'];
	if (!($rs=$dbext->PageExecute($query,$pgsz,$pg))) {
		echo "<h6>".$dbext->ErrorMsg()."</h6>\n";
		return;
	}
	echo "<b>".myhtml($_REQUEST['F1'])."</b>\n";
?>
<form method=POST action="<?php echo $_SERVER['PHP_SELF']; ?>" name="goForm">
<input type=HIDDEN name="RSPAGE">
<input type=HIDDEN name="F1" value="<?php echo $_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) {
		no_external();
		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) {
		no_external();
		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";
?>
<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="">
<?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) {
		no_external();
		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
   /*
   if (!empty($_SERVER['PATH_TRANSLATED']))
      $prog=$_SERVER['PATH_TRANSLATED'];
   else if (!empty($_SERVER['SCRIPT_FILENAME']))
      $prog=$_SERVER['SCRIPT_FILENAME'];

   $prog=strtr($prog,"\\","/");
   $ar1=explode("/",$prog);
   $ex1=array_pop($ar1);
   $pdir=implode("\\",$ar1);
   */

   if (($shell=new COM('WScript.Shell'))==null) {
      echo "<h6>COM failed!</h6>";
      return;
   }

   $basekey="HKEY_LOCAL_MACHINE\\SOFTWARE\\PHP\\InstallDir";
   try {
      $x=@$shell->RegRead( $basekey );
   }
   catch (Exception $e) {
      echo "<h6>COM error: $e</h6>";
      $x=false;
   }
   $shell=null;

   if (empty($x))
      return;

   $php_exe="$x\\php.exe";
?>
<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="<?php echo myhtml($php_exe); ?>"

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

cd <?php echo $pdir ?>
%phpexe% -f "<?php
   // We use strtr() for Apache on Windows
   echo $ex1;
   ?>" 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['EXT102_SALESERIES']))
	   $series=$x2->Agp['EXT102_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) {
		no_external();
		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) {
		no_external();
		// however, do not return
	}
	else {
      $query="SELECT COMPANY, NAME FROM COMPANY ORDER BY COMPANY";
      if (($rs=$db_remote->Execute($query))===false) {
         echo "<h6>$query: ".$db_remote->ErrorMsg()."</h6>";
      }
      else {
         while ($o1=$rs->FetchNextObject()) {
            $ar1[ $o1->COMPANY ] = ToUTF8('#'.$o1->COMPANY.' '.$o1->NAME);
         }
         $rs->Close();
      }
   }

   if (isset($x2->Agp['EXT102_COMPANY']))
      $company=(int)$x2->Agp['EXT102_COMPANY'];
   else
      $company=1;

   if (!array_key_exists($company, $ar1)) {
      $ar1[$company]='Company #'.$company;
   }

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

   if (isset($x2->Agp['EXT102_AUTO_ORD']))
      $auto_ord=(int)$x2->Agp['EXT102_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="EXT102_COMPANY"><?php
      prAssocSelect($ar1,$company);
      ?></select></td>
</tr>
<tr>
   <td>Data</td>
   <td><select name="EXT102_IDATA"><?php
      prAssocSelect($ar2,$idata);
      ?></select></td>
</tr>
<tr>
   <td>Αυτόματη ενημέρωση παραγγελιών</td>
   <td><input type=CHECKBOX name="EXT102_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="EXT102_SALESERIES" value="<?php
      echo myhtml((string)@$x2->Agp['EXT102_SALESERIES']);
      ?>" MAXLENGTH=255 size=40></td>
</tr>
<tr>
   <td>Αντιστοίχιση καθεστώτος ΦΠΑ (τιμή iShop βάσει ERP)
      <br><small>Source=$x, result=$y. Example $y=$x+1</small></td>
   <td><input type=TEXT name="EXT102_VATENCODE" value="<?php
      echo @$x2->Agp['EXT102_VATENCODE'];
      ?>" MAXLENGTH=255 size=40></td>
</tr>
<tr>
   <td>Αντιστοίχιση καθεστώτος ΦΠΑ (τιμή ERP βάσει iShop)
      <br><small>Source=$x, result=$y. Example $y=$x-1</small></td>
   <td><input type=TEXT name="EXT102_VATDECODE" value="<?php
      echo @$x2->Agp['EXT102_VATDECODE'];
      ?>" MAXLENGTH=255 size=40></td>
</tr>
<tr>
   <td>Αντιστοίχιση κατηγορίας ΦΠΑ (τιμή iShop βάσει ERP)
      <br><small>Source=$x, result=$y. Example $y=$x+1</small></td>
   <td><input type=TEXT name="EXT102_VCAENCODE" value="<?php
      echo @$x2->Agp['EXT102_VCAENCODE'];
      ?>" MAXLENGTH=255 size=40></td>
</tr>
<tr>
   <td>Αντιστοίχιση ποσοστού ΦΠΑ σε κωδικό (τιμή ERP βάσει iShop)
      <br><small>Source=$x, result=$y. Example $y=$x-1</small></td>
   <td><input type=TEXT name="EXT102_VCADECODE" value="<?php
      echo @$x2->Agp['EXT102_VCADECODE'];
      ?>" MAXLENGTH=255 size=40></td>
</tr>
<tr>
   <td>&nbsp;</td>
</tr>
<tr>
   <td>Detached execution</td>
   <td><input type=checkbox name="EXT102_DETACHED" <?php if (!empty($x2->Agp['EXT102_DETACHED'])) { 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($db_local)
{
   global $x2;

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

   $pars=array('EXT102_COMPANY', 'EXT102_IDATA', 'EXT102_AUTO_ORD', 'EXT102_SALESERIES',
      'EXT102_VATENCODE', 'EXT102_VATDECODE', 'EXT102_VCAENCODE', 'EXT102_VCADECODE', 'EXT102_DETACHED' );
   $prim=array('AGENTID', 'PNAME');

   foreach ($pars as $par1) {
      $data=array( 'PNAME'=>$par1, 'PVALUE'=>(string)@$_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>";
   }
}
//--------------------------------------
?>
