<?php session_name('iAdmin'); session_start();
require('ishop_ahe.inc.php');
// $x2 has been defined and initialized, so we can now include ishop_tax.inc.php
include('ishop_tax.inc.php');
?>
<style>
.green { color:green; font-weight:bold; }
.red { color:red; font-weight:bold; }
.REVERSE { color:white; background-color:black; }
span.pgroup { text-decoration: underline; cursor:pointer; }
div[id^="pnames"] li { text-decoration: underline; cursor:pointer; }
.info td { white-space: nowrap; }
TABLE.masterTable { border-collapse: collapse; }
TABLE.masterTable td { border: 1px solid gray; }
.inframe { border: 1px solid gray; padding: 0.5em; }
.addMore {
   background-image: url(/img/plus.gif);
   background-repeat: no-repeat;
   padding-left:1.5em;
   cursor: pointer;
}
</style>
<script>
function theSizer()
{
   // first things first
   $('div.bgButton2').width( $(window).width()-8 ); // -8

   // second
   var y1=$('#theleft').offset().top;
   var y2=$('div.bgButton2').offset().top;
   var h=y2-y1; // padding 2 x 4 = 8
   if (h<100) {
      h=100;
   }
   $('#theleft').height(h);
}
function goExport(fx)
{
   var url = '/ishop/ishop_taxout.php?FUNCTION=' + fx + iadmin_str();
   window.open(url);
}
</script><?php

$multiFields = array('paymentMethodDetails', 'invoiceDetails', 'incomeClassification',
   'expensesClassification', 'taxes');

switch ($fu)
{
case 1:
   monitor_curr_data();
   break;
case 2:
   show_records();
   break;
case 3:
   update_grid_size();
   monitor_curr_data();
   break;
case 4:
   monitor_eafdss();
   break;
case 5:
   show_eafdss_details();
   break;
case 6:
   eafdss_history();
   break;
case 7: // deprecated
   break;
case 8:
   toggle_enable_eafdss();
   monitor_curr_data();
   break;
case 9:
   eafdss_alerts();
   break;
case 10:
   alert_history();
   break;
case 11:
   show_pos_details();
   break;
case 12:
   zoom_pos();
   break;
case 13:
   update_location();
   zoom_pos();
   break;
case 14:
   purge_old_recs();
   show_records();
   break;
case 15:
   reset_grpFilter();
   monitor_curr_data();
   break;
case 16:
   prepare_toggle();
   toggle_enable_eafdss();
   monitor_curr_data();
   break;
case 17:
   upd_machine_group();
   monitor_curr_data();
   break;
case 18:
   toggle_enable_eafdss();
   zoom_pos();
   break;
case 19:
   update_aeskey();
   show_eafdss_details();
   break;
case 20:
   show_s_txt_details();
   break;
case 21:
   delete_eafdss();
   show_eafdss_details();
   break;
case 22:
case 23:
   $_SESSION['EAFDSS_DETAILS_ORDER_BY'] = $fu-22;
   show_eafdss_details();
   break;
case 24:
   show_eafdss_info2(0); // taxspooler version
   break;
case 25:
   show_eafdss_info2(1); // O/S version
   break;
case 26:
   //eafdss_grp_properties();
   eafdss_grp_nodes();
   break;
case 27:
   eafdss_detail_properties();
   break;
case 28:
   eafdss_ask_compare();
   break;
case 29:
   eafdss_do_compare();
   break;
case 30:
case 31:
case 32:
case 33: // reserved
case 34: // reserved
case 35: // reserved
   $_SESSION['EAFDSS_DETAILS_ORDER_BY']=$fu-28;
   show_eafdss_details();
   break;
case 36:
   wmic_cleandays();
   eafdss_ask_compare();
   break;
case 37:
   eafdss_node_property_grp();
   break;
case 40:
   upd_vers_request();
   show_eafdss_details();
   break;
case 42:
   $_REQUEST['ORDERBY']=" CREDATE, CRETIME";
   eafdss_do_compare();
   break;
case 43:
   list_disk_free();
   break;
case 44:
   tab_disk_free();
   break;
case 45:
   remote_params();
   break;
case 46:
   remote_param_one();
   break;
case 47:
   set_remote_params();
   break;
case 48:
   remote_param_progress();
   break;
case 49:
   reset_allowSendTaxis();
   show_eafdss_details();
   break;
case 50:
   wmic_list_updates();
   break;
case 51:
   branch_per_group();
   break;
case 52:
   update_brgroup();
   branch_per_group();
   break;
case 53:
   remote_param_one(true);
   break;
case 54:
   list_tax_properties();
   break;
case 60:
   show_z_collection();
   break;
case 61:
   show_pending_Z();
   break;
case 62:
   show_pending_group();
   break;
case 63:
   show_z_of_s11();
   break;
case 64:
   show_z_contents();
   break;
case 70:
   show_mydata_dates();
   break;
case 71:
   show_mydata_agents();
   break;
case 72:
   show_mydata_date1();
   break;
case 73:
   show_myrecord();
   break;
case 74:
   show_mydata_w_filter();
   break;
case 75:
   edit_myrecord();
   break;
case 76:
   update_myrecord();
   show_mydata_date1();
   break;
case 77:
   cre_mycancel_rec();
   show_mydata_date1();
   break;
case 78:
   del_my_rec();
   show_mydata_date1();
   break;
case 79:
   show_mydata_err_vat();
   break;
case 80:
   show_mymatch();
   break;
case 81:
   update_mymatch();
   show_mymatch();
   break;
case 82:
   show_mydata_can();
   break;
case 83:
   show_mydata_date_by_rid();
   break;
case 84:
   del_my_rec_group();
   show_mydata_can();
   break;
case 85:
   reset_myrecord();
   show_mydata_date1();
   break;
case 92:
   list_unmatched();
   break;
   /* deprecated 3-1-2022
case 93:
   load_ascii_enum();
   aeskey_list();
   break;
   */
case 94:
   open_eafdss();
   break;
case 95:
   ask_load_aeskeys();
   break;
case 96:
   do_load_aeskeys();
   break;
case 97:
   aeskey_list();
   break;
case 98:
   upd_eafdss_data();
   aeskey_list();
   break;
//
// administrative selections: 100+
//
case 100:
   ask_params();
   break;
case 101:
   upd_params();
   break;
case 102:
   clear_all_data(); // taxi_wmic
   break;
case 103:
   ask_params(true);
   break;
case 104:
   show_mydata_dates(1);
   break;
case 105:
   show_mydata_dates(2);
   break;
//
// superuser selections: 200+
//
case 200:
   list_sms_units();
   break;
case 201:
   add_sms_invoice();
   list_sms_units();
   break;
case 202:
   show_incoming_files();
   break;
default:
   echo "<h6>Incorrect function number: $fu<br>
      <a href=\"ishop_m2.php\">Login</a>
      </h6>";
   break;
}
$db->Close();
?>
</body elapsed="<?php echo $prof->elapsed(); ?>" mu="<?php showMemUsage(); ?>"></html>
<?php
//--------------------------------------
//
// Function area
//
//--------------------------------------
function update_grid_size()
{
   global $x2;
   $db=&$x2->db;

   if ($x2->reselid==0) {
      $t1="agent_main";
      $data=array(
         'PVALUE' => $_REQUEST['RECORDID'],
         'AGENTID' => $x2->agentid,
         'PNAME' => 'TXC_HORIZONTAL'
      );
      $prim=array('AGENTID', 'PNAME');
   }
   else {
      $t1="reselpref";
      $data=array(
         'PVALUE' => $_REQUEST['RECORDID'],
         'RESELID' => $x2->reselid,
         'PNAME' => 'TXC_HORIZONTAL'
      );
      $prim=array('RESELID', 'PNAME');
   }

   if (!ReplaceEx($db, $t1, $data, $prim)) {
      echo __LINE__.$db->ErrorMsg();
   }
   else if ($x2->reselid==0) {
      $x2->Agp['TXC_HORIZONTAL'] =  $_REQUEST['RECORDID'];
   }
}
//--------------------------------------
function open_eafdss()
{
   global $x2, $ar3;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('javascript:goTo(94)', 1, 'Open(r)')
		);
   $x2->make_header($tarray);

   $query="SELECT MAX(LASTUPDATE) FROM taxi_log WHERE AGENTID=? AND MS11=?";
   $data=array($x2->agentid, $_SESSION['MS11']);
   if (($rs=$db->Execute($query,$data))===false) {
      echo __LINE__.$db->ErrosMsg();
      return;
   }
   $row=$rs->FetchRow();
   $rs->Close();
   if ($row===false) {
      echo "No data";
      return;
   }
   $mLU=$row[0];

   $query="SELECT T1.*, T2.L_PROCID, T2.L_NPROC, T2.L_OS, T2.L_ARCH, T2.MACHINETYPE, T2.TXLOCATION FROM taxi_log T1
      LEFT JOIN taxi_eafdss T2 ON (T2.MS11=T1.MS11 AND T2.AGENTID=T1.AGENTID)
      WHERE T1.AGENTID=? AND T1.MS11=? AND T1.LASTUPDATE=?";
   $data=array($x2->agentid, $_SESSION['MS11'], $mLU);
   if (($rs=$db->Execute($query,$data))===false) {
      $c1->error = __LINE__.$db->ErrorMsg();
      return;
   }
   $o1=$rs->FetchNextObject();
   $rs->Close();
   if ($o1===false) {
      echo "No data";
      return;
   }

   $c1=new cTXCERROR();
   $c1->debug=true;
   $c1->parse($o1);
}
//--------------------------------------
function reset_allowSendTaxis()
{
   global $x2;
   $db=&$x2->db;

   $s11 = $_REQUEST['RECORDID'];
   $query = "SELECT ALLOWSENDTAXIS FROM taxi_eafdss WHERE MS11=?";
   $data = array($s11);
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__." ".$db->ErrorMsg();
      return;
   }
   $row = $rs->FetchRow();
   $rs->Close();

   if ($row===false) {
      echo '<div class=error>Master record disappeared!</div>';
      return;
   }

   if ((int)$row[0]==0) {
      $query = "UPDATE taxi_eafdss SET ALLOWSENDTAXIS=1 WHERE MS11=?";
   }
   else {
      $query = "UPDATE taxi_eafdss SET ALLOWSENDTAXIS=NULL WHERE MS11=?";
   }
   $data = array($s11);
   if (!$db->Execute($query, $data))
      echo __LINE__." ".$db->ErrorMsg();
}
//--------------------------------------
function update_aeskey()
{
   global $x2;
   $db=&$x2->db;

   $ar1=explode(';', $_REQUEST['RECORDID']); // s11;aeskey
   if (count($ar1)<2) {
      echo "<h5>Request data not good!</h5>";
      return;
   }

   $query="SELECT COUNT(*) FROM taxi_eafdss WHERE MS11=?";
   $data=array( $ar1[0] );
   if (($rs=$db->Execute($query,$data))===false) {
      echo __LINE__." ".$db->ErrorMsg();
      return;
   }
   $row=$rs->FetchRow();
   $n=$row[0];
   $rs->Close();

   if ($n==0) {
      $query="INSERT INTO taxi_eafdss (MS11, AGENTID, AESKEYHEX) VALUES (?,?,?)";
      $data=array($ar1[0], $x2->agentid, $ar1[1]);
   }
   else {
      $query="UPDATE taxi_eafdss SET AESKEYHEX=? WHERE MS11=?";
      $data=array_reverse($ar1);
   }
   if (!$db->Execute($query,$data)) {
      echo __LINE__." ".$db->ErrorMsg();
   }
}
//--------------------------------------
function update_location()
{
   global $x2;
   $db=&$x2->db;

   $ar_s11=array();
   $query="SELECT DISTINCT(MS11) FROM taxi_log WHERE AGENTID=? AND RECTYPE=3 AND POSAREAID=?";
   $data=array($x2->agentid, (int)$_REQUEST['AREAID']);
   if (($rs=$db->Execute($query,$data))===false) {
      echo __LINE__." ".$db->ErrorMsg();
      return;
   }
   while ($row=$rs->FetchRow()) {
      $ar_s11[]=$row[0];
   }
   $rs->Close();

   $query="UPDATE taxi_eafdss SET TXLOCATION=? WHERE MS11=? AND AGENTID=?";
   foreach ($ar_s11 as $ms11) {
      $data=array($_REQUEST['LOCATION'], ToUtf8($ms11), $x2->agentid);
      if (!$db->Execute($query,$data)) {
         echo __LINE__." ".$db->ErrorMsg();
      }
   }
}
//--------------------------------------
function zoom_pos()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('', 1, 'POS') // function=12
		);
   $x2->make_header($tarray);

   if (!empty($_REQUEST['RECORDID'])) {
      $_SESSION['MS11'] = $_REQUEST['RECORDID'];
   }
   $ms11 = $_SESSION['MS11'];

   $query="SELECT MAX(LASTUPDATE) FROM taxi_log WHERE AGENTID=? AND MS11=?";
   $data=array($x2->agentid, $ms11);
   if (($rs=$db->Execute($query,$data))===false) {
      $c1->error = __LINE__.$db->ErrorMsg();
      return;
   }
   $row=$rs->FetchRow();
   $rs->Close();
   if ($row===false) {
      $c1->error = "No data";
      return;
   }
   $mLU=$row[0];

   $query="SELECT T1.*, T2.ENABLED, T2.L_PROCID, T2.L_NPROC, T2.L_OS, T2.L_ARCH, T2.MACHINETYPE, T2.TXLOCATION FROM taxi_log T1
      LEFT JOIN taxi_eafdss T2 ON (T2.AGENTID=T1.AGENTID AND T2.MS11=T1.MS11)
      WHERE T1.AGENTID=? AND T1.MS11=? AND T1.LASTUPDATE>=?";
   $data=array($x2->agentid, $ms11, $mLU);
   if (($rs=$db->Execute($query,$data))===false) {
      $c1->error = __LINE__.$db->ErrorMsg();
      return;
   }
   $o1=$rs->FetchNextObject();
   $rs->Close();
   if ($o1===false) {
      echo "<h5>Record not found: ".myhtml($ms11)."</h5>";
   }

   $ar1=(array)$o1;
   $row = $db->verify_8( $ar1 );

   $gr1=new cXRID('grid8');

   $gr1->rows=array(
      array('Serial', $row['MS11']),
      array('Alert', $row['ENABLED']?'Enabled':'DISABLED' ),
      array('Κατάστημα (κωδ.)', $row['POSAREAID']),
      array('Κατάστημα (ονομασία)', myhtml($row['TXLOCATION'])),
      array('Ενημέρωση', $row['LASTUPDATE']),
      array('Sender IP', $row['SENDERIP']),
      array('Εκδοση client', $row['CLOGIC']),
      array('Date last Z', $row['LASTZTAKEN']),
      array('Last Z nr.', $row['LASTZNR']),
      array('Memory available', $row['MEM_USG'].' MB'),
      array('Cpu load', $row['CPU_USG'].'%'),
      array('Αποδείξεις', $row['POSRECEIPTS']),
      array('Αλλαγές ΦΠΑ', $row['POSFPACHANGE']),
      array('Αλλαγές επικεφαλίδας', $row['POSHDRCHANGE']),
      array('CMOS λάθη', $row['POSCMOSERR']),
      array('Λάθη επικοινωνίας CF', $row['POSCFERR']),
      array('Αποσυνδέσεις εκτυπωτή', $row['POSPRNDETACH']),
      array('Επεμβάσεις τεχνικού', $row['POSTECHOPEN']),
      array('Αποσυνδέσεις ΔΗΜΕ', $row['POSDIMEDETACH']),
      array('Processor', $row['L_PROCID']),
      array('Total processors', $row['L_NPROC']),
      array('O/S description', $row['L_OS']),
      array('O/S architecture', $row['L_ARCH'])
      );

   array_push($gr1->cols,
      array( 'Πεδίο', 200),
		array( 'Αξία', 300)
   );

   $gr1->play();
?>
<div class=bgButton2>
   <b>
      <button type=button onclick="goTo(18)"><?php echo $row['ENABLED']?'Disable':'Enable'; ?></button>
      <button type=button onclick="getLocation()">Location</button>
      <a href="javascript:goTo(6)">Ιστορικό</a> |
      <a href="javascript:goTo(11)">Ολες οι POS</a> |
      <a href="javascript:goTo(2)">Logfile</a>
   </b>
   <span style="border: 1px solid gray; padding:2px">Last update: <span id=lastupd></span></span>
</div>
<div id=mlocation title="Ονομασία καταστήματος">
   <table>
      <tr>
         <td>Κατάστημα</td>
         <td><b><?php echo $row['POSAREAID']; ?></b></td>
      </tr>
      <tr>
         <td>Ονομασία</td>
         <td><input type=text id=txlocation value="<?php echo myhtml($row['TXLOCATION']); ?>"></td>
      </tr>
      <tr>
         <td></td>
         <td><input type=button value="Update" onclick="setLocation()"></td>
      </tr>
   </table>
</div>

<script>
$(function(){
   $('#mlocation').dialog({autoOpen:false, modal:true, resizable:false});
});
function getLocation()
{
   $('#mlocation').dialog('open');
}
function setLocation()
{
   $('<form/>', {
      'action': location.pathname,
      'method': 'post'
   }).append($('<input>', {
      'type': 'hidden',
      'name': 'FUNCTION',
      'value': 13
   })).append($('<input>', {
      'type': 'hidden',
      'name': 'AREAID',
      'value': <?php echo $row['POSAREAID']; ?>
   })).append($('<input>', {
      'type': 'hidden',
      'name': 'LOCATION',
      'value': $('#txlocation').val()
   })).appendTo('body').submit();
}
</script>
<?php
}
//--------------------------------------
function prepare_machineType()
{
   global $x2;
?>
<div id=matype title="Set Machine Type">
   <table>
      <tr>
         <td>Initial letters for</td>
         <td><input type=TEXT id=LTR value=""></td>
      </tr>
      <tr>
         <td>Machine Type</td>
         <td><select id=selmatype><?php
            prAssocSelect($x2->M_MODELS,0);
            ?></select></td>
      </tr>
      <tr>
         <td></td>
         <td><input type=button value="Update" onclick="setMachineType()"></td>
      </tr>
   </table>
</div>
<?php
}
//--------------------------------------
function wmic_cleandays()
{
   global $x2;
   $db=&$x2->db;

   // $_REQUEST['RECORDID'] constains days to go back
   $dx = (int)$_REQUEST['RECORDID'];
   if ($dx<10) { $dx=10; }
   $d1 = date('Y-m-d', time() - $dx*24*3600);

   $query="DELETE FROM taxi_wmic WHERE AGENTID=? AND LASTUPDATE<?";
   $data=array($x2->agentid, $d1);
   if (!$db->Execute($query, $data)) {
      echo __LINE__." ".$db->ErrorMsg();
   }
   else {
      $nrec=$db->Affected_Rows();
      umessage("Deleted $nrec records");
   }
}
//--------------------------------------
function eafdss_grp_nodes()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('', 1, 'Πληροφορίες (nodes)')
		);
   $x2->make_header($tarray);
?>
<script>
function oclick(stage, row, col)
{
	var ngrp = this.cells(row, 0).getValue();
	goRecord(37, ngrp);
	return false;
}
function goCleanDays()
{
   goRecord(36, $('#cleandays').val() );
}
</script>
<?php
   $txlocation="";
   if (!empty($_REQUEST['RECORDID'])) {
      $query="SELECT TXLOCATION FROM taxi_eafdss WHERE AGENTID=? AND MS11=? ";
      $data=array($x2->agentid, $_REQUEST['RECORDID']);
      if (($rs=$db->Execute($query,$data))===false) {
         echo $db->ErrorMsg();
         return;
      }
      if ($o1=$rs->FetchNextObject()) {
         $txlocation = $db->verify_8($o1->TXLOCATION);
      }
      $rs->Close();

      if (empty($txlocation)) {
         echo "<h5>Location not set for ".$_REQUEST['RECORDID']."</h5>";
         return;
      }

      $_SESSION['TXLOCATION'] =  $txlocation;
   }
   else {
      $txlocation = $_SESSION['TXLOCATION'];
   }

   echo "<div class=bgHeader>".myhtml($txlocation)."</div>";

   $gr1=new cXRID('grid11');

   array_push($gr1->cols,
      array( 'Node', 120)
      );

   $query="SELECT DISTINCT PNODE FROM taxi_wmic WHERE AGENTID=? AND TXLOCATION=?
      /*GROUP BY PNODE, PGROUP*/ ORDER BY PNODE";
   $data=array($x2->agentid, $txlocation);
   if (($rs=$db->Execute($query,$data))===false) {
      echo $db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1=array();

      $row1[]=myhtml($db->verify_8($o1->PNODE));
      //$row1[]=myhtml($db->verify_8($o1->PGROUP));

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

   $gr1->click='oclick';
   $gr1->play();

   echo "<div id=tbar2><small>End of data</small>&nbsp;
      <span style=\"border: 1px solid gray; padding:4px\">Cleanup days long:
      <input type=text id=cleandays style=\"width:60px\"><button type=button class=NavButton
         onclick=\"goCleanDays()\"><img src=\"/img/right1.gif\"></button>
      </span>
      <b><a href=\"javascript:goTo(28)\">Σύγκριση</a></b></div>";
}
//--------------------------------------
function eafdss_node_property_grp()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('javascript:goTo(26)', 1, 'Πληροφορίες (Nodes)'),
      array('javascript:goTo(37)', 1, 'Πληροφορίες (Properties groups)')
		);
   $x2->make_header($tarray);

   // Handle input
   if (!empty($_REQUEST['RECORDID'])) {
      $_SESSION['PNODE'] = $_REQUEST['RECORDID'];
   }

   // Set 'pnode' based on session (or input)
   if (empty($_SESSION['PNODE'])) {
      echo "<h6>Session var PNONE not set!</h6>";
      return;
   }
   else {
      $pnode = $_SESSION['PNODE'];
   }
?>
<script>
function oclick(stage, row, col)
{
	var ngrp = this.cells(row, 0).getValue() + ';' + this.cells(row, 1).getValue();
	goRecord(27, ngrp);
	return false;
}
function goCleanDays()
{
   goRecord(36, $('#cleandays').val() );
}
</script>
<?php
   $txlocation = $_SESSION['TXLOCATION'];

   echo "<div class=bgHeader>".myhtml($txlocation)."</div>";

   $gr1=new cXRID('grid15');

   array_push($gr1->cols,
      array( 'Node', 120),
      array( 'Ομάδα', 180)
      );

   $query="SELECT DISTINCT PGROUP FROM taxi_wmic WHERE AGENTID=? AND TXLOCATION=? AND PNODE=?
      ORDER BY PGROUP";
   $data=array($x2->agentid, $txlocation, $pnode);
   if (($rs=$db->Execute($query,$data))===false) {
      echo $db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1=array();

      $row1[]=myhtml($pnode);
      $row1[]=myhtml($db->verify_8($o1->PGROUP));

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

   $gr1->click='oclick';
   $gr1->play();

   echo "<div id=tbar2><small>End of data</small>&nbsp;
      <span style=\"border: 1px solid gray; padding:4px\">Cleanup days long:
      <input type=text id=cleandays style=\"width:60px\"><button type=button class=NavButton
         onclick=\"goCleanDays()\"><img src=\"/img/right1.gif\"></button>
      </span>
      <b><a href=\"javascript:goTo(28)\">Σύγκριση</a></b></div>";
}
//--------------------------------------
function eafdss_detail_properties()
{
   global $x2;
   $db=&$x2->db;

   list($pnode, $pgroup) = explode(';', $_REQUEST['RECORDID']); //  node, group
   if ($pgroup === '!_TAX_PARAMS')
      return subgroups();

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('javascript:goTo(26)', 1, 'Πληροφορίες (Nodes)'),
      array('javascript:goTo(37)', 1, 'Property groups'),
      array('', 1, 'Ιδιότητες')
		);
   $x2->make_header($tarray);

   echo "<div class=bgHeader>".myhtml($_SESSION['TXLOCATION'])."</div>";

   $gr1=new cXRID('grid12');

   array_push($gr1->cols,
      array( 'Node', 60),
      array( 'Ομάδα', 120),
      array( 'Εγγραφή', 60),
      array( 'Ιδιότητα', 120),
      array( 'Αξία', 120),
      array( 'Ενημέρωση', 120)
      );

   $query="SELECT * FROM taxi_wmic WHERE AGENTID=? AND TXLOCATION=? AND PNODE=? AND PGROUP=?
      ORDER BY RECNR, PNAME";
   $data=array($x2->agentid, $_SESSION['TXLOCATION'], $pnode, $pgroup);
   if (($rs=$db->Execute($query,$data))===false) {
      echo $db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1=array();

      $row1[]=myhtml($db->verify_8($o1->PNODE));
      $row1[]=myhtml($db->verify_8($o1->PGROUP));
      $row1[]=$o1->RECNR;
      $row1[]=myhtml($db->verify_8($o1->PNAME));
      $row1[]=myhtml($db->verify_8($o1->PVALUE));
      $row1[]=sprintf("20%02d-%02d-%02d %02d:%02d:%02d",
         $o1->CREDATE/10000, ($o1->CREDATE%10000)/100, $o1->CREDATE%100,
         $o1->CRETIME/10000, ($o1->CRETIME%10000)/100, $o1->CRETIME%100 );

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

   $gr1->play();

   echo "<div id=tbar2><small>End of data</small>&nbsp;
      <b><a href=\"javascript:goTo(28)\">Σύγκριση</a></b></div>";
}
//--------------------------------------
function tab_disk_free()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('javascript:goTo(44)', 1, 'Disk free(r)')
		);
   $x2->make_header($tarray);
?>
<script>
$(function(){
   $(document).tooltip({
      //track: true,
      content: function(){
         var elem = $(this);
         return '<div style="width:450px; background-color:white;">' + elem.children('div').html() + '</div>';
      }
   });

   theSizer();
   $(window).resize( theSizer );
});
</script>
<?php
   $tropen=false;
   $nrec=0;

   $last_location = false;
   $pgroup='LogicalDisk';
   $mb=1024*1024;
   $openTitle = false;
   $query="SELECT m1.TXLOCATION, m1.PNODE, m1.RECNR, m1.CREDATE, m1.CRETIME,
      m2.PVALUE AS DNAME, m3.PVALUE AS DSIZE, m4.PVALUE AS DFREE
      FROM taxi_wmic m1
      LEFT JOIN taxi_wmic m2 ON (m2.TXLOCATION=m1.TXLOCATION AND m2.PNODE=m1.PNODE AND m2.PGROUP=m1.PGROUP AND m2.RECNR=m1.RECNR AND m2.PNAME='Name')
      LEFT JOIN taxi_wmic m3 ON (m3.TXLOCATION=m1.TXLOCATION AND m3.PNODE=m1.PNODE AND m3.PGROUP=m1.PGROUP AND m3.RECNR=m1.RECNR AND m3.PNAME='Size')
      LEFT JOIN taxi_wmic m4 ON (m4.TXLOCATION=m1.TXLOCATION AND m4.PNODE=m1.PNODE AND m4.PGROUP=m1.PGROUP AND m4.RECNR=m1.RECNR AND m4.PNAME='FreeSpace')
      WHERE m1.AGENTID=? AND m1.PGROUP=? AND m1.PNAME='DriveType' AND m1.PVALUE='3'
      ORDER BY m1.TXLOCATION, m1.PNODE, m1.RECNR";
   $data=array($x2->agentid, $pgroup);
   if (($rs=$db->Execute($query,$data))===false) {
      echo $db->ErrorMsg();
      return;
   }
   echo "<div id=theleft style=\"overflow:scroll\">
      <table>";
   while ($o1=$rs->FetchNextObject()) {
      if ($o1->TXLOCATION !== $last_location) {
         $nrec++;
         if ($last_location !== false) {
            $info .= "</table>";
            echo "<td title=\"i\" style=\"background-color:".($ok?'green':'red')."; color:white;\">
               <div style=\"display:none\">$info</div>".myhtml($db->verify_8($last_location))."</td>";
            if ($nrec%6==1) {
               echo "</tr>";
            }
         }
         if ($nrec%6==1) {
            echo "<tr>";
         }
         $lo = $o1->TXLOCATION;
         $info = "<div style=\"background-color:#c0c0c0;\">".myhtml($db->verify_8($lo))."</div><table class=info>
            <tr>
            <th>Node</th>
            <th>Drive</th>
            <th>Size MB</th>
            <th>Free MB</th>
            <th>Available</th>
            <th>Created</th>
            </tr>";
         $last_location = $o1->TXLOCATION;
         $ok = true;
      }
      else {
         $dsize=$o1->DSIZE/$mb;
         $dfree=$o1->DFREE/$mb;
         $perc = $dsize>0?sprintf("%.02f %%", $dfree/$dsize*100.0):'0 %';

         $created = sprintf("20%02d/%02d/%02d %02d:%02d:%02d",
            $o1->CREDATE/10000, ($o1->CREDATE%10000)/100, $o1->CREDATE%100,
            $o1->CRETIME/10000, ($o1->CRETIME%10000)/100, $o1->CRETIME%100 );

         $info .= "<tr>
            <td>".myhtml($db->verify_8($o1->PNODE))."</td>
            <td>".myhtml($db->verify_8($o1->DNAME))."</td>
            <td>".number_format($dsize)."</td>
            <td>".number_format($dfree)."</td>
            <td>$perc</td>
            <td>$created</td>
            </tr>";

         if ($perc<25 || $dfree<10000) {
            $ok=false;
         }
      }
   }
   $rs->Close();
   if ($last_location !== false) {
      $info .= "</table>";
      echo "<td title=\"i\" style=\"background-color:".($ok?'green':'red')."; color:white;\">
               <div style=\"display:none\">$info</div>".myhtml($db->verify_8($last_location))."</td>";
   }
   echo "</table></div>";

   echo "<div class=bgButton2>
      <button type=button onclick=\"goTo(43)\">List</button>
      Records: ".count($nrec)."</div>";
}
//--------------------------------------
function list_disk_free()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('javascript:goTo(43)', 1, 'Disk free(R)')
		);
   $x2->make_header($tarray);

   $gr1=new cXRID('grid14');

   array_push($gr1->cols,
      array( 'Location', 120),
      array( 'Node', 120),
      array( 'Disk name', 60),
      array( 'Size MB', 100, 'right'),
      array( 'Free MB', 100, 'right'),
      array( 'Available', 100, 'right'),
      array( 'Ενημέρωση', 180)
      );

   $pgroup='LogicalDisk';
   $mb=1024*1024;
   $query="SELECT m1.TXLOCATION, m1.PNODE, m1.RECNR, m1.CREDATE, m1.CRETIME,
      m2.PVALUE AS DNAME, m3.PVALUE AS DSIZE, m4.PVALUE AS DFREE
      FROM taxi_wmic m1
      LEFT JOIN taxi_wmic m2 ON (m2.TXLOCATION=m1.TXLOCATION AND m2.PNODE=m1.PNODE AND m2.PGROUP=m1.PGROUP AND m2.RECNR=m1.RECNR AND m2.PNAME='Name')
      LEFT JOIN taxi_wmic m3 ON (m3.TXLOCATION=m1.TXLOCATION AND m3.PNODE=m1.PNODE AND m3.PGROUP=m1.PGROUP AND m3.RECNR=m1.RECNR AND m3.PNAME='Size')
      LEFT JOIN taxi_wmic m4 ON (m4.TXLOCATION=m1.TXLOCATION AND m4.PNODE=m1.PNODE AND m4.PGROUP=m1.PGROUP AND m4.RECNR=m1.RECNR AND m4.PNAME='FreeSpace')
      WHERE m1.AGENTID=? AND m1.PGROUP=? AND m1.PNAME='DriveType' AND m1.PVALUE='3'
      ORDER BY m1.TXLOCATION, m1.PNODE, m1.RECNR";
   $data=array($x2->agentid, $pgroup);
   if (($rs=$db->Execute($query,$data))===false) {
      echo $db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1=array();

      $row1[] = myhtml($db->verify_8($o1->TXLOCATION));
      $row1[] = myhtml($db->verify_8($o1->PNODE));
      $row1[] = myhtml($db->verify_8($o1->DNAME));
      $row1[] = number_format($o1->DSIZE/$mb);
      $row1[] = number_format($o1->DFREE/$mb);

      $dsize=$o1->DSIZE;
      $dfree=$o1->DFREE;
      $row1[] = $dsize>0?sprintf("%.02f %%", $dfree/$dsize*100.0):'0 %';

      $row1[]=sprintf("20%02d-%02d-%02d %02d:%02d:%02d",
         $o1->CREDATE/10000, ($o1->CREDATE%10000)/100, $o1->CREDATE%100,
         $o1->CRETIME/10000, ($o1->CRETIME%10000)/100, $o1->CRETIME%100 );

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

   $gr1->play();

   echo "<div id=tbar2>
      <button type=button onclick=\"goTo(44)\">Tab</button>
      Records: ".count($gr1->rows)."</div>";
}
//--------------------------------------
function list_tax_properties()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
   $tarray=array(
		array('#', 1, 'TaxSpooler properties')
		);
   $x2->make_header($tarray);

   $gr1 = new cXRID('grid30');
   $gr1->cols = [
      array('Property', 180),
	  array('Node', 100),
      array('Value', 200)
   ];

   $query = "SELECT PNODE, PNAME, PVALUE FROM taxi_wmic WHERE AGENTID=? AND TXLOCATION=? AND PGROUP='!_TAX_PARAMS' ORDER BY PNAME, PNODE";
   $data = array($x2->agentid, $_REQUEST['TXLOCATION']);
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__.' '.$db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1 = [
         myhtml($o1->PNAME),
		 myhtml($o1->PNODE),
         myhtml($o1->PVALUE)
      ];
      $gr1->rows[] = $row1;
   }
   $rs->Close();

   $gr1->play();
   echo '<div id=tbar2><small>End of data</small></div>';
}
//--------------------------------------
function eafdss_do_compare()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('javascript:goTo(28)', 1, 'Σύγκριση - επιλογή'),
      array('javascript:goTo(29)', 1, 'Σύγκριση - αποτέλεσμα(R)')
		);
   $x2->make_header($tarray);

   $gr1=new cXRID('grid13');

   $ar1=array('PGROUP', 'PNAME');
   foreach ($ar1 as $key) {
      if (isset($_REQUEST[$key])) {
         $_SESSION[$key] = $_REQUEST[$key];
      }
   }

   $pgroup=$_SESSION['PGROUP'];
   $pname=$_SESSION['PNAME'];

   echo "<div class=bgHeader>".myhtml($pgroup.' - '.$pname)."</div>";

   array_push($gr1->cols,
      array( 'Location', 120),
      array( 'Node', 120),
      array( 'Εγγραφή', 60),
      array( 'Αξία', 300),
      array( 'Ενημέρωση', 180)
      );

   $query="SELECT TXLOCATION, PNODE, RECNR, PVALUE, CREDATE, CRETIME FROM taxi_wmic
      WHERE AGENTID=? AND PGROUP=? AND PNAME=?
      ORDER BY ";
   if (!empty($_REQUEST['ORDERBY'])) {
      $query .= $_REQUEST['ORDERBY'];
   }
   else {
      $query .= " TXLOCATION, PNODE, RECNR";
   }
   $data=array($x2->agentid, $pgroup, $pname);
   if (($rs=$db->Execute($query,$data))===false) {
      echo $db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1=array();

      $row1[] = myhtml($db->verify_8($o1->TXLOCATION));
      $row1[] = myhtml($db->verify_8($o1->PNODE));
      $row1[] = $o1->RECNR;
      $row1[] = myhtml($db->verify_8($o1->PVALUE));
      $row1[]=sprintf("20%02d-%02d-%02d %02d:%02d:%02d",
         $o1->CREDATE/10000, ($o1->CREDATE%10000)/100, $o1->CREDATE%100,
         $o1->CRETIME/10000, ($o1->CRETIME%10000)/100, $o1->CRETIME%100 );

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

   $gr1->play();

   echo "<div id=tbar2>
      <button type=button onclick=\"goExport(29)\">Export (Excel)</button>
      <button type=button onclick=\"goTo(42)\">Last update</button>
      Records: ".count($gr1->rows)."</div>";
}
//--------------------------------------
function wmic_list_updates()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('javascript:goTo(50)', 1, 'Ενημέρωση πληροφοριών(R)')
		);
   $x2->make_header($tarray);
?>
<script>
function lastOfGroup(grp)
{
   var url='/ishop/ishop_taxi.php?FUNCTION=50&PARAM50_1='+encodeURIComponent(grp);
   location.href=url;
}
</script>
<?php

   if (isset($_REQUEST['PARAM50_1']))
      $_SESSION['PARAM50_1'] = $_REQUEST['PARAM50_1'];

   if (empty($_SESSION['PARAM50_1']))
      $_SESSION['PARAM50_1'] = '/_FILE_VERSION';

   $gr1=new cXRID('grid18');

   $gr1->cols = array(
      array('Group', 120),
      array('Date', 140),
      array('Location', 250),
      array('Node', 120)
   );

   $query = "SELECT TXLOCATION, PNODE, MAX(LASTUPDATE) F1 FROM taxi_wmic WHERE AGENTID = ? ";
   $data=array($x2->agentid);
   $c1 = substr($_SESSION['PARAM50_1'], 0, 1);
   if ($c1 === '!' || $c1 === '/') {
      $query .= " AND PGROUP=? ";
      $data[] = $_SESSION['PARAM50_1'];
   }
   else {
      $query .= " AND PGROUP NOT LIKE '!%' AND PGROUP NOT LIKE '/%' ";
   }
   $query .= " GROUP BY TXLOCATION, PNODE ".
	     " ORDER BY MAX(LASTUPDATE) DESC, TXLOCATION, PNODE";

   if (($rs=$db->Execute($query,$data))===false) {
      echo $db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1=array();

      $row1[]=myhtml($_SESSION['PARAM50_1']);
      $row1[]=myhtml($db->verify_8($o1->F1));
      $row1[]=myhtml($db->verify_8($o1->TXLOCATION));
      $row1[]=myhtml($db->verify_8($o1->PNODE));

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

   $gr1->play();

   echo "<div id=tbar2><small>End of data</small>&nbsp
      Group: <b>;
      <a href=\"javascript:lastOfGroup('!_NET_FRAMEWORK')\">!_NET_FRAMEWORK</a> |
      <a href=\"javascript:lastOfGroup('!_TAX_FILEINFO')\">!_TAX_FILEINFO</a> |
      <a href=\"javascript:lastOfGroup('!_TAX_PARAMS')\">!_TAX_PARAMS</a> |
      <a href=\"javascript:lastOfGroup('/_FILE_VERSION')\">/_FILE_VERSION</a> |
      <a href=\"javascript:lastOfGroup('wmic')\">wmic</a>
      </b></div>";
}
//--------------------------------------
function eafdss_ask_compare()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('javascript:goTo(28)', 1, 'Σύγκριση(R)')
		);
   $x2->make_header($tarray);

?>
<script>
$(function() {
   $('.pgroup').next('div').hide();
   $('.pgroup').css('cursor', 'pointer').click(function() {
      var n1 = $(this).next('div');
      if (n1.html().trim() === '') {
         var pgroup = $(this).text();
         var url = '/ishop/ishop_taxout.php?FUNCTION=30&PGROUP=' + encodeURIComponent(pgroup);
         $.getJSON(url, function(oret){
            var html = '';
            if (oret.error) {
               html = oret.error;
            }
            else {
               var html = '<ul>';
               for (var i in oret.data)
               {
                  html += '<li class=pname>' + $('<span>').text(oret.data[i]).html() + '</li>';
               }
               html += '</ul>';
            }
            n1.html(html);
         } );
      }
      n1.toggle();
   });

   $(document).on('click', '.pname', function(){
      var pname = $(this).text();
      var pgroup = $(this).parents('li').children('span').text();
      var url='/ishop/ishop_taxi.php?FUNCTION=29&PNAME='+encodeURIComponent($(this).text())+
         '&PGROUP='+encodeURIComponent($(this).parents('li').children('span').text());
      location.href = url;
   } );
} );
</script>
<?php
   $oldgroup=false;
   /*
   $query="SELECT DISTINCT PGROUP, PNAME FROM taxi_wmic WHERE AGENTID=? AND RECNR>0 ORDER BY PGROUP, PNAME";
   */
   // Do not use any fields in 'where' close that do not belong to a key
   $query="SELECT DISTINCT PGROUP FROM taxi_wmic WHERE AGENTID=? ORDER BY PGROUP";
   $data=array($x2->agentid);
   if (($rs=$db->Execute($query,$data))===false) {
      echo $db->ErrorMsg();
      return;
   }
   $openLi=false;
   $i=1;
   echo "<ul type=square>";
   while ($o1=$rs->FetchNextObject()) {
      $pgroup = $db->verify_8($o1->PGROUP);
      /*
      $pname = $db->verify_8($o1->PNAME);

      if ($pgroup!==$oldgroup) {
         // close old group (if exists)
         if ($openLi) {
            echo "</ul></div></li>";
         }
         // open new group
         /*
         echo "<li><span class=pgroup data-id=$i>".myhtml($pgroup)."</span>".
            "<div id=pnames$i><ul type=disc>";
         */

         echo "<li><span class=pgroup data-id=$i>".myhtml($pgroup)."</span>".
            "<div id=pnames$i></div></li>";
         $openLi=true;
         $i++;
      /*
         $oldgroup = $pgroup;
      }


      echo "<li>".myhtml($pname)."</li>";
      */
   }
   $rs->Close();

   // close open group (if exists)
   /*
   if ($openLi) {
      echo "</ul></div></li>";
   }
   */

   echo "</ul>";

   echo '<hr><b><a href="javascript:goTo(50)">Updates</a></b>';
}
//--------------------------------------
function monitor_eafdss()
{
   global $x2, $ar3, $LIMITS;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('', 1, 'ΕAΦΔΣΣ') // function=4
		);
   $x2->make_header($tarray);

   if (!empty($_REQUEST['RECORDID'])) {
      $_SESSION['MS11'] = $_REQUEST['RECORDID'];
   }

   // BODY
   $info=array(
      array(0, 0, 'ΕΑΦΔΣΣ'), // level, image, string
      array(1, 1, 'Port'),

      array(2, 2, 'Identity'),
      array(3, 3, 'Vendor'),
      array(3, 3, 'Model'),
      array(3, 4, 'Version'),

      array(2, 4, 'String Id'),
   );

   $enabled=false;
   $query="SELECT ENABLED FROM taxi_eafdss WHERE MS11=? AND AGENTID=?";
   $data=array( $_SESSION['MS11'], $x2->agentid );
   if (($rs=$db->Execute($query,$data))===false) {
      echo $db->ErrorMsg();
      return;
   }
   $row=$rs->FetchRow();
   $rs->Close();
   if ($row!==false) {
      $enabled=(bool)$row[0];
   }
   else {
      $query="INSERT INTO taxi_eafdss (MS11, AGENTID) VALUES(?,?)";
      $data=array( $_SESSION['MS11'], $x2->agentid );
      if (!$db->Execute($query,$data)) {
         echo $db->ErrorMsg();
         return;
      }
   }
?>
<style>
span.troot span.dynatree-icon    { background-image: url("/img/folder_all.png"); }
.dev_ok { list-style-image: url("/img/device_ok.png"); }
.folder { list-style-image: url("/img/folder2_16x16.png"); }
li.report { list-style-image: url("/img/report16x16.png"); }
td.report { width: 1em; background-image: url("/img/report16x16.png"); background-repeat: no-repeat; }
.ok_box {  width: 1em; background-image: url("/img/ok_box.png"); background-repeat: no-repeat; }
.attention {  width: 1em; background-image: url("/img/attention.png"); background-repeat: no-repeat; }
.cancel_box {  width: 1em; background-image: url("/img/cancel_box.png"); background-repeat: no-repeat; }
.chkbox_red {  width: 1em; background-image: url("/img/checkbox_red.png"); background-repeat: no-repeat; }
.cancelbox_red {  width: 1em; background-image: url("/img/cancelbox_red.png"); background-repeat: no-repeat; }
.device_err {  width: 1em; background-image: url("/img/device_err.png"); background-repeat: no-repeat; }
.folder_attention {  width: 1em; background-image: url("/img/folder_attention.png"); background-repeat: no-repeat; }
.infoT td { padding: 0 4px 0 4px; }
</style>

<div id=msgdiv class=error style="padding:4px; display:none"></div>

<?php prepare_machineType(); ?>

<div id=theleft style="overflow:scroll">
<ul>
   <li class="dev_ok"><span><b><?php echo $_SESSION['MS11']; ?></b> <span id=EAFDSSPORT></span>
      <ul>

      <li class="folder">Global
         <table class="infoT">
         <tr>
            <td class="report"></td>
            <td>Machine Type:</td>
            <td id=MACHINETYPE></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>TaxSpooler version:</td>
            <td id=TXVERSION></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Location:</td>
            <td id=TXLOCATION></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Ομάδα:</td>
            <td id=MACHINEGROUP></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Sender IP:</td>
            <td id=SENDERIP></td>
         </tr>
         <tr>
            <td class="report" id=lastupdate></td>
            <td>Last query:</td>
            <td id=LASTUPDATE></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Query type:</td>
            <td id=RECTYPE></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Alert:</td>
            <td id=ALERT><?php echo $enabled?'Enabled':'DISABLED'; ?></td>
         </tr>
         </table>
      </li>

      <li class="folder">Operating System
         <table class=infoT>
         <tr>
            <td class="report"></td>
            <td>O/S description:</td>
            <td id=L_OS></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>O/S architecture:</td>
            <td id=L_ARCH></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Processor:</td>
            <td id=L_PROCID></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Total processors:</td>
            <td id=L_NPROC></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Memory available:</td>
            <td id=MEM_USG></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Cpu load:</td>
            <td id=CPU_USG></td>
         </tr>
         </table>
      </li>

      <li class="folder">Identity
         <table class=infoT>
         <tr>
            <td class="report"></td>
            <td>Vendor:</td>
            <td id=MVENDOR></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Model:</td>
            <td id=MMODEL></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Version:</td>
            <td id=MVERSION></td>
         </tr>
         </table>
      </tr>

      <li class="folder">String Id
         <table>
         <tr>
            <td id=stringID class="report"></td>
         </tr>
         </table>
      </tr>

      <li class="folder">Data
         <table>
         <tr>
            <td class="report"></td>
            <td>Date open:</td>
            <td id=OPENTIME></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Date 1st sign:</td>
            <td id=FIRSTSIGNINZ></td>
         </tr>
         <tr>
            <td class="report" id=c_timesince1></td>
            <td>Time since 1st sign:</td>
            <td id=C_TIMESINCE1></td>
         </tr>
         <tr>
            <td class="report" id=lastztaken></td>
            <td>Date last Z:</td>
            <td id=LASTZTAKEN></td>
         </tr>
         <tr>
            <td class="report" id=c_timesincelz></td>
            <td>Time since last Z:</td>
            <td id=C_TIMESINCELZ></td>
         </tr>
         <tr>
            <td class="report" id=lastznr></td>
            <td>Max Z (current or next):</td>
            <td id=LASTZNR></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Progressive no:</td>
            <td id=MPROGRESSIVE></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Next Daily no:</td>
            <td id=MDAILY></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Time since last comm.:</td>
            <td id=MTIMEPASSED></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Last o.k. operation:</td>
            <td id=MLASTOK></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Last error operation:</td>
            <td id=MLASTFAIL></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Last error code:</td>
            <td id=MLASTERROR></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>First S.TXT ever:</td>
            <td id=MFISRTSEVER></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>First not sent S.TXT:</td>
            <td id=MFIRSTSNOTSENT></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>Not sent creation:</td>
            <td id=MNOTSENTCRE></td>
         </tr>
         <tr>
            <td class="report"></td>
            <td>TAXIS error returned:</td>
            <td id=MTAXISRETERR></td>
         </tr>
         </table>
      </li>

      <li class="folder">Hardware Status
         <table class=infoT><?php
         for ($i=0;$i<8;$i++) {
            echo "<tr>
               <td class=\"report\" id=st$i></td>
               <td>".myhtml( $ar3[$i][1] )."</td>
               </tr>\n";
         }
         ?></table>
      </li>

      <li class="folder">Application Status
         <table class=infoT><?php
         for ($i=8;$i<16;$i++) {
            echo "<tr>
               <td class=\"report\" id=st$i></td>
               <td>".myhtml( $ar3[$i][1] )."</td>
               </tr>\n";
         }
         ?></table>
      </li>

      </ul>
   </li>
</ul>
</div>

<div class=bgButton2>
   <b>
      <button type=button onclick="goTo(8)"><?php echo $enabled?'Disable':'Enable'; ?></button>
      <button type=button onclick="getMachineType()">Machine Type</button>
      <a href="javascript:goTo(9)">Alerts</a> |
      <a href="javascript:goTo(6)">Ιστορικό</a> |
      <a href="javascript:goTo(5)">Ολες οι ΕΑΦΔΣΣ</a> |
      <a href="javascript:goTo(2)">Logfile</a>
   </b>
   <span style="border: 1px solid gray; padding:2px">Last update: <span id=lastupd></span></span>
</div>
<script>
var dyntree;

$(function(){
   $('#matype').dialog({autoOpen:false, modal:true, resizable:false});
   theSizer();
   $(window).resize( theSizer );

   EAquery();
});

function getMachineType()
{
   $('#matype').dialog('open');
}

function setMachineType()
{
   var pdata={ 'FUNCTION':3, 'LTR':$('#LTR').val(), 'MACHINETYPE':$('#selmatype').val() };
   $('#matype').dialog('close');
   $.ajax('/ishop/ishop_jsontx.php', {
      error: function (jqXHR, textStatus, errorThrown){
         if (jqXHR) {
            if (jqXHR.responseText.length>0) {
               $('#msgdiv').html( jqXHR.responseText );
            }
            else {
               $('#msgdiv').html( 'Error '+jqXHR.status );
            }
         }
         else {
            $('#msgdiv').html( textStatus );
         }
         $('#msgdiv').show();
      },

      success: function(ro){
         if (ro[0].error.length>0) {
            $('#msgdiv').html( ro[0].error );
            $('#msgdiv').show();
         }
         else {
            $('#msgdiv').hide();
         }
      },

      data: pdata,

      dataType: 'json'
      }
   );
}

var ar31 = [ <?php
   $n=count($ar3);
   for ($i=0;$i<$n;$i++) {
      if ($i>0) { echo ","; }
      echo $ar3[$i][0];
   }
?> ];

var classes = [
      'report',     'dev_ok',    'folder',     'report',            'ok_box',
      'cancel_box', 'attention', 'chkbox_red', 'cancelbox_red.png',
      'device_err.png',
      'folder_attention.png' ];

var limits=[0, <?php echo implode(', ', $LIMITS); ?>];

var machinetypes=[<?php ?>];

function timeLengthStr(dT) // milliseconds
{
   var s1='';
   var sec=Math.floor(dT/1000);

   var days=Math.floor(sec/3600/24);
   if (days>0) {
      s1=days+'d';
   }

   var left = sec - days*3600*24;
   var hours=Math.floor(left/3600);
   if (hours>0 || s1.length>0) {
      if (s1.length>0) {
         s1 += ' ';
      }
      s1 += hours+'h';
   }

   left -= hours*3600;
   var mins=Math.floor(left/60);
   if (mins>0 || s1.length>0) {
      if (s1.length>0) {
         s1 += ' ';
      }
      s1 += mins+'m';
   }

   if (s1.length>0) {
      s1 += ' ';
   }
   s1 += (left%60)+'s';

   return s1;
}
function EAquery()
{
   var d1, dT, cname, insi, node, reg1, rex;
   var one_day = 24*3600*1000;
   var dnow=new Date();
   $('#lastupd').text( dnow.toLocaleTimeString() );

   $.ajax('/ishop/ishop_jsontx.php?FUNCTION=2', {
      error: function (jqXHR, textStatus, errorThrown){
         if (jqXHR) {
            if (jqXHR.responseText.length>0) {
               $('#msgdiv').html( 'AJAX error: '+jqXHR.responseText );
            }
            else {
               $('#msgdiv').html( 'AJAX error: '+jqXHR.status );
            }
         }
         else {
            $('#msgdiv').html( 'AJAX error: '+textStatus );
         }
         $('#msgdiv').show();

         window.setTimeout(EAquery,3000);
      },

      success: function(ro){
         if (ro[0].error.length>0) {
            $('#msgdiv').html( ro[0].error );
            $('#msgdiv').show();
         }
         else {
            $('#msgdiv').hide();
            if (ro[0].data.length>0) {
               var rec=ro[0].data[0];
               var s1, s2;

               if (rec.EAFDSSPORT.length>0) {
                  s1 = '('+rec.EAFDSSPORT+')';
               }
               else {
                  s1 = '(Unknown port)';
               }
               $('#EAFDSSPORT').text(s1);

               var mtype=parseInt(rec.MACHINETYPE);
               if (isNaN(mtype)) {
                  mtype=0;
               }
               switch (mtype)
               {
               case 1:
                  s1='TaxSpooler (DM100/1000)';
                  s2=rec.TXVERSION;
                  break;
               case 2:
                  s1='FASY';
                  s2='';
                  break;
               case 3:
                  s1='POS';
                  s2='';
                  break;
               default:
                  s1='Unknown #'+mtype;
                  s2='';
                  break;
               }
               $('#MACHINETYPE').text(s1);
               $('#TXVERSION').text(s2);

               $('#MACHINEGROUP').text( rec.MACHINEGROUP+'# '+rec.MENUDES );

               $('#TXLOCATION').text(rec.TXLOCATION);
               $('#SENDERIP').text(rec.SENDERIP);
               $('#RECTYPE').text(rec.RECTYPE==1?'online':'disk');

               $('#L_OS').text( rec.L_OS );
               $('#L_ARCH').text( rec.L_ARCH );
               $('#L_PROCID').text( rec.L_PROCID );
               $('#L_NPROC').text( rec.L_NPROC );
               $('#MEM_USG').text( rec.MEM_USG.length>0 ? (rec.MEM_USG + ' MB') : '' );
               $('#CPU_USG').text( rec.CPU_USG.length>0 ? (rec.CPU_USG + '%') : '' );

               $('#MVENDOR').text(rec.MVENDOR);
               $('#MMODEL').text(rec.MMODEL);
               $('#MVERSION').text(rec.MVERSION);
               $('#OPENTIME').text(GrDateTime(rec.OPENTIME));

               $('#FIRSTSIGNINZ').text( rec.MDAILY > 1 ? GrDateHour(rec.FIRSTSIGNINZ) : '' );

               $('#MPROGRESSIVE').text(rec.MPROGRESSIVE);
               $('#MDAILY').text(rec.MDAILY);

               if (rec.LASTZNR >= limits[rec.MACHINETYPE])
               {
                  $('#lastznr').removeClass().addClass('attention');
               }
               else
               {
                  $('#lastznr').removeClass().addClass('report');
               }
               $('#LASTZNR').html( rec.LASTZNR + (rec.MDAILY > 1 ? ' <b>OPEN</b>':' (closed)') );

               $('#MLASTOK').text(GrDateTime(rec.MLASTOK));
               $('#MLASTFAIL').text(GrDateTime(rec.MLASTFAIL));
               $('#MLASTERROR').text(rec.MLASTERROR);

               // 'Last Update' rule
               //node = dyntree.dynatree('getTree').getNodeByKey('c4');
               cname='report';
               rex=/\-| |\:/;
               ar1=rec.LASTUPDATE.replace(/[T,Z]/g, ' ').split(rex);
               d1=new Date(ar1[0], parseInt(ar1[1])-1, ar1[2], ar1[3], ar1[4], ar1[5] );
               dT = dnow.getTime() - d1.getTime(); // milliseconds
               if (dT>3600000) {
                  cname='attention';
               }
               $('#lastupdate').removeClass().addClass(cname);
               var s1=GrDateTime(rec.LASTUPDATE)+' ('+timeLengthStr(dT)+' passed)';
               $('#LASTUPDATE').text( s1 );

               // once we have calculated dT, we can also calculate and display
               if (rec.MTIMEPASSED.length>0) {
                  $('#MTIMEPASSED').text( timeLengthStr(rec.MTIMEPASSED*1000 + dT) );
               }
               else {
                  $('#MTIMEPASSED').text('');
               }

               // Update calculated fields (#1)
               //node = dyntree.dynatree('getTree').getNodeByKey('c1');
               cname='report';
               insi='';
               if (rec.FIRSTSIGNINZ.length>0 && rec.FIRSTSIGNINZ.substr(0,2)!='00' && rec.MDAILY>1) {
                  rex=/\-| |\:/;
                  ar1=rec.FIRSTSIGNINZ.replace(/[T,Z]/g, ' ').split(rex);
                  d1=new Date(ar1[0], parseInt(ar1[1])-1, ar1[2], ar1[3], ar1[4], ar1[5] );
                  dT = dnow.getTime() - d1.getTime();
                  insi=timeLengthStr(dT);
                  if (dT > one_day) {
                     cname='attention';
                  }
               }
               $('#c_timesince1').removeClass().addClass(cname);
               $('#C_TIMESINCE1').text(insi);

               // Check date LASTZTAKEN
               if (rec.LASTZTAKEN.length==0 && rec.LASTZNR>1) {
                  cname='attention';
                  insi='(missing)';
               }
               else {
                  cname='report';
                  insi=GrDateHour(rec.LASTZTAKEN);
               }
               $('#lastztaken').removeClass().addClass(cname);
               $('#LASTZTAKEN').text(insi);

               // Update calculated fields (#2)
               //node = dyntree.dynatree('getTree').getNodeByKey('c2');
               cname='report';
               insi='';
               if (rec.LASTZTAKEN.length>0 && rec.LASTZTAKEN.substr(0,2)!='00') {
                  rex=/\-| |\:/;
                  ar1=rec.LASTZTAKEN.replace(/[T,Z]/g, ' ').split(rex);
                  d1=new Date(ar1[0], parseInt(ar1[1])-1, ar1[2], ar1[3], ar1[4], ar1[5] );
                  dT = dnow.getTime() - d1.getTime();
                  insi=timeLengthStr(dT);
                  if (dT > one_day) {
                     cname='attention';
                  }
               }
               $('#c_timesincelz').removeClass().addClass(cname);
               $('#C_TIMESINCELZ').text(insi);

               if (rec.MLASTHARDST.length>0) {
                  var stx = parseInt(rec.MLASTHARDST);
                  for (i=0;i<8;i++) {
                     key='#st'+i;
                     var x = stx & (1<<i);
                     var ec = ar31[i];
                     var ImageIndex = x?(ec==1?6:(ec==2?7:4)):(ec==3?8:5);
                     cname=classes[ImageIndex];
                     $(key).removeClass().addClass(cname);
                  }
               }
               else {
                  cname='report';
                  for (i=0;i<8;i++) {
                     key='#st'+i;
                     $(key).removeClass().addClass(cname);
                  }
               }

               if (rec.MLASTAPPST.length>0) {
                  var stx = parseInt(rec.MLASTAPPST);
                  for (i=0;i<8;i++) {
                     key='#st'+(i+8);
                     var x = stx & (1<<i);
                     var ec = ar31[i+8];
                     var ImageIndex = x?(ec==1?6:(ec==2?7:4)):(ec==3?8:5);
                     cname=classes[ImageIndex];
                     $(key).removeClass().addClass(cname);
                  }
               }
               else {
                  cname='report';
                  for (i=8;i<16;i++) {
                     key='#st'+i;
                     $(key).removeClass().addClass(cname);
                  }
               }
            }
         }

         window.setTimeout(EAquery,3000);
      },

      dataType: 'json'
   } );
}
</script>
<?php
}
//--------------------------------------
function prepare_toggle()
{
   $_SESSION['MS11'] = $_REQUEST['RECORDID'];
}
//--------------------------------------
function toggle_enable_eafdss()
{
   global $x2;
   $db=&$x2->db;

   $ms11 = $_SESSION['MS11'];

   $query="SELECT ENABLED FROM taxi_eafdss WHERE MS11=?";
   $data=array( $ms11 );
   if (($rs=$db->Execute($query,$data))===false) {
      echo $db->ErrorMsg();
      return;
   }
   $row=$rs->FetchRow();
   $rs->Close();

   if ($row===false) {
      $fi=false;
      $enabled=0; // new
   }
   else {
      $fi=true;
      $enabled=$row[0];
   }

   //
   // limit = MAX_COUNT_AB
   //
   if ($enabled != 1) {
      // Will enable, check limit of MAX_COUNT_AB
      $query="SELECT COUNT(*) FROM taxi_eafdss WHERE AGENTID=? AND ENABLED>0";
      $data=array($x2->agentid);
      if (($rs=$db->Execute($query,$data))===false) {
         echo $db->ErrorMsg();
         return;
      }
      $row=$rs->FetchRow();
      $rs->Close();
      if ($row[0]>=MAX_COUNT_AB) {
         umessage("Exceeded license number!");
         return;
      }
   }

   if ($fi) { // found, toggle
      $en2 = ($enabled==1 ? 2 : 1);
      $query="UPDATE taxi_eafdss SET ENABLED=? WHERE MS11=? AND AGENTID=?";
      $data=array($en2, $ms11, $x2->agentid);
   }
   else {
      // if not found, always enable
      $query="INSERT INTO taxi_eafdss (MS11, AGENTID, ENABLED) VALUES(?,?,1)";
      $data=array($ms11, $x2->agentid);
   }
   if (!$db->Execute($query,$data))
      echo $db->ErrorMsg();
}
//--------------------------------------
function upd_machine_group()
{
   global $x2;
   $db=&$x2->db;

   $ar1=explode(';', $_REQUEST['RECORDID'], 2);
   if (count($ar1)<2) {
      return;
   }

   $query="UPDATE taxi_eafdss SET MACHINEGROUP=? WHERE MS11 LIKE ? AND AGENTID=?";
   $data=array( (int)$ar1[0], $ar1[1].'%', $x2->agentid );
   if (!$db->Execute($query,$data)) {
      echo __LINE__.' '.$db->ErrorMsg();
   }
}
//--------------------------------------
function reset_grpFilter()
{
   $ar1 = explode(';', $_REQUEST['RECORDID']);
   $_SESSION['STAFILTER'] = (int)$ar1[0];
   $_SESSION['GRPFILTER'] = (int)$ar1[1];
}
//--------------------------------------
function draw_popup_FHM()
{
   $selx2=array(
      array(5, '/img/go_next.gif', 'Στοιχεία ΕΑΦΔΣΣ'),
      array(11, '/img/go_next.gif', 'Στοιχεία POS'),
      array(24, '/img/go_next.gif', 'TaxSpooler version'),
      array(25, '/img/go_next.gif', 'O/S'),
      array(28, '/img/go_next.gif', 'Σύγκριση')
   );
   draw_popup($selx2, false, 'popmenuFHM');
}
//-------------------------------------
function prepare_curr_data()
{
   global $x2;
   $db=&$x2->db;
   $eafdss=array();

   if (isset($_SESSION['STAFILTER'])) {
      $StaFilter=(int)$_SESSION['STAFILTER'];
   }
   else {
      $StaFilter=1;
   }
   $GrpFilter=(int)@$_SESSION['GRPFILTER'];

   $query="SELECT T1.MS11, T2.ENABLED, T2.MACHINEGROUP
      FROM taxi_log T1
      LEFT JOIN taxi_eafdss T2 ON (T2.MS11=T1.MS11)
      INNER JOIN (
	      SELECT MS11, MAX(LASTUPDATE) LUPD FROM taxi_log WHERE AGENTID=? AND RECTYPE<>3
		   GROUP BY MS11
      ) J1
      ON T1.MS11=J1.MS11 AND T1.LASTUPDATE>=J1.LUPD
      WHERE T1.AGENTID=?
      ORDER BY TXLOCATION, MS11";
   $data=array($x2->agentid, $x2->agentid);
   if (($rs=$db->Execute($query,$data))===false) {
      error_log(__FILE__.':'.__LINE__.' '.$db->ErrorMsg() );
      return false;
   }
   while ($o1=$rs->FetchNextObject()) {
         if (($GrpFilter<0 && $o1->MACHINEGROUP!=0) ||
            ($GrpFilter>0 && $o1->MACHINEGROUP!=0 && $o1->MACHINEGROUP!=$GrpFilter))
         {
            continue;
         }

         if (($StaFilter==1 && $o1->ENABLED==2) || ($StaFilter==2 && $o1->ENABLED!=2))
         {
            continue;
         }

         $eafdss[]=$o1->MS11;
   }
   $rs->Close();

   return $eafdss;
}
//-------------------------------------
function monitor_curr_data()
{
   global $x2, $ar3;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('', 1, 'TaxCenter')
		);
   $x2->make_header($tarray);

   // BODY
   $StaFilter=(int)@$_SESSION['STAFILTER']; // state
   $GrpFilter=(int)@$_SESSION['GRPFILTER']; // group

   $magroup=array();
   $grpFilterAr=array(0=>'All');
   $query="SELECT MENUID, MENUDES FROM menurep
      WHERE AGENTID=? AND MENUTYPE=22
      ORDER BY MENUDES";
   $data=array($x2->agentid);
   if (($rs=$db->Execute($query,$data))===false) {
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $menudes=$db->verify_8($o1->MENUDES); // $db->verify_8() must be called only once for a single field
      $magroup[ $o1->MENUID ] = $menudes;
      $grpFilterAr[ $o1->MENUID ] = $menudes;
   }
   $rs->Close();
   $grpFilterAr['-1'] = '(Unknown)';

   $horz=0;
   if ($x2->reselid==0) {
      $horz = (int)@$x2->Agp['TXC_HORIZONTAL'];
   }
   else {
      $query="SELECT PVALUE FROM reselpref WHERE RESELID=? AND PNAME=?";
      $data=array($x2->reselid, 'TXC_HORIZONTAL');
      if (($rs=$db->Execute($query,$data))===false) {
         echo __LINE__.$db->ErrorMsg();
      }
      else {
         if ($row=$rs->FetchRow()) {
            $horz = $row[0];
         }
         $rs->Close();
      }
   }
   if ($horz<1) {
      $horz=1;
   }
?>
<style>
.mtable { width:100%; text-align:center; }
.mtable td { cursor:pointer; }
.okEn { background-color: green; color: white; }
.errEn { background-color: red; color: white; }
.okUndef { background-color: #0000C0; color: #00FF00; } /* undefined machine type */
.errUndef { background-color: #0000C0; color: red; }
.okDis { background-color: black; color: #00FF00; }
.errDis { background-color: black; color: red; }
.okNew { background-color: rgb(0,204,255); color: green; } /* ciel */
.errNew { background-color: rgb(0,204,255); color: red; }  /* ciel */
</style>
<div id=msgdiv class=error style="padding:4px; display:none"></div>

<div id=theleft style="height:100px; overflow:auto">
   <table id=masterT class=mtable><?php
      $eafdss = prepare_curr_data();
      if ($eafdss!==false) {
         $tdn=0;
         echo "<tr>";
         foreach ($eafdss as $m1) {
            if (($tdn%$horz)==0) {
               echo "</tr><tr>";
            }
            echo "<td id=td_$m1>";
            $tdn++;
         }
         echo "</tr>";
      }
   ?></table>
</div>

<div class=bgButton2>
   <button type=button onclick="goResize()">Resize</button>
   <span style="border: 1px solid gray; padding:4px">Filter:
   <select id=stafilter onchange="resetGrpFilter()" title="State"><?php
      $ar1=array(0=>'All', 1=>'Enabled', 2=>'Disabled');
      prAssocSelect($ar1, $StaFilter);
   ?></select>
   <select id=grpfilter onchange="resetGrpFilter()" title="Group"><?php
      prAssocSelect($grpFilterAr, $GrpFilter);
   ?></select>
   </span>&nbsp;
   <b>
      <button type=button onclick="show_popup('popmenuFHM')">ΕΑΦΔΣΣ/ POS</button>
      <button type=button onclick="goTo(44)">Disk free</button>
      <a href="javascript:goTo(20)">Στοιχεία S.TXT</a> |
      <a href="<?php echo $_SERVER['PHP_SELF']; ?>?FUNCTION=2&RSPAGE=1">Logfile</a> |
      <a href="javascript:goTo(10)">Alerts (all)</a>
   </b>
   <span style="border: 1px solid gray; padding:2px">Last update: <span id=lastupd></span></span>
</div>

<?php
   // Popup must be drawn last in page in order to have a proper z-index
   $selx=array(
      array(4, '/img/open_folder.gif', 'Ανοιγμα' ),
      array(904, '/img/ok_box.png', 'Enable' ),
      array(905, '/img/cancel_box.png', 'Disable' ),
      array(17, 'img/filter.png', 'Ομάδα ΕΑΦΔΣΣ' ),
      array(26, '/img/properties16x16.png', 'Πληροφορίες')
   );
	draw_popup($selx);

   draw_popup_FHM();
?>

<div id="szdlg" title="Display frame" style="display:none">
<table>
<tr>
   <td>Cells per row</td>
   <td><select id="Horizontal"><?php
      prSelect(1, 30, $horz);
      ?></select></td>
</tr>
</table>
</div>

<div id="eafdssgrp" title="Ομάδα ΕΑΦΔΣΣ" style="display:none">
<table>
<tr>
   <td>ΕΑΦΔΣΣ</td>
   <td id=eafdss style="font-weight:bold"></td>
</tr>
<tr>
   <td>Ομάδα</td>
   <td><select id="seEafdssGrp"><?php
      prAssocSelect($magroup, $GrpFilter);
      ?></select></td>
</tr>
</table>
</div>

<script>
var horz=<?php echo $horz; ?>;
var gS11;

$(function(){
   theSizer();
   $(window).resize( theSizer );
   $('#matype').dialog({autoOpen:false, modal:true, resizable:false});
   $('#masterT').on('click', 'td', function(){
      gS11 = $(this).attr('id').substr(3);
      show_popup('popmenu');
   } );
   TCquery();
});

function resetGrpFilter()
{
   var v = $('#stafilter').val() + ';' + $('#grpfilter').val();
   goRecord(15, v);
}

function setMachineGroup()
{
   $('#eafdssgrp').dialog( { modal:true, resizable:false, buttons:{
         'Set': function() {
            goRecord(17, $('#seEafdssGrp').val() + ';' +gS11 );
         },
         'Cancel': function() {
            $(this).dialog('close');
         }
      } } ).dialog('open');

   $('#eafdss').text(gS11);
}

function goResize()
{
   $('#szdlg').dialog( { modal:true, resizable:false, buttons:{
         'Resize': function() {
            goRecord(3, $('#Horizontal').val() );
         },
         'Cancel': function() {
            $(this).dialog('close');
         }
      } } ).dialog('open');
}

function add_cell2(s11)
{
   var cells = $('#masterT td').length;

   if ((cells%horz)==0) {
      $('#masterT').append('<tr align=center><td id="td_'+s11+'"></td></tr>');
   }
   else {
      $('#masterT tr:last').append('<td id="td_'+s11+'"></td>');
   }

   return $('#masterT td:last');
}

function winRet(x)
{
   hide_popup();

   switch (x)
   {
   case 4: // open
   case 26: // details
      goRecord( x, gS11 );
      break;
   case 5:
   case 11:
   case 24:
   case 25:
   case 28:
      goTo(x);
      break;
   case 904: // Enable
   case 905: // Disable
      reset_enable(x-900);
      break;
   case 17:
      setMachineGroup();
      break;
   }
}

function reset_enable(x)
{
   var pdata={ 'MS11':gS11, 'FUNCTION':x };
   $.ajax('/ishop/ishop_jsontx.php', {
      error: function (jqXHR, textStatus, errorThrown){
         if (jqXHR) {
            if (jqXHR.responseText.length>0) {
               $('#msgdiv').html( jqXHR.responseText );
            }
            else {
               $('#msgdiv').html( 'Error '+jqXHR.status );
            }
         }
         else {
            $('#msgdiv').html( textStatus );
         }
         $('#msgdiv').show();
      },

      success: function(ro){
         if (ro[0].error.length>0) {
            $('#msgdiv').html( ro[0].error );
            $('#msgdiv').show();
         }
         else {
            $('#msgdiv').hide();
         }
      },

      data: pdata,

      dataType: 'json'
      }
   );
}

function getClassName(rec)
{
   var cnm;

   if (rec.ENABLED==0) { // new EAFDSS record
      cnm = rec.STATUS.length>0?'errNew':'okNew';
   }
   else if (rec.ENABLED==1) {
      if (rec.MACHINETYPE>0) { // 0=Unknown, 1=TaxSpooler, 2=FaSy, 3=POS
         cnm = rec.STATUS.length>0?'errEn':'okEn';
      }
      else {
         cnm = rec.STATUS.length>0?'errUndef':'okUndef';
      }
   }
   else { // disabled (terinated)
      cnm = rec.STATUS.length>0?'errDis':'okDis';
   }

   return cnm;
}

function SafeStringId(s11)
{
   var rets=new String();
   var patt=/[a-z]|[0-9]/i;
   for (var i=0;i<s11.length;i++) {
      if (patt.test(s11.charAt(i))) {
         rets += s11.charAt(i);
      }
      else {
         rets += '_';
      }
   }
   return rets;
}

function TCquery()
{
   var d1=new Date();
   $('#lastupd').text( d1.toLocaleTimeString() );

   $.ajax('/ishop/ishop_jsontx.php?FUNCTION=1', {

      error: function (jqXHR, textStatus, errorThrown){
         if (jqXHR) {
            if (jqXHR.responseText.length>0) {
               $('#msgdiv').html( jqXHR.responseText );
            }
            else {
               $('#msgdiv').html( 'Error '+jqXHR.status );
            }
         }
         else {
            $('#msgdiv').html( textStatus );
         }
         $('#msgdiv').show();
      },

      success: function(ro){
         if (ro[0].error.length>0) {
            $('#msgdiv').html( ro[0].error );
            $('#msgdiv').show();
         }
         else {
            $('#msgdiv').hide();
            var s11, coclass, slabel, stitle, tdo, tdId;
            var n=ro[0].data.length;
            for (var i=0;i<n;i++) {
               s11 = ro[0].data[i].MS11;
               if (s11.length==0) {
                  s11='empty';
               }
               s11=SafeStringId(s11);
               /*
               if (s11.length==0 || s11==='(auto)') // safety
                  continue;
               */

               coclass = getClassName(ro[0].data[i]);
               slabel = ro[0].data[i].TXLOCATION;
               if (slabel.length==0) {
                  slabel = s11;
               }

               var j = -1, maxj=0;
               var p;

               tdId = '#td_'+s11;
               if ($(tdId).length==0) {
                  // not found so far, create
                  tdo = add_cell2(s11);
               }
               else {
                  tdo = $(tdId);
               }

               tdo.text(slabel).attr('class', coclass);

               stitle = s11;
               if (ro[0].data[i].STATUS.length>0) {
                  stitle += ' ' + ro[0].data[i].STATUS;
               }
               tdo.attr('title', stitle);
            }
         }
      },

      complete: function(){
         window.setTimeout(TCquery,3000);
      },

      dataType: 'json'
   } );
}
</script>
<?php
}
//--------------------------------------
function show_pos_details()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('javascript:goTo(11)', 1, 'Στοιχεία POS(r)')
		);
   $x2->make_header($tarray);

   // BODY
?>
<script>
var s11=null;
function oclick(stage, row, col)
{
	s11=$( this.cells(row, 4).getValue() ).text();
	goRecord(12, s11);
	return false;
}
function winRet(x)
{
   hide_popup();

   switch (x)
   {
   case 5:
   case 11:
   case 24:
   case 25:
      goTo(x);
      break;
   }
}
</script>
<?php
   $gr1=new cXRID('grid7');

   $query="SELECT T1.*, T2.ENABLED, T2.MACHINETYPE, T2.TXLOCATION
      FROM taxi_log T1
      LEFT JOIN taxi_eafdss T2 ON (T2.MS11=T1.MS11)
      INNER JOIN (
	      SELECT MS11, MAX(LASTUPDATE) LUPD FROM taxi_log WHERE AGENTID=? AND RECTYPE=3
		   GROUP BY MS11
      ) J1
      ON T1.MS11=J1.MS11 AND T1.LASTUPDATE>=J1.LUPD
      WHERE T1.AGENTID=?
      ORDER BY T1.MS11";
   $data=array($x2->agentid, $x2->agentid );
   if (($rs=$db->Execute($query,$data))===false) {
		echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
		return;
   }
   while ($o1=$rs->FetchNextObject()) {
         $rsx=new cTXCERROR($o1);

         $cmt = new cMACHINETYPE($o1->MACHINETYPE);

         $row1=array();

         $row1[]=myhtml($db->verify_8($o1->POSAREAID));
         $row1[]=myhtml($db->verify_8($o1->TXLOCATION));
         $row1[]=myhtml($db->verify_8($o1->SENDERIP));
         $row1[]=$cmt->ToString();

         $ms11 = $db->verify_8($o1->MS11);
         $row1[] = ($o1->ENABLED ? myhtml($ms11):"<span class=REVERSE>".myhtml($ms11)."</span>");

         $row1[]=GrDateHour($o1->LASTZTAKEN);
         $row1[]=myhtml($o1->LASTZNR);
         $row1[]=GrDateTime($o1->LASTUPDATE);

         $row1[]=$o1->POSRECEIPTS;
         $row1[]=$o1->POSFPACHANGE;
         $row1[]=$o1->POSHDRCHANGE;
         $row1[]=$o1->POSCMOSERR;
         $row1[]=$o1->POSCFERR;
         $row1[]=$o1->POSPRNDETACH;
         $row1[]=$o1->POSTECHOPEN;
         $row1[]=$o1->POSDIMEDETACH;

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

   array_push($gr1->cols,
      array( 'Κατάστημα', 60),
		array( 'T/S Location', 100),
      array( 'Sender IP', 100),
      array( 'Machine Type', 80),
      array( 'Serial', 80),
      array( 'Last Z taken', 100), // DATETIME
      array( 'Z nr', 80),
      array( 'Last update', 100),
      array( 'Αποδείξεις εσόδων', 100),
      array( 'Αλλαγές τιμών φπα', 100),
      array( 'Αλλαγές λεκτικού', 100),
      array( 'Βλάβες cmos', 100),
      array( 'Βλάβη επικοινωνίας cf', 100),
      array( 'Αποσυνδέσεις εκτυπωτή', 100),
      array( 'Επεμβάσεις τεχνικού', 100),
      array( 'Αποσυνδέσεις ΔΗΜΕ', 100)
   );

   $gr1->click='oclick';
   $gr1->play();

   echo "<div id=tbar2>
      <button type=button onclick=\"goExport(2)\">Export (Excel)</button>
      <button type=button onclick=\"show_popup('popmenuFHM')\">ΕΑΦΔΣΣ/ POS</button>
      <b><a href=\"javascript:goTo(20)\">Στοιχεία S.TXT</a> |
      <a href=\"javascript:goTo(2)\">Logfile</a> | </b>
      Records: ".count($gr1->rows)."
      </div>";

    draw_popup_FHM();
}
//--------------------------------------
function show_s_txt_details()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('javascript:goTo(20)', 1, 'Στοιχεία S.TXT(r)')
		);
   $x2->make_header($tarray);

   // BODY
   $magroup=array(); // Ομάδες ΕΑΦΔΣΣ
   $query="SELECT MENUID, MENUDES FROM menurep
      WHERE AGENTID=? AND MENUTYPE=22
      ORDER BY MENUDES";
   $data=array($x2->agentid);
   if (($rs=$db->Execute($query,$data))===false) {
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $magroup[ $o1->MENUID ] = $db->verify_8($o1->MENUDES); // $db->verify_8() must be called only once for a single field
   }
   $rs->Close();

   $gr1=new cXRID('grid9');

   $query="SELECT T1.*, T2.MACHINETYPE, T2.MACHINEGROUP, T2.TXLOCATION, T2.AESKEYHEX
      FROM taxi_log T1
      INNER JOIN (
	      SELECT MS11, MAX(ROWID) LUPD FROM taxi_log WHERE AGENTID=? AND RECTYPE<>3
		   GROUP BY MS11
      ) J1 ON T1.MS11=J1.MS11 AND T1.ROWID=J1.LUPD
      LEFT JOIN taxi_eafdss T2 ON (T2.MS11=T1.MS11)
      WHERE T1.AGENTID=? AND T2.MACHINETYPE!=2 AND T2.MACHINETYPE!=3
      ORDER BY T1.MS11";
   $data=array($x2->agentid, $x2->agentid);
   if (($rs=$db->Execute($query,$data))===false) {
		echo( "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n" );
		return;
   }
   while ($o1=$rs->FetchNextObject()) {
         $rsx=new cTXCERROR($o1);
         $status=$rsx->Get();
         $cmt = new cMACHINETYPE($o1->MACHINETYPE);

         $row1=array();

         $row1[]=myhtml($o1->RECTYPE==1?'online':'disk');
         $row1[]=myhtml($db->verify_8($o1->TXVERSION));
         $row1[]=myhtml($db->verify_8($o1->TXLOCATION));
         $row1[]=$cmt->ToString();

         $row1[]="<span class=".(empty($status)?'green':'red').">".$db->verify_8($o1->MS11)."</span>";
         $row1[]=myhtml($o1->MACHINEGROUP.' '.@$magroup[$o1->MACHINEGROUP]);

         $row1[]=GrDateHour($o1->LASTZTAKEN);

         $row1[]=myhtml($o1->LASTZNR);

         $row1[]=myhtml($o1->FIRSTSTXT);
         $row1[]=myhtml($o1->FIRSTNOTSENT);
         $row1[]=GrDateTime($o1->NOTSENTCRE);
         $row1[]=myhtml($o1->NOTSENTERROR);

         $row1[]=GrDateTime($o1->LASTUPDATE);
         $row1[]=myhtml($status);

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

   array_push($gr1->cols,
      array( 'Rec. type', 40),
		array( 'T/S Version', 100),
		array( 'T/S Location', 100),
      array( 'Machine Type', 80),
      array( 'Serial', 80),
      array( 'Ομάδα', 80),
      array( 'Last Z taken', 100), // DATETIME
      array( 'Z nr', 80),
      array( 'First S.TXT ever created', 60),
      array( 'First S.TXT not sent', 60),
      array( 'Creation datetime of not sent', 60),
      array( 'Not sent TAXIS error', 60),
      array( 'Last update', 100),
      array( 'Status', 100)
   );

   $gr1->play();

   echo "<div id=tbar2>
      <button type=button onclick=\"goExport(20)\">Export (Excel)</button>
      Records: ".count($gr1->rows)."
      </div>";

   $selx=array(
		array(4, '/img/open_folder.gif', $x2->xxlabel('open') ),
      array(19, '/img/button_edit.png', $x2->xxlabel('edit') )
   );
   draw_popup($selx);
}
//--------------------------------------
function delete_eafdss()
{
   global $x2;
   $db=&$x2->db;

   $db->StartTrans();

   do {
      // Agentid not really needed, we use it for extra security
      //
      $query="DELETE FROM taxi_log WHERE MS11=? AND AGENTID=?";
      $data=array($_REQUEST['RECORDID'], $x2->agentid);
      if (!$db->Execute($query,$data)) {
         echo( "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n" );
         break;
      }

      $query="DELETE FROM taxi_eafdss WHERE MS11=? AND AGENTID=?";
      $data=array($_REQUEST['RECORDID'], $x2->agentid);
      if (!$db->Execute($query,$data)) {
         echo( "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n" );
         break;
      }
   } while (false);

   $db->CompleteTrans();
}
//--------------------------------------
function show_eafdss_info2($LiType)
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('javascript:goTo('.($LiType==0?24:25).')', 1, ($LiType==0?'TaxSpooler version(r)':'O/S(r)'))
		);
   $x2->make_header($tarray);

   // BODY
?>
<script>
var s11=null, aes=null;
function oclick(stage, row, col)
{
	s11=$( this.cells(row, 6).getValue() ).text();
   aes=this.cells(row, 8).getValue();
   show_popup('popmenu');
	return false;
}
function winRet(x)
{
   switch (x)
   {
   case 4:
      goRecord(4, s11);
      break;
   case 5:
   case 11:
   case 24:
   case 25:
   case 28:
      goTo(x);
      break;
   case 21:
      goRecDelete(21, s11);
      break;
   case 22:
   case 23:
      goTo(x);
      break;
   case 241:
      goRecord(24,1);
      break;
   case 242:
      goRecord(24,2);
      break;
   case 251:
      goRecord(25,1);
      break;
   case 252:
      goRecord(25,2);
      break;
   }
   hide_popup();
}
function goUpdateAesKey()
{
   goRecord(19, s11+';'+$('#aeskey').val() );
}
</script>
<?php
   $magroup=array();
   $query="SELECT MENUID, MENUDES FROM menurep
      WHERE AGENTID=? AND MENUTYPE=22
      ORDER BY MENUDES";
   $data=array($x2->agentid);
   if (($rs=$db->Execute($query,$data))===false) {
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $magroup[ $o1->MENUID ] = $db->verify_8($o1->MENUDES); // $db->verify_8() must be called only once for a single field
   }
   $rs->Close();

   $gr1=new cXRID('grid10');

   if (!empty($_REQUEST['RECORDID']))
      $_SESSION['EAFDSS_DETAILS_ORDER_BY'] =  $_REQUEST['RECORDID']-1;

   switch ((int)@$_SESSION['EAFDSS_DETAILS_ORDER_BY'])
   {
      case 1:
         $orderby="TXLOCATION";
         break;
      default:
         $orderby = $LiType==0?'TXVERSION, TXLOCATION':'L_OS, TXLOCATION';
         break;
   }

   if ($LiType==0) {
      $fields =  "T1.RECTYPE, T1.TXVERSION, T2.TXLOCATION";
   }
   else {
      $fields =  "T1.RECTYPE, T2.TXLOCATION, T2.L_OS, T2.L_ARCH, T2.L_PROCID, T2.L_NPROC";
   }

   $query="SELECT MAX(T1.LASTUPDATE) F1, $fields FROM taxi_log T1
      LEFT JOIN taxi_eafdss T2 ON (T2.MS11=T1.MS11)
      INNER JOIN (
	      SELECT MS11, MAX(LASTUPDATE) LUPD FROM taxi_log WHERE AGENTID=? AND RECTYPE<>3
		   GROUP BY MS11
      ) J1
      ON T1.MS11=J1.MS11 AND T1.LASTUPDATE>=J1.LUPD
      WHERE T1.AGENTID=? AND T2.ENABLED<>2
      GROUP BY $fields
      ORDER BY $orderby";
   $data=array($x2->agentid, $x2->agentid);
   if (($rs=$db->Execute($query,$data))===false) {
		echo( "<h6>".__LINE__.$db->ErrorMsg()."<br>$query</h6>\n" );
		return;
   }
   while ($o1=$rs->FetchNextObject()) {
         $row1=array();

         $row1[]=myhtml($o1->RECTYPE==1?'online':'disk');
         $row1[]=myhtml($db->verify_8($o1->TXLOCATION));

         if ($LiType==0) {
            $row1[]=myhtml($db->verify_8($o1->TXVERSION));
         }
         else {
            $row1[]=myhtml($db->verify_8($o1->L_OS));
            $row1[]=myhtml($db->verify_8($o1->L_ARCH));
            $row1[]=myhtml($db->verify_8($o1->L_PROCID));
            $row1[]=myhtml($db->verify_8($o1->L_NPROC));
         }

         $row1[]=myhtml($db->verify_8($o1->SENDERIP));
         $row1[]=GrDateTime(strtr($o1->F1, "TZ", "  "));

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

   array_push($gr1->cols,
      array( 'Rec. type', 40),
		array( 'T/S Location', 100)
   );

   if ($LiType==0) {
      array_push($gr1->cols,
         array( 'T/S Version', 100)
      );
   }
   else {
      array_push($gr1->cols,
         array( 'O/S', 80),
         array( 'Architecture', 80),
         array( 'Processor', 80),
         array( 'Total', 80)
      );
   }

   array_push($gr1->cols,
      array( 'Sender IP', 100),
      array( 'Last update', 100)
   );

   $gr1->click='oclick';
   $gr1->play();

   echo "<div id=tbar2>
      <button type=button onclick=\"show_popup('popmenu2')\">Sort</button>
      <button type=button onclick=\"goExport(".($LiType==0?3:4).")\">Export (Excel)</button>
      <button type=button onclick=\"show_popup('popmenuFHM')\">ΕΑΦΔΣΣ/ POS</button>
      <b>
      <a href=\"javascript:goTo(20)\">Στοιχεία S.TXT</a> |
      <a href=\"javascript:goTo(2)\">Logfile</a> |
      </b>
      Records: ".count($gr1->rows)."
      </div>";

   $selx=array(
		array(4, '/img/open_folder.gif', $x2->xxlabel('open') )
   );
   draw_popup($selx);

   $x = $LiType==0?240:250;
   $selx2=array(
      array($x+1, '/img/go_next.gif', $LiType==0?'TaxSpooler version':'O/S'),
      array($x+2, '/img/go_next.gif', 'Location')
   );
   draw_popup($selx2, false, 'popmenu2');

   draw_popup_FHM();
}
//--------------------------------------
function list_version_avail()
{
   $key="taxspooler_";
   $keyLen=strlen($key);
   $vers=array();

   $dir1 = "e:\\inca\\upgrades";
   if (!is_dir($dir1)) {
      $dir1 = "c:\\tmp\\ab";
   }

   if (!is_dir($dir1)) {
      echo "Directory for upgrades not found!";
      return;
   }

   if (($ar1=scandir($dir1))===false) {
      echo "Could not scan $dir1";
      return;
   }
   foreach ($ar1 as $file1) {
      if ($file1==='.' || $file1==='..')
         continue;

      $fpath=$dir1."\\".$file1;
      if (is_dir($fpath))
         continue;

      if (strncasecmp($file1, $key, $keyLen)!=0)
         continue;

      $ar2 = explode('.', substr($file1, $keyLen));
      if (count($ar2)!=2 || strcasecmp($ar2[1],"zip")!=0)
         continue;

      $vers[] = strtr($ar2[0], '_', '.');
   }

   if (empty($vers)) {
      echo "Version info. not available";
      return;
   }

   usort($vers, 'version_compare');
   echo "<select id=versions>";
   foreach ($vers as $v1) {
      echo "<option>$v1</option>";
   }
   echo "</select>";
}
//--------------------------------------
function upd_vers_request()
{
   global $x2;
   $db=&$x2->db;

   $query="DELETE FROM taxi_update WHERE SENDERIP=? AND UPDPROGRAM='taxspooler' AND AGENTID=?"; // agentid not really needed
   $data=array($_REQUEST['SENDERIP'], $x2->agentid );
   if (!$db->Execute($query,$data)) {
      echo __LINE__.$db->ErrorMsg();
      return;
   }

   $query="INSERT INTO taxi_update (SENDERIP, UPDPROGRAM, UPDVERSION, AGENTID) VALUES(?, 'taxspooler', ?, ?)";
   $data=array($_REQUEST['SENDERIP'], $_REQUEST['UPDVERSION'], $x2->agentid );
   if (!$db->Execute($query,$data)) {
      echo __LINE__.$db->ErrorMsg();
   }
}
//--------------------------------------
function upd_eafdss_data()
{
   global $x2;
   $db=&$x2->db;

   if (!MyEditRightsOk())
      return;

   $query = sprintf('UPDATE taxi_eafdss SET SAPENUMCODE=?, TAXISBRANCHID=%s, MYSTREET=?, MYNUMBER=?, MYZIP=?, MYCITY=? WHERE MS11=?',
               (empty($_REQUEST['TAXISBRANCHID']) ? 'NULL' : $_REQUEST['TAXISBRANCHID']));
   $data = array($_REQUEST['SAPENUMCODE'], $_REQUEST['MYSTREET'], $_REQUEST['MYNUMBER'],
      $_REQUEST['MYZIP'], $_REQUEST['MYCITY'], $_REQUEST['MS11']);
   if (!$db->Execute($query,$data)) {
      echo __LINE__.$db->ErrorMsg();
   }
}
//--------------------------------------
function load_ascii_enum()
{
   global $x2;
   $db=&$x2->db;

   $src = "C:\\temp\\branch_AB.csv";
   if (!file_exists($src)) {
      echo "<h6>File dows not exist: $src</h6>";
      return;
   }

   $eafdss = array();
   $query = 'SELECT MS11, TXLOCATION FROM taxi_eafdss';
   if (($rs=$db->Execute($query))===false) {
      echo '<h6>'.__LINE__.' '.$db->ErrorMsg().'</h6>';
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $ar1 = explode(' ', $o1->TXLOCATION);
      if (!empty($ar1)) {
         $abId = (int)$ar1[0];
         $eafdss[trim($o1->MS11)] = $abId;
      }
   }

   //pre($abCodes);

   if (($ar1 = file($src))===false) {
      echo "<h6>Could not read: $src</h6>";
      return;
   }

   $query = 'UPDATE taxi_eafdss SET SAPENUMCODE=?, TAXISBRANCHID=? WHERE MS11=?';

   $hdr_read = false;
   foreach ($ar1 as $line) {
      if (!$hdr_read) {
         $hdr_read = true;
         continue;
      }

      $fields = explode(';', $line);
      $ar2 = explode(' ', $fields[3]); // [3] = Shop code - description -> Code, Description
      if (empty($ar2)) {
         echo "Data not adequate: ".$fields[3]."<br>";
         continue;
      }
      while ($ar2[0][0] === '0') { $ar2[0] = substr($ar2[0], 1); }
      $abId = (int)$ar2[0];
      if ($abId >= 101 && $abId <= 199) { $abId -= 100; } // correction

      foreach ($eafdss as $key=>$val)
      {
         if ($val == $abId) {
            $data = array($fields[4], (int)$fields[2], $key);
            if (!$db->Execute($query, $data)) {
               echo '<h6>'.__LINE__.' '.$db->ErrorMsg().'</h6>';
               break;
            }
         }
      }
   }
}
//--------------------------------------
function list_unmatched()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
   $tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('javascript:goTo(5)', 1, 'Στοιχεία ΕΑΦΔΣΣ'),
      array('javascript:goTo(97)', 1, 'AESKEY list'),
      array('javascript:goTo(92)', 1, 'Unmatched ΕΑΦΔΣΣ(r)')
		);
   $x2->make_header($tarray);

   $gr1=new cXRID('grid20');
   $gr1->cols = array(
      array('S11', 120),
      array('Created', 420)
   );

   $query = 'DELETE FROM taxi_unmatch WHERE MS11 IN (
         SELECT MS11 FROM taxi_eafdss WHERE TAXISBRANCHID > 0
      )';
   if (!$db->Execute($query)) {
      echo $db->ErrorMsg();
      return;
   }

   $query = 'SELECT * FROM taxi_unmatch ORDER BY MS11';
   if (($rs=$db->Execute($query))===false) {
      echo $db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1 = array(
         myhtml($o1->MS11),
         myhtml($o1->CREDAYTIME)
      );
      $gr1->rows[]=$row1;
   }
   $rs->Close();
   $gr1->play();
?>
<div id=tbar2>
   <small>End of data</small>
</div>
<?php
}
//--------------------------------------
function aeskey_list()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
   $tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(5)', 1, 'Στοιχεία ΕΑΦΔΣΣ'),
        array('javascript:goTo(97)', 1, 'AESKEY list(r)')
		);
   $x2->make_header($tarray);
?>
<script>
function oclick(stage, row, col)
{
   $('#myForm :input[name=MS11]').val(this.cells(row, 0).getValue());
   $('#myForm :input[name=LOCATION]').val(this.cells(row, 2).getValue());
   $('#myForm :input[name=SAPENUMCODE]').val(this.cells(row, 3).getValue());
   $('#myForm :input[name=TAXISBRANCHID]').val(this.cells(row, 4).getValue());
   $('#myForm :input[name=MYSTREET]').val(this.cells(row, 5).getValue());
   $('#myForm :input[name=MYNUMBER]').val(this.cells(row, 6).getValue());
   $('#myForm :input[name=MYZIP]').val(this.cells(row, 7).getValue());
   $('#myForm :input[name=MYCITY]').val(this.cells(row, 8).getValue());

   $('#eafdssEnum').dialog('open');
   return false;
}
$(function(){
   $('#eafdssEnum').dialog({autoOpen:false, modal:true, resizable:false});
});
</script>
<div id="eafdssEnum" title="EAFDSS enumeration">
   <form id="myForm" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
   <input type=hidden name="FUNCTION" value="98">
      <table>
         <tr>
            <td>S11</td>
            <td><input type=text name="MS11" readonly></td>
         </tr>
         <tr>
            <td>Location</td>
            <td><input type=text name="LOCATION" readonly></td>
         </tr>
         <tr>
            <td>SAP</td>
            <td><input type=text name="SAPENUMCODE"></td>
         </tr>
         <tr>
            <td>Taxis Id</td>
            <td><input type=text name="TAXISBRANCHID"></td>
         </tr>
		 <tr>
            <td>My street</td>
            <td><input type=text name="MYSTREET"></td>
         </tr>
         <tr>
            <td>My number</td>
            <td><input type=text name="MYNUMBER"></td>
         </tr>
         <tr>
            <td>My ZIP</td>
            <td><input type=text name="MYZIP"></td>
         </tr>
         <tr>
            <td>My city</td>
            <td><input type=text name="MYCITY"></td>
         </tr>
         <tr>
            <td></td>
            <td><input type=submit value="Update"></td>
         </tr>
      </table>
   </form>
</div>
<?php
   $query = 'SELECT MS11, AESKEYHEX, TXLOCATION, SAPENUMCODE, TAXISBRANCHID, MYSTREET, MYNUMBER, MYZIP, MYCITY FROM taxi_eafdss ORDER BY MS11';
   if (($rs=$db->Execute($query))===false) {
      echo $db->ErrorMsg();
      return;
   }

   $gr1=new cXRID('grid19');

   while ($o1=$rs->FetchNextObject()) {
      $row1 = array(
         myhtml($o1->MS11),
         myhtml($o1->AESKEYHEX),
         myhtml($o1->TXLOCATION),
         myhtml($o1->SAPENUMCODE),
         $o1->TAXISBRANCHID,
         myhtml($o1->MYSTREET),
         myhtml($o1->MYNUMBER),
         myhtml($o1->MYZIP),
         myhtml($o1->MYCITY)
      );
      $gr1->rows[]=$row1;
   }
   $rs->Close();

   $gr1->cols = array(
      array('S11', 120),
      array('AESKEY', 420),
      array('Location', 200),
      array('SAP enumeration', 120),
      array('Taxis ID', 120),
	  array('My street', 100),
      array('My number', 50),
      array('My ZIP', 50),
      array('My city', 80)
   );
   $gr1->sort = 'str,na,str,str,int';
   $gr1->click='oclick';
   $gr1->play();
?>
<div id=tbar2>
   <small>End of data</small>
   <!-- deprecated 3/1/2022
   <button type=button title="Load c:/temp/branch_AB.csv (utf-8, delimited, a/a-name-taxis-branchID-SAP)" onclick="goTo(93)">Load ascii</button>
   -->
   <b><a href="javascript:goTo(92)">Unmatched ΕΑΦΔΣΣ</a></b>
</div>
<?php
}
//--------------------------------------
function do_load_aeskeys() // 96:
{
   global $x2;
   $db=&$x2->db;

   // HEADER
   $tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('javascript:goTo(5)', 1, 'Στοιχεία ΕΑΦΔΣΣ'),
      array('javascript:goTo(95)', 1, 'Ask load AESKEY'),
      array('', 1, 'Load AESKEY')
		);
   $x2->make_header($tarray);
?>
<style>
.tdata table, .tdata th, .tdata td {
  border: 1px solid black;
}
table.tdata {
  border-collapse: collapse;
}
.tdata td {
   font-family: courier new;
}
</style>
<?php
   $ok = false;
   do {
      if (!isset($_FILES['AESFILE'])) {
         echo 'File not sent!';
         break;
      }

      if ($_FILES['AESFILE']['error'] > 0) {
         echo 'Error '.$_FILES['AESFILE']['error'].' loading file!';
         break;
      }

      if (($fp = fopen($_FILES['AESFILE']['tmp_name'], 'r'))===false) {
         echo 'Could not open downloaded file!';
         break;
      }

      $query = 'SELECT COUNT(*) FROM taxi_eafdss WHERE MS11=?';
      $qinsert = 'INSERT INTO taxi_eafdss (MS11, AGENTID, AESKEYHEX) VALUES(?,?,?)';
      $qupdate = 'UPDATE taxi_eafdss SET AESKEYHEX=? WHERE MS11=?';

      echo '<table class="tdata">';
      $nline = 0;
      while (($ar1 =fgetcsv($fp, 0, ';'))!==false) {
         if (++$nline == 1) {
            $idxKey = (int)array_search("Taxis Key", $ar1);
            $idxAgent = (int)array_search("AGENTID", $ar1);
            $idxS11 = (int)array_search("Serial", $ar1);
            continue;
         }

         echo '<tr>';
         /*
         foreach ($ar1 as $field) {
            echo '<td>'.myhtml($field).'</td>';
         }
         */
         $s11 = $ar1[$idxS11];
         $aeskey = $ar1[$idxKey];
         echo '<td>'.myhtml($ar1[$idxAgent]).'</td>'.
            '<td>'.myhtml($s11).'</td>'.
            '<td>'.myhtml($aeskey).'</td>'.
            '<td>'.strlen($aeskey).'</td>'.
            '<td>';

         $data = array($s11);
         if (($rs=$db->Execute($query, $data))===false) {
            echo __LINE__.' '.$db->ErrorMsg();
            break;
         }
         $row=$rs->FetchRow();
         $rs->Close();

         if ($row[0] > 0) { // found in database
            $data = array($aeskey, $s11);
            if (!$db->Execute($qupdate, $data)) {
               echo __LINE__.' '.$db->ErrorMsg();
               break;
            }
         }
         else {
            $data = array($s11, $ar1[$idxAgent], $aeskey);
            if (!$db->Execute($qinsert, $data)) {
               echo __LINE__.' '.$db->ErrorMsg();
               break;
            }
         }

         echo '</td>';

         echo '</tr>';
      }
      echo '</table>';

      fclose($fp);

      $ok = true;
   } while (false);
   if (!$ok)
      return;

   //$_FILES['AESFILE']['tmp_name']
   echo 'Finished!';
}
//--------------------------------------
function ask_load_aeskeys() // 95:
{
   global $x2;
   $db=&$x2->db;

   // HEADER
   $tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('javascript:goTo(5)', 1, 'Στοιχεία ΕΑΦΔΣΣ'),
      array('', 1, 'Ask load AESKEY')
		);
   $x2->make_header($tarray);

   // BODY
?>
   <form enctype="multipart/form-data" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method=POST>
      <input type=hidden name="FUNCTION" value="96">
      <table>
         <tr>
            <td>Αρχείο</td>
            <td><input type=file name="AESFILE"></td>
         </tr>
         <tr>
            <td></td>
            <td><input type=submit value="Load"></td>
         </tr>
      </table>
   </form>
<?php
}
//--------------------------------------
function show_pending_group() // #62
{
   global $x2;
   $db=&$x2->db;

   // HEADER
   $tarray=array(
      array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(60)', 1, 'Esend/ Z'),
      array('javascript:goTo(61)', 1, 'Εκκρεμή Ζ'),
      array('javascript:goTo(62)', 1, 'Group/ Eκκρεμή Ζ(r)')
   );
   $x2->make_header($tarray);


   $gr1 = new cXRID('grid26');
   $gr1->cols = [
      array('ΕΑΦΔΣΣ', 100),
      array('Πλήθος Ζ', 100)
   ];

   $query = "SELECT T1.S11, COUNT(*) AS NREC ".
           " FROM abfirstd T1 ".
           " LEFT JOIN abmaiz T2 ON (T2.S11=T1.S11 AND T2.Z4>=T1.Z4) ".
           " WHERE T2.S11 IS NOT NULL AND (T2.DATASRET IS NULL OR T2.DATASRET<>0) ".
           " GROUP BY T1.S11 ".
           " ORDER BY T1.S11";
   if (($rs=$db->Execute($query)) === false) {
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>";
		return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1 = [
         myhtml($o1->S11),
         myhtml($o1->NREC)
      ];
      $gr1->rows[] = $row1;
   }
   $rs->Close();

   $gr1->play();
   echo "<div id=tbar2><small>End of data</small></div>";
}
//--------------------------------------
function show_pending_Z() // #61
{
   global $x2;
   $db=&$x2->db;

   $allRecords = false; // not all, just sent

   // HEADER
   $tarray=array(
      array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(60)', 1, 'Esend/ Z'),
      array('javascript:goTo(61)', 1, 'Εκκρεμή Ζ(r)')
   );
   $x2->make_header($tarray);

   $gr1 = new cXRID('grid25');
   $gr1->cols = [
      array('ΕΑΦΔΣΣ', 80),
      array('Z', 50),
      array('Ημ/νία Ζ', 80),
      array('Ωρα Ζ', 50),
      array('Αποστολή', 120),
      array('Απάντηση', 100),
      array('Τελευταίο Ζ', 50)
   ];

   $data = array();
   $query = "SELECT T1.S11, T2.Z4, T2.YYMMDD, T2.HHMM, T2.DATASENT, T2.DATASRET, T2.DATARETPARAM ".
           " FROM abfirstd T1 ".
           " LEFT JOIN abmaiz T2 ON (T2.S11=T1.S11 AND T2.Z4>=T1.Z4) ".
           " WHERE ";
   if (!empty($forS11))
   {
      $query .= " T1.S11=? AND ";
      $data[] = $forS11;
   }
   $query .= " T2.S11 IS NOT NULL ";

   if (!$allRecords)
   {
      // Only "not sent"
      $query .= " AND (T2.DATASRET IS NULL OR T2.DATASRET<>0) ";
   }

   $query .= " ORDER BY T1.S11, T2.Z4";

   if (($rs=$db->Execute($query, $data)) === false) {
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>";
		return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1 = [
         myhtml($o1->S11),
         myhtml($o1->Z4),
         sprintf('20%02d-%02d-%02d', $o1->YYMMDD/10000, ($o1->YYMMDD%10000)/100, $o1->YYMMDD%100),
         sprintf('%02d:%02d', $o1->HHMM/100, $o1->HHMM%100),
         $o1->DATASENT,
         $o1->DATASRET,
         $o1->DATARETPARAM
      ];
      $gr1->rows[] = $row1;
   }
   $rs->Close();

   $gr1->play();
   echo "<div id=tbar2><button type=button onclick=\"goTo(62)\">Group (unsent)</button></div>";
}
//--------------------------------------
function show_z_contents()
{
   global $x2;
   $db=&$x2->db;

   $s11 = $_REQUEST['S11'];
   $znr = (int)$_REQUEST['ZNR'];

   // HEADER
   $tarray=array(
      array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(60)', 1, 'Esend/ Ζ'),
      array('javascript:followMe({FUNCTION:63, S11:\''.$s11.'\'})', 1, 'Z of '.$s11),
      array('', 1, 'Contents of Z '.$znr)
   );
   $x2->make_header($tarray);
?>
<div id=myrecord>
   <div id=myinfo></div>
</div>
<script>
var s11='<?php echo myjs($s11); ?>';
var znr=<?php echo $znr ?>;
var daily;
function oclick(stage, row, col)
{
   daily = parseInt(this.cells(row, 0).getValue());
   if (isNaN(daily)) { daily = 0; } // normalization
   show_popup('popmenu');
	return false;
}
function winRet(x)
{
   let url, title;

   switch (x)
   {
   case 1: // zoom
      url = '/ishop/ishop_taxout.php?FUNCTION=10&S11=' + encodeURIComponent(s11) +
         '&ZNR=' + znr + '&DAILY=' + daily;
      title = 'Zoom'; //'Αριθμός εγγραφής ' + rid;
      $('#myinfo').html('loading...');
      $('#myrecord').dialog('option', 'title', title).dialog('open');
      $('#myinfo').load(url);
      break;
   }
   hide_popup();
}
$(function(){
   $('#myrecord').dialog({autoOpen:false, modal:false, resizable:true, width:620});
});
</script>
<?php
   $gr1 = new cXRID('grid29');
   $gr1->cols = [
      array('Ημερήσιος α/α', 100),
      array('Ημ/νία Ε', 120),
      array('MYDATAREAD', 100),
      array('Τύπος παρ/κού', 260),
      array('Σειρά παρ/κού', 60),
      array('Αριθμός παρ/κού', 60),
      array('ΑΦΜ παραλήπτη', 60),
      array('Αξία χ/φπα', 60),
      array('Συνολική αξία', 60)
   ];

   $query = "SELECT DAILY, YYMMDD, HHMM, MYDATAREAD, ETXT FROM abmaiex
      WHERE S11=? AND Z4=? ORDER BY DAILY";
   $data = array($s11, $znr);
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__.' '.$db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1 = [
         $o1->DAILY
      ];

      $val = sprintf('%06d%04d', $o1->YYMMDD, $o1->HHMM);
      $row1[] = substr($val, 4, 2) . "-" . substr($val, 2, 2) . "-20" . substr($val, 0, 2) . " " .
         substr($val, 6, 2) . ":" . substr($val, 8, 2);

      $row1[] = $o1->MYDATAREAD;

      if (!empty($o1->ETXT)) {
         $ar1 = explode(';', $o1->ETXT);
         if (count($ar1) >= 23) {
            $row1[] = myhtml($ar1[8]. ' ' . getDocName($ar1[8]));
            $row1[] = myhtml($ar1[9]);
            $row1[] = myhtml($ar1[10]);
            $row1[] = myhtml($ar1[1]);
            $row1[] = toFloat($ar1[11]) + toFloat($ar1[12]) + toFloat($ar1[13]) + toFloat($ar1[14]) + toFloat($ar1[15]);
            $row1[] = toFloat($ar1[20]);
         }
      }

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

	$gr1->click = 'oclick';
   $gr1->play();
   echo '<div id=tbar2><small>End of data</small></div>';

	$selx=array(
      array(1, '/img/details.gif', 'Zoom' )
   );
   draw_popup($selx);
}
//--------------------------------------
function show_z_of_s11() // 63
{
   global $x2;
   $db=&$x2->db;

   $s11 = $_REQUEST['S11'];

   // HEADER
   $tarray=array(
      array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(60)', 1, 'Esend/ Ζ'),
      array('', 1, 'Z of '.$s11)
   );
   $x2->make_header($tarray);
?>
<script>
function oclick(stage, row, col)
{
   var znr = this.cells(row, 0).getValue();
   var html = '<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method=POST>';
   html += '<input type=hidden name="FUNCTION" value="64">';
   html += '<input type=hidden name="S11" value="<?php echo myjs($_REQUEST['S11']); ?>">';
   html += '<input type=hidden name="ZNR" value="' + znr + '">';
   html += '</form>';
   $(html).appendTo('body').submit();
}
</script>
<?php
   $gr1 = new cXRID('grid28');
   $gr1->cols = [
      array('Z α/α', 100),
      array('Ημ/νία Ζ', 120),
      array('Datasent', 100),
      array('Datasret', 100),
      array('Dataretparam', 100),
      array('Esend err.msg.', 100)
   ];

   $query = "SELECT T1.Z4, T1.YYMMDD, T1.HHMM, T1.COMMENTS, T1.DATASENT, T1.DATASRET, T1.DATARETPARAM, T1.ESENDERRMSG, COUNT(T2.DAILY) AS N1 FROM abmaiz T1
      LEFT JOIN abmaiex T2 ON (T2.S11=T1.S11 AND T2.Z4=T1.Z4)
      WHERE T1.S11=?
      GROUP BY T1.Z4, T1.YYMMDD, T1.HHMM, T1.COMMENTS, T1.DATASENT, T1.DATASRET, T1.DATARETPARAM, T1.ESENDERRMSG
      ORDER BY T1.Z4";
   $data = array($s11);
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__.' '.$db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1 = [
         $o1->Z4
      ];

      $val = sprintf('%06d%04d', $o1->YYMMDD, $o1->HHMM);
      $row1[] = substr($val, 4, 2) . "-" . substr($val, 2, 2) . "-20" . substr($val, 0, 2) . " " .
         substr($val, 6, 2) . ":" . substr($val, 8, 2);

      $row1[] = myhtml($o1->COMMENTS);
      $row1[] = (int)$o1->DATASENT > 0 ? date('Y-m-d H:i:s', $o1->DATASENT) : '';
      $row1[] = $o1->DATASRET;
      $row1[] = $o1->DATARETPARAM;
      $row1[] = myhtml($o1->ESENDERRMSG);

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

   $gr1->click = 'oclick';
   $gr1->play();
   echo '<div id=tbar2><small>End of data</small></div>';
}
//--------------------------------------
function show_z_collection() // 60
{
   global $x2;
   $db=&$x2->db;

   // HEADER
   $tarray=array(
      array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(60)', 1, 'Esend/ Ζ(r)')
   );
   $x2->make_header($tarray);

	$_SESSION['X2FILTER'] = $_REQUEST['X2FILTER']??'';
?>
<script>
function oclick(stage, row, col)
{
   var s11 = this.cells(row, 0).getValue();
   var html = '<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method=POST>';
   html += '<input type=hidden name="FUNCTION" value="63">';
   html += '<input type=hidden name="S11" value="' + s11 + '">';
   html += '</form>';
   $(html).appendTo('body').submit();
}
var x2Filter = '<?php echo myjs($_SESSION['X2FILTER']); ?>';
function onFilter()
{
   var userInput;
   if ((userInput = window.prompt('Εφαρμογή φίλτρου σε ΦΗΜ ή Location', x2Filter)) !== null) {
      x2Filter = userInput;
      location.href = location.pathname + '?FUNCTION=60&X2FILTER=' + encodeURIComponent(x2Filter);
   }
}
</script>
<?php
   $gr1 = new cXRID('grid24');
   $gr1->cols = [
      array('ΕΑΦΔΣΣ', 100),
		array('Location', 150),
      array('Πρώτο Ζ', 80),
      array('Ημ/νία Ζ', 90),
      array('Τελευταίο Ζ', 60),
      array('Τύπος', 60),
      array('Τελευταίο S', 60),
      array('Ώρα UTC Taxis', 60),
      array('Αποστολή κάθε (λεπτά)', 80)
   ];

   if (strlen($_SESSION['X2FILTER']) > 0) {
      $likeStr = '%'.$_SESSION['X2FILTER'].'%';
      $data = [$likeStr, $likeStr];
   }
   else {
      $data = false;
   }
   $query = "SELECT T1.S11, T1.Z4, T4.TXLOCATION, T2.YYMMDD, T2.HHMM, T3.Z4 MAXS, T3.ISZ, ".
                       " T3.POSTDATE, T3.POSTTIME, T3.SERVERTIME, T3.REPEATAFTER FROM abfirstd T1 ".
                       " LEFT JOIN abmaiz T2 ON (T2.S11=T1.S11 AND T2.Z4=T1.Z4) ".
                       " LEFT JOIN absendtaxis T3 ON (T3.S11=T1.S11) ".
                       " LEFT JOIN taxi_eafdss T4 ON (T4.MS11=T1.S11) ";
   if ($data !== false) {
      $query .= " WHERE T1.S11 LIKE ? OR T4.TXLOCATION LIKE ? ";
   }
   $query .= " ORDER BY T1.S11";
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__.' '.$db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1 = array(
         myhtml($o1->S11),
			myhtml($o1->TXLOCATION),
         $o1->Z4
      );

      $val = sprintf('%06d%04d', $o1->YYMMDD, $o1->HHMM);
      $row1[] = substr($val, 4, 2) . "-" . substr($val, 2, 2) . "-20" . substr($val, 0, 2) . " " .
         substr($val, 6, 2) . ":" . substr($val, 8, 2);

      if (!empty($o1->MAXS))
      {
         $row1[] = $o1->MAXS;
         $row1[] = $o1->ISZ == 1 ? "Z" : "s.tmp";

         $val = sprintf('%08d%06d', $o1->POSTDATE, $o1->POSTTIME); // YYYYMMDDhhmmss
         $row1[] = substr($val, 6, 2) . "-" . substr($val, 4, 2) . "-" . substr($val, 0, 4) . " " .
            substr($val, 8, 2) . ":" . substr($val, 10, 2) . ":" . substr($val, 12, 2);

         $val = $o1->SERVERTIME; // string YYYYMMDDhhmmss
         $row1[] = substr($val, 6, 2) . "-" . substr($val, 4, 2) . "-" . substr($val, 0, 4) . " " .
            substr($val, 8, 2) . ":" . substr($val, 10, 2) . ":" . substr($val, 12, 2);

         $row1[] = ($o1->REPEATAFTER == 0 ? 'Δεν αποστέλλει' : $o1->REPEATAFTER);
      }

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

   $gr1->click = 'oclick';
   $gr1->play();
   echo "<div id=tbar2>
      <button type=button class=NavButton onclick=\"onFilter()\" title=\"Εφαρμογή φίλτρου\"><img src=\"/img/filter.png\"></button>
      <button type=button onclick=\"goTo(61)\">Ολα τα εκκρεμή Ζ</button>
      <button type=button onclick=\"goTo(70)\">myDATA</button>
      </div>";
}
//--------------------------------------
function show_mydata_agents() // 71
{
   global $x2;
   $db=&$x2->db;

   // HEADER
   $tarray=array(
      array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(71)', 1, 'myDATA Agents(r)')
   );
   $x2->make_header($tarray);
?>
<script>
function oclick(stage, row, col)
{
   var myagentid = this.cells(row, 0).getValue();
   var html = '<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method=POST>';
   html += '<input type=hidden name="FUNCTION" value="70">';
   html += '<input type=hidden name="MYAGENTID" value="' + myagentid + '">';
   html += '</form>';
   $(html).appendTo('body').submit();
}
</script>
<?php

   $gr1=new cXRID('grid22');

   $query = 'SELECT AGENTID, CAFM, CNAME FROM myagent ORDER BY AGENTID';
   if (($rs=$db->Execute($query))===false) {
      echo __LINE__.' '.$db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1 = array(
         $o1->AGENTID,
         myhtml($o1->CAFM),
         myhtml($o1->CNAME)
      );
      $gr1->rows[] = $row1;
   }
   $rs->Close();

   $gr1->cols = [
      array('Agent Id', 100),
      array('ΑΦΜ', 100),
      array('Επωνυμία', 200)
   ];
   $gr1->sort = 'int,str,str';
   $gr1->click = 'oclick';
   $gr1->play();
   echo "<div id=tbar2><small>End of data</small></div>";
}
//--------------------------------------
function RecTypeLabel($rectype)
{
   switch ($rectype)
   {
   case 1:
      $rets = "Παραστατικό"; // "Invoice";
      break;
   case 2:
      $rets = "Χαρακτ.εσόδων"; // "Income Classification";
      break;
   case 3:
      $rets = "Χαρακτ.εξόδων"; // "Expenses Classification";
      break;
   case 4:
      $rets = "Ζήτηση παρ.τρίτων"; // "Request Docs";
      break;
   case 5:
      $rets = "Ζήτηση αποσταλέντων"; // "Request Transmitted documents";
      break;
   case 6:
      $rets = "Ακύρωση παραστατικού"; // "Cancel Invoice";
      break;
   default:
      $rets = "$rectype# unknown type";
      break;
   }
   return $rets;
}
//--------------------------------------
function show_myrecord() // #73
{
   global $x2;
   $db=&$x2->db;

   $rid = (int)@$_REQUEST['RECORDID'];

   // HEADER
   $tarray=array(
		array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(71)', 1, 'Agents'),
		array('javascript:goTo(70)', 1, 'myDATA (dates)'),
      array('javascript:goTo(72)', 1, 'Records'),
      array('', 1, 'Record #'.$rid)
		);
   $x2->make_header($tarray);
}
//--------------------------------------
function show_mydata_w_filter()
{
   switch (@$_REQUEST['FIWHAT'])
   {
   case 1: // MARK
      return show_mydata_bymark();
   case 2:
      $_SESSION['DOCSERIES'] = (string)@$_REQUEST['DOCSERIES'];
      $_SESSION['DOCAA'] = (string)@$_REQUEST['DOCAA'];
      $_SESSION['FHMKEY'] = '';
      return show_mydata_date1();
   case 3:
      return show_mydata_rid();
   case 4: // FHMKEY
      $_SESSION['DOCSERIES'] = '';
      $_SESSION['DOCAA'] = '';
      $_SESSION['FHMKEY'] = (string)@$_REQUEST['FHMKEY'].'%';
      return show_mydata_date1();
   }
}
//--------------------------------------
function show_mydata_can()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
   $tarray=array(
		array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(71)', 1, 'Agents'),
		array('javascript:goTo(70)', 1, 'myDATA (dates)'),
      array('javascript:goTo(82)', 1, 'Ακυρωτικά(r)')
		);
   $x2->make_header($tarray);

   $myagentid = (int)@$_SESSION['MYAGENTID'];

   $query = make_query_mydata_recs();
   $query .= " LEFT JOIN mydata C2 ON C2.RID=T1.XFLAG
					LEFT JOIN mydata C3 ON (C3.AGENTID=C2.AGENTID AND C3.OWNOTHER=1 AND C3.RECTYPE=6 AND C3.XMLTOSEND=C2.MARK)
					WHERE T1.AGENTID=? AND T1.OWNOTHER=1 AND T1.MARK IS NULL AND T1.XFLAG IS NOT NULL AND C3.RID IS NULL
					ORDER BY T1.RID";
   $data = [$myagentid];

   $epage = do_show_mydata_recs($query, $data, true);

   echo "<div id=tbar2>";
   $pg=getPage();
   print_page_navEx($pg,$epage,82);
   echo '<button type=button class=NavButton onclick="onFilter()" title="Εφαρμογή φίλτρου"><img src="/img/filter.png"></button>';
   echo '<button type=button onclick="ask_for_del()">Διαγραφή όλων των επιλεγμένων</button>';
   echo "</div>";
}
//--------------------------------------
function show_mydata_rid()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
   $tarray=array(
		array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(71)', 1, 'Agents'),
		array('javascript:goTo(70)', 1, 'myDATA (dates)'),
      array('javascript:goTo(72)', 1, 'Records'),
      array('', 1, 'RID')
		);
   $x2->make_header($tarray);

   $myagentid = (int)@$_SESSION['MYAGENTID'];

   $query = make_query_mydata_recs();
   $query .= " WHERE T1.AGENTID=? AND T1.OWNOTHER=1 AND T1.RID=? ";
   $data = [$myagentid, $_REQUEST['MYRID'] ];

   $epage = do_show_mydata_recs($query, $data);

   echo "<div id=tbar2>";
   $pg=getPage();
   print_page_navEx($pg,$epage,72);
   echo '<button type=button class=NavButton onclick="onFilter()" title="Εφαρμογή φίλτρου"><img src="/img/filter.png"></button>';
   echo "</div>";
}
//--------------------------------------
function show_mydata_err_vat()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
   $tarray=array(
		array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(71)', 1, 'Agents'),
		array('javascript:goTo(70)', 1, 'myDATA (dates)'),
      array('javascript:goTo(79)', 1, 'Πρόβλημα ΑΦΜ(r)')
		);
   $x2->make_header($tarray);

   $myagentid = (int)@$_SESSION['MYAGENTID'];

   $query = make_query_mydata_recs();
   $query .= " WHERE T1.RID IN (SELECT RID FROM mydata ".
             " WHERE MARK IS NULL AND T1.AGENTID=? AND T1.OWNOTHER=1 AND RETDATA LIKE '%Invalid Greek VAT number%' )";
   $data = [$myagentid];

   $epage = do_show_mydata_recs($query, $data);

   echo "<div id=tbar2>";
   $pg=getPage();
   print_page_navEx($pg,$epage,79);
   echo '<button type=button class=NavButton onclick="onFilter()" title="Εφαρμογή φίλτρου"><img src="/img/filter.png"></button>';
   echo "</div>";
}
//--------------------------------------
function show_mydata_bymark()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
   $tarray=array(
		array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(71)', 1, 'Agents'),
		array('javascript:goTo(70)', 1, 'myDATA (dates)'),
      array('javascript:goTo(72)', 1, 'Records'),
      array('', 1, 'MARK')
		);
   $x2->make_header($tarray);

   $myagentid = (int)@$_SESSION['MYAGENTID'];

   $query = make_query_mydata_recs();
   $query .= " WHERE T1.AGENTID=? AND T1.OWNOTHER=1 AND MARK=? ".
             " ORDER BY T1.RECTYPE, T1.SUBMISSION, T1.RID";
   $data = [$myagentid, $_REQUEST['MYMARK'] ];

   $epage = do_show_mydata_recs($query, $data);

   echo "<div id=tbar2>";
   $pg=getPage();
   print_page_navEx($pg,$epage,72);
   echo '<button type=button class=NavButton onclick="onFilter()" title="Εφαρμογή φίλτρου"><img src="/img/filter.png"></button>';
   echo "</div>";
}
//--------------------------------------
function cre_mycancel_rec()
{
   global $x2;
   $db=&$x2->db;

   if (!MyEditRightsOk())
      return;

   $rid = (int)($_REQUEST['RECORDID'] ?? 0);

   // Read document to be canceled
   //
   $query = 'SELECT MARK, RECTYPE, AGENTID, OWNOTHER, CONVERT(VARCHAR, SUBMISSION, 120) AS SUBMISSION FROM mydata WHERE RID=?';
   $data = array($rid);
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__.' '.$db->ErrorMsg();
      return;
   }
   $o1 = $rs->FetchNextObject();
   $rs->Close();
   if ($o1 === false) {
      echo "<div class=UMessage>Record Id $rid disappeared!</div>";
      return;
   }
   else if (strlen($o1->RECTYPE) != 1) {
      echo "<div class=UMessage>Ακατάλληλος τύπος εγγραφής (RID=$rid), μόνο πωλήσεις επιτρέπονται!</div>";
      return;
   }
   else if (strlen($o1->MARK) == 0) {
      echo "<div class=UMessage>Η εγγραφή $rid δεν έχει πάρει MARK, δεν μπορεί να γίνει ακύρωση!</div>";
      return;
   }

   // Check if cancelation record already exists
   //
   $query = 'SELECT COUNT(*) FROM mydata WHERE AGENTID=? AND RECTYPE=6 AND XMLTOSEND=?';
   $data = array($o1->AGENTID, $o1->MARK);
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__.' '.$db->ErrorMsg();
      return;
   }
   $row = $rs->FetchRow();
   $rs->Close();
   if ($row[0] > 0) {
      echo '<div class=UMessage>Ηδη έχει δοθεί για ακύρωση!</div>';
      return;
   }

   // Create cancelation rec
   //
   $fhm = 'CAN.' .$o1->MARK;
   $query = 'INSERT INTO mydata (AGENTID, OWNOTHER, RECTYPE, FHMKEY, XMLTOSEND, CREDAYTIME, SUBMISSION) VALUES(?,?,6,?,  ?,?,?)';
   $data = array($o1->AGENTID, $o1->OWNOTHER, $fhm, $o1->MARK, date('Y-m-d H:i:s'), $o1->SUBMISSION);
   if (!$db->Execute($query, $data)) {
      echo '<div class=UMessage>Database INSERT error!</div>';
   }
   else {
      $query = 'SELECT @@IDENTITY'; // do not use SCOPE_IDENTITY()
      if (($rs=$db->Execute($query))!==false) {
         if (($row = $rs->FetchRow())!==false) {
            $rid2 = $row[0];
         }
         $rs->Close();
      }
      echo '<div class=UMessage>Did insert record '.$rid2.' for FHMKEY '.$fhm.'</div>';
   }
}
//--------------------------------------
function del_my_rec_group()
{
   global $x2;
   $db=&$x2->db;

   if (!MyEditRightsOk())
      return;

   //pre($_REQUEST);
   delete_my_rid_array($_REQUEST['CBK']);
}
//--------------------------------------
function del_my_rec()
{
   global $x2;
   $db=&$x2->db;

   if (!MyEditRightsOk())
      return;

   if (empty($_REQUEST['RECORDID'])) {
      echo '<div class=UMessage>Λείπει η παράμετρος (record Id)!</div>';
      return;
   }

   $rid = (int)$_REQUEST['RECORDID'];
   delete_my_rid_array([$rid]);
}
//--------------------------------------
function delete_my_rid_array($arids)
{
   global $x2;
   $db=&$x2->db;

   $rdel = array();

   $query = 'SELECT RID, MARK FROM mydata WHERE RID IN ('.implode(',', $arids).')';
   if (($rs=$db->Execute($query))===false) {
      echo __LINE__.' '.$db->ErrorMsg();
      return;
   }
   while ($o1 = $rs->FetchNextObject()) {
      if (strlen($o1->MARK) > 0) {
         echo '<div class=UMessage>Η εγγραφή '.$o1->RID.' έχει πάρει MARK, δεν μπορεί να γίνει διαγραφή!</div>';
      }
      else {
         $rdel[] = $o1->RID;
      }
   }
   $rs->Close();
   if (empty($rdel)) {
      echo '<div class=UMessage>Δεν υπάρχουν εγγραφές για διαγραφή!</div>';
      return;
   }

   $db->StartTrans();
   do {
      $query = 'DELETE FROM mydata WHERE RID IN ('.implode(',', $rdel).')';
      if (!$db->Execute($query)) {
         echo __LINE__.' '.$db->ErrorMsg();
         break;
      }

      $query = 'DELETE FROM myprop WHERE RID IN ('.implode(',', $rdel).')';
      if (!$db->Execute($query)) {
         echo __LINE__.' '.$db->ErrorMsg();
         break;
      }
   } while (false);
   $db->CompleteTrans();
}
//--------------------------------------
function UpdateMyMatch($rid, $afm, $country, $cname)
{
   // Match problematic AFM with the right one, plus country info etc.
   //
   global $x2;
   $db=&$x2->db;

   $agentid = 0;
   $count = 0;

   $query = "SELECT AGENTID FROM mydata WHERE RID=$rid";
   if (($rs=$db->Execute($query))===false) {
      echo __LINE__.' '.$db->ErrorMsg();
      return;
   }
   $row = $rs->FetchRow();
   $rs->Close();
   if ($row===false) {
      umessage("Agentid not found for RID=$rid");
      return;
   }
   // else:
   $agentid = $row[0];

   $query = "SELECT COUNT(*) FROM mymatch WHERE AGENTID=$agentid AND MYMODEL=0 AND MATCHSRC=?";
   $data = [$afm];
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__.' '.$db->ErrorMsg();
      return;
   }
   $row = $rs->FetchRow();
   $rs->Close();
   if ($row===false) {
      umessage("Could not read mymatch!");
      return;
   }
   // else:
   $count = $row[0];

   if ($count > 0)
   {
      $query = "UPDATE mymatch SET VALUE1=?, VALUE2=? ".
         " WHERE AGENTID=$agentid AND MYMODEL=0 AND MATCHSRC=?";
      $data = [$country, $cname, $afm];
   }
   else
   {
      $query = "INSERT INTO mymatch (AGENTID, MYMODEL, MATCHSRC, VALUE1, VALUE2) ".
         " VALUES($agentid, 0, ?, ?, ?)";
      $data = [$afm, $country, $cname];
   }
   if (!$db->Execute($query, $data)) {
      echo __LINE__.' '.$db->ErrorMsg();
	  return;
   }
   echo '<div class=UMessage>Records updated: '.$db->affected_rows().'</div>';
}
//--------------------------------------
function reset_myrecord() // 85:
{
   global $x2;
   $db=&$x2->db;

   if (!MyEditRightsOk())
      return;

   $rid = (int)$_REQUEST['RECORDID'];

   $query = 'UPDATE mydata SET /*XMLTOSEND=NULL,*/ RETVAL=NULL, RETDATA=NULL
		WHERE RID=? AND MARK IS NULL AND (RETDATA IS NULL OR RETDATA NOT LIKE \'%invoiceMark%\')';
   $data = array($rid);
   if (!$db->Execute($query, $data)) {
      echo __LINE__.' '.$db->ErrorMsg();
		return;
   }
	echo '<div class=UMessage>Records updated for RID('.$rid.'): '.$db->affected_rows().'</div>';
}
//--------------------------------------
function update_myrecord()
{
   global $x2;
   $db=&$x2->db;

   if (!MyEditRightsOk())
      return;

   $rid = (int)$_REQUEST['RID'];

   if (empty($_SESSION['MYAGENTID'])) {
      echo '<div class=UMessage>myDATA agent (MYAGENTID) not defined!</div>';
      return;
   }

   if (empty($_SESSION['MYDATE'])) {
      echo '<div class=UMessage>Date (MYDATE) not defined!</div>';
      return;
   }

   $props = array();
   foreach ($_REQUEST as $key=>$val) {
      if (substr($key, 0 , 3) === 'my/') {
         if (strlen($val) > 0) {
            $key2 = strtr(substr($key, 3), '-_', './');
            $props[$key2] = $val;
         }
      }
   }

   if (array_key_exists(($k1 = 'counterpart/country'), $props)) {
      $country = $props[$k1]; // counterpart
      if (!empty($country) && $country !== 'GR') {
         if (array_key_exists(($k1 = 'counterpart/vatNumber'), $props)) {
            $afm = $props[$k1];
            if (!empty($afm)) {
               if (array_key_exists(($k1 = 'counterpart/name'), $props)) {
                  $cname = $props[$k1];
               }
               else {
                  $cname = '';
               }
               //echo 'About to update...';
               UpdateMyMatch($rid, $afm, $country, $cname);
            }
         }
      }
   }

   $db->StartTrans();
   do {
      if ($rid==0) { // new record
         // Find a non-existing FHMKEY
         //
         $aa = 0;
         do {
            $fhm = 'USER.'.time().'.'.(++$aa);
            $query = 'SELECT COUNT(*) FROM mydata WHERE WHERE RECTYPE=1 AND FHMKEY=?';
            $data = array($fhm);
            if (($rs=$db->Execute($query, $data))===false) {
               echo __LINE__.' '.$db->ErrorMsg();
               return;
            }
            $row = $rs->FetchRow();
            $rs->Close();
         } while ($row[0] > 0);

         $query = 'INSERT INTO mydata (AGENTID, OWNOTHER, RECTYPE, FHMKEY, CREDAYTIME, SUBMISSION) VALUES(?,1,1,?,  ?,?)';
         $data = array((int)$_SESSION['MYAGENTID'], $fhm, date('Y-m-d H:i:s'), $_SESSION['MYDATE']);
         if (!$db->Execute($query, $data)) {
            echo __LINE__.' '.$db->ErrorMsg();
            break;
         }
         $query = 'SELECT @@IDENTITY'; // do not use SCOPE_IDENTITY()
         if (($rs=$db->Execute($query))===false) {
            echo __LINE__.' '.$db->ErrorMsg();
            break;
         }
         $row = $rs->FetchRow();
         $rs->Close();
         $rid = $row[0];
      }
      else { // update existing record
         $query = 'UPDATE mydata SET XMLTOSEND=NULL, RETDATA=NULL WHERE RID=?';
         $data = array($rid);
         if (!$db->Execute($query, $data)) {
            echo __LINE__.' '.$db->ErrorMsg();
            break;
         }
      }

      $query = 'DELETE FROM myprop WHERE RID=?';
      $data = array($rid);
      if (!$db->Execute($query, $data)) {
         echo $db->ErrorMsg();
         break;
      }

      $query = '';
      $data = array();
      foreach ($props as $key=>$val) {
         if (empty($query))
            $query = 'INSERT INTO myprop (RID, PNAME, PVALUE) VALUES';
         else
            $query .= ', ';

         $query .= '(?,?,?)';
         array_push($data, $rid, $key, $val);
      }
      if (!$db->Execute($query, $data)) {
         echo $db->ErrorMsg();
         break;
      }
   } while (false);
   $db->CompleteTrans();
}
//--------------------------------------
function draw_datalist_1($id, $ar1)
{
   echo "<datalist id=\"$id\">\n";
   foreach ($ar1 as $val) {
      echo "<option value=\"".myhtml($val)."\">\n";
   }
   echo "</datalist>\n";
}
//--------------------------------------
function draw_incomeClassificationType()
{
   $ar1 = [
      "E3_106 Ιδιοπαραγωγή παγίων - Αυτοπαραδόσεις - Καταστροφές αποθεμάτων/Εμπορεύματα",
      "E3_205 Ιδιοπαραγωγή παγίων - Αυτοπαραδόσεις - Καταστροφές αποθεμάτων/Πρώτες ύλες και λοιπά υλικά",
      "E3_210 Ιδιοπαραγωγή παγίων - Αυτοπαραδόσεις - Καταστροφές αποθεμάτων/Προϊόντα και παραγωγή σε εξέλιξη",
      "E3_305 Ιδιοπαραγωγή παγίων - Αυτοπαραδόσεις  Καταστροφές αποθεμάτων/Πρώτες ύλες και λοιπά υλικά",
      "E3_310 Ιδιοπαραγωγή παγίων - Αυτοπαραδόσεις - Καταστροφές αποθεμάτων/Προϊόντα και παραγωγή σε εξέλιξη",
      "E3_318 Ιδιοπαραγωγή παγίων - Αυτοπαραδόσεις - Καταστροφές αποθεμάτων/Έξοδα παραγωγής",
      "E3_561_001 Πωλήσεις αγαθών και υπηρεσιών Χονδρικές - Επιτηδευματιών",
      "E3_561_002 Πωλήσεις αγαθών και υπηρεσιών Χονδρικές βάσει άρθρου 39α παρ 5 του Κώδικα Φ.Π.Α. (Ν.2859/2000)",
      "E3_561_003 Πωλήσεις αγαθών και υπηρεσιών Λιανικές - Ιδιωτική Πελατεία",
      "E3_561_004 Πωλήσεις αγαθών και υπηρεσιών Λιανικές βάσει άρθρου 39α παρ 5 του Κώδικα Φ.Π.Α. (Ν.2859/2000)",
      "E3_561_005 Πωλήσεις αγαθών και υπηρεσιών Εξωτερικού Ενδοκοινοτικές",
      "E3_561_006 Πωλήσεις αγαθών και υπηρεσιών Εξωτερικού Τρίτες Χώρες",
      "E3_561_007 Πωλήσεις αγαθών και υπηρεσιών Λοιπά",
      "E3_562 Λοιπά συνήθη έσοδα",
      "E3_563 Πιστωτικοί τόκοι και συναφή έσοδα",
      "E3_564 Πιστωτικές συναλλαγματικές διαφορές",
      "E3_565 Έσοδα συμμετοχών",
      "E3_566 Κέρδη από διάθεση μη κυκλοφορούντων περιουσιακών στοιχείων",
      "E3_567 Κέρδη από αναστροφή προβλέψεων και απομειώσεων",
      "E3_568 Κέρδη από επιμέτρηση στην εύλογη αξία",
      "E3_570 Ασυνήθη έσοδα και κέρδη",
      "E3_595 Έξοδα σε ιδιοπαραγωγή",
      "E3_596 Επιδοτήσεις - Επιχορηγήσεις",
      "E3_597 Επιδοτήσεις - Επιχορηγήσεις για επενδυτικούς σκοπούς - κάλυψη δαπανών",
      "E3_880_001 Πωλήσεις Παγίων Χονδρικές",
      "E3_880_002 Πωλήσεις Παγίων Λιανικές",
      "E3_880_003 Πωλήσεις Παγίων Εξωτερικού Ενδοκοινοτικές",
      "E3_880_004 Πωλήσεις Παγίων Εξωτερικού Τρίτες Χώρες",
      "E3_881_001 Πωλήσεις για λογ/σμο Τρίτων Χονδρικές",
      "E3_881_002 Πωλήσεις για λογ/σμο Τρίτων Λιανικές",
      "E3_881_003 Πωλήσεις για λογ/σμο Τρίτων Εξωτερικού Ενδοκοινοτικές",
      "E3_881_004 Πωλήσεις για λογ/σμο Τρίτων Εξωτερικού Τρίτες Χώρες"
   ];
   draw_datalist_1('incomeClassificationType', $ar1);
}
//--------------------------------------
function draw_incomeClassificationCategory()
{
   $ar1 = [
      "category1_1 Έσοδα από Πώληση Εμπορευμάτων (+) / (-)",
      "category1_2 Έσοδα από Πώληση Προϊόντων (+) / (-)",
      "category1_3 Έσοδα από Παροχή Υπηρεσιών (+) / (-)",
      "category1_4 Έσοδα από Πώληση Παγίων (+) / (-)",
      "category1_5 Λοιπά Έσοδα/ Κέρδη (+) / (-)",
      "category1_6 Αυτοπαραδόσεις / Ιδιοχρησιμοποιήσεις (+) / (-)",
      "category1_7 Έσοδα για λ/σμο τρίτων (+) / (-)",
      "category1_8 Έσοδα προηγούμενων χρήσεων (+)/ (-)",
      "category1_9 Έσοδα επομένων χρήσεων (+) / (-)",
      "category1_10 Λοιπές Εγγραφές Τακτοποίησης Εσόδων (+) / (-)",
      "category1_95 Λοιπά Πληροφοριακά Στοιχεία Εσόδων (+) / (-)"
   ];
   draw_datalist_1('incomeClassificationCategory', $ar1);
}
//--------------------------------------
function draw_countryList()
{
   $ar1 = [
      "GR Greece",
      "AF Afghanistan",
      "AL Albania",
      "DZ Algeria",
      "AS American Samoa",
      "AD Andorra",
      "AO Angola",
      "AI Anguilla",
      "AQ Antarctica",
      "AG Antigua and Barbuda",
      "AR Argentina",
      "AM Armenia",
      "AW Aruba",
      "AU Australia",
      "AT Austria",
      "AZ Azerbaijan",
      "BS Bahamas (the)",
      "BH Bahrain",
      "BD Bangladesh",
      "BB Barbados",
      "BY Belarus",
      "BE Belgium",
      "BZ Belize",
      "BJ Benin",
      "BM Bermuda",
      "BT Bhutan",
      "BO Bolivia (Plurinational State of)",
      "BQ Bonaire, Sint Eustatius and Saba)",
      "BA Bosnia and Herzegovina",
      "BW Botswana",
      "BV Bouvet Island",
      "BR Brazil",
      "IO British Indian Ocean Territoty (the)",
      "BN Brunei Darussalam",
      "BG Bulgaria",
      "BF Burkina Faso",
      "BI Burundi",
      "CV Cabo Verde",
      "KH Cambodia",
      "CM Cameroon",
      "CA Canada",
      "KY Cayman Islands (the)",
      "CF Central African Republic (the)",
      "TD Chad",
      "CL Chile",
      "CN China",
      "CX Christmas Island",
      "CC Cocos (Keelinng) Island (the)",
      "CO Colombia",
      "KM Comoros (the)",
      "AX Aland Islands",
      "CD Congo (the Democratic Republic of the)",
      "CG Congo (the)",
      "CK Cook Islands (the)",
      "CR Costa Rica",
      "HR Croatia",
      "CU Cuba",
      "CW Curacao",
      "CY Cyprus",
      "CZ Czechia",
      "CI Cote D lvoire",
      "DK Denmark",
      "DJ Djibuti",
      "DM Dominica",
      "DO Dominican Republic (the)",
      "EC Ecuador",
      "EG Egypt",
      "SV El Salvador",
      "GQ Equatorial Guinea",
      "ER Eritrea",
      "EE Estonia",
      "SZ Eswatini",
      "ET Ethiopia",
      "FK Falkland Islands (the) [Malvinas]",
      "FO Faroe Islands (the)",
      "FJ Fiji",
      "FI Finland",
      "FR France",
      "GF French Guiana",
      "PF French Polynesia",
      "TF French Southern Territories (the)",
      "GA Gabon",
      "GM Gambia (the)",
      "GE Georgia",
      "DE Germany",
      "GH Ghana",
      "GI Gibraltar",
      "GL Greenland",
      "GD Grenada",
      "GP Guadeloupe",
      "GU Guam",
      "GT Guatemala",
      "GG Guernsey",
      "GN Guinea",
      "GW Guinea - Bissau",
      "GY Guyana",
      "HT Haiti",
      "HM Heard Island and McDonald Islands",
      "VA Holy See (the)",
      "HN Honduras",
      "HK Hong Kong",
      "HU Hungary",
      "IS Iceland",
      "IN India",
      "ID Indonesia",
      "IR Iran (Islamic Republic of)",
      "IQ Iraq",
      "IE Ireland",
      "IM Isle of Man",
      "IL Israel",
      "IT Italy",
      "JM Jamaica",
      "Jp Japan",
      "JE Jersey",
      "JO Jordan",
      "KZ Kazakhstan",
      "KE Kenya",
      "KI Kiribati",
      "KP Korea (the Democratic people's Republic of)",
      "KR Korea (the Republic of)",
      "KW Kuwait",
      "KZ Kyrgyzstan",
      "LA Lao People's Democratic Republic (the)",
      "LV Latvia",
      "LB Lebanon",
      "LS Lesotho",
      "LR Liberia",
      "LY Libya",
      "LI Liechtenstein",
      "LT Lithuania",
      "LU Luxenbourg",
      "MO Macao",
      "MG Madagascar",
      "MW Malawi",
      "MY Malaysia",
      "MV Maldives",
      "ML Mali",
      "MT Malta",
      "MH Marshall Islands (the)",
      "MQ Martinique",
      "MR Mauritania",
      "MU Mauritious",
      "YT Mayotte",
      "MX Mexico",
      "FM Micronesia (federated States of)",
      "MD Moldova (the Republic of)",
      "MC Monaco",
      "MN Mongolia",
      "ME Montenegro",
      "MS Montserrat",
      "MA Morocco",
      "MZ Mozampique",
      "MM Myanmar",
      "NA Namibia",
      "NR Nauru",
      "NP Nepal",
      "NL Netherlands (the)",
      "NC New Caledonia",
      "NZ New Zealand",
      "NI Nicaragua",
      "NE Niger (the)",
      "NG Nigeria",
      "Nu Niue",
      "NF Norfolk Island",
      "MK North Macedonia",
      "MP Northern Mariana Islands  (the)",
      "NO Norway",
      "OM Oman",
      "PK Pakistan",
      "PW Palau",
      "PS Palestine,State of",
      "PA Panama",
      "PG Papua New Guinea",
      "PY Paraguay",
      "PE Peru",
      "PH Philippines",
      "PN Pitcairn",
      "PL Poland",
      "PT Portugal",
      "PR Puerto Rico",
      "QA Qatar",
      "RO Romania",
      "RU Russian Federation (the)",
      "RW Rwanda",
      "RE Reunion",
      "BL Saint Barthelemy",
      "SH Saint Helena, Ascension and Tristan da Cunha",
      "KN Saint Kitts and Nevis",
      "LC Saint Lucia",
      "MF Saint Martin (French part)",
      "PM Saint Pierre and Miquelon",
      "VC Saint Vincent and the Grenadines",
      "WS Samoa",
      "SM San Marino",
      "ST Sao Tome and Principe",
      "SA Saudi Arabia",
      "SN Senegal",
      "RS Serbia",
      "SC Seychelles",
      "SL Sierra Leone",
      "SG Singapore",
      "SX Sint Maarten (Dutch part)",
      "SK Slovakia",
      "SI Slovenia",
      "SB Solomon Islands",
      "SO Somalia",
      "ZA South Africa",
      "GS South Georgia and the South Sandwich Islands",
      "SS South Sudan",
      "ES Spain",
      "LK Sri Lanka",
      "SD Sudan (the)",
      "SR Suriname",
      "SJ Svalbard and Jan Mayen",
      "SE Sweden",
      "CH Switzerland",
      "SY Syrian Arab Republic (the)",
      "TW Taiwan (Province of China)",
      "TJ Tajikistan",
      "TZ Tanzania, the United Republic of",
      "TH Thailand",
      "TL Timor-Leste",
      "TG Togo",
      "TK Tokelau",
      "TO Tonga",
      "TT Trinidad and Tobago",
      "TN Tunisia",
      "TR Turkey",
      "TM Turkmenistan",
      "TC Turks and Caicos Islands (the)",
      "TV Tuvalu",
      "UG Uganda",
      "UA Ukraine",
      "AE United Arab Emirates (the)",
      "GB United Kinkdom of Great Britain and Northern Ireland",
      "UM United States Minor Outlying Isands (the)",
      "US United States of America (the)",
      "UY Uruguay",
      "UZ Uzbekistan",
      "VU Vanuatu",
      "VE Venezuela (Bolivarian Republic of)",
      "VN Viet Nam",
      "VG Virgin Islands (British)",
      "VI Virgin Islands (U.S.)",
      "WF Wallis and Fortuna",
      "EH Western Sahara",
      "YE Yemen",
      "ZM Zambia",
      "ZW Zimbabwe"
   ];
   draw_datalist_1('countryList', $ar1);
}
//--------------------------------------
function draw_datalists()
{
   draw_countryList();

   draw_incomeClassificationType();

   draw_incomeClassificationCategory();

   $ar1 = [
      "E3_101 Εμπορεύματα έναρξης",
      "E3_102_001 Αγορές εμπορευμάτων χρήσης (καθαρό ποσό)/Χονδρικές",
      "E3_102_002 Αγορές εμπορευμάτων χρήσης (καθαρό ποσό)/Λιανικές",
      "E3_102_003 Αγορές εμπορευμάτων χρήσης (καθαρό ποσό)/Αγαθών του άρθρου 39α παρ.5 του Κώδικα Φ.Π.Α. (ν.2859/2000)",
      "E3_102_004 Αγορές εμπορευμάτων χρήσης (καθαρό ποσό)/Εξωτερικού Ενδοκοινοτικές",
      "E3_102_005 Αγορές εμπορευμάτων χρήσης (καθαρό ποσό)/Εξωτερικού Τρίτες Χώρες",
      "E3_102_006 Αγορές εμπορευμάτων χρήσης (καθαρό ποσό)Λοιπά",
      "E3_104 Εμπορεύματα λήξης",
      "E3_201 Πρώτες ύλες και υλικά έναρξης/Παραγωγή",
      "E3_202_001 Αγορές πρώτων υλών και υλικών χρήσης (καθαρό ποσό)/Χονδρικές",
      "E3_202_002 Αγορές πρώτων υλών και υλικών χρήσης (καθαρό ποσό)/Λιανικές",
      "E3_202_003 Αγορές πρώτων υλών και υλικών χρήσης (καθαρό ποσό)/Εξωτερικού Ενδοκοινοτικές",
      "E3_202_004 Αγορές πρώτων υλών και υλικών χρήσης (καθαρό ποσό)/Εξωτερικού Τρίτες Χώρες",
      "E3_202_005 Αγορές πρώτων υλών και υλικών χρήσης (καθαρό ποσό)/Λοιπά",
      "E3_204 Αποθέματα λήξης πρώτων υλών και υλικών/Παραγωγή",
      "E3_207 Προϊόντα και παραγωγή σε εξέλιξη έναρξης/Παραγωγή",
      "E3_209 Προϊόντα και παραγωγή σε εξέλιξη λήξης/Παραγωγή",
      "E3_301 Πρώτες ύλες και υλικά έναρξης/Αγροτική",
      "E3_302_001 Αγορές πρώτων υλών και υλικών χρήσης (καθαρό ποσό)/Χονδρικές",
      "E3_302_002 Αγορές πρώτων υλών και υλικών χρήσης (καθαρό ποσό)/Λιανικές",
      "E3_302_003 Αγορές πρώτων υλών και υλικών χρήσης (καθαρό ποσό)/Εξωτερικού Ενδοκοινοτικές",
      "E3_302_004 Αγορές πρώτων υλών και υλικών χρήσης (καθαρό ποσό)/Εξωτερικού Τρίτες Χώρες",
      "E3_302_005 Αγορές πρώτων υλών και υλικών χρήσης (καθαρό ποσό)/Λοιπά",
      "E3_304 Αποθέματα λήξης πρώτων υλών και υλικών/Αγροτική",
      "E3_307 Προϊόντα και παραγωγή σε εξέλιξη έναρξης/Αγροτική",
      "E3_309 Προϊόντα και παραγωγή σε εξέλιξη λήξης/Αγροτική",
      "E3_312 Αποθέματα έναρξης (ζώων - φυτών)",
      "E3_313_001 Αγορές ζώων - φυτών (καθαρό ποσό)/Χονδρικές",
      "E3_313_002 Αγορές ζώων - φυτών (καθαρό ποσό)/Λιανικές",
      "E3_313_003 Αγορές ζώων - φυτών (καθαρό ποσό)/Εξωτερικού Ενδοκοινοτικές",
      "E3_313_004 Αγορές ζώων - φυτών (καθαρό ποσό)/Εξωτερικού Τρίτες Χώρες",
      "E3_313_005 Αγορές ζώων - φυτών (καθαρό ποσό)/Λοιπά",
      "E3_315 Αποθέματα τέλους (ζώων - φυτών)/Αγροτική",
      "E3_581_001 Παροχές σε εργαζόμενους/Μικτές αποδοχές",
      "E3_581_002 Παροχές σε εργαζόμενους/Εργοδοτικές εισφορές",
      "E3_581_003 Παροχές σε εργαζόμενους/Λοιπές παροχές",
      "E3_582 Ζημιές επιμέτρησης περιουσιακών στοιχείων",
      "E3_583 Χρεωστικές συναλλαγματικές διαφορές",
      "E3_584 Ζημιές από διάθεση-απόσυρση μη κυκλοφορούντων περιουσιακών στοιχείων",
      "E3_585_001 Προμήθειες διαχείρισης ημεδαπής - αλλοδαπής (management fees)",
      "E3_585_002 Δαπάνες από συνδεδεμένες επιχειρήσεις",
      "E3_585_003 Δαπάνες από μη συνεργαζόμενα κράτη ή από κράτη με προνομιακό φορολογικό καθεστώς",
      "E3_585_004 Δαπάνες για ενημερωτικές ημερίδες",
      "E3_585_005 Έξοδα υποδοχής και φιλοξενίας",
      "E3_585_006 Έξοδα ταξιδιών",
      "E3_585_007 Ασφαλιστικές Εισφορές Αυτοαπασχολούμενων",
      "E3_585_008 Έξοδα και προμήθειες παραγγελιοδόχου για λογαριασμό αγροτών",
      "E3_585_009 Λοιπές Αμοιβές για υπηρεσίες ημεδαπής",
      "E3_585_010 Λοιπές Αμοιβές για υπηρεσίες αλλοδαπής",
      "E3_585_011 Ενέργεια",
      "E3_585_012 Ύδρευση",
      "E3_585_013 Τηλεπικοινωνίες",
      "E3_585_014 Ενοίκια",
      "E3_585_015 Διαφήμιση και προβολή",
      "E3_585_016 Λοιπά έξοδα",
      "E3_586 Χρεωστικοί τόκοι και συναφή έξοδα",
      "E3_587 Αποσβέσεις",
      "E3_588 Ασυνήθη έξοδα, ζημιές και πρόστιμα",
      "E3_589 Προβλέψεις (εκτός από προβλέψεις για το προσωπικό)",
      "E3_882_001 Αγορές ενσώματων παγίων χρήσης/Χονδρικές",
      "E3_882_002 Αγορές ενσώματων παγίων χρήσης/Λιανικές",
      "E3_882_003 Αγορές ενσώματων παγίων χρήσης/Εξωτερικού Ενδοκοινοτικές",
      "E3_882_004 Αγορές ενσώματων παγίων χρήσης/Εξωτερικού Τρίτες Χώρες",
      "E3_883_001 Αγορές μη ενσώματων παγίων χρήσης/Χονδρικές",
      "E3_883_002 Αγορές μη ενσώματων παγίων χρήσης/Λιανικές",
      "E3_883_003 Αγορές μη ενσώματων παγίων χρήσης/Εξωτερικού Ενδοκοινοτικές",
      "E3_883_004 Αγορές μη ενσώματων παγίων χρήσης/Εξωτερικού Τρίτες Χώρες",
      "VAT_361 Αγορές & δαπάνες στο εσωτερικό της χώρας",
      "VAT_362 Αγορές & εισαγωγές επενδ. Αγαθών (πάγια)",
      "VAT_363 Λοιπές εισαγωγές εκτός επενδ. Αγαθών (πάγια)",
      "VAT_364 Ενδοκοινοτικές αποκτήσεις αγαθών",
      "VAT_365 Ενδοκοινοτικές λήψεις υπηρεσιών άρθρ. 14.2.α",
      "VAT_366 Λοιπές πράξεις λήπτη"
   ];
   draw_datalist_1('expenseClassificationType', $ar1);

   $ar1 = [ // expenseClassificationCategory
      "category2_1 Αγορές Εμπορευμάτων (-) / (+)",
      "category2_2 Αγορές Α'-Β' Υλών (-) / (+)",
      "category2_3 Λήψη Υπηρεσιών (-) / (+)",
      "category2_4 Γενικά Έξοδα με δικαίωμα έκπτωσης ΦΠΑ (-) / (+)",
      "category2_5 Γενικά Έξοδα χωρίς δικαίωμα έκπτωσης ΦΠΑ (-) / (+)",
      "category2_6 Αμοιβές και Παροχές προσωπικού (-) / (+)",
      "category2_7 Αγορές Παγίων (-) / (+)",
      "category2_8 Αποσβέσεις Παγίων (-) / (+)",
      "category2_9 Έξοδα για λ/σμο τρίτων (-) / (+)",
      "category2_10 Έξοδα προηγούμενων χρήσεων (-) / (+)",
      "category2_11 Έξοδα επομένων χρήσεων (-) / (+)",
      "category2_12 Λοιπές Εγγραφές Τακτοποίησης Εξόδων (-) / (+)",
      "category2_13 Αποθέματα Έναρξης Περιόδου (-) / (+)",
      "category2_14 Αποθέματα Λήξης Περιόδου (-) / (+)",
      "category2_95 Λοιπά Πληροφοριακά Στοιχεία Εξόδων (-) / (+)"
   ];
   draw_datalist_1('expenseClassificationCategory', $ar1);

   $ar1 = [ // taxType
      "1 Παρακρατούμενος Φόρος", // s_withheldPercentCategory
      "2 Τέλη",                  // s_feesPercentCategory
      "3 Λοιποί Φόροι",          // s_otherTaxesPercentCategory
      "4 Χαρτόσημο",             // s_stampDutyPercentCategory
      "5 Κρατήσεις"
   ];
   draw_datalist_1('taxType', $ar1);

   $ar1 = [ // measurementUnit
      "1 Τεμάχια", "2 Κιλά", "3 Λίτρα"
   ];
   draw_datalist_1('measurementUnit', $ar1);

   $ar1 = [ // invoiceDetailType
      "1 Εκκαθάριση Πωλήσεων Τρίτων", "2 Αμοιβή από Πωλήσεις Τρίτων"
   ];
   draw_datalist_1('invoiceDetailType', $ar1);

   $ar1 = [ // vatCategory
      "1 ΦΠΑ συντελεστής 24%",
      "2 ΦΠΑ συντελεστής 13%",
      "3 ΦΠΑ συντελεστής 6%",
      "4 ΦΠΑ συντελεστής 17%",
      "5 ΦΠΑ συντελεστής 9%",
      "6 ΦΠΑ συντελεστής 4%",
      "7 ’νευ Φ.Π.Α.",
      "8 Εγγραφές χωρίς ΦΠΑ (πχ Μισθοδοσία, Αποσβέσεις)"
   ];
   draw_datalist_1('vatCategory', $ar1);

   $ar1 = [ // vatExemptionCategory
      "1 Χωρίς ΦΠΑ - άρθρο 3 του Κώδικα ΦΠΑ - εταιρία ειδικού σκοπού διαχείρισης οικογενειακής περιουσίας",
      "2 Χωρίς ΦΠΑ - άρθρο 5 του Κώδικα ΦΠΑ - μεταβίβαση αγαθών επιχείρησης από επαχθή ή χαριστική αιτία ή με τη μορφή εισφοράς",
      "3 Χωρίς ΦΠΑ - άρθρο 13 του Κώδικα ΦΠΑ - παράδοση αγαθών εκτός χώρας",
      "4 Χωρίς ΦΠΑ - άρθρο 14 του Κώδικα ΦΠΑ - παράδοση υπηρεσιών εκτός χώρας",
      "5 Χωρίς ΦΠΑ - άρθρο 16 του Κώδικα ΦΠΑ - οριστική πράξη σε μεταγενέστερο χρόνο",
      "6 Χωρίς ΦΠΑ - άρθρο 19 του Κώδικα ΦΠΑ - εκπτώσεις και επιστροφές υπηρεσιών",
      "7 Χωρίς ΦΠΑ - άρθρο 22 του Κώδικα ΦΠΑ - απαλοσσόμενος εκδότης/είδη/υπηρεσίες",
      "8 Χωρίς ΦΠΑ - άρθρο 24 του Κώδικα ΦΠΑ - εξαγωγή εκτός Κοινότητας",
      "9 Χωρίς ΦΠΑ - άρθρο 25 του Κώδικα ΦΠΑ - Ενδοκοινοτικές/εξωκοινοτικές πράξεις",
      "10 Χωρίς ΦΠΑ - άρθρο 26 του Κώδικα ΦΠΑ - παράδοση σε φορολογική αποθήκη",
      "11 Χωρίς ΦΠΑ - άρθρο 27 του Κώδικα ΦΠΑ - περιπτώσεις πλοίων",
      "12 Χωρίς ΦΠΑ - άρθρο 27 - Πλοία Ανοικτής Θαλάσσης του Κώδικα ΦΠΑ",
      "13 Χωρίς ΦΠΑ - άρθρο 27.1.γ - Πλοία  Ανοικτής Θαλάσσης του Κώδικα ΦΠΑ",
      "14 Χωρίς ΦΠΑ - άρθρο 28 του Κώδικα ΦΠΑ - παράδοση αγαθών σε άλλο κράτος-μέλος",
      "15 Χωρίς ΦΠΑ - άρθρο 39 του Κώδικα ΦΠΑ - απαλοσσόμενος λήπτης λόγω τζίρου",
      "16 Χωρίς ΦΠΑ - άρθρο 39α του Κώδικα ΦΠΑ - ανακυκλώσιμα απορρίματα, ηλεκτρονικές συσκευές",
      "17 Χωρίς ΦΠΑ - άρθρο 40 του Κώδικα ΦΠΑ - κατ' αποκοπή υπολογισμός ΦΠΑ",
      "18 Χωρίς ΦΠΑ - άρθρο 41 του Κώδικα ΦΠΑ - Ειδικό καθεστώς αγροτών",
      "19 Χωρίς ΦΠΑ - άρθρο 47 του Κώδικα ΦΠΑ - Ειδικό καθεστώς επενδυτικού χρυσού",
      "20 ΦΠΑ εμπεριεχόμενος - άρθρο 43 του Κώδικα ΦΠΑ - Ειδικό καθεστώς πρακτορείων ταξιδιών",
      "21 ΦΠΑ εμπεριεχόμενος - άρθρο 44 του Κώδικα ΦΠΑ - Ειδικό καθεστώς φορολογίας βιομηχανοποιημένων καπνών",
      "22 ΦΠΑ εμπεριεχόμενος - άρθρο 45 του Κώδικα ΦΠΑ - μεταχειρισμένα αγαθά και αντικείμενα καλλιτεχνικής, συλλεκτικής ή αρχαιολογικής αξίας",
      "23 ΦΠΑ εμπεριεχόμενος - άρθρο 46 του Κώδικα ΦΠΑ - πωλήσεις σε δημοπρασία"
   ];
   draw_datalist_1('vatExemptionCategory', $ar1);

   $ar1 = [ // withheldPercentCategory
      "1 Περιπτ. β- Τόκοι - 15%",
      "2 Περιπτ. γ - Δικαιώματα - 20%",
      "3 Περιπτ. δ - Αμοιβές Συμβουλών Διοίκησης - 20%",
      "4 Περιπτ. δ - Τεχνικά Έργα - 3%",
      "5 Υγρά καύσιμα και προϊόντα καπνοβιομηχανίας 1%",
      "6 Λοιπά Αγαθά 4%",
      "7 Παροχή Υπηρεσιών 8%",
      "8 Προκαταβλητέος Φόρος Αρχιτεκτόνων και Μηχανικών επί Συμβατικών Αμοιβών, για Εκπόνηση Μελετών και Σχεδίων 4%",
      "9 Προκαταβλητέος Φόρος Αρχιτεκτόνων και Μηχανικών επί Συμβατικών Αμοιβών, που αφορούν οποιασδήποτε άλλης φύσης έργα 10%",
      "10 Προκαταβλητέος Φόρος στις Αμοιβές Δικηγόρων 15%",
      "11 Παρακράτηση Φόρου Μισθωτών Υπηρεσιών παρ. 1 αρ. 15 ν. 4172/2013 ποσό",
      "12 Παρακράτηση Φόρου Μισθωτών Υπηρεσιών παρ. 2 αρ. 15 ν. 4172/2013 - Αξιωματικών Εμπορικού Ναυτικού 15%",
      "13 Παρακράτηση Φόρου Μισθωτών Υπηρεσιών παρ. 2 αρ. 15 ν. 4172/2013 - Κατώτερο Πλήρωμα Εμπορικού Ναυτικού 10%",
      "14 Παρακράτηση Ειδικής Εισφοράς Αλληλεγγύης ποσό",
      "15 Παρακράτηση Φόρου Αποζημίωσης λόγω Διακοπής Σχέσης Εργασίας παρ. 3 αρ. 15 ν. 4172/2013"
   ];
   draw_datalist_1('withheldPercentCategory', $ar1);

   $ar1 = [ // stampDutyPercentCategory
      "1 Συντελεστής 1,20 %",
      "2 Συντελεστής 2,40 %",
      "3 Συντελεστής 3,60 %"
   ];
   draw_datalist_1('stampDutyPercentCategory', $ar1);

   $ar1 = [ // feesPercentCategory
      "1 Για μηνιαίο λογαριασμό μέχρι και 50 ευρώ 12%",
      "2 Για μηνιαίο λογαριασμό από 50,01 μέχρι και 100 ευρώ 15%",
      "3 Για μηνιαίο λογαριασμό από 100,01 μέχρι και 150 ευρώ 18%",
      "4 Για μηνιαίο λογαριασμό από 150,01 ευρώ και άνω 20%",
      "5 Τέλος καρτοκινητής επί της αξίας του χρόνου ομιλίας (12%)",
      "6 Τέλος στη συνδρομητική τηλεόραση 10%",
      "7 Τέλος συνδρομητών σταθερής τηλεφωνίας 5%",
      "8 Περιβαλλοντικό Τέλος & πλαστικής σακούλας ν. 2339/2001 αρ. 6α 0,07 ευρώ ανά τεμάχιο",
      "9 Εισφορά δακοκτονίας 2%"
   ];
   draw_datalist_1('feesPercentCategory', $ar1);

   $ar1 = [ // otherTaxesPercentCategory
      "1 α1) ασφάλιστρα κλάδου πυρός 20% 15%",
      "2 α2) ασφάλιστρα κλάδου πυρός 20% 5%",
      "3 β) ασφάλιστρα κλάδου ζωής 4%",
      "4 γ) ασφάλιστρα λοιπών κλάδων 15%",
      "5 δ) απαλλασσόμενα φόρου ασφαλίστρων 0%",
      "6 Ξενοδοχεία 1-2 αστέρων 0,50  ποσό",
      "7 Ξενοδοχεία 3 αστέρων 1,50  ποσό",
      "8 Ξενοδοχεία 4 αστέρων 3,00  ποσό",
      "9 Ξενοδοχεία 4 αστέρων 4,00  ποσό",
      "10 Ενοικιαζόμενα - επιπλωμένα δωμάτια - διαμερίσματα 0,50  ποσό",
      "11 Ειδικός Φόρος στις διαφημίσεις που προβάλλονται από την τηλεόραση (ΕΦΤΔ) 5%",
      "12 3.1 Φόρος πολυτελείας 10% επί της φορολογητέας αξίας για τα ενδοκοινοτικώς αποκτούμενα και εισαγόμενα από τρίτες χώρες 10%",
      "13 3.2 Φόρος πολυτελείας 10% επί της τιμής πώλησης προ Φ.Π.Α. για τα εγχωρίως παραγόμενα είδη 10%",
      "14 Δικαίωμα του Δημοσίου στα εισιτήρια των καζίνο (80% επί του εισιτηρίου)"
   ];
   draw_datalist_1('otherTaxesPercentCategory', $ar1);

   $ar1 = [ // invoiceType
      "1.1 Τιμολόγιο Πώλησης",
      "1.2 Τιμολόγιο Πώλησης / Ενδοκοινοτικές Παραδόσεις",
      "1.3 Τιμολόγιο Πώλησης / Παραδόσεις Τρίτων Χωρών",
      "1.4 Τιμολόγιο Πώλησης / Πώληση για Λογαριασμό Τρίτων",
      "1.5 Τιμολόγιο Πώλησης / Εκκαθάριση Πωλήσεων Τρίτων - Αμοιβή από Πωλήσεις Τρίτων",
      "1.6 Τιμολόγιο Πώλησης / Συμπληρωματικό Παραστατικό",
      "2.1 Τιμολόγιο Παροχής",
      "2.2 Τιμολόγιο Παροχής / Ενδοκοινοτική Παροχή Υπηρεσιών",
      "2.3 Τιμολόγιο Παροχής / Παροχή Υπηρεσιών σε λήπτη Τρίτης Χώρας",
      "2.4 Τιμολόγιο Παροχής / Συμπληρωματικό Παραστατικό",
      "3.1 Τίτλος Κτήσης (μη υπόχρεος Εκδότης)",
      "3.2 Τίτλος Κτήσης (άρνηση έκδοσης από υπόχρεο Εκδότη)",
      "5.1 Πιστωτικό Τιμολόγιο / Συσχετιζόμενο",
      "5.2 Πιστωτικό Τιμολόγιο / Μη Συσχετιζόμενο",
      "6.1 Στοιχείο Αυτοπαράδοσης",
      "6.2 Στοιχείο Ιδιοχρησιμοποίησης",
      "7.1 Συμβόλαιο - Έσοδο",
      "8.1 Ενοίκια - Έσοδο",
      "8.2 Ειδικό Στοιχείο  Απόδειξης Είσπραξης Φόρου Διαμονής",
      "11.1 ΑΛΠ",
      "11.2 ΑΠΥ",
      "11.3 Απλοποιημένο Τιμολόγιο",
      "11.4 Πιστωτικό Στοιχ. Λιανικής",
      "11.5 Απόδειξη Λιανικής Πώλησης για Λογ/σμό Τρίτων",
      "13.1 Έξοδα - Αγορές Λιανικών Συναλλαγών ημεδαπής / αλλοδαπής",
      "13.2 Παροχή Λιανικών Συναλλαγών ημεδαπής / αλλοδαπής",
      "13.3 Κοινόχρηστα",
      "13.4 Συνδρομές",
      "13.30 Παραστατικά Οντότητας ως Αναγράφονται από την ίδια (Δυναμικό)",
      "13.31 Πιστωτικό Στοιχ. Λιανικής ημεδαπής / αλλοδαπής",
      "14.1 Τιμολόγιο / Ενδοκοινοτικές Αποκτήσεις",
      "14.2 Τιμολόγιο / Αποκτήσεις Τρίτων Χωρών",
      "14.3 Τιμολόγιο / Ενδοκοινοτική Λήψη Υπηρεσιών",
      "14.4 Τιμολόγιο / Λήψη Υπηρεσιών Τρίτων Χωρών",
      "14.5 ΕΦΚΑ και λοιποί Ασφαλιστικοί Οργανισμοί",
      "14.30 Παραστατικά Οντότητας ως Αναγράφονται από την ίδια (Δυναμικό)",
      "14.31 Πιστωτικό ημεδαπής / αλλοδαπής",
      "15.1 Συμβόλαιο - Έξοδο",
      "16.1 Ενοίκιο Έξοδο",
      "17.1 Μισθοδοσία",
      "17.2 Αποσβέσεις",
      "17.3 Λοιπές Εγγραφές Τακτοποίησης Εσόδων - Λογιστική Βάση",
      "17.4 Λοιπές Εγγραφές Τακτοποίησης Εσόδων - Φορολογική Βάση",
      "17.5 Λοιπές Εγγραφές Τακτοποίησης Εξόδων - Λογιστική Βάση",
      "17.6 Λοιπές Εγγραφές Τακτοποίησης Εξόδων - Φορολογική Βάση"
   ];
   draw_datalist_1('invoiceType', $ar1);

   $ar1 = [ // movePurpose
      "1 Πώληση",
      "2 Πώληση για Λογαριασμό Τρίτων",
      "3 Δειγματισμός",
      "4 Έκθεση",
      "5 Επιστροφή",
      "6 Φύλαξη",
      "7 Επεξεργασία Συναρμολόγηση",
      "8 Μεταξύ Εγκαταστάσεων Οντότητας"
   ];
   draw_datalist_1('movePurpose', $ar1);

   $ar1 = [ // paymentType
      "1 Επαγ. Λογαριασμός Πληρωμών Ημεδαπής",
      "2 Επαγ. Λογαριασμός Πληρωμών Αλλοδαπής",
      "3 Μετρητά",
      "4 Επιταγή",
      "5 Επί Πιστώσει"
   ];
   draw_datalist_1('paymentType', $ar1);
}
//--------------------------------------
function MyEditRightsOk()
{
   global $x2;
   $db=&$x2->db;

   $reselid = $_SESSION['RESELID'] ?? 0;
   if ($reselid == 0) // login as admin of site
      return true;

   $query = "SELECT PVALUE FROM reselpref WHERE RESELID=$reselid AND PNAME='MYDATA_ALLOW_EDIT' ";
   if (($rs=$db->Execute($query))===false) {
      echo __LINE__.' '.$db->ErrorMsg();
      return false;
   }
   $row = $rs->FetchRow();
   $rs->Close();
   $ok = ($row !== false && $row[0]==1);
   if (!$ok) {
      umessage("User not allowed to edit database!");
   }
   return $ok;
}
//--------------------------------------
function edit_myrecord()
{
   global $x2, $multiFields;
   $db=&$x2->db;
   $readonly = false;

   $rid = (int)($_REQUEST['RECORDID'] ?? 0);

   // HEADER
   $tarray=array(
		array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(71)', 1, 'Agents'),
		array('javascript:goTo(70)', 1, 'myDATA (dates)'),
      array('javascript:goTo(72)', 1, 'Records'),
      array('', 1, 'Edit record id '.$rid)
		);
   $x2->make_header($tarray);

   if (!MyEditRightsOk()) {
      $readonly = true;
   }
?>
<div id=myrecord>
   <div id=myinfo></div>
</div>
<script>
var readonly = false; // global

$.fn.addBefore = function(array) {
    var newArray = $(this).toArray();
    array.each(function(){
        newArray.push(this);
    });
    return $(newArray);
}

function onZoom()
{
   var rid = <?php echo $rid; ?>;
   if (rid==0)
      return;

   var url = '/ishop/ishop_taxout.php?FUNCTION=5&RID=' + rid; // + iadmin_str();
   var title = 'Αριθμός εγγραφής ' + rid;
   $('#myinfo').html('loading...');
   $('#myrecord').dialog('option', 'title', title).dialog('open');
   $('#myinfo').load(url);
}

$(function(){
   $('#myrecord').dialog({autoOpen:false, modal:true, resizable:true, width:620});

   $('table').on('click', '.addMore', function(evt){
      if (readonly)
         return;

      var tr1 = $(evt.target).closest('tr');
      var ids = tr1.attr('id');
      var idsEOF = ids+'_EOF';
      var ids_sub = ids.substring(0, ids.lastIndexOf('-')+1); // includes terminating separator '-'

      var ar1 = tr1.nextAll().clone(); // array of siblings following 'tr1' (copy)

      // parse once (read all siblings to the end) to get max.
      var idx, ids2;
      var x2, maxx = 0;
      var s1 = '';
      ar1.each(function(){
         ids2 =$(this).prop('id');
         if ((idx = ids2.lastIndexOf('-')) > 0) {
            if (ids2.substring(0, idx+1) === ids_sub) {
               x2 = parseInt(ids2.substring(idx+1));
               if (x2 > maxx) { maxx = x2; }
            }
         }
      });

      // parse again to get contents
      var s2 = '';
      var l1 = ids.length;
      var ar2, val2;
      ar1 = tr1.clone().addBefore(ar1); // reset 'ar1' by prepending 'tr1'
      for (var p in ar1) {
         ids2 = $(ar1[p]).prop('id');
         if (ids2 == ids || (ids2.length > l1 && ids2.substring(0,l1)==ids && ids2.substring(l1, l1+1)=='_'))  {
            var ids2B = ids_sub + (maxx + 1) + ids2.substring(l1);
            $(ar1[p]).prop('id', ids2B);
         }

         $(ar1[p]).find('input').each(function(){
            ids2 = $(this).prop('name');
            if (ids2.length > l1+3 && ids2.substring(3,l1+3)==ids && ids2.substring(l1+3, l1+4)=='_')  {
               var ids2B = 'my/' + ids_sub + (maxx + 1) + ids2.substring(l1+3);
               $(this).prop('name', ids2B);
            }
            ar2 = ids2.split('_');
            val2 = (ar2.length>0 && ar2[ar2.length-1]==='lineNumber') ? (maxx + 1) : '';
            $(this).attr('value', val2); // attention! 'value' is an attribute, not a property
         });

         s2 += $(ar1[p]).prop('outerHTML');

         if (ids2 === idsEOF) {
            break;
         }
      }
      $('#'+idsEOF).after(s2);
   });

   $('table').on('change', 'input', function(evt){
      var attr = $(evt.target).attr('list');
      if (typeof attr !== 'undefined' && attr !== false) {
         var ar1 = $(evt.target).val().split(' ');
         if (ar1.length >= 2) { $(evt.target).val(ar1[0]); }
      }
   });
});
</script>
<?php
   $pro1 = array();

   if ($rid > 0) {
      $query = 'SELECT MARK, RECTYPE FROM mydata WHERE RID=?'; // read master record
      $data = array($rid);
      if (($rs=$db->Execute($query, $data))===false) {
         echo __LINE__.' '.$db->ErrorMsg();
         return;
      }
      $o1 = $rs->FetchNextObject();
      $rs->Close();
      if ($o1 === false) {
         echo '<div class=UMessage>Record disappeared!</div>';
         return;
      }
      else if ($o1->RECTYPE===NULL || strlen($o1->RECTYPE) != 1) {
         echo '<div class=UMessage>Ακατάλληλος τύπος εγγραφής, μόνο πωλήσεις επιτρέπονται!</div>';
         return;
      }

      if ($o1->MARK !== NULL && strlen($o1->MARK) > 0) {
         echo '<div class=UMessage>Ηδη έχει πάρει MARK, δεν μπορεί να γίνει διόρθωση!</div>';
         $readonly = true;
      }

      $query = 'SELECT PNAME, PVALUE FROM myprop WHERE RID=?'; // read properties (XML contents)
      $data = array($rid);
      if (($rs=$db->Execute($query, $data))===false) {
         echo __LINE__.' '.$db->ErrorMsg();
         return;
      }
      while ($o1 = $rs->FetchNextObject()) {
         $pro1[$o1->PNAME] = $o1->PVALUE;
      }
      $rs->Close();
   }

   $props = array();
   array_walk($pro1, function($val, $key) use(&$props, $multiFields) {
      $ar1 = explode('/', $key); // split $key
      array_walk($ar1, function(&$val2, $key2) use($multiFields) {
         if (in_array($val2, $multiFields)) {
            $val2 .= '.1'; // reset
         }
      });
      $key = implode('/', $ar1); // reset $key
      $props[$key] = $val;
   } );

   $AddressType = [
      ["street", "Οδός"],
      ["number", "Αριθμός"],
      ["postalCode", "ΤΚ"],
      ["city", "Πόλη"]
   ];

   $PartyType = [
      ["vatNumber", "ΑΦΜ"],
      ["country", "Κωδ. Χώρας", "countryList"],
      ["branch", "Αρ. Εγκατάστασης"], // "xs:int;4" // max 4 digits
      ["name", "Επωνυμία"],
      ["AddressType", "Διεύθυνση", $AddressType]
   ];

   $IncomeClassificationType = [
      ["N1:classificationType", "Κωδικός Χαρακτηρισμού", "incomeClassificationType"],
      ["N1:classificationCategory", "Κατηγορία Χαρακτηρισμού", "incomeClassificationCategory"],
      ["N1:amount", "Ποσό", "xs:decimal"],
      ["N1:id", "Αύξων αριθμός Χαρακτηρισμού", "xs:byte"]
   ];

   $ExpensesClassificationType = [
      ["N1:classificationType", "Κωδικός Χαρακτηρισμού", "expenseClassificationType"],
      ["N1:classificationCategory", "Κατηγορία Χαρακτηρισμού", "expenseClassificationCategory"],
      ["N1:amount", "Ποσό", "xs:decimal"], // Υποχρεωτικό
      ["N1:id", "Αύξων αριθμός Χαρακτηρισμού", "xs:byte"]
   ];

   $ShipType = [
      [ "applicationId", "Αριθμός Δήλωσης Διενέργειας Δραστηριότητας"], // Υποχρεωτικό
      [ "applicationDate", "Ημερομηνία Δήλωσης", "xs:date"], // Υποχρεωτικό
      [ "doy", "ΔΟΥ Δήλωσης"],
      [ "shipID", "Στοιχεία Πλοίου"] // Υποχρεωτικό
   ];

   $TaxTotalsType = [
      ["taxType", "Είδος Φόρου", "taxType"],
      ["taxCategory", "Κατηγορία Φόρου", "xs:byte"],
      ["underlyingValue", "Υποκείμενη Αξία", "xs:decimal"],
      ["taxAmount", "Ποσό Φόρου", "xs:decimal"]
   ];

   $InvoiceRowType = [
      [ "lineNumber", "ΑΑ Γραμμής", "xs:int;1"], // Υποχρεωτικό, min=1
      [ "quantity", "Ποσότητα", "xs:decimal"],
      [ "measurementUnit", "Είδος Ποσότητας", "measurementUnit"],
      [ "invoiceDetailType", "Επισήμανση", "invoiceDetailType"],
      [ "netValue", "Καθαρή Αξία", "xs:decimal"], // Υποχρεωτικό
      [ "vatCategory", "Κατηγορία ΦΠΑ", "vatCategory"], // Υποχρεωτικό
      [ "vatAmount", "Ποσό ΦΠΑ", "xs:decimal"], // Υποχρεωτικό
      [ "vatExemptionCategory", "Κατηγορία Αιτίας Εξαίρεσης ΦΠΑ", "vatExemptionCategory"],
      [ "dienergia", "ΠΟΛ 1177/2018 Αρ. 27", $ShipType],
      [ "discountOption", "Δικαίωμα Έκπτωσης", "xs:boolean"],
      [ "withheldAmount", "Ποσό Παρ. Φόρου", "xs:decimal"],
      [ "withheldPercentCategory", "Κατηγορία Συντελεστή Παρ. Φόρου", "withheldPercentCategory"],
      [ "stampDutyAmount", "Ποσό Χαρτοσήμου", "xs:decimal"],
      [ "stampDutyPercentCategory", "Κατηγορία Συντελεστή Χαρτοσήμου", "stampDutyPercentCategory"],
      [ "feesAmount", "Ποσό Τελών", "xs:decimal"],
      [ "feesPercentCategory", "Κατηγορία Συντελεστή Τελών", "feesPercentCategory"],
      [ "otherTaxesPercentCategory", "Κατηγορία Συντελεστή Λοιπών Φόρων", "otherTaxesPercentCategory"],
      [ "otherTaxesAmount", "Ποσό Φόρου Διαμονης", "xs:decimal"],
      [ "deductionsAmount", "Ποσό Κρατήσεων", "xs:decimal"],
      [ "lineComments", "Σχόλια Γραμμής", "xs:string"],
      [ "incomeClassification", "Λίστα Χαρακτηρισμών Εσόδων", $IncomeClassificationType],
      [ "expensesClassification", "Λίστα Χαρακτηρισμών Εξόδων", $ExpensesClassificationType]
   ];

   $doc = [
      ["issuer", "Στοιχεία Εκδότη", $PartyType],
      ["counterpart", "Στοιχεία Λήπτη", $PartyType],
      ["invoiceHeader", "Γενικά Στοιχεία",
         [
            ["series", "Σειρά παραστατικού"], // "xs:string" }, // Υποχρεωτικό
            ["aa", "ΑΑ Παραστατικού"], // "xs:string"
            ["issueDate", "Ημερομηνία Έκδοσης Παραστατικού", "xs:date"],
            ["invoiceType", "Είδος Παραστατικού", "invoiceType"],
            ["vatPaymentSuspension", "Αναστολή Καταβολής ΦΠΑ", "xs:boolean"],
            ["currency", "Νόμισμα", "currency"],
            ["exchangeRate", "Ισοτιμία", "xs:decimal;5"], // min=0, 5 decimals
            ["correlatedInvoices", "Συσχετιζόμενα Παραστατικά"], // "xs:long", NULL, true
            ["selfPricing", "Ένδειξη Αυτοτιμολόγησης", "xs:boolean"],
            ["dispatchDate", "Ημερομηνία Έναρξης Αποστολής", "xs:date"],
            ["dispatchTime", "Ώρα Έναρξης Αποστολής", "xs:time"],
            ["vehicleNumber", "Αριθμός Μεταφορικού Μέσου"], // "xs:string"
            ["movePurpose", "Σκοπός Διακίνησης", "movePurpose"]
         ]
      ],
      ["paymentMethods", "Πληρωμές",
         [
            ["paymentMethodDetails", "Στοιχεία Πληρωμών",
               [
                  ["type", "Τύπος Πληρωμής", "paymentType"],
                  ["amount", "Αναλογούν Ποσό", "xs:decimal"],
                  ["paymentMethodInfo", "Λοιπές Πληροφορίες"] // "xs:string"
               ]
            ]
         ]
      ],
      ["invoiceDetails", "Λεπτομέρειες Παραστατικού", $InvoiceRowType],
      ["taxesTotals", "Σύνολα Φόρων (εκτός ΦΠΑ)",
         [
            ["taxes", "Φόροι", $TaxTotalsType]
         ]
      ],
      ["invoiceSummary", "Συγκεντρωτικά Στοιχεία",
         [
            ["totalNetValue", "Σύνολο Καθαρής Αξίας", "xs:decimal"],
            ["totalVatAmount", "Σύνολο ΦΠΑ", "xs:decimal"],
            ["totalWithheldAmount", "Σύνολο Παρακρατήσεων Φόρων", "xs:decimal"],
            ["totalFeesAmount", "Σύνολο Τελών", "xs:decimal"],
            ["totalStampDutyamount", "Σύνολο Χαρτοσήμου", "xs:decimal"],
            ["totalOtherTaxesAmount", "Σύνολο Λοιπών Φόρων", "xs:decimal"],
            ["totalDeductionsAmount", "Σύνολο Κρατήσεων", "xs:decimal"],
            ["totalGrossValue", "Συνολική Αξία", "xs:decimal"],
            ["incomeClassification", "Χαρακτηρισμοί Εσόδων", $IncomeClassificationType],
            ["expensesClassification", "Χαρακτηρισμοί Εξόδων", $ExpensesClassificationType]
         ]
      ]
   ];

   draw_datalists();

   echo '<form action="ishop_taxi.php" method=POST>
      <input type=hidden name="FUNCTION" value="76">
      <input type=hidden name="RID" value="'.$rid.'">
      <table>
      <colgroup>
         <col style="width:3em">
         <col style="width:5em">
      </colgroup>';
   walkdown('', $doc, 0, $props);
   echo '<tr>
      <td class=bgButton colspan=10 style="padding:0.5em">
         <input type=button value="Zoom" ';
   if ($rid==0) { echo ' disabled '; }
   echo ' onclick="onZoom()">';
   if ($readonly) {
      echo '<input type=button value="Ενημέρωση" disabled>';
   }
   else {
      echo '<input type=submit value="Ενημέρωση">';
   }
   echo '<input type=button value="Ακυρο" onclick="goTo(72)">
         <input type=reset value="Επαναφορά">
      </td>
      </tr>
      </table>
      </form>';

   if ($readonly) {
      echo "<script>readonly=true; $('input').prop('disabled', true);</script>";
   }
}
//--------------------------------------
function find_max_propname($fieldname, $props)
{
   $maxx = 0;

   $pname = strtr($fieldname, '-_', './');
   array_walk($props, function($val, $key) use($pname, &$maxx) {
      $lf = strlen($pname);
      if (substr($key, 0, $lf)===$pname && strlen($key) > ($lf + 1) && $key[$lf] === '.') {
         $x2 = (int)substr($key, $lf + 1);
         if ($x2 > $maxx) {
            $maxx = $x2;
            //echo "maxx=$maxx<br>";
         }
      }
   }) ;

   return $maxx;
}
//--------------------------------------
function walkdown($parent, $ar1, $depth, $props)
{
   global $multiFields;

   foreach ($ar1 as $ar2) { // $ar2 example: ["invoiceDetails", "Λεπτομέρειες Παραστατικού", $InvoiceRowType]
      $multiply = false;
      $fieldname = $parent;
      if (!empty($fieldname)) { $fieldname .= '_'; } // depth separator
      $maxx = 1;

      $fieldname .= $ar2[0];
      if (in_array($ar2[0], $multiFields)) { // if ar2[0] can be multiplied
         $multiply = true;

         $maxx = find_max_propname($fieldname, $props); // before we add '-1' on $fieldname
         if ($maxx<1) { $maxx = 1; } // normalize
      }
      $label = $ar2[1];
      $hasAnalysis = (count($ar2)==3 && is_array($ar2[2]));

      for ($ix=1; $ix<=$maxx; $ix++) {
         if ($multiply) {
            $fieldnameEx = $fieldname."-$ix";
         }
         else {
            $fieldnameEx = $fieldname;
         }

         echo "<tr";
         if ($hasAnalysis && $multiply) { echo " id=\"$fieldnameEx\""; }
         echo ">\n";

         // Print empty cells in the beginning
         for ($i=0;$i<$depth;$i++) {
            echo '<td></td>';
         }

         if (!$hasAnalysis) {
            $utype = $ar2[2] ?? 'xs:string';
            $uparam = false;
            $uar = explode(';', $utype);
            if (count($uar)==2) {
               $utype = $uar[0]; // reset
               $uparam = $uar[1];
            }
            echo "<td colspan=2 class=bgLabel>".myhtml($label)."</td>
               <td class=bgInput><input ";
            switch ($utype)
            {
               case 'xs:date':
                  echo 'type=date';
                  break;
               case 'xs:time':
                  echo 'type=time';
                  break;
               case 'xs:boolean':
                  echo 'type=number min="0" max="1" ';
                  break;
               case 'xs:byte':
                  echo 'type=number min="0" max="9" ';
                  echo ' title="1 single digit" ';
                  break;
               case 'xs:decimal':
                  if (empty($uparam)) { $uparam = 2; }
                  echo 'type=text pattern="\d.*\.\d{0,'.$uparam.'}" title="decimal, '.$uparam.' digits" ';
                  break;
               case 'xs:int':
                  $minvalue = 0;
                  if ($uparam == 1) { $minvalue=1; }
                  echo 'type=number min="'.$minvalue.'" ';
                  if ($uparam > 1) { echo ' maxlength="'.$uparam.'" '; }
                  echo ' title="integer" ';
                  break;
               case 'xs:string':
                  echo 'type=text title="text" ';
                  break;
               default:
                  echo "type=text list=\"$utype\" ";
                  break;
            }
            echo " name=\"my/$fieldnameEx\" value=\"";
            $pname = strtr($fieldnameEx, '-_', './');
            if (array_key_exists($pname, $props)) {
               echo myhtml($props[$pname]);
            }
            echo "\"></td>";
         }
         else { // $hasAnalysis
            echo "<td colspan=2 ";
            if ($multiply) {
               echo " class=\"bgLine addMore\">";
            }
            else {
               echo " class=\"bgLine\">";
            }
            echo myhtml($label)."</td>";
         }
         echo "</tr>\n";

         if ($hasAnalysis) {
            walkdown($fieldnameEx, $ar2[2], $depth+1, $props);
         }

         if ($hasAnalysis && $multiply) {
            echo "<tr id=\"{$fieldnameEx}_EOF\"><td></td></tr>\n";
         }
      }
   }
}
//--------------------------------------
function show_mydata_date_by_rid()
{
   global $x2;
   $db=&$x2->db;

   $query = "SELECT CONVERT(VARCHAR, SUBMISSION, 120) AS SUBMISSION FROM mydata WHERE RID=?";
   $data = array($_REQUEST['RECORDID']);
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__.' '.$db->ErrorMsg();
      return;
   }
   $row = $rs->FetchRow();
   $rs->Close();
   if ($row === false) {
      umessage('Record disappeared!');
      return show_mydata_dates();
   }

   $_REQUEST['MYRECFILTER'] = -1; // cleanup all filters
   $_REQUEST['MYDATE'] = $row[0];
   show_mydata_date1(); // #72
}
//--------------------------------------
function show_mydata_date1() // #72
{
   global $x2;
   $db=&$x2->db;

   if (!empty($_REQUEST['MYDATE']))
      $_SESSION['MYDATE'] = $_REQUEST['MYDATE'];
   else if (empty($_SESSION['MYDATE']))
      return show_mydata_dates();

   if (isset($_REQUEST['RECORDID'])) {
      $_SESSION['MYRECFILTER'] = $_REQUEST['RECORDID'];
   }
   $MyRecFilter = (int)@$_SESSION['MYRECFILTER'];
   if (!empty($_REQUEST['MYRECFILTER'])) {
      $MyRecFilter = $_REQUEST['MYRECFILTER']; // overwrite session value
   }
   $myagentid = (int)@$_SESSION['MYAGENTID'];
   $mydate = $_SESSION['MYDATE'];

   $ownother = $_SESSION['OWNOTHER']??1;

   // HEADER
   $tarray=array(
		array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(71)', 1, 'Agents'),
		array('javascript:goTo(70)', 1, 'myDATA (dates)'),
      array('javascript:goTo(72)', 1, 'Records '.$mydate.' '.($ownother==1?'Own':'Other').'(r)')
		);
   $x2->make_header($tarray);

   $query = make_query_mydata_recs();
   $query .= " WHERE T1.AGENTID=? AND T1.OWNOTHER=$ownother AND SUBMISSION=? ";
   if ($MyRecFilter == -1) { // clear all filters
      unset($_SESSION['FHMKEY']);
      unset($_SESSION['DOCSERIES']);
      unset($_SESSION['DOCAA']);
   }
   else if ($MyRecFilter == 1) { // sent only
      $query .= " AND MARK IS NOT NULL ";
   }
   else if ($MyRecFilter == 2) { // unsent only
      $query .= " AND MARK IS NULL ";
   }
   $data = [$myagentid, $mydate];

   if (!empty($_SESSION['FHMKEY'])) {
      $query .= " AND T1.FHMKEY LIKE ? ";
      $data[] = $_SESSION['FHMKEY'];
   }
   else {
      if (!empty($_SESSION['DOCSERIES'])) {
         $query .= " AND T2.PVALUE=? ";
         $data[] = $_SESSION['DOCSERIES'];
      }
      if (!empty($_SESSION['DOCAA'])) {
         $query .= " AND T3.PVALUE=? ";
         $data[] = $_SESSION['DOCAA'];
      }
   }

   $query .= " ORDER BY T1.RECTYPE, T1.SUBMISSION, T1.RID";

   $epage = do_show_mydata_recs($query, $data);

   echo "<div id=tbar2>";
      $pg=getPage();
	   print_page_navEx($pg,$epage,72);
	   echo '<span style="border: 1px solid gray; padding:4px; margin-left:2px; margin-right:2px;">Filter:
		  <select id=myfilter onchange="resetMyFilter()" title="State">';
	   $ar1=array(0=>'Ολες', 1=>'Αποσταλλείσες', 2=>'Εκκρεμείς');
	   prAssocSelect($ar1, $MyRecFilter);
	   echo '</select></span>
         <button type=button class=NavButton onclick="onFilter()" title="Εφαρμογή φίλτρου"><img src="/img/filter.png"></button>
         <button type=button class=NavButton onclick="onExport()" title="CSV export (όλες οι εγγραφές)"><img src="/img/export.png"></button>';
      if ($ownother==1) {
         echo '<button type=button xclass=NavButton onclick="goTo(75)">Νέα εγγραφή</button>
            <b><a href="javascript:goTo(79)">Πρόβλημα ΑΦΜ</a> | <a href="javascript:goTo(82)">Ακυρωτικά</a></b>';
      }
   echo "</div>";
}
//--------------------------------------
function do_show_mydata_recs($query, $data, $cancelations = false)
{
   global $x2;
   $db=&$x2->db;
?>
<div id=myrecord>
   <div id=myinfo></div>
</div>

<style>
table.rowbox { border-collapse: collapse; }
table.rowbox tr { border: solid thin; padding:0.5em; }
table.rowbox td { padding:0.5em; }
</style>

<div id=filterDiv title="Καθορισμός φίλτρου">
   <form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
   <input type=hidden name="FUNCTION" value="74">
   <table class="rowbox">
      <tr>
         <td><label><input type=radio id=firid name="FIWHAT" value="3" checked>Εγγραφή</label></td>
         <td><input type=text id=inmark name="MYRID" onclick="$('#firid').prop('checked', true);">
            <small>(ανεξάρτητα από ημερομηνία)</small></td>
      </tr>

      <tr>
         <td><label><input type=radio id=fimark name="FIWHAT" value="1">MARK</label></td>
         <td><input type=text id=inmark name="MYMARK" onclick="$('#fimark').prop('checked', true);">
            <small>(ανεξάρτητα από ημερομηνία)</small></td>
      </tr>

      <tr>
         <td><label><input type=radio id=fidoc name="FIWHAT" value="2">Παρ/κό</label></td>
         <td>
            Σειρά παραστατικού<br>
            <input type=text name="DOCSERIES" value="<?php echo myhtml(@$_SESSION['DOCSERIES']); ?>" onclick="$('#fidoc').prop('checked', true);"><br>
            Αριθμός παραστατικού<br>
            <input type=text name="DOCAA" value="<?php echo myhtml(@$_SESSION['DOCAA']); ?>" onclick="$('#fidoc').prop('checked', true);">
         </td>
      </tr>

      <tr>
         <td><label><input type=radio id=fhmkey name="FIWHAT" value="4">Ταυτότητα</label></td>
         <td><input type=text id=inmark name="FHMKEY" onclick="$('#fhmkey').prop('checked', true);"
            placeholder="S11"></td>
      </tr>
   </table>

   <center>
      <input type=submit type=button style="margin-top:0.5em" value="Εφαρμογή">
   </center>

   </form>
</div>

<script>
var rid;
function oclick(stage, row, col)
{
   var colId = 0;
<?php
   if ($cancelations) {
      echo 'if (col==0) { return false; } colId = 1;';
   }
   else {

   }
?>
   rid = this.cells(row, colId).getValue();
   show_popup('popmenu');
	return false;
}
function winRet(x)
{
   let url, title;

   switch (x)
   {
   case 1: // zoom
      url = '/ishop/ishop_taxout.php?FUNCTION=5&RID=' + rid; // + iadmin_str();
      title = 'Αριθμός εγγραφής ' + rid;
      $('#myinfo').html('loading...');
      $('#myrecord').dialog('option', 'title', title).dialog('open');
      $('#myinfo').load(url);
      break;
   case 2: // PDF
      url = '/ishop/ishop_taxout.php?FUNCTION=6&RID=' + rid; // + iadmin_str();
      $.get(url, function(data){
         let ar1 = data.split(' ');
         if (ar1.length>0 && ar1[0]==='ERROR') {
            window.alert(data);
         }
         else {
            url = 'https://10.180.3.69/iform/iform_exp.php?FUNCTION=100&STATIONID=98921&DOCID=' + data;
            window.open(url);
         }
      }, 'text');
      break;
   case 3: // edit
      goRecord(75, rid);
      break;
   case 4: // create cancelation record
      if (window.confirm('Δημιουργία εγγραφής ΑΚΥΡΩΣΗΣ')) {
         <?php
         if ($cancelations) {
            ?>
            url = '/ishop/ishop_taxout.php?FUNCTION=9&MYRID=' + rid;
            $.get(url, function(data){
               window.alert(data);
            });
            <?php
         }
         else {
            ?>
            goRecord(77, rid);
            <?php
         }
         ?>
      }
      break;
   case 5: // del record
      goRecDelete(78, rid);
      break;
   case 6: // original doc.
      url = '/ishop/ishop_taxout.php?FUNCTION=8&RID=' + rid; // + iadmin_str();
      title = 'Αριθμός εγγραφής ' + rid;
      $('#myinfo').html('loading...');
      $('#myrecord').dialog('option', 'title', title).dialog('open');
      $('#myinfo').load(url);
      break;
   case 7:
      goRecord(83, rid);
      break;
	case 8:
      goRecord(85, rid);
      break;
   }
   hide_popup();
}
function ask_for_del()
{
   if (!window.confirm('Really delete record(s)?'))
		return;

   send_grp_action(84, grid23, null, 1);
}
$(function(){
   $('#myrecord').dialog({autoOpen:false, modal:false, resizable:true, width:620});
   $('#filterDiv').dialog({autoOpen:false, modal:true, resizable:true, width:480});
});
function onFilter()
{
   $('#filterDiv').dialog('open');
}
function onExport()
{
   let url = '/ishop/ishop_taxout.php?FUNCTION=7';
   window.open(url);
}
function resetMyFilter()
{
   let v = $('#myfilter').val();
   goRecord(72, v);
}
</script>
<?php
   $gr1=new cXRID('grid23');

   $pg=getPage();
   $pgsz=getPageSize('grid23');

   $gr1->cols = [
      array('Id εγγραφής', 60),
      array('Τύπος εγγραφής', 80),
      array('Ταυτότητα', 80),
      array('Mark', 60),
      array('Ετοιμη', 60),
      array('Δημιουργήθηκε', 60),
      array('Αποστάλθηκε', 60),
      array('Απάντηση', 60),
      array('Απάντηση (bytes)', 60),
      array('Υποκ/μα', 60),
      array('Είδος παρ/κού', 60),
      array('Σειρά', 60),
      array('Α/Α', 60),
      array('ΑΦΜ', 60),
      array('Καθαρή αξία', 60),
      array('Συνολική αξία', 60)
   ];
   if ($cancelations) {
      array_unshift($gr1->cols, array('<input type=CHECKBOX onclick="checkUncheckAll(this)">', 30) );
   }

   if (($rs=$db->PageExecute($query,$pgsz,$pg,$data))===false) {
		echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>";
		return;
	}
   $nrec = 0;
   while ($o1=$rs->FetchNextObject()) {
      if (!empty($o1->MARK)) {
         $markInfo = $o1->MARK;
      }
      else if (!empty($o1->XFLAG)) {
         $markInfo = 'X/'.$o1->XFLAG;
      }
      else {
         $markInfo = '';
      }

      $row1 = [
         $o1->RID,
         myhtml(RecTypeLabel($o1->RECTYPE)),
         myhtml($o1->FHMKEY),
         myhtml($markInfo),
         $o1->ISREADY, // integer
         myhtml($o1->CREDAYTIME),
         myhtml($o1->LASTSENT),
         myhtml($o1->RETVAL),
         ((empty($o1->MARK) && $o1->DATALEN > 0) ? '...' : ''),
         myhtml($o1->ISSBRANCH),
         myhtml($o1->DOCTYPE),
         myhtml($o1->DOCSERIES),
         myhtml($o1->DOCAA),
         myhtml($o1->DESTAFM),
         myhtml($o1->DOCNET),
         myhtml($o1->DOCGROSS)
      ];
      if ($cancelations) {
         array_unshift($row1, "<input type=CHECKBOX id=\"ii$nrec\">");
      }

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

   $gr1->click = 'oclick';
   $gr1->play();

   // Popup must be drawn last in page in order to have a proper z-index
   $selx=array(
      array(1, '/img/details.gif', 'Zoom' ),
      array(2, '/img/pdf16x16.png', 'PDF/ XPS' ),
      '<hr>',
      array(3, '/img/button_edit.png', 'Διόρθωση' ),
		array(8, '/img/reset.png', 'Reset'),
      array(4, '/img/cancelbox_blue.png', 'Ακυρωτικό' ),
      array(5, '/img/drop.png', 'Διαγραφή' )
   );
   if ($cancelations) {
      $selx[] = '<hr>';
      $selx[] = array(6, '/img/report16x16.png', 'Πρωτότυπο');
      $selx[] = array(7, '/img/go_next.gif', 'Εγγραφές ημ/νίας');
   }
	draw_popup($selx);

   return $epage;
}
//--------------------------------------
function update_mymatch()
{
   global $x2;
   $db=&$x2->db;

   $ar1 = explode(' ', $_REQUEST['VALUE1']);
   $value1 = $ar1[0];

   $value2 = $_REQUEST['VALUE2'];

   $ar1 = explode(' ', $_REQUEST['VALUE3']);
   $value3 = $ar1[0];

   $ar1 = explode(' ', $_REQUEST['VALUE4']);
   $value4 = $ar1[0];

   $query = "UPDATE mymatch SET VALUE1=?, VALUE2=?, VALUE3=?, VALUE4=?
      WHERE AGENTID=? AND MYMODEL=? AND MATCHSRC=?";
   $data = array($value1, $value2, $value3, $value4,
      $_REQUEST['MYAGENTID'], $_REQUEST['MYMODEL'], $_REQUEST['MATCHSRC']);
   if (!$db->Execute($query, $data)) {
      echo __LINE__.' '.$db->ErrorMsg();
      return;
   }
}
//--------------------------------------
function show_mymatch()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
   $tarray=array(
		array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(71)', 1, 'Agents'),
		array('javascript:goTo(70)', 1, 'myDATA'),
      array('javascript:goTo(80)', 1, 'Αντιστοίχιση(r)')
		);
   $x2->make_header($tarray);

   draw_countryList();
   draw_incomeClassificationType();
   draw_incomeClassificationCategory();
?>
<script>
$(function(){
   $('#editRecDiv').dialog({autoOpen:false, modal:true, resizable:false, width:480});
});
function oclick(stage, row, col)
{
   $('input[name=MYAGENTID]').val(this.cells(row, 0).getValue());
   $('input[name=MYMODEL]').val(this.cells(row, 1).getValue());
   $('input[name=MATCHSRC]').val(this.cells(row, 2).getValue());
   $('input[name=VALUE1]').val(this.cells(row, 3).getValue());
   $('input[name=VALUE2]').val(this.cells(row, 4).getValue());
   $('input[name=VALUE3]').val(this.cells(row, 5).getValue());
   $('input[name=VALUE4]').val(this.cells(row, 6).getValue());
   $('#editRecDiv').dialog('open');
}
</script>
<div id="editRecDiv" title="Διόρθωση εγγραφής">
   <form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method=POST>
   <input type="hidden" name="FUNCTION" value="81">
      <table>
         <tr>
            <td>Agent Id</td>
            <td><input type="text" name="MYAGENTID" readonly></td>
         </tr>
         <tr>
            <td>Μοντέλο</td>
            <td><input type="text" name="MYMODEL" readonly></td>
         </tr>
         <tr>
            <td>ΑΦΜ/td>
            <td><input type="text" name="MATCHSRC" readonly></td>
         </tr>
         <tr>
            <td>Χώρα/td>
            <td><input type="text" name="VALUE1" list="countryList"></td>
         </tr>
         <tr>
            <td>Επωνυμία/td>
            <td><input type="text" name="VALUE2"></td>
         </tr>
         <tr>
            <td>Κωδικός Χαρακτηρ.Εσόδων</td>
            <td><input type="text" name="VALUE3" list="incomeClassificationType"></td>
         </tr>
         <tr>
            <td>Κατηγορία Χαρακτηρ.Εσόδων</td>
            <td><input type="text" name="VALUE4" list="incomeClassificationCategory"></td>
         </tr>
         <tr>
            <td></td>
            <td><input type="submit" value="Ενημέρωση"></td>
         </tr>
      </table>
   </form>
</div>
<?php
   $gr1=new cXRID('grid27');

   $query = "SELECT * FROM mymatch ORDER BY AGENTID, MYMODEL, MATCHSRC";
   if (($rs=$db->Execute($query))===false) {
      echo __LINE__.' '.$db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1 = [
         $o1->AGENTID,
         $o1->MYMODEL,
         myhtml($o1->MATCHSRC),
         myhtml($o1->VALUE1),
         myhtml($o1->VALUE2),
         myhtml($o1->VALUE3),
         myhtml($o1->VALUE4)
      ];
      $gr1->rows[] = $row1;
   }
   $rs->Close();

   $gr1->cols = [
      array('Agent  Id', 50),
      array('Μοντέλο', 50),
      array('ΑΦΜ', 120),
      array('Χώρα', 120),
      array('Επωνυμία', 280),
      array('Κωδικός Χαρακτηρ.Εσόδων', 200),
      array('Κατηγορία Χαρακτηρ.Εσόδων', 200)
   ];
   $gr1->click = 'oclick';
   $gr1->play();
   echo '<div id=tbar2><small>End of data</small></div>';
}
//--------------------------------------
function show_mydata_dates($ownother=false) // 70/104
{
   global $x2;
   $db=&$x2->db;

   if ($ownother!==false) {
      $_SESSION['OWNOTHER'] = $ownother;
   }
   $ownother = (int)@$_SESSION['OWNOTHER']; // reset
   if (empty($ownother)) { $ownother = 1; } // normalize

   if (!empty($_REQUEST['MYAGENTID'])) {
      $_SESSION['MYAGENTID'] = $_REQUEST['MYAGENTID'];
   }
   else if (empty($_SESSION['MYAGENTID'])) {
      $agents = array();
      $query = 'SELECT AGENTID FROM myagent';
      if (($rs=$db->Execute($query))===false) {
         echo __LINE__.' '.$db->ErrorMsg();
         return;
      }
      while ($row=$rs->FetchRow()) {
         $agents[] = $row[0];
      }
      $rs->Close();
      if (count($agents) != 1)
         return show_mydata_agents();

      $_SESSION['MYAGENTID'] = $agents[0];
   }

   $myagentid = (int)$_SESSION['MYAGENTID'];

   // HEADER
   $tarray=array(
		array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(71)', 1, 'Agents'),
		array('javascript:goTo(70)', 1, 'myDATA '.($ownother==1?'Own':'Other').'(r)')
		);
   $x2->make_header($tarray);
?>
<script>
function oclick(stage, row, col)
{
   let mydate = this.cells(row, 0).getValue(); // yyyy-mm-dd
   //postTo(null, {'FUNCTION':72, 'MYRECFILTER':-1, 'MYDATE':mydate}); // MYRECFILTER=-1 > cleanup all filters
	postTo(null, {'FUNCTION':72, 'MYRECFILTER':2, 'MYDATE':mydate}); // MYRECFILTER=-1 > cleanup all filters
}
</script>
<?php
   $gr1=new cXRID('grid21');

	// SUBMISSION: date to perform submission
   $results = array();
   $query = 'SELECT CONVERT(VARCHAR, SUBMISSION, 120) AS SUBMISSION, CASE WHEN MARK IS NULL THEN 0 ELSE 1 END AS XMARK, COUNT(*) AS N1 FROM mydata '.
      ' WHERE AGENTID=? AND OWNOTHER=? GROUP BY SUBMISSION, CASE WHEN MARK IS NULL THEN 0 ELSE 1 END ORDER BY SUBMISSION DESC';
   $data = [$myagentid, $ownother];
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__.' '.$db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $key = $o1->SUBMISSION;
      if (!array_key_exists($key, $results)) {
         $results[$key] = [0, 0];
      }
      $results[$key][(int)$o1->XMARK] = $o1->N1;
   }
   $rs->Close();

   foreach ($results as $key=>$val) {
      $row1 = array(
         $key,
         $val[0],
         $val[1],
         $val[0] + $val[1]
      );
      $gr1->rows[] = $row1;
   }

   $gr1->cols = [
      array('Ημερομηνία', 150),
      array('Εκκρεμείς', 100),
      array('Αποσταλείσες', 100),
      array('Σύνολο εγγρφών', 100)
   ];
   $gr1->sort = 'str,int,int,int';
   $gr1->click = 'oclick';
   $gr1->play();

   $for_rdbms_rc = CountForRdbms();

   echo '<div id=tbar2><small>End of data</small> ';
   if ($ownother==1) {
      echo ' <b><a href="javascript:goTo(80)">Αντιστοίχιση</a> |
      <a href="javascript:goTo(79)">Πρόβλημα ΑΦΜ</a> |
      <a href="javascript:goTo(82)">Ακυρωτικά</a></b>';
   }
   echo ' Αρχεία σε αναμονή: <b>'.$for_rdbms_rc.'</b></div>';
}
//--------------------------------------
function CountForRdbms()
{
   $rets = '';

   do {
      if (($xml = simplexml_load_file("c:\\inca hellas\\taxspooler.xml")) === false) {
         $rets = "Could not load taxspooler.xml";
         break;
      }
      $baseDataPath = $xml->ClientSaveDir; // ../userdata
      $xpath = $baseDataPath.'\\for_rdbms';
      $rc = 0;
      //$t1 = microtime(true);

      if (($hdir = opendir($xpath)) === false) {
         $rets = 'Could not open dir.';
         break;
      }

      while (($fname=readdir($hdir))!==false) {
         if ($fname !== '.' && $fname !== '..') { $rc++; }
      }

      closedir($hdir);
      //$t2 = microtime(true);
      $rets = $rc;
   } while (false);

   return $rets;
}
//--------------------------------------
function show_eafdss_details()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('javascript:goTo(5)', 1, 'Στοιχεία ΕΑΦΔΣΣ(r)')
		);
   $x2->make_header($tarray);

   // BODY
?>
<script>
var s11=null, aes=null, senderIP=null, currentVersion=null, field=null, txlocation=null;
function oclick(stage, row, col)
{
	field = this.cells(row, col).getValue();
   currentVersion=this.cells(row, 1).getValue();
   txlocation=this.cells(row, 2).getValue();
   senderIP=this.cells(row, 4).getValue();
	s11=$( this.cells(row, 7).getValue() ).text();
   aes=this.cells(row, 10).getValue();
   show_popup('popmenu');
	return false;
}
function versionCompare(a, b) {
    if (a === b) {
       return 0;
    }

    var a_components = a.split(".");
    var b_components = b.split(".");

    var len = Math.min(a_components.length, b_components.length);

    // loop while the components are equal
    for (var i = 0; i < len; i++) {
        // A bigger than B
        if (parseInt(a_components[i]) > parseInt(b_components[i])) {
            return 1;
        }

        // B bigger than A
        if (parseInt(a_components[i]) < parseInt(b_components[i])) {
            return -1;
        }
    }

    // If one's a prefix of the other, the longer one is greater.
    if (a_components.length > b_components.length) {
        return 1;
    }

    if (a_components.length < b_components.length) {
        return -1;
    }

    // Otherwise they are the same.
    return 0;
}
function winRet(x)
{
   switch (x)
   {
   case 1:
      var minRequired='2.4.5.78';
      if (versionCompare(currentVersion, minRequired)<0) {
         alert('Ελάχιστη απαιτούμενη έκδοση για να μπορεί να γίνει αναβάθμιση: '+minRequired);
         return;
      }
      showUpdateLocations(senderIP);
      $('#upgradeDiv').dialog('open');
      break;
   case 2:
      window.prompt("Field value", field);
      break;
   case 4:
      goRecord(4, s11);
      break;
   case 5:
   case 11:
   case 24:
   case 25:
      goTo(x);
      break;
   case 19:
      $('#s11').val(s11);
      $('#s11').attr('readonly', 'readonly');
      $('#aeskey').val(aes);
      $('#aesdiv').dialog('open');
      break;
   case 21:
      goRecDelete(21, s11);
      break;
   case 22:
   case 23:
   case 28:
   case 30:
   case 31:
   case 32:
      goTo(x);
      break;
   case 49: // Reset 'Allow Send Taxis'
      goRecord(49, s11);
      break;
   case 54:
      var url = location.pathname + '?FUNCTION=54&TXLOCATION=' + encodeURIComponent(txlocation);
      window.open(url, 'TaxSpoolerParams');
      break;
   case 191:
      $('#s11').val('');
      $('#s11').removeAttr('readonly');
      $('#aeskey').val('');
      $('#aesdiv').dialog('open');
      break;
   }
   hide_popup();
}
function goUpdateAesKey()
{
   goRecord(19, s11+';'+$('#aeskey').val() );
}
$(function(){
   $('#aesdiv').dialog({autoOpen:false, modal:true, resizable:false, width:640});
   $('#upgradeDiv').dialog({autoOpen:false, modal:true, resizable:false});
} );
function showUpdateLocations(senderIP)
{
   $('#locations').text('querying...');

   var pdata={ 'FUNCTION':6, 'SENDERIP':senderIP };
   $.ajax('/ishop/ishop_jsontx.php', {
      error: function (jqXHR, textStatus, errorThrown){
         if (jqXHR) {
            if (jqXHR.responseText.length>0) {
               $('#locations').html( jqXHR.responseText );
            }
            else {
               $('#locations').html( 'Error '+jqXHR.status );
            }
         }
         else {
            $('#locations').html( textStatus );
         }
         $('#locations').show();
      },

      success: function(ro){
         if (ro[0].error.length>0) {
            $('#locations').html( ro[0].error );
            $('#locations').show();
         }
         else {
            var outs='';
            for (var i=0;i<ro[0].data.length;i++) {
               if (outs.length>0) { outs += ', '; }
               outs += ro[0].data[i].TXLOCATION + ' (' + ro[0].data[i].MS11 + ')';
            }
            $('#locations').text(outs);
         }
      },

      data: pdata,

      dataType: 'json'
      }
   );
}
function requestUpd(bUpdate)
{
   var vers1 = bUpdate ? $('#versions').val() : '';
   if (typeof(vers1) === "undefined") {
      vers1 = '';
   }
   var url='/ishop/ishop_taxi.php?FUNCTION=40&SENDERIP='+encodeURIComponent(senderIP)+'&UPDVERSION='+encodeURIComponent(vers1);
   location.href=url;
}
</script>

<div id=aesdiv title="Taxis Key">
   <table>
      <tr>
         <td>ΕΑΦΔΣΣ</td>
         <td><input type=text id=s11></td>
      </tr>
      <tr>
         <td>AES key</td>
         <td><input type=text id=aeskey style="width:540px"></td>
      </tr>
      <tr>
         <td></td>
         <td><input type=button value="<?php $x2->xprint('upd'); ?>" onclick="goRecord(19, $('#s11').val()+';'+$('#aeskey').val() );"></td>
      </tr>
   </table>
</div>

<div id=upgradeDiv title="Αίτηση ενημέρωσης">
   <table>
      <tr>
         <td>Καταστήματα που θα ενημερωθούν:</td>
         <td id=locations></td>
      </tr>
      <tr>
         <td>Εκδοση:</td>
         <td><?php list_version_avail(); ?></td>
      </tr>
      <tr>
         <td></td>
         <td>
            <button type=button onclick="requestUpd(true)">ΝΑΙ</button>
            <button type=button onclick="requestUpd(false)">ΟΧΙ</button>
            <button type=button onclick="$('#upgradeDiv').dialog('close');">Ακυρο</button>
         </td>
      </tr>
   </table>
</div>

<?php
   $magroup=array();
   $query="SELECT MENUID, MENUDES FROM menurep
      WHERE AGENTID=? AND MENUTYPE=22
      ORDER BY MENUDES";
   $data=array($x2->agentid);
   if (($rs=$db->Execute($query,$data))===false) {
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $magroup[ $o1->MENUID ] = $db->verify_8($o1->MENUDES); // $db->verify_8() must be called only once for a single field
   }
   $rs->Close();

   $gr1=new cXRID('grid2');

   switch ((int)@$_SESSION['EAFDSS_DETAILS_ORDER_BY'])
   {
      case 1:
         $orderby="TXLOCATION, MS11";
         break;
      case 2:
         $orderby="TXVERSION, TXLOCATION, MS11";
         break;
      case 3:
         $orderby="L_OS, TXLOCATION, MS11";
         break;
      case 4:
         $orderby="SENDERIP, MS11";
         break;
      default:
         $orderby = 'T1.MS11';
         break;
   }

   $query="SELECT T1.*, T2.L_OS, T2.MACHINETYPE, T2.MACHINEGROUP, T2.TXLOCATION, T2.AESKEYHEX, T2.ALLOWSENDTAXIS,
         T3.UPDVERSION
      FROM taxi_log T1
      LEFT JOIN taxi_eafdss T2 ON (T2.MS11=T1.MS11)
      INNER JOIN (
	      SELECT MS11, MAX(LASTUPDATE) LUPD FROM taxi_log WHERE AGENTID=? AND RECTYPE<>3
		      GROUP BY MS11
      ) J1 ON T1.MS11=J1.MS11 AND T1.LASTUPDATE>=J1.LUPD
      LEFT JOIN taxi_update T3 ON (T3.SENDERIP=T1.SENDERIP AND T3.UPDPROGRAM='taxspooler' AND T3.AGENTID=T1.AGENTID)
      WHERE T1.AGENTID=?
      ORDER BY $orderby";
   $data=array($x2->agentid, $x2->agentid);
   if (($rs=$db->Execute($query,$data))===false) {
		echo( "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n" );
		return;
   }
   while ($o1=$rs->FetchNextObject()) {
         $rsx=new cTXCERROR($o1);
         $status=$rsx->Get();
         $cmt = new cMACHINETYPE($o1->MACHINETYPE);

         $row1=array();

         $row1[]=myhtml($o1->RECTYPE==1?'online':'disk');
         $row1[]=myhtml($db->verify_8($o1->TXVERSION));
         $row1[]=myhtml($db->verify_8($o1->TXLOCATION));
         $row1[]=myhtml($db->verify_8($o1->L_OS));

         $row1[]=myhtml($db->verify_8($o1->SENDERIP));
         $row1[]=$cmt->ToString();
         $row1[]=myhtml($db->verify_8($o1->EAFDSSPORT));

         $row1[]="<span class=".(empty($status)?'green':'red').">".$db->verify_8($o1->MS11)."</span>";
         $row1[]=myhtml($o1->MACHINEGROUP.' '.@$magroup[$o1->MACHINEGROUP]);

         $row1[] = ($o1->ALLOWSENDTAXIS>0 ? "ΝΑΙ" : "Οχι");
         $row1[]=myhtml($db->verify_8($o1->AESKEYHEX));

         $row1[]=myhtml($db->verify_8($o1->UPDVERSION));

         $row1[]=myhtml($db->verify_8($o1->MVENDOR));
         $row1[]=myhtml($db->verify_8($o1->MMODEL));
         $row1[]=myhtml($db->verify_8($o1->MVERSION));

         $row1[]=GrDateHour($o1->LASTZTAKEN);

         $row1[]=myhtml($o1->LASTZNR);

         $row1[]=GrDateTime($o1->LASTUPDATE);

         $row1[]=myhtml($status);

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

   array_push($gr1->cols,
      array( 'Rec. type', 40),
		array( 'TaxSpooler', 100),
		array( 'Location', 100),
      array( 'Operating', 120),
      array( 'Sender IP', 100),
      array( 'Machine Type', 80),
      array( 'Port', 60),
      array( 'Serial', 80),
      array( 'Ομάδα', 80),
      array( 'Send to Taxis', 40),
      array( 'Taxis Key', 80),
      array( 'Update request', 80),
      array( 'Vendor', 80),
      array( 'Model', 80),
      array( 'Version', 80),
      array( 'Last Z taken', 100), // DATETIME
      array( 'Z nr', 80),
      array( 'Last update', 100),
      array(' Status', 100)
   );

   $gr1->click='oclick';
   $gr1->play();

   echo "<div id=tbar2>
      <button type=button onclick=\"show_popup('popmenu2')\">Sort</button>
      <button type=button onclick=\"goExport(1)\">Export (Excel)</button>
      <button type=button onclick=\"winRet(191)\">Προσθήκη νέας</button>
      <button type=button onclick=\"show_popup('popmenuFHM')\">ΕΑΦΔΣΣ/ POS</button>
      <b>
      <a href=\"javascript:goTo(20)\">Στοιχεία S.TXT</a> |
      <a href=\"javascript:goTo(2)\">Logfile</a> |
      <a href=\"javascript:goTo(95)\">Load AESKEY</a> |
      <a href=\"javascript:goTo(97)\">AESKEY list</a> |
      <a href=\"javascript:goTo(60)\">Esend Z</a> |
      <a href=\"javascript:goTo(70)\">myDATA</a> |
      </b>
      Records: ".count($gr1->rows)."
      </div>";

   $selx=array(
      array(1, '/img/upload.png', 'Update'),
      '<hr>',
		array(4, '/img/open_folder.gif', $x2->xxlabel('open') ),
      array(19, '/img/button_edit.png', 'AES key' ),
      array(49, '/img/checkedbox16x16.png', 'Reset [Allow Send Taxis]'),
      array(21, '/img/button_drop.png', $x2->xxlabel('del') ),
	  '<hr>',
      array(2, '/img/copy.gif', 'Copy field'),
	  array(54, '/img/details.gif', 'TaxSpooler parameters')
   );
   draw_popup($selx);

   $selx2=array(
      array(22, '/img/go_next.gif', 'EAFDSS serial'),
      array(23, '/img/go_next.gif', 'Location'),
      array(30, '/img/go_next.gif', 'TaxSpooler version'),
      array(31, '/img/go_next.gif', 'O/S'),
      array(32, '/img/go_next.gif', 'Sender IP')
   );
   draw_popup($selx2, false, 'popmenu2');

   draw_popup_FHM();
}
//--------------------------------------
function alert_history()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('javascript:goTo(10)', 1, 'Alerts all(r)')
		);
   $x2->make_header($tarray);

   $query="SELECT MS11, ALRTYPE, LASTSEND FROM taxi_alert
      WHERE AGENTID=?
      ORDER BY LASTSEND DESC, MS11";
   $data=array( $x2->agentid );
   if (($rs=$db->Execute($query,$data))===false) {
      echo $db->ErrorMsg();
      return;
   }

   $gr1=new cXRID('grid5');
   while ($o1=$rs->FetchNextObject()) {
      $gr1->rows[] = array(
         GrDateTime($o1->LASTSEND),
         myhtml($o1->MS11),
         myhtml($db->verify_8($o1->ALRTYPE))
         );
   }
   $rs->Close();

   array_push($gr1->cols,
      array('Last sent', 150),
      array('ΕΑΦΔΣΣ', 100),
      array('Alert type', 150)
      );

   $gr1->play();

   echo "<div class=bgButton2>End of data</div>";
}
//--------------------------------------
function eafdss_alerts()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('javascript:goTo(4)', 1, 'ΕΑΦΔΣΣ'),
      array('javascript:goTo(9)', 1, 'Alerts(r)')
		);
   $x2->make_header($tarray);

   echo "<div class=bgHeader>".myhtml($_SESSION['MS11'])."</div>";

   $query="SELECT ALRTYPE, LASTSEND FROM taxi_alert WHERE MS11=? AND AGENTID=?";
   $data=array($_SESSION['MS11'], $x2->agentid);
   if (($rs=$db->Execute($query,$data))===false) {
      echo $db->ErrorMsg();
      return;
   }

   $gr1=new cXRID('grid4');
   while ($o1=$rs->FetchNextObject()) {
      $gr1->rows[] = array(
         myhtml($db->verify_8($o1->ALRTYPE)),
         GrDateTime($o1->LASTSEND)
         );
   }
   $rs->Close();

   array_push($gr1->cols,
      array('Alert type', 150),
      array('Last sent', 150)
      );

   $gr1->play();

   echo "<div class=bgButton2><b><a href=\"javascript:goTo(10)\">Alerts (όλες οι ΕΑΦΔΣΣ)</a></b></div>";
}
//--------------------------------------
function eafdss_history()
{
   global $x2;
   $db=&$x2->db;

   $matype=0; // default
   $query="SELECT MACHINETYPE FROM taxi_eafdss WHERE MS11=? AND AGENTID=?";
   $data=array($_SESSION['MS11'], $x2->agentid);
   if (($rs=$db->Execute($query,$data))===false) {
      echo( "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n" );
		return;
   }
   if ($row=$rs->FetchRow()) {
      $matype=$row[0];
   }
   $rs->Close();

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter')
      );
   if ($matype==3) {
      $tarray[] = array('javascript:goTo(12)', 1, 'POS');
   }
   else {
      $tarray[] = array('javascript:goTo(4)', 1, 'ΕΑΦΔΣΣ');
   }
   $tarray[] = array('javascript:goTo(6)', 1, 'Ιστορικό(r)');
   $x2->make_header($tarray);

   // BODY
   $cmt = new cMACHINETYPE($matype);

   echo "<div class=bgHeader>".myhtml($_SESSION['MS11'])." machine type: ".myhtml($cmt->ToString())."</div>";

   $gr1=new cXRID('grid3');

   $pg=getPage();
   $pgsz=getPageSize('grid3');

   $query="SELECT * FROM taxi_log WHERE AGENTID=? AND MS11=? ORDER BY ROWID DESC";
   $data=array($x2->agentid, $_SESSION['MS11']);
   if (($rs=$db->PageExecute($query,$pgsz,$pg,$data))===false) {
		echo( "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n" );
		return;
	}
   while ($o1=$rs->FetchNextObject()) {
      $row1=array();

      $row1[]=GrDateTime($o1->LASTUPDATE);

      $row1[]=myhtml($o1->RECTYPE);
      $row1[]=myhtml($db->verify_8($o1->TXVERSION));
      $row1[]=myhtml($db->verify_8($o1->CLOGIC));

      $row1[]=myhtml($db->verify_8($o1->SENDERIP));

      $row1[]=myhtml($o1->LASTZNR);
      $row1[]=myhtml($o1->MDAILY);
      $row1[]=myhtml($o1->MPROGRESSIVE);

      $row1[]=GrDateTime($o1->MLASTOK);
      $row1[]=GrDateTime($o1->MLASTFAIL);

      $row1[]=myhtml($o1->MLASTERROR);
      $row1[]=myhtml($o1->MLASTHARDST);
      $row1[]=myhtml($o1->MLASTAPPST);

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

   array_push($gr1->cols,
      array( 'Last update', 100),
      array( 'Rec. type', 40),
		array( 'TaxSpooler Version', 100),
      array( 'Logic Version', 100),
      array( 'Sender IP', 100),
      array( 'Z nr', 80),
      array( 'Next Daily no', 80),
      array( 'Progressive no.', 80),
      array( 'Last O.K.', 100), // DATETIME
      array( 'Last Failure', 100), // DATETIME
      array( 'Last Error code', 80), // Error Code (0-255)
      array( 'Last Hardware Status', 80), // (0-255)
      array( 'Last Application Status', 80) // (0-255)
   );
   $gr1->play();

   echo "<div id=tbar2>";
   print_page_navEx($pg,$epage,6);
   echo "&nbsp;<b><a href=\"javascript:goTo(2)\">Logfile</a></b></div>";
}
//--------------------------------------
function purge_old_recs()
{
   global $x2;
   $db=&$x2->db;

   //
   // Delete all but the last record
   //
   $s11=array();
   $query="SELECT MS11, MAX(LASTUPDATE) LUPD FROM taxi_log WHERE AGENTID=? /* AND RECTYPE=3 */
		GROUP BY MS11
		ORDER BY MS11";
   $data=array($x2->agentid);
   if (!($rs=$db->Execute($query,$data))) {
		echo( "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n" );
		return;
	}
   while ($o1=$rs->FetchNextObject()) {
      $s11[ $db->verify_8($o1->MS11) ] = $o1->LUPD;
   }
   $rs->Close();

   $dt = (int)@$_REQUEST['RECORDID'];
   if ($dt>=0) { // days
      $t2 = time() - $dt*24*3600;
   }
   else { // hours (negative)
      $t2 = time() + $dt*3600;
   }
   $dlimit = date('Y-m-d H:i:s', $t2);
   $query="DELETE FROM taxi_log WHERE AGENTID=? AND LASTUPDATE<? AND LASTUPDATE<?";
   foreach ($s11 as $ms11=>$lu) {
      $data=array($x2->agentid, $dlimit, $lu );
      if (!$db->Execute($query,$data)) {
         echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
      }
   }
}
//--------------------------------------
function set_remote_params()
{
   global $x2, $pname_desc;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(45)', 1, 'Remote parameters'),
      array('', 1, 'Set parameter')
		);
   $x2->make_header($tarray);

   $xgroup = (int)$_REQUEST['XGROUP'];

   $db->StartTrans();

   do {
      // Read locations applied
      $locations = array();
      if (!empty($_REQUEST['BRAGROUP'])) {
         $query = 'SELECT TXLOCATION FROM taxi_brgroup WHERE AGENTID=? AND GROUPID IN ('.
            implode(',', $_REQUEST['BRAGROUP']).') ORDER BY GROUPID';
         $data = [$x2->agentid];
         if (($rs=$db->Execute($query, $data))===false) {
            echo __LINE__.' '.$db->ErrorMsg();
            return;
         }
         while ($o1 = $rs->FetchNextObject()) {
            $locations[] = $o1->TXLOCATION;
         }
         $rs->Close();
      }

      //
      // Delete all 'TaxSpooler.EsParastat' taxi_newpropfor.packages for locations applied, no matter the XGROUP
      //
      $query = '';
      $data = array();
      foreach ($locations as $txlocation) {
         if (empty($query)) {
            $query = "SELECT T2.PACKAGE, T2.TXLOCATION FROM taxi_newproppkg T1
               LEFT JOIN taxi_newpropfor T2 ON (T2.AGENTID=T1.AGENTID AND T2.PACKAGE=T2.PACKAGE)
               WHERE T1.AGENTID=$x2->agentid AND T1.PNAME LIKE 'TaxSpooler.EsParastat.%' AND T2.TXLOCATION IN (?";
            $data[] = $txlocation;
         }
         else {
            $query .= ", ?";
            $data[] = $txlocation;
         }
      }
      if (!empty($query)) {
         $fordel = array();
         $query .= ") GROUP BY T2.PACKAGE, T2.TXLOCATION";
         if (($rs=$db->Execute($query, $data))===false) {
            echo __LINE__.' '.$db->ErrorMsg();
            return;
         }
         while ($o1 = $rs->FetchNextObject()) {
            $fordel[] = $o1;
         }
         $rs->Close();

         $query = 'DELETE FROM taxi_newpropfor WHERE AGENTID=? AND TXLOCATION=? AND PACKAGE=?';
         $db->StartTrans();
         foreach ($fordel as $o1) {
            $data = [$x2->agentid, $o1->TXLOCATION,$o1->PACKAGE];
            if (!$db->Execute($query, $data)) {
               echo __LINE__.' '.$db->ErrorMsg();
               return;
            }
         }
         $db->CompleteTrans();
      }

      // Cleanup packages for XGROUP
      $query = "DELETE FROM taxi_newproppkg
         WHERE AGENTID=? AND XGROUP=? AND PNAME LIKE 'TaxSpooler.EsParastat.%' ";
      $data = [$x2->agentid, $xgroup];
      if (!$db->Execute($query, $data)) {
         echo __LINE__.' '.$db->ErrorMsg();
         break;
      }

      // Cleanup orphans (any taxi_newpropfor records that do not have corresponding taxi_newproppkg records)
      $ardel = array();
      $query = "SELECT T1.PACKAGE FROM taxi_newpropfor T1
         LEFT JOIN taxi_newproppkg T2 ON (T2.AGENTID=T1.AGENTID AND T2.PACKAGE=T2.PACKAGE)
         WHERE T1.AGENTID=? AND T2.PACKAGE IS NULL
         GROUP BY T1.PACKAGE";
      $data = array($x2->agentid);
      if (($rs=$db->Execute($query, $data))===false) {
         echo __LINE__.' '.$db->ErrorMsg();
         break;
      }
      while ($row=$rs->FetchRow()) {
         $ardel[] = $row[0];
      }
      $rs->Close();

      if (!empty($ardel)) {
         $query = "DELETE FROM taxi_newpropfor
            WHERE AGENTID=? AND PACKAGE IN (".implode(',', $ardel).")";
         if (!$db->Execute($query, $data)) {
            echo __LINE__.' '.$db->ErrorMsg();
            break;
         }
      }

      // Get package no., using time();
      // could be a conflict if 2 users do the same, but it is unlike to happen;
      // it is also better then mt_rand() in case TaxSpooler is in the middle of a transaction
      $package=time();

      // Create new data for taxi_newproppkg
      $data = array();
      $query = '';
      foreach ($_REQUEST['key'] as $k=>$val)
      {
         $val = trim($val); // reset
         if ($val==='')
            continue;

         if (empty($query)) {
            $query = "INSERT INTO taxi_newproppkg (AGENTID, PACKAGE, XGROUP, PNAME, PVALUE) VALUES ";
         }
         else {
            $query .= ", ";
         }
         $query .= "($x2->agentid, $package, $xgroup, ?,?), ($x2->agentid, $package, $xgroup, ?,?), ($x2->agentid, $package, $xgroup, ?,?)";

         $pname = sprintf('TaxSpooler.EsParastat._%d.key', $k+1);
         array_push($data, $pname, $val);

         $pname = sprintf('TaxSpooler.EsParastat._%d.val', $k+1);
         array_push($data, $pname, (string)((int)$_REQUEST['val'][$k]));

         $pname = sprintf('TaxSpooler.EsParastat._%d.assoc', $k+1);
         array_push($data, $pname, (string)((int)$_REQUEST['assoc'][$k]));
      }

      if (!empty($query) && !$db->Execute($query, $data)) {
         echo __LINE__.' '.$db->ErrorMsg();
         break;
      }

      // Create new data for taxi_newpropfor (for which nodes/subnodes is package intended)
      $nodes = (int)$_REQUEST['NODES'];
      $now = date('Y-m-d H:i:s');
      $data = array();
      $query = '';
      foreach ($locations as $txlocation) {
         if (empty($query)) {
            $query = "INSERT INTO taxi_newpropfor (AGENTID, TXLOCATION, PACKAGE, NODES, CREDAYTIME) VALUES";
         }
         else {
            $query .= ", ";
         }
         $query .= " ($x2->agentid, ?, {$package}, {$nodes}, '$now')";
         array_push($data, $txlocation);
      }
      if (!empty($query) && !$db->Execute($query, $data)) {
         echo __LINE__.' '.$db->ErrorMsg();
         break;
      }

   } while (false);

   $err = $db->hasFailedTrans();
   $db->CompleteTrans();

   if (!$err) {
      echo "<h5>OK</h5>
         <button type=button onclick=\"goRecord(48, '{$xgroup}.EsParastat')\">Next</button>";
   }
}
//--------------------------------------
function remote_param_one($load_from_file = false)
{
   global $x2, $pname_desc, $documentPOL;
   $db=&$x2->db;
?>
<script>
var divSelDoc = null;
var valFld = null;
$(function(){
   divSelDoc = $('#divSelDocument').dialog({autoOpen:false, modal:true, width:640});
   $('#selXmlFile').dialog({autoOpen:false, modal:true, width:440});
   $('body').on('click', '.selPar', function(){
      valFld = $(this).prev();
      divSelDoc.dialog('open');
   });
} );
function makeDocSelection()
{
   valFld.val( $('#selDocument').val() );
   divSelDoc.dialog('close');
}
</script>
<div id=divSelDocument title="Select document">
   <select id=selDocument size=20><?php
      foreach ($documentPOL as $ar1) {
         echo "<option>".$ar1[0].'# '.myhtml($ar1[1])."</option>";
      }
      $docs = 0;
   ?></select>
   <button type=button onclick="makeDocSelection()">Select</button>
   <button type=button onclick="divSelDoc.dialog('close');">Cancel</button>
</div>
<div id=selXmlFile title="Select TaxSpooler XML export">
   <form enctype="multipart/form-data" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method=POST>
      <input type=hidden name="FUNCTION" value="53">
      <input type=hidden name="RECORDID" value="<?php echo myhtml($_REQUEST['RECORDID']); ?>">
      <input type=file name="XMLFILE"><br>
      <input type=submit value="Load">
   </form>
</div>
<?php
   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(45)', 1, 'Remote parameters'),
      array('', 1, 'Set parameter')
		);
   $x2->make_header($tarray);

   $ar1 = explode('.', $_REQUEST['RECORDID'], 2);
   if (count($ar1) != 2) {
      echo 'Error in parameter!';
      return;
   }
   $xgroup = (int)$ar1[0];
   $pname = $ar1[1];

   if ($pname !== 'EsParastat') { // EsCurrency, EsFuel, EsNonSenseAfm
      echo "Not implemented!";
      return;
   }

   $xname = '';
   $query = 'SELECT MENUDES FROM menurep WHERE AGENTID=? AND MENUTYPE=24 AND MENUID=?';
   $data = array($x2->agentid, $xgroup);
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__.' '.$db->ErrorMsg();
      return;
   }
   if ($row=$rs->FetchRow()) { $xname = $row[0]; }
   $rs->Close();

   echo "<div class=bgHeader style=\"padding:10px\">
      Parameter: [$pname] ".myhtml($pname_desc[$pname])." Group: {$xgroup}.".myhtml($xname)."</div>
      <form action=\"".$_SERVER['SCRIPT_NAME']."\" method=POST>
      <input type=hidden name=\"FUNCTION\" value=\"47\">
      <input type=hidden name=\"XGROUP\" value=\"$xgroup\">
      <table class=masterTable>
      <tr>
      <td>";
   // Left part
   ask_rsetup_parastat($xgroup, $load_from_file); // key[], val[], assoc[]
   echo "</td>
      <td>";
   // Middle part
   echo "<b>Location</b>";
   ask_location(); // TaxCenter geolocation groups (none preselected)
   echo "</td>
      <td>";
   // Right part
   echo "<b>Workstation</b><br>
         <label><input type=radio name=\"NODES\" value=\"1\" checked> LAN server</label><br>
         <label><input type=radio name=\"NODES\" value=\"2\"> LAN client</label><br>
         <label><input type=radio name=\"NODES\" value=\"3\"> Both</label>";
   echo "</td>
      </tr>
      </table>
      <div id=tbar2>
         <input type=submit value=\"Ενημέρωση\">
      </div>
      </form>";
}
//--------------------------------------
function ask_location()
{
   global $x2;
   $db=&$x2->db;
?>
<script>
function checUnchkLocation()
{
   var Checked = true;
   $('input[name="BRAGROUP[]"]').each(function(){
      if (!$(this).prop('checked')) {
         Checked = false;
      }
   } );
   $('input[name="BRAGROUP[]"]').prop('checked', !Checked);
}
</script>
<?php
   $query = 'SELECT MENUID, MENUDES FROM menurep WHERE AGENTID=? AND MENUTYPE=23 ORDER BY MENUID';
   $data = array($x2->agentid);
   if (($rs=$db->Execute($query,$data))===false) {
      echo $db->ErrorMsg();
      return;
   }
   echo "<div style=\"border:1px solid gray;\">";
   while ($o1=$rs->FetchNextObject()) {
      echo "<label><input type=checkbox name=\"BRAGROUP[]\" value=\"$o1->MENUID\">".
         myhtml($o1->MENUDES)."</label><br>";
   }
   $rs->Close();
   echo "</div>
      <button type=button onclick=\"checUnchkLocation()\">Check/Uncheck all</button>";
}
//--------------------------------------
function ask_rsetup_parastat($xgroup, $load_from_file)
{
   global $x2;
   $db=&$x2->db;

?>
<script>
function addInputRow()
{
   $('#rowInput').append( '<tr>' +
         '<td><input type=TEXT name="key[]"></td>' +
         '<td><input type=TEXT name="val[]"><button type=button class=\"selPar\">...</button></td>' +
         '<td><input type=TEXT name="assoc[]"><button type=button class=\"selPar\">...</button></td>' +
         '</tr>' );
}
</script>
<?php
   $pa = array();
   if ($load_from_file) {
      if (isset($_FILES['XMLFILE']) && $_FILES['XMLFILE']['error']==0) {
         if (strcasecmp(pathinfo($_FILES['XMLFILE']['name'], PATHINFO_EXTENSION), "xml") != 0) {
            echo '<h5>Not an XML file!</h5>';
         }
         else {
            if (($xml = simplexml_load_file($_FILES['XMLFILE']['tmp_name'])) === false) {
               echo '<h5>Failed to load XML file!</h5>';
            }
            else {
               $ar1 = get_object_vars($xml->EsParastat);
               foreach ($ar1 as $o1) {
                  $pa[] = (array)$o1;
               }
            }
         }
      }
   }
   else {
      $query = "SELECT PNAME, PVALUE FROM taxi_newproppkg
         WHERE AGENTID=? AND XGROUP=? AND PNAME LIKE 'TaxSpooler.EsParastat.%' ";
      $data = [$x2->agentid, $xgroup];
      if (($rs=$db->Execute($query,$data))===false) {
         echo $db->ErrorMsg();
         return;
      }
      while ($o1=$rs->FetchNextObject()) {
         $ar1 = explode('.', $o1->PNAME); // ie.: TaxSpooler.EsParastat._14.key
         if (count($ar1)==4) {
            $k = (int)substr($ar1[2], 1);
            if (!array_key_exists($k, $pa)) {
               $pa[$k] = array('key'=>'', 'val'=>0, 'assoc'=>0);
            }
            switch ($ar1[3])
            {
               case 'key':
                  $pa[$k]['key'] = $o1->PVALUE;
                  break;
               case 'val':
                  $pa[$k]['val'] = $o1->PVALUE;
                  break;
               case 'assoc':
                  $pa[$k]['assoc'] = $o1->PVALUE;
                  break;
            }
         }
      }
      $rs->Close();
   }

   ksort($pa);

   echo "<table>
      <thead>
      <tr class=bgHeader>
      <th>Περιγραφή</th>
      <th>Κωδικός ΠΟΛ</th>
      <th>Σχετικό παραστατικό ΠΟΛ</th>
      </tr>
      </thead>
      <tbody id=rowInput>";
   foreach ($pa as $k=>$ar1) {
      $val = $ar1['val'].'# '.getDocName($ar1['val']);
      echo "<tr>
         <td><input type=TEXT name=\"key[]\" value=\"".myhtml($ar1['key'])."\"></td>
         <td><input type=TEXT name=\"val[]\" value=\"".myhtml($val)."\"><button type=button class=\"selPar\">...</button></td>
         <td><input type=TEXT name=\"assoc[]\" value=\"".myhtml($ar1['assoc'])."\"><button type=button class=\"selPar\">...</button></td>
         </tr>";
   }
   echo "</tbody>
      <tfoot>
      <tr>
      <td colspan=3>
         <button type=button onclick=\"addInputRow()\">Add record</button>
         <button type=button onclick=\"$('#selXmlFile').dialog('open');\">Load file</button>
      </td>
      </tr>
      </tfoot>
      </table></form>";

}
//--------------------------------------
function update_brgroup()
{
   global $x2;
   $db=&$x2->db;

   $db->StartTrans();

   do {
      $query = 'DELETE FROM taxi_brgroup WHERE AGENTID=?';
      $data = [$x2->agentid];
      if (!$db->Execute($query, $data)) {
         echo __LINE__.' '.$db->ErrorMsg();
         break;
      }

      $query = 'INSERT INTO taxi_brgroup (AGENTID, TXLOCATION, GROUPID) VALUES(?, ?, ?)';
      $n = count($_REQUEST['TXLOCATION']);
      for ($i=0;$i<$n;$i++) {
         if ($_REQUEST['GROUPID'][$i] >= 0) {
            $data = [ $x2->agentid, $_REQUEST['TXLOCATION'][$i], $_REQUEST['GROUPID'][$i] ];
            if (!$db->Execute($query, $data)) {
               echo __LINE__.' '.$db->ErrorMsg();
               break;
            }
         }
      }

   } while (false);

   $db->CompleteTrans();
}
//--------------------------------------
function branch_per_group()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
   $tarray=array(
		array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(45)', 1, 'Remote parameters'),
      array('javascript:goTo(51)', 1, 'Καταστήματα ομάδας(r)')
		);
   $x2->make_header($tarray);

   $grp = array( (object)['MENUID'=>-1, 'MENUDES'=>''] );
   $query = 'SELECT MENUID, MENUDES FROM menurep WHERE AGENTID=? AND MENUTYPE=23 ORDER BY MENUID';
   $data = [$x2->agentid];
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__.' '.$db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $grp[] = $o1;
   }
   $rs->Close();

   // Read all locations
   $locations = array();
   //$query = 'SELECT DISTINCT TXLOCATION FROM taxi_wmic WHERE AGENTID=? ORDER BY TXLOCATION';
   $query = 'SELECT DISTINCT TXLOCATION FROM taxi_eafdss WHERE AGENTID=? ORDER BY TXLOCATION';
   $data = [$x2->agentid];
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__.' '.$db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      if (!empty($o1->TXLOCATION)) {
         $locations[] = $o1->TXLOCATION;
      }
   }
   $rs->Close();

   // Read location - group assignment
   $bgroup = array();
   $query = 'SELECT TXLOCATION, GROUPID FROM taxi_brgroup WHERE AGENTID=?';
   $data = [$x2->agentid];
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__.' '.$db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $bgroup[$o1->TXLOCATION] = $o1->GROUPID;
   }
   $rs->Close();
?>
   <form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method=POST>
   <input type=hidden name="FUNCTION" value="52">
      <table>
         <tr>
            <th>Κατάστημα</th>
            <th>Ομάδα</th>
         </tr>
<?php
   foreach ($locations as $location1) {
      if (array_key_exists($location1, $bgroup))
         $id1 = $bgroup[$location1];
      else
         $id1 = -1;

      echo '<tr>'.
         '<td><input type=text name="TXLOCATION[]" value="'.myhtml($location1).'"></td>'.
         '<td><select name="GROUPID[]">';
      foreach ($grp as $o1) {
         echo '<option value="'.$o1->MENUID.'"';
         if ($o1->MENUID == $id1) { echo ' selected'; }
         echo '>'.myhtml($o1->MENUDES).'</option>';
      }
      echo '</select></td>'.
         '</tr>';
   }
?>
         <tr>
            <td colspan=2 class="bgButton">
               <input type=submit value="Update">
            </td>
         </tr>
      </table>
   </form>
<?php
}
//--------------------------------------
function remote_params()
{
   global $x2, $pname_desc;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(45)', 1, 'Remote parameters(r)')
		);
   $x2->make_header($tarray);

   $paramGrp = array();
   $query = 'SELECT MENUID, MENUDES FROM menurep WHERE AGENTID=? AND MENUTYPE=24 ORDER BY MENUID';
   $data = [$x2->agentid];
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__.$db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $paramGrp[] = $o1;
   }
   $rs->Close();

   ?>
<script>
var recordId=null;
function oclick(stage, row, col)
{
   var grpArray = this.cells(row,2).getValue().split('.');
   recordId = grpArray[0] + '.' + this.cells(row, 0).getValue();
   show_popup('popmenu');
	return false;
}
function winRet(x)
{
   switch (x)
   {
   case 46:
   case 48:
      goRecord(x, recordId);
      break;
   }
   hide_popup();
}
</script>
<?php
   $gr1=new cXRID('grid16');
   array_push($gr1->cols,
      array( 'Name', 140),
      array( 'Description', 340),
      array( 'Param group', 200)
      );

   foreach ($pname_desc as $key=>$val) {
      foreach ($paramGrp as $p1) {
         $grp = $p1->MENUID.'.'.$p1->MENUDES;
         $row1 = array($key, myhtml($val), myhtml($grp));
         $gr1->rows[] = $row1;
      }
   }

   $gr1->click='oclick';
   $gr1->play();

   echo "<div id=tbar2><small>End of data</small>
      <b>
      <a href=\"javascript:goFX('/ishop/ishop_wre.php',270)\">Ομάδες καταστημάτων</a> |
      <a href=\"javascript:goTo(51)\">Καταστήματα ομάδας</a> |
      <a href=\"javascript:goFX('/ishop/ishop_wre.php',280)\">Ομάδες παραμέτρων</a> |
      <a href=\"javascript:goRecord(48, 'x.EsParastat')\">Πρόοδος ενημέρωσης</a>
      </b></div>";

   $selx=array(
      array(46, '/img/button_edit.png', 'Set property'),
      array(48, '/img/report16x16.gif', 'Update progress')
   );
   draw_popup($selx);
}
//--------------------------------------
function remote_param_progress()
{
   global $x2, $pname_desc;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(45)', 1, 'Remote parameters'),
      array('javascript:goRecord(48, \'x.EsParastat\')', 1, 'Update progress(r)')
		);
   $x2->make_header($tarray);
?>
<script>
$(function(){
   $('#propZoom').dialog({autoOpen:false, modal:true, width:620, height:460});
});
function oclick(stage, row, col)
{
   $('#propZoom').dialog('open');
}
</script>
<?php
   $ar1 = explode('.', $_REQUEST['RECORDID'], 2);
   $xgroup = (int)$ar1[0];
   $pname = $ar1[1];

   echo "<div class=bgHeader style=\"padding:10px\">
      Parameter: [$pname] ".myhtml($pname_desc[$pname])."</div>"; // $xgroup not needed

   $gr1=new cXRID('grid17');
   array_push($gr1->cols,
      array( 'Package', 120),
      array( 'Location', 200),
      array( 'Nodes', 180),
      array( 'Request', 160),
      array( 'Updated', 160)
      );

   $pname = 'TaxSpooler.'.$pname; // normalize (after we have drawn header)

   $packages=array();
   $query = "SELECT T1.TXLOCATION, T1.PACKAGE, T1.NODES, T1.CREDAYTIME, T1.CLIUPDATE
      FROM taxi_newpropfor T1
      LEFT JOIN taxi_newproppkg T2 ON (T2.AGENTID=T1.AGENTID AND T2.PACKAGE=T1.PACKAGE)
      WHERE T1.AGENTID=? AND T2.PNAME LIKE ?
      GROUP BY T1.TXLOCATION, T1.PACKAGE, T1.NODES, T1.CREDAYTIME, T1.CLIUPDATE
      ORDER BY T1.TXLOCATION, T1.PACKAGE";
   $data = [$x2->agentid, "{$pname}.%"];
   if (($rs=$db->Execute($query,$data))===false) {
      echo __LINE__.$db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      if (!in_array($o1->PACKAGE, $packages)) {
         $packages[] = $o1->PACKAGE;
      }

      switch ($o1->NODES)
      {
      case 0:
         $nodes_des='Nothing';
         break;
      case 1:
         $nodes_des='Server';
         break;
      case 2:
         $nodes_des='Client';
         break;
      case 3:
         $nodes_des='BOTH';
         break;
      default:
         $nodes_des='Unknown #'.$o1->NODES;
         break;
      }
      $row1=array(
         myhtml($o1->PACKAGE),
         myhtml($o1->TXLOCATION),
         myhtml($nodes_des),
         myhtml($o1->CREDAYTIME),
         myhtml($o1->CLIUPDATE)
      );
      $gr1->rows[] = $row1;
   }
   $rs->Close();

   $gr1->click='oclick';
   $gr1->play();

   echo "<div id=tbar2><small>End of data</small></div>";

   echo "<div id=propZoom title=\"Properties\" style=\"overflow:auto;\">";
   $query = "SELECT PACKAGE, PNAME, PVALUE FROM taxi_newproppkg
      WHERE AGENTID=? AND PNAME LIKE ? AND PACKAGE IN (".implode(',', $packages).")
      ORDER BY PNAME, PACKAGE";
   $data = array($x2->agentid, "{$pname}.%" );
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__.$db->ErrorMsg();
   }
   else {
      echo "<table class=masterTable>
         <tr>
         <th>Pakcage</th>
         <th>Propery name</th>
         <th>Property value</th>
         </tr>";
      while ($o1=$rs->FetchNextObject()) {
         $val = $o1->PVALUE;
         $ar1 = explode('.', $o1->PNAME);
         if (array_pop($ar1)==='val') {
            $val .= '# '.getDocName($val);
         }

         echo "<tr>
            <td>".myhtml($o1->PACKAGE)."</td>
            <td>".myhtml($o1->PNAME)."</td>
            <td>".myhtml($val)."</td>
            </tr>";
      }
      $rs->Close();
      echo "</table>";
   }
   echo "</div>";
}
//--------------------------------------
function show_records()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
		array('javascript:goTo(1)', 1, 'TaxCenter'),
      array('javascript:goTo(2)', 1, 'Logfile(r)')
		);
   $x2->make_header($tarray);

   // BODY
   $mif=array( 'Row Id', 'Connection Port', 'Machine Vendor', 'Machine Model',
      'Bios version', 'Time open', 'First signature', 'Last Z taken', 'Time passed',
      'Last OK operation', 'Last Error operation', 'Last Error code',
      'Last Hardware status', 'Last Application status', 'Text spec.' );
   echo "<div id=moreinfo title=\"More info\"><table>";
   $n=count($mif);
   for ($i=0;$i<$n;$i++) {
      echo "<tr>
         <td class=bgLabel>".myhtml($mif[$i])."</td>
         <td class=bgInput id=mif$i></td>
         </tr>";
   }
   echo "</table></div>";
?>
<div id=deldiv title="Cleanup old records">
   Να διαγραφούν εγγραφές παλιότερες από:<br>
   <select id=delperiod>
      <option value="365">1 year</option>
      <option value="183">6 months</option>
      <option value="61">2 months</option>
      <option  value="31">1 month</option>
      <option value="10">10 days</option>
      <option value="3">3 days</option>
      <option value="2">2 days</option>
      <option value="1">1 days</option>
      <option value="-12">12 hours</option>
      <option value="-6">6 hours</option>
      <option value="-3">3 hours</option>
   </select><br>
   <button type=button onclick="goDeleteOld()">Διαγραφή</button>
</div>
<script>
$(function(){
   $('#moreinfo').dialog({autoOpen:false, modal:true});
   $('#deldiv').dialog({autoOpen:false, modal:true, resizable:false});
} );
function onAskDel()
{
   $('#deldiv').dialog('open');
}
function goDeleteOld()
{
   goRecord(14, $('#delperiod').val() );
}
function oclick(stage, row, col)
{
   var mi = this.getUserData(row, 'moreinfo');
   var mia=mi.split('~');
   for (var i=0;i<mia.length;i++) {
      $('#mif'+i).text(mia[i]);
   }
   $('#moreinfo').dialog('open');
}
</script>
<?php
   $f1=new cFORM('goForm',0);
	$f1->vars=array( 'FUNCTION'=>'', 'RECORDID'=>'', 'RSPAGE'=>'' );
	$f1->run();

   $gr1=new cXRID('grid1');

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

   $machines=array();
   $query="SELECT MS11, MACHINETYPE, TXLOCATION FROM taxi_eafdss WHERE AGENTID=?";
   $data=array($x2->agentid);
   if (($rs=$db->Execute($query,$data))===false) {
      echo( "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n" );
		return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $machines[$o1->MS11] = (array)$o1; //$o1->MACHINETYPE;
   }
   $rs->Close();

   $query="SELECT * FROM taxi_log WHERE AGENTID=? ORDER BY ROWID DESC";
   $data=array($x2->agentid);
   if (!($rs=$db->PageExecute($query,$pgsz,$pg,$data))) {
		echo( "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n" );
		return;
	}
   while ($o1=$rs->FetchNextObject()) {
      $row1=array();

      $ms11 = $o1->MS11;
      if (array_key_exists($ms11, $machines)) {
         $oM=$machines[$ms11];
      }
      else {
         $oM=array('MACHINETYPE'=>0, 'TXLOCAION'=>'');
      }

      $diffti='';
      $ti1=sql2date($o1->RETEAFDSSTIME);
      $ti2=sql2date($o1->ASKEAFDSSTIME);
      if ($ti1!=0 && $ti2!=0) {
         $dx=$ti2-$ti1; // seconds
         if (abs($dx)<1800)
            $diffti = sprintf("%.1lf mininutes", $dx/60.0);
         else
            $diffti = sprintf("%.1lf hours", $dx/3600.0);
      }

      $moreinfo=implode('~', array(
         $o1->ROWID,
         $o1->EAFDSSPORT,
         myhtml($db->verify_8($o1->MVENDOR)),
         myhtml($db->verify_8($o1->MMODEL)),
         myhtml($db->verify_8($o1->MVERSION)),
         GrDateTime($o1->OPENTIME),
         GrDateHour($o1->FIRSTSIGNINZ),
         GrDateHour($o1->LASTZTAKEN),
         $o1->MTIMEPASSED,
         GrDateTime($o1->MLASTOK),
         GrDateTime($o1->MLASTFAIL),
         $o1->MLASTERROR,
         $o1->MLASTHARDST,
         $o1->MLASTAPPST,
         $o1->MLASTERROR,
         $o1->MLASTHARDST,
         $o1->MLASTAPPST,
         myhtml($db->verify_8($o1->TXSPEC))
      ) );

      $row1[]=array(
         'data'=>GrDateTime($o1->LASTUPDATE),
         'userdata'=>array('moreinfo'=>$moreinfo)
         );

      $row1[]=myhtml($o1->RECTYPE);
      $row1[]=myhtml($db->verify_8($o1->TXVERSION));
      $row1[]=myhtml($db->verify_8( $oM['TXLOCATION'] ));
      $row1[]=myhtml($db->verify_8($o1->CLOGIC));

      $row1[]=myhtml($db->verify_8($o1->SENDERIP));

      $j=(int)$oM['MACHINETYPE'];
      if (array_key_exists($j, $x2->M_MODELS)) {
         $row1[]=$x2->M_MODELS[$j];
      }
      else {
         $row1[]='Unknown';
      }

      $row1[]=myhtml($db->verify_8($o1->MS11));

      $row1[]=myhtml($o1->LASTZNR);
      $row1[]=myhtml($o1->MDAILY);
      $row1[]=myhtml($o1->MPROGRESSIVE);

      $row1[]=myhtml($o1->MEM_USG);
      $row1[]=myhtml($o1->CPU_USG);

      $row1[]=GrDateTime($o1->MLASTOK);
      $row1[]=GrDateTime($o1->MLASTFAIL);

      $row1[]=GrDateTime($o1->RETEAFDSSTIME);
      $row1[]=GrDateTime($o1->ASKEAFDSSTIME);
      $row1[]=$diffti;

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

   array_push($gr1->cols,
      array( 'Last update', 100),
      array( 'Rec. type', 40),
		array( 'TaxSpooler Version', 100),
		array( 'Location', 100),
      array( 'Logic Version', 100),
      array( 'Sender IP', 100),
      array( 'Machine Type', 80),
      array( 'Serial', 100),
      array( 'Z nr', 80),
      array( 'Next Daily no', 80),
      array( 'Progressive no.', 80),
      array( 'Memory free (MB)', 100),
      array( 'CPU usage %', 100),
      array( 'Last OK comm.', 120),
      array( 'Last Error comm.', 120),
      array( 'EAFDSS time', 120),
      array( 'System ask time', 120),
      array( 'Diff.', 120)
   );
   $gr1->click='oclick';
   $gr1->play();

   echo "<div id=tbar2>";
   print_page_navEx($pg,$epage,2);
   echo "<button type=button class=NavButton onclick=\"onAskDel()\"><img src=\"/img/drop.png\"></button>
      <b>
      <a href=\"javascript:goTo(5)\">Στοιχεία ΕΑΦΔΣΣ</a> |
      <a href=\"javascript:goTo(11)\">Στοιχεία POS</a> |
      <a href=\"javascript:goTo(20)\">Στοιχεία S.TXT</a>
      </b>
      </div>";
}
//--------------------------------------
function show_incoming_files()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("ADMIN", 0, 'Main'),
      array('javascript:goTo(202)', 1, 'Show incoming files(r)')
		);
	$x2->make_header($tarray);

   echo '<table>
      <colgroup>
      <col>
      <col style="background-color:#e0e0e0;">
      </colgroup>
      <tbody>';
   $ar1 = scandir($_SESSION['TAX_Catalog']);
	foreach ($ar1 as $f1) {
		if ($f1 === '.' || $f1 === '..' || $f1 === 'err')
			continue;

		$ff1 = $_SESSION['TAX_Catalog']."\\$f1";
		if (is_dir($ff1)) {
         $sz2 = 0;
			echo "<tr><td>$f1</td>";
         $ar2 = scandir($ff1);
         foreach ($ar2 as $f2) {
            $ff2 = "$ff1\\$f2";
            if (!is_dir($ff2)) {
               $info = stat($ff2);
               $sz2 += $info['size'];
            }
         }
         echo "<td>$sz2</td></tr>";
		}
	}
	echo '</tbody></table>';
}
//--------------------------------------
function add_sms_invoice()
{
   global $x2;
   $db=&$x2->db;

   $query="INSERT INTO ishop_sms_unit (AGENTID, INVOICENR, INVDATE, INVUNITS, UNITSLEFT) VALUES(?,?,?,?,?)";
   $data=array( $_SESSION['FORAGENTID'], $_REQUEST['INVOICENR'], $_REQUEST['INVDATE'],
      (int)$_REQUEST['INVUNITS'], (int)$_REQUEST['INVUNITS'] );
   if (!$db->Execute($query,$data)) {
      umessage($db->ErrorMsg());
   }
}
//--------------------------------------
function list_sms_units()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("ADMIN", 0, 'Main'),
      array('javascript:goTo(200)', 1, 'SMS units(r)')
		);
	$x2->make_header($tarray);

   if ($_REQUEST['FUNCTION']==200 && !empty($_REQUEST['RECORDID'])) {
      $query="SELECT AGENTID FROM agents WHERE LPATH=?";
      $data=array($_REQUEST['RECORDID']);
      if (($rs=$db->Execute($query,$data))===false) {
         echo $db->ErrorMsg();
         return;
      }
      $row=$rs->FetchRow();
      $rs->Close();
      if ($row===false) {
         echo "<h6>Could not find agent ".myhtml($_REQUEST['RECORDID'])."</h6>";
         return;
      }
      $_SESSION['FORLPATH'] = $_REQUEST['RECORDID'];
      $_SESSION['FORAGENTID'] = (int)$row[0];
   }

   echo "<div class=bgHeader>Agent: ".myhtml($_SESSION['FORLPATH'])."</div>";

   $query="SELECT * FROM ishop_sms_unit WHERE AGENTID=? ORDER BY INVDATE DESC";
   $data=array( $_SESSION['FORAGENTID'] );
   if (($rs=$db->Execute($query,$data))===false) {
      echo $db->ErrorMsg();
      return;
   }

   $gr1=new cXRID('grid6');

   while ($o1=$rs->FetchNextObject()) {
      $row1=array(
         $o1->UID,
         myhtml($db->verify_8($o1->INVOICENR)),
         GrDateTime($o1->INVDATE),
         $o1->INVUNITS,
         $o1->UNITSLEFT,
         GrDateTime($o1->LASTUPDATE)
      );
      $gr1->rows[]=$row1;
   }
   $rs->Close();

   $gr1->cols=array(
      array('Record ID', 80),
      array('Invoice nr.', 80),
      array('Invoice date', 120),
      array('Invoice units', 80),
      array('Units left', 80),
      array('Last update', 120)
   );

   $gr1->play();
?>
<div class=bgButton2>
   <button type=button onclick="askInvoice()">Add Units</button>
</div>
<div id=invdlg title="Add Invoice" style="display:none">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method=POST>
<input type=hidden name="FUNCTION" value="201">
<table>
<tr>
   <td class=bgLabel>Invoice number</td>
   <td class=bgInput><input type=TEXT name="INVOICENR"></td>
</tr>
<tr>
   <td class=bgLabel>Invoice date</td>
   <td class=bgInput><input type=TEXT name="INVDATE" value="<?php echo date('Y-m-d'); ?>"></td>
</tr>
<tr>
   <td class=bgLabel>Units</td>
   <td class=bgInput><input type=TEXT name="INVUNITS"></td>
</tr>
<tr>
   <td></td>
   <td class=bgButton><input type=SUBMIT value="Save"></td>
</tr>
</table>
</form>
</div>
<script>
function askInvoice()
{
   $('#invdlg').dialog({'modal':true, 'resizable':false}).dialog('open');
}
</script>
<?php
}
//--------------------------------------
function ask_params($check_tables=false)
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
      array('', 1, 'TaxCenter setup')
		);
   $x2->make_header($tarray);

   // BODY
   if ($check_tables)
   {
      require_once('ishop_tables.php');
      chk_tables_txc($db);
   }
?>
<script>
function clearall()
{
   if (window.confirm('Clear all wmic database data?')) {
      goTo(102);
   }
}
</script>
<button type=button onclick="clearall()" title="wmic data">Clear database</button>
<hr>
<table>
   <tr>
      <td>System date/time:</td>
      <td><?php echo date('Y-m-d H:i:s'); ?></td>
   </tr>
   <tr>
      <td>SQL date/time:</td>
      <td><?php
   $query="SELECT NOW()";
   if (($rs=$db->Execute($query))!==false) {
      if (($row=$rs->FetchRow())!==false) {
         echo $row[0];
      }
      $rs->Close();
   }
      ?></td>
   </tr>
</table>
<?php

   $AllowEmail=false;
   $query="SELECT PVALUE FROM agent_main WHERE AGENTID=0 AND PNAME='TXC_ALLOW_EMAIL' ";
   if (($rs=$db->Execute($query))===false) {
      echo $db->ErrorMsg();
      return;
   }
   if ($row=$rs->FetchRow()) {
      $AllowEmail = (bool)$row[0];
   }
   $rs->Close();

   $ar_span_typ=array(1=>'minutes', 2=>'hours');
   $x=(int)@$x2->Agp['TXC_QUERYSPAN'];
   if ($x<=180) {
      if ($x<=0) { $x=60; } // default
      $qry_span_val=$x;
      $qry_span_typ=1;
   }
   else {
      $qry_span_val=(int)$x/60;
      $qry_span_typ=2;
   }

   if (empty($x2->Agp['TXC_KEEPDATA'])) {
      $x2->Agp['TXC_KEEPDATA']=30;
   }

   if ((int)@$x2->Agp['TXC_HOURSFIRSTSIGN'] <= 0) {
      $x2->Agp['TXC_HOURSFIRSTSIGN'] = 24;
   }

   if ((int)@$x2->Agp['TXC_HOURSLASTZ'] <= 0) {
      $x2->Agp['TXC_HOURSLASTZ'] = 24;
   }
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method=POST>
<input type=hidden name="FUNCTION" value="101">
   <table>
   <tr>
      <td class=bgHeader colspan=3>Parameters</td>
   </tr>
   <tr>
      <td class=bgLabel>Z Limit for DM100/1000</td>
      <td class=bgInput colspan=2><input type=text name="TXC_ZLIMIT"
         value="<?php echo myhtml(@$x2->Agp['TXC_ZLIMIT']); ?>" MAXLENGTH=5></td>
   </tr>
   <tr>
      <td class=bgLabel>Z Limit for FASY</td>
      <td class=bgInput colspan=2><input type=text name="TXC_ZLIMITFASY"
         value="<?php echo myhtml(@$x2->Agp['TXC_ZLIMITFASY']); ?>" MAXLENGTH=5></td>
   </tr>
   <tr>
      <td class=bgLabel>Z Limit for POS</td>
      <td class=bgInput colspan=2><input type=text name="TXC_ZLIMITPOS"
         value="<?php echo myhtml(@$x2->Agp['TXC_ZLIMITPOS']); ?>" MAXLENGTH=5></td>
   </tr>
   <tr>
      <td class=bgLabel>EAFDSS/System time diffirence</td>
      <td class=bgInput colspan=2><input type=text name="TXC_MAXTIMEDIFF"
         value="<?php echo myhtml(@$x2->Agp['TXC_MAXTIMEDIFF']); ?>" MAXLENGTH=5>
         max. seconds allowed</td>
   </tr>
   <tr>
      <td class=bgLabel>Time diffirence since first signature</td>
      <td class=bgInput colspan=2><input type=text name="TXC_HOURSFIRSTSIGN"
         value="<?php echo myhtml(@$x2->Agp['TXC_HOURSFIRSTSIGN']); ?>" MAXLENGTH=5 size=7>
         hours</td>
   </tr>
   <tr>
      <td class=bgLabel>Time diffirence since last Z</td>
      <td class=bgInput colspan=2><input type=text name="TXC_HOURSLASTZ"
         value="<?php echo myhtml(@$x2->Agp['TXC_HOURSLASTZ']); ?>" MAXLENGTH=5 size=7>
         hours</td>
   </tr>
   <tr>
      <td class=bgLabel>Emails for alert (comma sep. list)</td>
      <td class=bgInput colspan=2><input type=text name="TXC_EMAILS"
         value="<?php echo myhtml(@$x2->Agp['TXC_EMAILS']); ?>" MAXLENGTH=255 SIZE=60></td>
   </tr>
   <tr>
      <td class=bgLabel>SMS for alert (comma sep. list)</td>
      <td class=bgInput colspan=2><input type=text name="TXC_SMSLIST"
         value="<?php echo myhtml(@$x2->Agp['TXC_SMSLIST']); ?>" MAXLENGTH=255 SIZE=60><br>
         Example: 306976112233,306977112244,...</td>
   </tr>
   <tr>
      <td class=bgLabel>Time span between alerts</td>
      <td class=bgInput colspan=2><input type=text name="TXC_ALRTSPAN"
         value="<?php echo myhtml(@$x2->Agp['TXC_ALRTSPAN']); ?>" MAXLENGTH=5 size=7>
         minutes</td>
   </tr>
   <tr>
      <td class=bgLabel>Last query span limit</td>
      <td class=bgInput colspan=2><input type=text name="QRY_SPAN_VAL"
         value="<?php echo $qry_span_val; ?>" MAXLENGTH=5 size=7>
         <select name="QRY_SPAN_TYP"><?php prAssocSelect($ar_span_typ, $qry_span_typ); ?></select></td>
   </tr>
   <tr>
      <td class=bgLabel>Keep data for</td>
      <td class=bgInput colspan=2><input type=text name="TXC_KEEPDATA"
         value="<?php echo myhtml(@$x2->Agp['TXC_KEEPDATA']); ?>" MAXLENGTH=5 SIZE=7>
         days</td>
   </tr>

   <tr>
      <td class=bgHeader colspan=3>Events</td>
   </tr>
   <?php print_evt_query($AllowEmail); ?>

   <tr>
      <td class=bgHeader colspan=3>S.TXT</td>
   </tr>
   <tr>
      <td class=bgLabel>Send S.TXT url</td>
      <td class=bgInput colspan=2><input type=text name="TXC_S_TXT_URL"
         value="<?php echo myhtml(@$x2->Agp['TXC_S_TXT_URL']); ?>" MAXLENGTH=255 size=60></td>
   </tr>
   <tr>
      <td class=bgLabel>Send S.TXT proxy</td>
      <td class=bgInput colspan=2><input type=text name="TXC_S_TXT_PROXY"
         value="<?php echo myhtml(@$x2->Agp['TXC_S_TXT_PROXY']); ?>" MAXLENGTH=255 size=60></td>
   </tr>
   <tr>
      <td class=bgLabel>Send S.TXT working dir.</td>
      <td class=bgInput colspan=2><input type=text name="TXC_S_TXT_WORKDIR"
         value="<?php echo myhtml(@$x2->Agp['TXC_S_TXT_WORKDIR']); ?>" MAXLENGTH=255 size=60></td>
   </tr>

   <tr>
      <td></td>
      <td class=bgButton colspan=2>
         <input type=submit  value="Update">
         <input type=button value="Check Tables" onclick="goTo(103)">
         <input type=button value="Incoming files" onclick="goTo(202)">
      </td>
   </tr>
   </table>
</form>
<?php
}
//--------------------------------------
function print_evt_query($AllowEmail)
{
   global $x2;

   $ar1=array(
         array('Last query passed limit', 'TXC_EVT_LASTUPDATE'),
         array('Time since 1st sign.', 'TXC_EVT_1STSIGN'),
         array('Time since last Z', 'TXC_EVT_TIMELASTZ'),
         array('Z exceeds machine limit', 'TXC_EVT_ZOVERLIMIT'),
         array('Z mssing from disk', 'TXC_EVT_ZMISSING'),
         array('EAFDSS/System time diffirence', 'TXC_EVT_TIMEDIFF'),
         array('TaxSpooler Alerts', 'TXC_EVT_ALERTS'),
         array('Hardware error', 'TXC_EVT_HARDERROR', 1),
         array('Application error', 'TXC_EVT_APPERROR', 1)
      );

   foreach($ar1 as $ar2) {
      $k=$ar2[1];
      echo "<tr title=\"";
      echo empty($ar2[2])?"Any EAFDSS/ Any version":"TaxSpooler version 2.4.4.0 or newer";
      echo "\">
         <td class=bgLabel>".myhtml($ar2[0])."</td>
         <td class=bgInput><label><input type=checkbox name=\"{$k}[]\" value=\"1\" ";
      if ($AllowEmail) {
         if (!empty($x2->Agp[$k]) && ($x2->Agp[$k] & 1)!=0) {
            echo 'checked';
         }
      }
      else {
         echo 'disabled';
      }
      echo "  >Email</label></td>
         <td class=bgInput><label><input type=checkbox name=\"{$k}[]\" value=\"2\" ";
      if (!empty($x2->Agp[$k]) && ($x2->Agp[$k] & 2)!=0) {
         echo 'checked';
      }
      echo " >SMS</label></td>
         </tr>";
   }
}
//--------------------------------------
function parse_number(&$val, $key)
{
   $val = ConvertSmsNumber( $val );
}
//--------------------------------------
function clear_all_data()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(100)', 1, 'TaxCenter setup'),
      array('', 1, 'Clear all data')
		);
   $x2->make_header($tarray);

   $arT=array('taxi_log', 'taxi_eafdss', 'taxi_update', 'taxi_wmic');
   foreach ($arT as $table1) {
      $query="DELETE FROM $table1 WHERE AGENTID=?";
      $data=array($x2->agentid);
      if (!$db->Execute($query,$data)) {
         echo "<div>$table1 error: ".$db->ErrorMsg()."</div>";
      }
   }

   echo "<h5>Completed!</h5>";
}
//--------------------------------------
function upd_params()
{
   global $x2;
   $db=&$x2->db;

   // HEADER
  	$tarray=array(
		array("CENTER", 1, 'ctr_center'),
      array('javascript:goTo(100)', 1, 'TaxCenter setup'),
      array('', 1, 'Ενημέρωση')
		);
   $x2->make_header($tarray);

   $_REQUEST['TXC_QUERYSPAN'] = $_REQUEST['QRY_SPAN_VAL'] * ($_REQUEST['QRY_SPAN_TYP']==1 ? 1 : 60);

   $vars=array('TXC_ZLIMIT', 'TXC_ZLIMITFASY', 'TXC_ZLIMITPOS', 'TXC_MAXTIMEDIFF', 'TXC_EMAILS', 'TXC_SMSLIST',
      'TXC_ALRTSPAN', 'TXC_QUERYSPAN', 'TXC_KEEPDATA', 'TXC_S_TXT_URL', 'TXC_S_TXT_PROXY', 'TXC_S_TXT_WORKDIR',
      'TXC_HOURSFIRSTSIGN', 'TXC_HOURSLASTZ');

   $v2=$vars;
	array_walk($v2,'squote');
	$query="DELETE FROM agent_main WHERE AGENTID=? AND PNAME IN (".implode(',',$v2).")";
	$data=array($x2->agentid);
	if (!$db->Execute($query,$data)) {
		echo "<h6>".$db->ErrorMsg()."</h6>\n";
		return;
	}

   if (!empty($_REQUEST['TXC_SMSLIST'])) {
      $ar1 = explode(',', $_REQUEST['TXC_SMSLIST']);
      array_walk($ar1, 'parse_number');
      $_REQUEST['TXC_SMSLIST'] = implode(',', $ar1);
   }

	// multiple values insertion !
	$data=array();
	$query="INSERT INTO agent_main (AGENTID,PNAME,PVALUE) VALUES (?,?,?)";
	$n=count($vars);
	for ($i=0;$i<$n;$i++) {
		if (!isset($_REQUEST[ $vars[$i] ]))
			continue;

      $data=array( $x2->agentid, $vars[$i], trim($_REQUEST[ $vars[$i] ]) );
      if (!$db->Execute($query,$data)) {
		   echo "<h6>".$db->ErrorMsg()."</h6>\n";
		   return;
	   }
	}

   update_evt();

   echo "<h5>Completed!</h5>";
}
//--------------------------------------
function update_evt()
{
   global $x2;
   $db=&$x2->db;

   $ar1=array('TXC_EVT_LASTUPDATE', 'TXC_EVT_1STSIGN', 'TXC_EVT_TIMELASTZ', 'TXC_EVT_ZOVERLIMIT',
      'TXC_EVT_ZMISSING', 'TXC_EVT_TIMEDIFF', 'TXC_EVT_HARDERROR', 'TXC_EVT_APPERROR', 'TXC_EVT_ALERTS');

   $v2=$ar1;
	array_walk($v2,'squote');
	$query="DELETE FROM agent_main WHERE AGENTID=? AND PNAME IN (".implode(',',$v2).")";
   $data=array($x2->agentid);
	if (!$db->Execute($query,$data)) {
		echo "<h6>".$db->ErrorMsg()."</h6>\n";
		return;
	}

   // multiple values insertion !
	$data=array();
	$query="INSERT INTO agent_main (AGENTID,PNAME,PVALUE) VALUES (?,?,?)";
	$n=count($ar1);
	for ($i=0;$i<$n;$i++) {
		if (!isset($_REQUEST[ $ar1[$i] ]))
			continue;

      $val=0;
      foreach($_REQUEST[ $ar1[$i] ] as $v1) {
         $val |= $v1;
      }
      $data=array( $x2->agentid, $ar1[$i], $val );
      if (!$db->Execute($query,$data)) {
		   echo "<h6>".$db->ErrorMsg()."</h6>\n";
		   break;
	   }
	}
}
//--------------------------------------
?>