<?php
/*
****** TaxSpooler database handling by authorized personel *****
****** Date of QR license 2020-02-06                       *****
*/
if ($_SERVER['HTTP_HOST']!=='www.metafuture.biz' || $_SERVER['REQUEST_SCHEME']!=='https')
{
   header('Location: https://www.metafuture.biz'.$_SERVER['SCRIPT_NAME']);
   exit();
}

$sess_name = session_name();
if (session_start()) {
    setcookie($sess_name, session_id(), null, '/', null, true, true);
}
//session_start();

header("Expires: Mon, 31 Dec 2001 00:00:00 GMT");
if (isset($_REQUEST['verbose'])) {
   $_SESSION['verbose'] = (bool)$_REQUEST['verbose'];
   setcookie('verbose', ''); // remove any 'verbose' cookie whether true or false
}
define('VERBOSE', (bool)@$_SESSION['verbose']);

include("../lib/ado/adodb.inc.php");
include("../lib/generic.inc.php");
include("taxspl1.inc.php");
define('ASSOCIATE1', 'support@a-s.gr');
define('ASSOCIATE2', 'johnkoulis@ics.gr, kg@ics.gr');
?>
<!DOCTYPE html>
<html>
<head>

<META http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>Metafuture - TaxSpooler</title>
<link rel="shortcut icon" type="image/x-icon" href="/metafuture/favicon.ico" />

<link rel="stylesheet" href="../script/dhtmlx/dhtmlx.css">
<script src="../script/dhtmlx/dhtmlx.js"></script>
<link rel="stylesheet" href="myweb.css" title="TaxSpooler">
<link rel="stylesheet" href="../script/themes/base/ui.all.css">
<style>
.linenum { font-family:Courier new; color:rgb(153,0,0); padding-right:8px;}
.custom-combobox {
   position: relative;
   display: inline-block;
}
.custom-combobox-toggle {
   position: absolute;
   top: 0;
   bottom: 0;
   margin-left: -1px;
   padding: 0;
}
.custom-combobox-input {
   margin: 0;
   padding: 5px 10px;
}
</style>
<script src="../script/jquery.js"></script>
<script src="../script/jquery-ui.js"></script>
<script src="../ishop/xadm.js.php"></script>
<script src="../script/eafdss.js"></script>

<link rel="stylesheet" type="text/css" href="../script/jqplot/jquery.jqplot.min.css" />
<script>
var mygroup=<?php echo (int)@$_SESSION['UGROUP']; ?>;
</script>
<script src="taxspl1.js.php"></script>

<?php
//--------------------------------------
function include_plot_js()
{
?>
<script src="../script/jqplot/jquery.jqplot.min.js"></script>
<script src="../script/jqplot/excanvas.min.js"></script>
<script src="../script/jqplot/plugins/jqplot.dateAxisRenderer.min.js"></script>
<script src="../script/jqplot/plugins/jqplot.barRenderer.min.js"></script>
<script src="../script/jqplot/plugins/jqplot.categoryAxisRenderer.min.js"></script>
<script src="../script/jqplot/plugins/jqplot.pointLabels.min.js"></script>
<script src="../script/jqplot/plugins/jqplot.canvasTextRenderer.min.js"></script>
<script src="../script/jqplot/plugins/jqplot.canvasAxisLabelRenderer.min.js"></script>
<script src="../script/jqplot/plugins/jqplot.canvasAxisTickRenderer.min.js"></script>
<?php
}
//--------------------------------------
function get_qua_left(&$db, $ugrp)
{
   $ar1=array();
   $query="SELECT ser_itemid, SUM(ser_quantity - ser_given) F1 FROM ser_deltia
      WHERE ser_ugroup=? AND ser_quantity > ser_given
      GROUP BY ser_itemid";
   $data=array($ugrp);
   if (($rs=$db->Execute($query, $data))===false) {
      echo $db->ErrorMsg();
      return false;
   }
   while ($o1=$rs->FetchNextObject()) {
      $ar1[$o1->SER_ITEMID] = $o1->F1;
   }
   $rs->Close();
   return $ar1;
}
//--------------------------------------
function add_user(&$db)
{
   if ($_REQUEST['SER_UGROUP']==0) {
      uerror("Δεν καθορίσατε group!");
      return;
   }

   $query="INSERT INTO ser_users (SER_UGROUP, SER_UNAME, SER_UPASS) VALUES(?, ?, ?)";
   $data=array($_REQUEST['SER_UGROUP'], $_REQUEST['SER_UNAME'], $_REQUEST['SER_UPASS'] );
   if (!$db->Execute($query,$data))
      echo __LINE__.$db->ErrorMsg();
}
//--------------------------------------
function del_user(&$db)
{
   $query="DELETE FROM ser_users WHERE SER_UNAME=?";
   $data=array($_REQUEST['UNAME']);
   if (!$db->Execute($query,$data))
      echo $db->ErrorMsg();
}
//--------------------------------------
function show_users(&$db)
{
   global $Groups;

   $query="SELECT * FROM ser_users ORDER BY ser_ugroup, ser_uname";
   if (($rs=$db->Execute($query))===false) {
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
      return;
   }
   echo "<form action=\"".myhtml($_SERVER['PHP_SELF'])."\" method=POST>
      <input type=hidden name=\"FU\" value=\"25\">
      <table>
      <tr class=MYTHEAD>
      <td>Group</td>
      <td>User name</td>
      <td>Pwd</td>
      <td>Lats mod. time</td>
      </tr>";
   while ($o1=$rs->FetchNextObject()) {
      echo "<tr>
         <td>";
      if (array_key_exists($o1->SER_UGROUP, $Groups)) {
         echo myhtml($Groups[$o1->SER_UGROUP]);
      }
      else {
         echo "#".$o1->SER_UGROUP." (error)";
      }
      echo "</td>
         <td>".myhtml($o1->SER_UNAME)."</td>
         <td>".myhtml($o1->SER_UPASS)."</td>
         <td>".GrDateTime($o1->SER_LASTMOD)."</td>
         <td><a href=\"".myhtml($_SERVER['SCRIPT_NAME'])."?FU=44&UNAME=".urlencode($o1->SER_UNAME)."\">Delete</a></td>
         </tr>";
   }
   $rs->Close();
   echo "<tr>
      <td><select name=\"SER_UGROUP\">";
   prAssocSelect($Groups,0,3);
   echo "</select></td>
      <td><input type=\"TEXT\" name=\"SER_UNAME\"></td>
      <td><input type=\"TEXT\" name=\"SER_UPASS\"></td>
      <td><input type=submit value=\"Add\"></td>
      </tr></table></form>";
}
//--------------------------------------
function upd_comments(&$db)
{
   $query="UPDATE ser_data SET ser_comments=? WHERE ser_itemid=? AND ser_auth=? AND ser_serial=?";
   $data=array_merge(array($_REQUEST['COMMENTS']), explode(',', $_REQUEST['ID']) );
   if (!$db->Execute($query,$data))
      echo __LINE__.$db->ErrorMsg();
}
//--------------------------------------
function show_upgrades(&$db)
{
   $pg=(int)@$_REQUEST['RSPAGE'];
   if ($pg<1) $pg=1;
   $pgsz=30;

   $query="SELECT *, (TO_DAYS(ser_expires) - TO_DAYS(ser_upgrade)) F1 FROM ser_data
      WHERE ser_upgrade IS NOT NULL
      ORDER BY ser_upgrade, ser_auth, ser_serial, ser_itemid";
   if (($rs=$db->PageExecute($query,$pgsz,$pg))===false) {
      echo __LINE__.$db->ErrorMsg();
      return;
   }
?>
   <script language=javascript>
   function editComment(id,defval)
   {
      var newval=window.prompt('Comments',defval);
      if (newval==null)
         return;

      var url=document.location.protocol + '//' + document.location.host + document.location.pathname +
         '?FU=27&ID=' +id + '&COMMENTS=' + encodeURIComponent(newval);
      document.location.href=url;
   }
   </script>
   <form method=POST action="<?php echo myhtml($_SERVER['PHP_SELF']); ?>" name="goForm">
   <input type=HIDDEN name="RSPAGE">
   <input type=HIDDEN name="FU" value="26">
   <table>
   <tr class=MYTHEAD>
      <td>Type</td>
      <td>Auth(3)</td>
      <td>Serial(8)</td>
      <td>Lic.Date</td>
      <td>Trans.Id</td>
      <td>Upgrade</td>
      <td>Expires</td>
      <td>Duration(m)</td>
      <td>Comments</td>
      <td>Edit</td>
   </tr>
<?php
   while ($o1=$rs->FetchNextObject()) {
      echo "<tr>
         <td>".myhtml($o1->SER_ITEMID)."</td>
         <td>".myhtml($o1->SER_AUTH)."</td>
         <td>".myhtml($o1->SER_SERIAL)."</td>
         <td>".GrDate($o1->SER_DATE)."</td>
         <td>".myhtml($o1->SER_TRANSID)."</td>
         <td>".GrDate($o1->SER_UPGRADE)."</td>
         <td>".GrDate($o1->SER_EXPIRES)."</td>
         <td align=right>".((int)($o1->F1/30))."</td>
         <td>".myhtml($o1->SER_COMMENTS)."</td>
         <td><a href=\"javascript:editComment('".
         implode(',', array($o1->SER_ITEMID, $o1->SER_AUTH, $o1->SER_SERIAL))."','".myhtml($o1->SER_COMMENTS)."')\">...</a></td>
         </tr>";
   }
   $epage=$rs->LastPageNo();
   $rs->Close();
   echo "</table>";

   echo "<table width=100%><tr class=MYNAVBAR><td>";
   print_page_nav2($pg,$epage,26);
	echo "</td></tr></table>
      </form>";
}
//--------------------------------------
function show_grp_analysis(&$db)
{
   $pg=(int)@$_REQUEST['RSPAGE'];
   if ($pg<1) $pg=1;
   $pgsz=30;

   $query="SELECT * FROM ser_data WHERE ser_date=? ORDER BY ser_itemid, ser_auth, ser_serial";
   $data=array( $_REQUEST['ID'] );
   if (($rs=$db->PageExecute($query,$pgsz,$pg,$data))===false) {
      echo __LINE__.$db->ErrorMsg();
      return;
   }
?>
   <form method=POST action="<?php echo myhtml($_SERVER['PHP_SELF']); ?>" name="goForm">
   <input type=HIDDEN name="RSPAGE">
   <input type=HIDDEN name="FU" value="29">
   <input type=HIDDEN name="ID" value="<?php echo $_REQUEST['ID']; ?>">
   <table>
   <tr class=MYTHEAD>
      <td>Type</td>
      <td>Auth(3)</td>
      <td>Serial(8)</td>
      <td>Lic.Date</td>
      <td>Trans.Id</td>
      <td>Upgrade</td>
      <td>Expires</td>
   </tr>
<?php
   while ($o1=$rs->FetchNextObject()) {
      echo "<tr>
         <td>".myhtml($o1->SER_ITEMID)."</td>
         <td>".myhtml($o1->SER_AUTH)."</td>
         <td>".myhtml($o1->SER_SERIAL)."</td>
         <td>".GrDate($o1->SER_DATE)."</td>
         <td>".myhtml($o1->SER_TRANSID)."</td>
         <td>".GrDate($o1->SER_UPGRADE)."</td>
         <td>".GrDate($o1->SER_EXPIRES)."</td>
         </tr>";
   }
   $epage=$rs->LastPageNo();
   $rs->Close();
   echo "</table>";

   echo "<table width=100%><tr class=MYNAVBAR><td>";
   print_page_nav2($pg,$epage,29);
	echo "&nbsp;<a href=\"".myhtml($_SERVER['SCRIPT_NAME'])."?FU=28\">Group by date</a></td></tr></table>
      </form>";
}
//--------------------------------------
function show_grp_bydate(&$db)
{
   $pg=(int)@$_REQUEST['RSPAGE'];
   if ($pg<1) $pg=1;
   $pgsz=30;

   $query="SELECT ser_date, COUNT(*) F1 FROM ser_data GROUP BY ser_date ORDER BY ser_date DESC";
   if (($rs=$db->PageExecute($query,$pgsz,$pg))===false) {
      echo __LINE__.$db->ErrorMsg();
      return;
   }
?>
   <form method=POST action="<?php echo myhtml($_SERVER['PHP_SELF']); ?>" name="goForm">
   <input type=HIDDEN name="RSPAGE">
   <input type=HIDDEN name="FU" value="28">
   <table>
   <tr class=MYTHEAD>
      <td>Lic.Date</td>
      <td>Count</td>
   </tr>
<?php
   while ($o1=$rs->FetchNextObject()) {
      echo "<tr>
         <td>".GrDate($o1->SER_DATE)."</td>
         <td align=right>".myhtml($o1->F1)."</td>
         <td><a href=\"".myhtml($_SERVER['SCRIPT_NAME'])."?FU=29&ID=".urlencode($o1->SER_DATE)."\">Analysis</a></td>
         </tr>";
   }
   $epage=$rs->LastPageNo();
   $rs->Close();
   echo "</table>";

   echo "<table width=100%><tr class=MYNAVBAR><td>";
   print_page_nav2($pg,$epage,28);
	echo "</td></tr></table>
      </form>";
}
//--------------------------------------
function show_licenses(&$db)
{
	global $aLevel;

   $pg=(int)@$_REQUEST['RSPAGE'];
   if ($pg<1) $pg=1;
   $pgsz=30;

   $query="SELECT * FROM ser_data ORDER BY ser_itemid, ser_auth, ser_serial";
   if (($rs=$db->PageExecute($query,$pgsz,$pg))===false) {
      echo __LINE__.$db->ErrorMsg();
      return;
   }
?>
   <form method=POST action="<?php echo myhtml($_SERVER['PHP_SELF']); ?>" name="goForm">
   <input type=HIDDEN name="RSPAGE">
   <input type=HIDDEN name="FU" value="24">
   <table>
   <tr class=MYTHEAD>
      <td>Type</td>
      <td>Auth(3)</td>
      <td>Serial(8)</td>
      <td>Lic.Date</td>
      <td>Trans.Id</td>
      <td>Upgrade</td>
      <td>Expires</td>
   </tr>
<?php
   while ($o1=$rs->FetchNextObject()) {
      echo "<tr>
         <td>".myhtml($o1->SER_ITEMID)."</td>
         <td>".myhtml($o1->SER_AUTH)."</td>
         <td>".myhtml($o1->SER_SERIAL)."</td>
         <td>".GrDate($o1->SER_DATE)."</td>
         <td>".myhtml($o1->SER_TRANSID)."</td>
         <td>".GrDate($o1->SER_UPGRADE)."</td>
         <td>".GrDate($o1->SER_EXPIRES)."</td>
         </tr>";
   }
   $epage=$rs->LastPageNo();
   $rs->Close();
   echo "</table>";

   echo "<div class=MYNAVBAR>";
   print_page_nav2($pg,$epage,24);
	echo "&nbsp;<a href=\"".myhtml($_SERVER['SCRIPT_NAME'])."?FU=28\">Group by date</a>\n";
	/*
	if ($aLevel==1) { // admin
		echo "<input type=button value=\"Group input\" onclick=\"35\">";
	}
	*/
	echo "</div>
      </form>";
}
//--------------------------------------
function su_del_ser_deltio(&$db)
{
   $n=0;
   $query="SELECT COUNT(*) FROM ser_deltia WHERE ser_deltio=? AND ser_itemid=?";
   $data=array( $_REQUEST['SER_DELTIO'], (int)$_REQUEST['SER_ITEMID'] );
   if (($rs=$db->Execute($query,$data))===false) {
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
      return;
   }
   if ($row=$rs->FetchRow()) {
      $n=(int)$row[0];
   }
   $rs->Close();

   if ($n!=1) {
      echo "<h6>Found $n records instead of 1!</h6>";
      return;
   }

   $query="DELETE FROM ser_deltia WHERE ser_deltio=? AND ser_itemid=?";
   $data=array( $_REQUEST['SER_DELTIO'], (int)$_REQUEST['SER_ITEMID'] );
   if (!$db->Execute($query,$data))
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
}
//--------------------------------------
function su_upd_ser_deltio(&$db)
{
   $o1=false;
   $query="SELECT SER_QUANTITY, SER_GIVEN FROM ser_deltia WHERE SER_DELTIO=? AND SER_ITEMID=?";
   $data=array($_REQUEST['SER_DELTIO'], $_REQUEST['SER_ITEMID']);
   if (($rs=$db->Execute($query, $data))) {
      $o1 = $rs->FetchNextObject();
      $rs->Close();
   }
   else {
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
      return;
   }
   if ($o1===false)
      return;

   if ((int)$_REQUEST['NEWQUA'] < $o1->SER_GIVEN) {
      echo "<h5>Can not update!</h5>";
      return;
   }

   $query="UPDATE ser_deltia SET ser_ugroup=?, ser_deltio=?, ser_quantity=?, ser_comments=? WHERE ser_deltio=? AND ser_itemid=? AND ser_given=?";
   $data=array( $_REQUEST['NEWGRP'], $_REQUEST['NEWVAL'], (int)$_REQUEST['NEWQUA'], $_REQUEST['NEWCOMM'],
      $_REQUEST['SER_DELTIO'], (int)$_REQUEST['SER_ITEMID'], $o1->SER_GIVEN );
   if (!$db->Execute($query,$data))
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
}
//--------------------------------------
function update_fga_sales()
{
   global $db, $Guname;

   $invoice = trim($_REQUEST['FGA_INV_SALES']);
   if (empty($invoice)) {
      echo "<h6>Δεν καθορίσατε τιμολόγιο πώλησης!</h6>";
      return;
   }

   $query="UPDATE ser_fgalic SET FGA_INV_SALES=?, FGA_SAL_DATE=NOW(), FGA_UNAME=?
      WHERE FGA_KEY=? "; //AND FGA_MACADDRESS IS NULL";
   $data=array( $invoice, $Guname, (int)$_REQUEST['FGA_KEY'] );
   if (!$db->Execute($query,$data))
      echo "<h6>".$db->ErrorMsg()."</h6>";
}
//--------------------------------------
function update_tg_sales(&$db)
{
   global $Guname;

   $invoice = trim($_REQUEST['TG_INV_SALES']);
   if (empty($invoice)) {
      echo "<h6>Δεν καθορίσατε τιμολόγιο πώλησης!</h6>";
      return;
   }

   $query="UPDATE ser_taxgate SET tg_inv_sales=?, tg_sal_date=NOW(), tg_uname=?
      WHERE tg_key=? AND tg_macaddress IS NULL";
   $data=array( $invoice, $Guname, (int)$_REQUEST['TG_KEY'] );
   if (!$db->Execute($query,$data))
      echo "<h6>".$db->ErrorMsg()."</h6>";
}
//--------------------------------------
function ymdex($ymd)
{
   if ($ymd==1) {
      return "Never expires";
   }
   else {
      $ymd .= '00000000';
      return implode('-', array(substr($ymd,0,4), substr($ymd,4,2), substr($ymd,6,2)) );
   }
}
//--------------------------------------
function show_fgalic()
{
   global $db, $aLevel;

   $pg=(int)@$_REQUEST['RSPAGE'];
   if ($pg<1) $pg=1;
   $pgsz=25;

   $data=array();
   $query="SELECT * FROM ser_fgalic ";
   if ($aLevel != 1)
   {
      $query .= " WHERE fga_ugroup=?";
      $data[] = $_SESSION['UGROUP'];
   }
   $query .= " ORDER BY fga_pur_date DESC, fga_inv_purchase";
   $rs=$db->PageExecute($query,$pgsz,$pg,$data);
   if ($rs===false) {
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
      return;
   }
?>
   <form method=POST action="<?php echo myhtml($_SERVER['PHP_SELF']); ?>" name="goForm">
   <input type=HIDDEN name="RSPAGE">
   <input type=HIDDEN name="FU" value="56">
   <table>
   <tr class=MYTHEAD>
      <td>Group</td>
      <td>Key</td>
      <td>Τιμολόγιο αγοράς</td>
      <td>Ημ/νία αγοράς</td>
      <td>Τιμολόγιο πώλησης</td>
      <td>Ημ/νία καταχώρισης</td>
      <td>Καταχωρητής</td>
      <td>MAC address</td>
      <td>Remote request IP</td>
      <td>Remote request Host</td>
      <td>Ημ/νία registration</td>
      <td>Designer expires</td>
      <td>Barcode expires</td>
      <td>Max. Instances</td>
      <td>Max. Instance expires</td>
      <td>Σχόλια</td>
      <td>Τελ. μεταβολής</td>
   </tr>
<?php
   $nrec=0;
   while ($o1=$rs->FetchNextObject()) {
      echo "<tr";
      if ($nrec++%2) {
         echo " class=HILINE";
      }
      echo ">
         <td>".myhtml($o1->FGA_UGROUP)."</td>
         <td style=\"font-weight:bold;\">".$o1->FGA_KEY."</td>
         <td>".myhtml($o1->FGA_INV_PURCHASE)."</td>
         <td>".GrDate($o1->FGA_PUR_DATE)."</td>
         <td onclick=\"editSalesInv($o1->FGA_KEY)\" style=\"cursor:pointer;\">".myhtml($o1->FGA_INV_SALES)."</td>
         <td>".GrDateTime($o1->FGA_SAL_DATE)."</td>
         <td>".myhtml($o1->FGA_UNAME)."</td>
         <td>".myhtml($o1->FGA_MACADDRESS)."</td>
         <td>".myhtml($o1->FGA_REMOTE_ADDR)."</td>
         <td>".myhtml($o1->FGA_REMOTE_HOST)."</td>
         <td>".GrDateTime($o1->FGA_REGMAC_DATE)."</td>
         <td>".ymdex($o1->FGA_DESIGNER_YMD)."</td>
         <td>".ymdex($o1->FGA_BARCODE_YMD)."</td>
         <td>$o1->FGA_MAXSESSIONS</td>
         <td>".ymdex($o1->FGA_SESSIONS_YMD)."</td>
         <td>".myhtml($o1->FGA_COMMENTS)."</td>
         <td>".GrDateTime($o1->FGA_LASTMOD)."</td>
         </tr>";
   }
   $epage=$rs->LastPageNo();
   $rs->Close();

   echo "</table><div class=MYNAVBAR>";
   print_page_nav2($pg,$epage,56);
   echo "</div>
      </form>";

?>
   <div id=zoomdlg title="Update"><iframe id=zoomframe width=400 height=260></iframe></div>
<script>
function editSalesInv(key)
{
   var url=location.pathname + '?FU=80&FGA_KEY='+key; // query data
   document.getElementById('zoomframe').src=url;
   $('#zoomdlg').dialog({modal:true, width:440, resizable:false}).dialog('open'); // content width + 32 (+2x16)
}
$(function(){
   $('#zoomdlg').dialog({autoOpen:false});
});
</script>
<?php
}
//--------------------------------------
function show_taxgate(&$db)
{
   global $aLevel;

   $pg=(int)@$_REQUEST['RSPAGE'];
   if ($pg<1) $pg=1;
   $pgsz=25;

   $data=array();
   $query="SELECT * FROM ser_taxgate ";
   if ($aLevel != 1)
   {
      $query .= " WHERE tg_ugroup=?";
      $data[] = $_SESSION['UGROUP'];
   }
   $query .= " ORDER BY tg_pur_date DESC, tg_inv_purchase";
   $rs=$db->PageExecute($query,$pgsz,$pg,$data);
   if ($rs===false) {
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
      return;
   }
?>
   <form method=POST action="<?php echo myhtml($_SERVER['PHP_SELF']); ?>" name="goForm">
   <input type=HIDDEN name="RSPAGE">
   <input type=HIDDEN name="FU" value="56">
   <table>
   <tr class=MYTHEAD>
      <td>Group</td>
      <td>Key</td>
      <td>Τιμολόγιο αγοράς</td>
      <td>Ημ/νία αγοράς</td>
      <td>Τιμολόγιο πώλησης</td>
      <td>Ημ/νία καταχώρισης</td>
      <td>Καταχωρητής</td>
      <td>MAC address</td>
      <td>Remote request IP</td>
      <td>Remote request Host</td>
      <td>Ημ/νία registration</td>
      <td>Σχόλια</td>
      <td>Τελ. μεταβολής</td>
   </tr>
<?php
   $nrec=0;
   while ($o1=$rs->FetchNextObject()) {
      echo "<tr";
      if ($nrec++%2) {
         echo " class=HILINE";
      }
      echo ">
         <td>".myhtml($o1->TG_UGROUP)."</td>
         <td style=\"font-weight:bold;\">".$o1->TG_KEY."</td>
         <td>".myhtml($o1->TG_INV_PURCHASE)."</td>
         <td>".GrDate($o1->TG_PUR_DATE)."</td>
         <td onclick=\"editSalesInv($o1->TG_KEY)\" style=\"cursor:pointer;\">".myhtml($o1->TG_INV_SALES)."</td>
         <td>".GrDateTime($o1->TG_SAL_DATE)."</td>
         <td>".myhtml($o1->TG_UNAME)."</td>
         <td>".myhtml($o1->TG_MACADDRESS)."</td>
         <td>".myhtml($o1->TG_REMOTE_ADDR)."</td>
         <td>".myhtml($o1->TG_REMOTE_HOST)."</td>
         <td>".GrDateTime($o1->TG_REGMAC_DATE)."</td>
         <td>".myhtml($o1->TG_COMMENTS)."</td>
         <td>".GrDateTime($o1->TG_LASTMOD)."</td>
         </tr>";
   }
   $epage=$rs->LastPageNo();
   $rs->Close();

   echo "</table><div class=MYNAVBAR>";
   print_page_nav2($pg,$epage,56);
   echo "</div>
      </form>";

?>
   <div id=zoomdlg title="Update"><iframe id=zoomframe width=400 height=260></iframe></div>
<script>
function editSalesInv(key)
{
   var url=location.pathname + '?FU=57&TG_KEY='+key; // query data
   document.getElementById('zoomframe').src=url;
   $('#zoomdlg').dialog({modal:true, width:440, resizable:false}).dialog('open'); // content width + 32 (+2x16)
}
$(function(){
   $('#zoomdlg').dialog({autoOpen:false});
});
</script>
<?php
}
//--------------------------------------
function show_stat(&$db, $group=0)
{
   global $ct, $aLevel, $Groups;

   $ar1=array(240,340,250,320,300,360,370,330,350,290,310,1003,1004,1012,1013); // 240 refres to 230,240; 250 refers to 256,260,270
   $gt=array();

   $data=array();
   $grp_read=array();
   $query="SELECT SER_UGROUP, SER_ITEMID, SUM(SER_QUANTITY) FQUA, SUM(SER_GIVEN) FGIV FROM ser_deltia ";
   if ($aLevel != 1)
   {
      $query .= " WHERE SER_UGROUP=? ";
      $data[]=$_SESSION['UGROUP'];
   }
   $query .= " GROUP BY SER_UGROUP, SER_ITEMID ORDER BY SER_UGROUP, SER_ITEMID";
   if (($rs=$db->Execute($query,$data))===false) {
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      switch ($o1->SER_ITEMID)
      {
      case 230:
         $o1->SER_ITEMID=240;
         break;
      case 260:
      case 270:
      case 280:
         $o1->SER_ITEMID=250;
         break;
      }

      if (!in_array($o1->SER_UGROUP, $grp_read))
         $grp_read[] = $o1->SER_UGROUP;

      if (in_array($o1->SER_ITEMID, $ar1)) { // if a known SER_ITEMID
         $key = $o1->SER_UGROUP.".".$o1->SER_ITEMID;
      }
      else { // unknown SER_ITEMID
         $key = $o1->SER_UGROUP.".999";
      }
      $gt[$key] = (int)@$gt[$key] + $o1->FQUA - $o1->FGIV;
   }
   $rs->Close();

   echo "<fieldset>
      <legend>Διαθέσιμες</legend>
      <table style=\"background-color:#c0c0c0\" cellspacing=1 cellpadding=4>
      <tr style=\"background-color:#ffffff\">
         <td>Group</td>
         <td>ETax Lite (#230/ #240)</td>
         <td>E-Xtend (#340)</td>
         <td>Old Base #250/ TCP/IP #260/ AS400 #270</td>
         <td>ESend-Complete (#320)</td>
         <td>FGA/SID Xtra (#300)</td>
         <td>FGA/IE11 (#360)</td>
         <td>FGA/Instance (#370)</td>
         <td>SAP (#330)</td>
         <td>Cluster (#350)</td>
         <td>E-Invoice Lite (#290)</td>
         <td>Graphics Overdraw (#310)</td>
         <td>10d Upgrade/ generic</td>
         <td>10d Upgrade/ SAP</td>
         <td>12M Upgrade/ generic</td>
         <td>12M Upgrade/ SAP</td>
         <td>Unknown</td>
      </tr>";

   foreach ($grp_read as $grp1) {
      echo "<tr style=\"background-color:#ffffff; text-align:center;\">
         <td>$grp1 (".(@$Groups[$grp1]).")</td>";

      foreach ($ar1 as $k) {
         $key = $grp1.'.'.$k;
         echo "<td><b>".((int)@$gt[$key])."</b></td>";
      }

      echo "<td><b>".((int)@$gt[$grp1.'.999'])."</b></td>
         </tr>";
   }

   echo "</table>
      </fieldset>";
?>
<script>
$(function(){
   $('#editDeltioId').dialog({autoOpen:false});
});

function onDelDeltio(s1)
{
   var ar1=s1.split(';');
   if (ar1.length<2) {
      window.alert('No data!');
      return;
   }

   if (!window.confirm('Really delete record?'))
      return;

   var url;
   var i=location.href.lastIndexOf('?');
   if (i<0)
      url=location.href;
   else
      url=location.href.substr(0,i);

   location.href = url + '?FU=46&SER_DELTIO=' + encodeURIComponent(ar1[0]) +
      '&SER_ITEMID=' + encodeURIComponent(ar1[1]);
}
function onEditDeltio(s1)
{
   var ar1 = $('#tr'+s1+' td:nth-child(1)').text().split(' ');
   var grp = ar1[0];

   var deltio = $('#tr'+s1+' td:nth-child(2)').text().trim();

   var val1 = $('#tr'+s1+' td:nth-child(4)').text();
   var i = val1.indexOf('(#');
   if (i<0) {
      alert('Can not change!');
      return;
   }
   ar1 = val1.substring(i+2).split(')');
   var itemid = ar1[0];

   var qua = $('#tr'+s1+' td:nth-child(5)').text();

   var comments = $('#tr'+s1+' td:nth-child(10)').text();

   $('#newgrp').val(grp);
   $('#newval').val(deltio);
   $('#newqua').val(qua);
   $('#newcomm').val(comments);

   $('#editDeltioId').dialog({modal:true, resizable:false, buttons: [
      {
         text: "Ok",
         click: function() {
            var i=location.href.lastIndexOf('?');
            var url = i<0?location.href:location.href.substr(0,i);
            url += '?FU=32&SER_DELTIO=' + encodeURIComponent(deltio) +
               '&SER_ITEMID=' + encodeURIComponent(itemid) + '&NEWVAL=' + encodeURIComponent($('#newval').val()) +
               '&NEWGRP=' + encodeURIComponent($('#newgrp').val()) + '&NEWQUA=' + encodeURIComponent($('#newqua').val()) +
               '&NEWCOMM=' + encodeURIComponent($('#newcomm').val());

            location.assign( url );
         }
      },
      {
         text: "Cancel",
         click: function() {
            $( this ).dialog( "close" );
         }
      }
    ]  }).dialog('open');
}
</script>
<div id=editDeltioId title="Edit">
<table>
<tr>
   <td>Νέα αξία για το Δελτίο:</td>
   <td><input type=text id=newval value=""></td>
</tr>
<tr>
   <td>Νέα αξία για το group:</td>
   <td><select id=newgrp><?php
      prAssocSelect($Groups,0);
   ?></select></td>
</tr>
<tr>
   <td>Νέα ποσότητα:</td>
   <td><input type=text id=newqua value=""></td>
</tr>
<tr>
   <td>Σχόλιο:</td>
   <td><input type=text id=newcomm value=""></td>
</tr>
</table>
</div>
<?php
   echo "<h5>Προμήθειες Αδειών</h5>";

   $pg=(int)@$_REQUEST['RSPAGE'];
   if ($pg<1) { $pg=1; }
   $pgsz=15;

   $data=array();
   $query="SELECT * FROM ser_deltia WHERE 1=1 ";
   if (!empty($_REQUEST['IIDFILTER'])) {
      $query .= " AND ser_itemid=?";
      $data[] = (int)@$_REQUEST['IIDFILTER'];
   }
   if ($aLevel != 1)
   {
      $query .= " AND SER_UGROUP=?";
      $data[] = (int)@$_SESSION['UGROUP'];
   }
   $query .= " ORDER BY ser_d_date DESC, ser_deltio, ser_itemid";
   if ($rs=$db->PageExecute($query, $pgsz, $pg, $data)) {
?>
<form method=POST action="<?php echo myhtml($_SERVER['PHP_SELF']); ?>" name="goForm">
<input type=HIDDEN name="RSPAGE">
<input type=HIDDEN name="FU">
<table>
   <tr class=MYTHEAD>
      <td>Group</td>
      <td>Δ/Αποστολής</td>
      <td>Ημ/νία</td>
      <td>Τύπος</td>
      <td>Ποσότητα</td>
      <td>Ανάλωση</td>
      <td>Μένει</td>
      <td>Τιμολόγιο</td>
      <td>Ημ/νία</td>
      <td>Σχόλια</td>
   </tr>
<?php
      $nrec=0;
      $last_deltio='';
      while ($o1=$rs->FetchNextObject()) {
         if ($o1->SER_DELTIO===$last_deltio) {
            $deltio = '&nbsp;&nbsp;'.myhtml($o1->SER_DELTIO);
         }
         else {
            $deltio = myhtml($o1->SER_DELTIO);
         }
         $last_deltio = $o1->SER_DELTIO;

         echo "<tr id=tr$nrec ";
         if ($nrec%2) {
            echo " class=HILINE";
         }
         echo ">\n".
            "<td>".$o1->SER_UGROUP." (".(@$Groups[$o1->SER_UGROUP]).")</td>\n".
            "<td>$deltio</td>\n".
            "<td>".GrDate($o1->SER_D_DATE)."</td>\n".
            "<td>";
         if ($o1->SER_ITEMID==1003)
            echo "<b>10d Upgrade/ generic (#1003)</b>";
         else if ($o1->SER_ITEMID==1004)
            echo "<b>10d Upgrade/ SAP (#1004)</b>";
         else if ($o1->SER_ITEMID==1012)
            echo "<b>12M Upgrade/ generic</b>";
         else if ($o1->SER_ITEMID==1013)
            echo "<b>12M Upgrade/ SAP</b>";
         else
            echo "<span style=\"color: #008000; font-weight:bold;\">".myhtml(@$ct->licTypes[$o1->SER_ITEMID])."</span>";
         echo "</td>\n".
            "<td>".(int)$o1->SER_QUANTITY."</td>\n".
            "<td>".(int)$o1->SER_GIVEN."</td>\n".
            "<td>".((int)$o1->SER_QUANTITY - (int)$o1->SER_GIVEN)."</td>\n".
            "<td>".myhtml($o1->SER_INVOICE)."</td>\n".
            "<td>".myhtml($o1->SER_I_DATE)."</td>\n".
            "<td>".myhtml($o1->SER_COMMENTS)."</td>\n";
         if ($aLevel == 1) { // admin
            echo "<td><a href=\"javascript:onEditDeltio($nrec)\">Edit</a></td>
               <td><a href=\"javascript:onDelDeltio('".myhtml($o1->SER_DELTIO.';'.$o1->SER_ITEMID)."')\">Del</a></td>\n";
         }
         echo "</tr>\n";

         $nrec++;
      }
      $epage=$rs->LastPageNo();
      $rs->Close();

      echo "</table>
         <div class=MYNAVBAR style=\"width:80%\">";
   	print_page_nav2($pg,$epage,0);
	   echo "&nbsp;Φίλτρο άδειας:<input type=text name=\"IIDFILTER\" value=\"".myhtml(@$_REQUEST['IIDFILTER'])."\" size=5>
			<input type=submit value=\"Refresh\"></div>
         </form>";
   }
   else {
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
   }
}
//------------------------------------------------------------------------------
function su_do_reassign(&$db)
{
   if (empty($_REQUEST['NEW_VERSION']) || empty($_REQUEST['OLD_VERSION'])) {
      echo "<h6>Empty version(s)!</h6>";
      return;
   }
   if (version_compare($_REQUEST['NEW_VERSION'], $_REQUEST['OLD_VERSION'])==0) {
      echo "<h6>Same versions!</h6>";
      return;
   }

   $db->StartTrans();
   do {
      $query="UPDATE IGNORE ser_version SET ser_version=? WHERE ser_version=?"; // ignore errors
      $data=array($_REQUEST['NEW_VERSION'], $_REQUEST['OLD_VERSION']);
      if (!$db->Execute($query,$data)) {
         echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>";
         break;
      }
      $n1=$db->Affected_Rows();

      $query="DELETE FROM ser_version WHERE ser_version=?";
      $data=array($_REQUEST['OLD_VERSION']);
      if (!$db->Execute($query,$data)) {
         echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>";
         break;
      }

      echo "<h6>Affected records: $n1</h6>";

   } while (false);
   $db->CompleteTrans();
}
//------------------------------------------------------------------------------
function su_ask_reassign(&$db)
{
   $ar1=array();
   get_versions_avail($ar1);
   if (empty($ar1)) {
      return;
   }
?>
   <div width="80%" class=MYBOX><b>Μεταφορά upgrade σε νεότερη έκδοση</b></div>

   <form action="<?php echo myhtml($_SERVER['PHP_SELF']); ?>" method=POST>
   <input type=HIDDEN name="FU" value="31">
   <table>
   <tr>
      <td>Παλιά έκδοση</td>
      <td><input type=text name="OLD_VERSION"></td>
   </tr>
   <tr>
      <td>Νέα έκδοση</td>
      <td><SELECT id=new_vers name="NEW_VERSION"><?php
         foreach ($ar1 as $val1) {
            echo "<option>$val1</option>";
         }
         ?></SELECT></td>
   </tr>
   <tr>
      <td></td>
      <td><input type=SUBMIT name="ok" value="Submit"></td>
   </tr>
   </table>
   </form>
   <script>
   window.dhx_globalImgPath="/script/dhtmlx/imgs/";
   dhtmlXComboFromSelect('new_vers');
   </script>
<?php
}
//------------------------------------------------------------------------------
function ask_upgrade_1(&$db)
{
   global $aLevel;

?>
   <table width="80%"><tr class=MYBOX><td><b>Upgrade υπάρχουσας άδειας</b></td></tr></table>

   <form action="<?php echo myhtml($_SERVER['PHP_SELF']); ?>" onSubmit="return CheckData2(this)" method=POST>
   <input type=HIDDEN name="FU" value="<?php
      echo $aLevel==1 ? 33 : 22;
      ?>">
   <table>
   <tr>
      <td>Τύπος μηχανής</td>
      <td><select id=ser_auth name="SER_AUTH"></select></td>
   </tr>
   <tr>
      <td>Κωδικός</td>
      <td><input type=TEXT name="SER_SERIAL" XMAXLENGTH=11></td>
   </tr>
   <tr>
      <td></td>
      <td><input type=SUBMIT name="ok" value="Submit"><?php
      	if ($aLevel == 1) { // admin
      		echo "<input type=button value=\"Group input\" onclick=\"location.href='".myhtml($_SERVER['PHP_SELF'])."?FU=37'\">";
			}
		?></td>
   </tr>
   </table>
   </form>
   <script>
      fill_eafdss(document.getElementById('ser_auth'));
   </script>
<?php
}
//------------------------------------------------------------------------------
function ask_group_license(&$db)
{
?>
	<table width="80%"><tr class=MYBOX><td><b>Group License (Helper function)</b></td></tr></table>

   <form action="<?php echo myhtml($_SERVER['PHP_SELF']); ?>" method=POST>
   <input type=HIDDEN name="FU" value="36">
   <table>
   <tr>
      <td>Example: Serial 11, space, 250, space, 260, new line, etc...</td>
      <td><textarea name="mixinput" style="width:400px; height:300px;"></textarea></td>
   </tr>
   <tr>
      <td></td>
      <td><input type=SUBMIT name="ok" value="Submit"></td>
   </tr>
   </table>
   </form>
<?php
}
//------------------------------------------------------------------------------
function ask_group_upgrade(&$db)
{
?>
	<table width="80%"><tr class=MYBOX><td><b>Group Upgrade (για υπάρχουσες άδειες)</b></td></tr></table>

   <form action="<?php echo myhtml($_SERVER['PHP_SELF']); ?>" method=POST>
   <input type=HIDDEN name="FU" value="38">
   <table>
   <tr>
      <td>Example: Serial 11, space, 250, space, 260, new line, etc...</td>
      <td><textarea name="mixinput" style="width:400px; height:300px;"></textarea></td>
   </tr>
   <tr>
   	<td>Upgrade period</td>
   	<td>
   		Till: <input type=TEXT name="TILLDATE" value="<?php echo date('d-m-Y'); ?>">
		</td>
   </tr>
   <tr>
   	<td>Comments</td>
   	<td>
   		<input type=TEXT name="COMMENTS" MALENGTH=200 size=40>
		</td>
   </tr>
   <tr>
      <td></td>
      <td><input type=SUBMIT name="ok" value="Submit"></td>
   </tr>
   </table>
   </form>
<?php
}
//------------------------------------------------------------------------------
function update_ser_data(&$db, $itemid, $expires)
{
   global $Guname;

   if ($expires===false)
      $expires='2000-01-01';

   $auth3=convertEngToGr($_REQUEST['SER_AUTH'], 1);

   $query="SELECT COUNT(*) FROM ser_data
      WHERE ser_itemid=? AND ser_auth=? AND ser_serial=?";
   $data=array($itemid, $auth3, $_REQUEST['SER_SERIAL'] );
   if (($rs=$db->Execute($query,$data))===false) {
      echo __LINE__.$db->ErrorMsg();
      return false;
   }
   $row=$rs->FetchRow();
   $rs->Close();

   if ($row[0]>0) {
      $query="UPDATE ser_data SET ser_upgrade=NOW(), ser_expires=?, SER_LASTUSER=? ";
      $data=array($expires, $Guname);
      if (!empty($_REQUEST['COMMENTS'])) {
      	$query .= ", ser_comments=? ";
      	$data[]=$_REQUEST['COMMENTS'];
		}
      $query .= " WHERE ser_itemid=? AND ser_auth=? AND ser_serial=?";
      $data2=array_merge($data, array($itemid, $auth3, $_REQUEST['SER_SERIAL'] ));
      if (!$db->Execute($query,$data2)) {
         echo __LINE__.$db->ErrorMsg();
         return false;
      }
      else {
         return true;
      }
   }
	// else: κανουμε εισαγωγή χωρίς actkey
   $query="INSERT INTO ser_data (ser_itemid, ser_auth, ser_serial, ser_date, ser_actkey, ser_deltio,
		ser_upgrade, ser_expires, ser_comments, SER_LASTUSER)
      VALUES(?,?,?, NOW(), '', 'Admin', NOW(), ?, ?, ?)";
   $data=array($itemid, $auth3, $_REQUEST['SER_SERIAL'], $expires, @$_REQUEST['COMMENTS'], $Guname );
   if (!$db->Execute($query,$data)) {
      echo __LINE__.$db->ErrorMsg();
      return false;
   }
   else {
      return true;
   }
}
//------------------------------------------------------------------------------
function admin_update_ser_version(&$db, $itemid, $version)
{
   $query="SELECT COUNT(*) FROM ser_version WHERE ser_itemid=? AND ser_auth=? AND ser_serial=? AND ser_version=?";
   $data=array($itemid, $_REQUEST['SER_AUTH'], $_REQUEST['SER_SERIAL'], $version );
   if (($rs=$db->Execute($query,$data))===false) {
      echo __LINE__.$db->ErrorMsg();
      return false;
   }
   $row=$rs->FetchRow();
   $rs->Close();
   if ($row[0]>0) {
      $query="UPDATE ser_version SET ser_date=NOW(), ser_forever=1 WHERE ser_itemid=? AND ser_auth=? AND ser_serial=? AND ser_version=?";
      $data=array($itemid, $_REQUEST['SER_AUTH'], $_REQUEST['SER_SERIAL'], $version );
   }
   else {
      $query="INSERT INTO ser_version (ser_itemid, ser_auth, ser_serial, ser_version, ser_date, ser_transid) VALUES(?,?,?,?,NOW(),0)";
      $data=array($itemid, $_REQUEST['SER_AUTH'], $_REQUEST['SER_SERIAL'], $version );
   }
   if (!$db->Execute($query,$data)) {
      echo __LINE__.$db->ErrorMsg();
      return false;
   }
   else {
      return true;
   }
}
//------------------------------------------------------------------------------
function apply_group_license(&$db)
{
	$expires=false;

	$query1="SELECT COUNT(*) FROM ser_data";
	$ar1=explode("\n",$_REQUEST['mixinput']);
	for ($i=0;$i<count($ar1);$i++) {
		$s1=trim($ar1[$i]);
		if (strlen($s1)==0)
			continue;


		$ar2=explode(' ',$s1);
		if (count($ar2)<2 || strlen($ar2[0])!=11)
			continue;

		$_REQUEST['SER_AUTH']=mb_substr($ar2[0],0,3);
		$_REQUEST['SER_SERIAL']=mb_substr($ar2[0],3);
		for ($j=1;$j<count($ar2);$j++) {
			$itemid=(int)$ar2[$j];
			update_ser_data($db, $itemid, $expires); // expires: yyyy-mm-dd
		}
	}
}
//------------------------------------------------------------------------------
function apply_group_upgrade(&$db)
{
	if (empty($_REQUEST['TILLDATE'])) {
      $expires=date('Y-m-d');
   }
   else {
   	$ar1=explode('-', $_REQUEST['TILLDATE']);
   	$ar2=array_reverse($ar1);
   	while (count($ar2)<3) {
   		$ar2[]=0;
   	}
   	$expires=implode('-', $ar2);
	}

	$ar1=explode("\n",$_REQUEST['mixinput']);
	for ($i=0;$i<count($ar1);$i++) {
		$s1=trim($ar1[$i]);
		if (strlen($s1)==0)
			continue;


		$ar2=explode(' ',$s1);
		if (count($ar2)<2 || strlen($ar2[0])!=11)
			continue;

		$_REQUEST['SER_AUTH']=mb_substr($ar2[0],0,3);
		$_REQUEST['SER_SERIAL']=mb_substr($ar2[0],3);
		for ($j=1;$j<count($ar2);$j++) {
			$itemid=(int)$ar2[$j];
			// expires: yyyy-mm-dd
			echo "expires=$expires\n";
			update_ser_data($db,$itemid,$expires);
		}
		echo "<br />";
	}
}
//------------------------------------------------------------------------------
function do_admin_upgrade(&$db)
{
   foreach ($_REQUEST as $k1=>$v1) {
      if (mb_substr($k1,0,3)!="ID_")
         continue;

      if (VERBOSE)
      {
         echo "$k1 = $v1 ";
      }

      if ($v1==0)
         continue;

      $itemid = (int)mb_substr($k1,3); // license type

      switch ($v1)
      {
      case 1: // now
         if (update_ser_data($db, $itemid, false))
         {
            if (VERBOSE)
            {
               echo "update_ser_data() OK!";
            }
            admin_update_ser_version($db, $itemid, $_REQUEST['VERSION'][$itemid]);
         }
         else if (VERBOSE)
         {
            echo "update_ser_data() failed!";
         }
         break;
      case 2: // till
         update_ser_data($db, $itemid, $_REQUEST['TILL'][$itemid]);
         break;
      }
   }
}
//------------------------------------------------------------------------------
function ask_admin_upgrade(&$db)
{
   global $ct, $aLevel;
   $ok=false;

   if ($aLevel!=1) { // Not Admin
      echo "<h6>Only Admin is allowed!</h6>";
      return;
   }

   $_REQUEST['SER_SERIAL'] = strtr($_REQUEST['SER_SERIAL'], [' '=>''] ); // reset self

   if (strlen($_REQUEST['SER_SERIAL']) ==  11)
   {  // reset input
      $_REQUEST["SER_AUTH"] = substr($_REQUEST['SER_SERIAL'], 0, 3);
      $_REQUEST['SER_SERIAL'] = substr($_REQUEST['SER_SERIAL'], 3);
   }

   $s11 = $_REQUEST["SER_AUTH"].$_REQUEST['SER_SERIAL'];

   $versions=array();
   get_versions_avail($versions);

   $query="SELECT * from ser_data
      WHERE SER_AUTH=? AND SER_SERIAL=?
      ORDER BY SER_ITEMID";
   $data=array(trim($_REQUEST["SER_AUTH"]), $_REQUEST['SER_SERIAL']);
   if ($rs=$db->Execute($query,$data)) {
      $verid=0;
      echo "<table border=0>";
      while ($o1=$rs->FetchNextObject()) {
         $ok=true;
         $records[]=$o1;
?>
         <!--
         <tr bgcolor="#d0d0d0">
            <td class=mysep>Αριθμός σειράς</td>
            <td class=mysep><b><?php echo $s11.' / '.$o1->SER_ITEMID.'# '.(@$ct->licTypes[$o1->SER_ITEMID]); ?></b></td>
         </tr>
         <tr>
            <td>Εκδοση</td>
            <td><b>2.4.1.1 ή παλιότερη</b></td>
         </tr>
         <tr>
            <td>Κωδικός άδειας χρήσης</td>
            <td><b><?php echo myhtml($o1->SER_ACTKEY); ?></b></td>
         </tr>
         <tr>
            <td>Ημ/νία χορήγησης</td>
            <td><b><?php echo GrDate($o1->SER_DATE); ?></b></td>
         </tr>
         -->
<?php
         $bigvers=array();
         show_versions($db,$o1,$bigvers);
?>
         <tr>
            <td class=mysep>Τελ. αναβάθμιση</td>
            <td class=mysep><b><?php
               if ($o1->SER_UPGRADE===null) {
                  echo "Δεν υπάρχει";
               }
               else {
                  echo GrDate($o1->SER_UPGRADE).', ισχύει μέχρι ';
                  $ar1=explode('-', $o1->SER_EXPIRES);
                  if (count($ar1)==3) {
                     $t2=mktime(23, 59, 59, (int)$ar1[1], (int)$ar1[2], (int)$ar1[0]);
                     echo date('d-m-Y',$t2);
                  }
                  else {
                     $t2=0;
                  }
                  if ($t2<time()) {
                     echo " (έληξε)";
                  }
                  else {
                     echo "&nbsp;<b style=\"color:green;\">(Can get new license)</b>";
                  }
               }
               ?></b></td>
         </tr>
<?php
         echo "<tr>
            <td></td>
            <td title=\"Υπάρχουν upgrades για να αγορασθούν\">Pending license</td>
            </tr>";

         $verid++;
      }
      $rs->Close();
      echo "</table>";
   }
   else {
      echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>\n";
   }

   if (!$ok) {
      echo "<b>Δεν βρέθηκε η άδεια χρήσης <font color=#000080>".
         myhtml($_REQUEST["SER_AUTH"].$_REQUEST['SER_SERIAL'])."</font>!</b>\n";
      return;
   }

   $now=date('Y-m-d');
?>
<p></p>
<small>Τέλος ερωτήματος</small>
<hr>
<h4>Αναβαθμίσεις</h4>
<form action="<?php echo myhtml($_SERVER['PHP_SELF']); ?>">
<input type=hidden name="FU" value="34">
<input type=hidden name="SER_AUTH" value="<?php echo $_REQUEST['SER_AUTH']; ?>">
<input type=hidden name="SER_SERIAL" value="<?php echo $_REQUEST['SER_SERIAL']; ?>">
<table>
<?php
   $ctx = new cTAX();
   $ar1=array(230, 240, 250, 260, 270, 290, 300, 310, 320, 330, 340, 345, 350, 360, 370 );
   foreach ($ar1 as $itemid) {
      echo "<tr>
         <td><b>$itemid</b></td>
         <td><input id=id_$itemid type=RADIO name=\"ID_$itemid\" value=\"1\">
            <label for=id_$itemid>Τώρα</label></td>
         <td>Version: <select id=vers$itemid name=\"VERSION[$itemid]\">";
      if (in_array($itemid, $ctx->oneOff)) {
         echo "<option>0.0.0.0</option>\n";
      }
      else {
         foreach ($versions as $v1) {
            echo "<option>".myhtml($v1)."</option>\n";
         }
      }
      echo "</select></td>
         <td>".$ctx->licTypes[$itemid]."</td>
         </tr>
         <tr>
         <td></td>
         <td><input type=RADIO name=\"ID_$itemid\" value=\"2\"> Μέχρι</td>
         <td><input type=TEXT name=\"TILL[$itemid]\" value=\"$now\"></td>
         </tr>
         <tr>
         <td></td>
         <td><input type=RADIO name=\"ID_$itemid\" value=\"0\" CHECKED> Οχι</td>
         </tr>";
      if ($itemid==300 || $itemid==370) {
         echo "<tr>
            <td></td>
            <td colspan=2>Πλήθος <input name=\"MPX_$itemid\" value=\"1\"></td>
            </tr>";
      }
   }
?>
<tr>
   <td>Σχόλια</td>
   <td colspan=2><input type=text name="COMMENTS"></td>
</tr>
<tr>
   <td colspan=3>
      <input type=submit value="Submit">
      <input type=button value="Νέο ερώτημα" onclick="location.assign(location.pathname + '?FU=16')">
   </td>
</tr>
</table>
</form>
<script>
   window.dhx_globalImgPath="/script/dhtmlx/imgs/";
   //dhtmlXComboFromSelect('new_vers');
<?php
   foreach ($ar1 as $itemid) {
      echo "dhtmlXComboFromSelect('vers${itemid}');";
   }
?>
</script>
<?php
}
//------------------------------------------------------------------------------
function ask_upgrade_2(&$db)
// May come as Superuser or simple user
{
   global $ct, $aLevel, $Guname;

   $versions=array();
   get_versions_avail($versions);

   $_REQUEST['SER_SERIAL'] = strtr($_REQUEST['SER_SERIAL'], [' '=>''] ); // reset self

   if (strlen($_REQUEST['SER_SERIAL']) ==  11)
   {  // reset input
      $_REQUEST["SER_AUTH"] = substr($_REQUEST['SER_SERIAL'], 0, 3);
      $_REQUEST['SER_SERIAL'] = substr($_REQUEST['SER_SERIAL'], 3);
   }

   $s11 = $_REQUEST["SER_AUTH"].$_REQUEST['SER_SERIAL'];

   // Make 192 for licenses newer then 16-4-2007

   $records=array();

   $ok=false;

   $query="SELECT * from ser_data
      WHERE SER_AUTH=? AND SER_SERIAL=?
      ORDER BY SER_ITEMID";
   $data=array($_REQUEST["SER_AUTH"], $_REQUEST['SER_SERIAL']);
   if ($rs=$db->Execute($query,$data)) {
      $verid=0;
      echo "<table border=0>";
      while ($o1=$rs->FetchNextObject()) {
         $ok=true;
         $records[]=$o1;
         $bigvers=array();
         show_versions($db,$o1,$bigvers);
?>
         <tr>
            <td class=mysep>Τελ. αναβάθμιση</td>
            <td class=mysep><b><?php
               if (is_null($o1->SER_UPGRADE)) {
                  echo "Δεν υπάρχει";
               }
               else {
                  echo GrDate($o1->SER_UPGRADE).', ισχύει μέχρι ';
                  $ar1=explode('-', strtr($o1->SER_EXPIRES, ' ', '-')); // YYYY-MM-DD hh:mm:ss
                  while (count($ar1)<3) {
                     $ar1[] = 0;
                  }
                  $t2=mktime(0, 0, 0, (int)$ar1[1], (int)$ar1[2], (int)$ar1[0]);
                  echo date('d-m-Y', $t2);
                  if ($t2<time()) {
                     echo " (έληξε)";
                  }
                  else {
                     echo "&nbsp;<b style=\"color:green;\">(Can get new license)</b>";
                  }
               }
               ?></b></td>
         </tr>
<?php
         echo "<tr>
            <td></td>
            <td><img src=\"../img/attention.png\" title=\"Υπάρχουν νεότερες εκδόσεις\"> Υπάρχουν νεότερες εκδόσεις (για αγορά)</td>
            </tr>";

         $verid++;
      }
      $rs->Close();
      echo "</table>";
   }
   else {
      echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>\n";
   }

   if (!$ok) {
      echo "<b>Δεν βρέθηκε η άδεια χρήσης <font color=#000080>".
         myhtml($_REQUEST["SER_AUTH"].$_REQUEST['SER_SERIAL'])."</font>!</b>\n";
   }

   echo "<HR><small>Τέλος ερωτήματος</small>";

   //
   // Print upgrade options
   //
   if ($aLevel!=1)
   { // reseller
      $avail = array();
      $query="SELECT ser_itemid, SUM(ser_quantity - ser_given) FROM ser_deltia
         WHERE ser_ugroup=? AND ser_itemid > 1000 AND ser_given < ser_quantity
         GROUP BY ser_itemid";
      $data=array($_SESSION['UGROUP']);
      if (($rs=$db->Execute($query, $data))===false)
      {
         echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>\n";
         return;
      }
      while ($row=$rs->FetchRow())
      {
         $avail[ $row[0] ] = $row[1];
      }
      $rs->Close();
   }
   if (VERBOSE) {
      pre($avail);
   }

   $today=date('Y-m-d');
   $exar1=explode('-', $today);
   $upn=0;
   foreach ($records as $o1) { // for all records in ser_data
      if (in_array($o1->SER_ITEMID, $ct->oneOff)) {
         // no need for update
         continue;
      }

      if (is_null($o1->SER_EXPIRES) || strcmp($o1->SER_EXPIRES, $today)<0) {
         $expired=true;
      }
      else {
         $expired=false;
      }

      if ($expired) {
         if ($upn==0) { // first record
            echo "<form action=\"".myhtml($_SERVER['SCRIPT_NAME'])."\">
               <input type=HIDDEN name=\"FU\" value=\"".($aLevel==1/*superuser*/?18:23)."\">
               <input type=HIDDEN name=\"EAFDSS\" value=\"$s11\">
               <table border=0>
               <tr bgcolor=\"#a9d2ff\">
               <td>&nbsp;</td>
               <td colspan=10><b>Εφαρμογή αναβαθμίσεων</b></td>
               </tr>";
         }
         else {
            tr_echo("<hr>");
         }

         if ($aLevel==1) { // Admin
            echo "<tr>
               <td><input type=RADIO name=\"CODEX[$upn]\" value=\"".$o1->SER_ITEMID.".0.2\"></td>
               <td>".$o1->SER_ITEMID.'# '.(@$ct->licTypes[$o1->SER_ITEMID])."</td>
               <td>+ Δωρεάν αναβαθμίσεις για 2 μέρες,
                  μέχρι ".date('d/m/Y',mktime(0,0,0,$exar1[1], $exar1[2]+2, $exar1[0] ))."</td>
               </tr>
               <tr>
               <td><input type=RADIO name=\"CODEX[$upn]\" value=\"".$o1->SER_ITEMID.".1\"></td>
               <td>".$o1->SER_ITEMID.'# '.(@$ct->licTypes[$o1->SER_ITEMID])."</td>
               <td>+ Δωρεάν αναβαθμίσεις για 1 μήνα,
                  μέχρι ".date('d/m/Y',mktime(0,0,0,$exar1[1]+1, $exar1[2], $exar1[0] ))."</td>
               </tr>
               <tr>
               <td><input type=RADIO name=\"CODEX[$upn]\" value=\"".$o1->SER_ITEMID.".0.10\"></td>
               <td>".$o1->SER_ITEMID.'# '.(@$ct->licTypes[$o1->SER_ITEMID])."</td>
               <td>+ Δωρεάν αναβαθμίσεις για 10 ημέρες,
                  μέχρι ".date('d/m/Y',mktime(0,0,0,$exar1[1], $exar1[2]+10, $exar1[0] ))."</td>
               </tr>";
         }
         else {
            if ( ($o1->SER_ITEMID != 330 /* Generic */ && array_key_exists(1003, $avail)) ||
               ($o1->SER_ITEMID == 330 /* SAP */ && array_key_exists(1004, $avail)) )
            {
               echo "<tr>
                  <td><input type=checkbox name=\"CODEX[$upn]\" value=\"".$o1->SER_ITEMID.".0.10\"></td>
                  <td>".$o1->SER_ITEMID.'# '.(@$ct->licTypes[$o1->SER_ITEMID])."</td>
                  <td>+ Δωρεάν αναβαθμίσεις για 10 ημέρες,
                     μέχρι ".date('d/m/Y',mktime(0,0,0,$exar1[1], $exar1[2]+10, $exar1[0] ))."</td>
                  </tr>";
            }
         }

         $upn++;
      }
   }
   if ($upn>0) {
      echo "<tr>
         <td></td>
         <td colspan=2><input type=SUBMIT value=\"Εφαρμογή\"></td>
         </tr>
         </table>
         </form>";
   }
}
//------------------------------------------------------------------------------
function user_apply_upgrade(&$db)
{
   global $Guname;

   $mail_msg='';

   if (VERBOSE) {
      pre($_REQUEST);
      return;
   }

   if (empty($_REQUEST['CODEX'])) {
      echo "<h6>Δεν επιλέξατε άδεια(ες)</h6>";
      return;
   }

   $serial=mb_substr($_REQUEST['EAFDSS'], 3); // S8$x2->ulevelmaint
   if (strlen($serial)!=8) {
      echo "<h6>Error in serial number!</h6>";
      return;
   }

   $_REQUEST["SER_AUTH"]=mb_substr($_REQUEST['EAFDSS'], 0, 3);

   $transid=0;
   $addnew=true;

   $remote_host='';
   if (isset($_SERVER["REMOTE_HOST"]))
      $remote_host=$_SERVER["REMOTE_HOST"];

   //
   // Get transaction Id (insert transaction)
   //
   $query1="INSERT INTO ser_transa
      (ser_tr_daytime, ser_ugroup, ser_tr_uname, ser_remote_addr, ser_remote_host, ser_codex_array, ser_s11_array, ser_version)
      VALUES (NOW(), ?, ?, ?, ?, ?, ?, ?)";
   $data=array($_SESSION['UGROUP'], $Guname, $_SERVER["REMOTE_ADDR"], $remote_host, implode(',',$_REQUEST['CODEX']), $_REQUEST['EAFDSS'], 'Upgrade');
   if (!$db->Execute($query1,$data)) { // error
      echo "<td colspan=3 class=ERROR>".__LINE__.$db->ErrorMsg()."</td>";
      return;
   }
   $transid = $db->Insert_ID();
?>
   <form name="myform" action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method=POST>
   <input type=HIDDEN name="FU" value="7">
   <input type=HIDDEN name="SER_ITEMID" value="<?php echo $_REQUEST["SER_ITEMID"]; ?>">
   <input type=HIDDEN name="SER_AUTH" value="<?php echo $_REQUEST["SER_AUTH"]; ?>">
   <input type=HIDDEN name="THISNR" value="">
   <input type=HIDDEN name="INVOICE" value="">
   </form>

   <table>
   <tr class=MYTHEAD>
      <td>Τύπος</td>
      <td>Serial</td>
      <td>Action</td>
      <td>Ημ/νία</td>
      <td>Act.key</td>
      <td>Δ/Α</td>
      <td>Τιμ.πελάτη</td>
      <td>Transaction</td>
   </tr>
<?php

   $line=0;
   $query1="SELECT * FROM ser_data WHERE ser_itemid=? AND ser_auth=? AND ser_serial=?";
   foreach ($_REQUEST['CODEX'] as $k1=>$codex1) {

      $ar1=explode('.', $codex1); // '250.3' -> array(250, 3), '250.0.10' -> array(250, 0, 10)
      if (count($ar1)<2)
         continue;

      $_REQUEST["SER_ITEMID"] = $ar1[0]; // i.e. 250

      if ($ar1[1]==0 && count($ar1)>=3 && $ar1[2]>0)
      {
         if ($ar1[0] == 330)
            $ser_itemid = 1004;  // SAP
         else
            $ser_itemid = 1003;  // generic
      }
      else {
         if ($ar1[0] == 330)
            $ser_itemid = 1001+$ar1[1]; // 1004 or 1013 (SAP)
         else
            $ser_itemid = 1000+$ar1[1]; // 1003 or 1012 (generic)
      }

      echo "<tr";
      if (++$line%3==0) {
         echo " class=HILINE";
      }
      echo ">\n".
         "<td>".myhtml($_REQUEST["SER_ITEMID"])."</td>\n".
         "<td>".myhtml($_REQUEST["SER_AUTH"].$serial)."</td>\n";

      //
      // Adding new value
      //
      $o2=false;
      $query2="SELECT ser_deltio, ser_d_date FROM ser_deltia
            WHERE SER_UGROUP = ? AND ser_itemid = ? AND ser_quantity > ser_given
            ORDER BY ser_d_date, ser_deltio";
      $data=array($_SESSION['UGROUP'], $ser_itemid); // $ser_itemid example: 1004
      if (($rs=$db->Execute($query2, $data))===false) {
         echo "<td colspan=3 class=ERROR>".__LINE__.$db->ErrorMsg()."</td>";
         break;
      }
      if ($o2=$rs->FetchNextObject()) {
         $deltio = $o2->SER_DELTIO;
      }
      $rs->Close();

      if ($o2===false) {
         echo "<td colspan=3 class=ASTERISK>Δεν βρέθηκε απόθεμα αδειών!</td>";
         $_REQUEST['CODEX'][$k1]=''; // reset
         break;
      }

      $ok=false;
      $query2="UPDATE ser_deltia SET ser_given=ser_given+1
         WHERE ser_deltio=? AND ser_itemid=? AND  ser_quantity > ser_given";
      //       ............key..............      ....... condition........
      $data=array($deltio, $ser_itemid);
      if (!$db->Execute($query2,$data)) {
         echo "<td colspan=3 class=ERROR>".__LINE__.$db->ErrorMsg()."</td>";
         $_REQUEST['CODEX'][$k1]=''; // reset
         break;
      }

      $mail_msg .= ($_REQUEST['EAFDSS']."\t".$codex1."\r\n");

      echo "</tr>\n";

   } // for ...
   echo "</table>\n";

   admin_apply_upgrade($db, $transid); // use $_REQUEST['CODEX'][...]

   if (!empty($mail_msg)) {
      $mti="New TaxSpooler upgrade(s)";
      send_mail_to_inca($db, $mti, $mail_msg);
   }
}
//------------------------------------------------------------------------------
function admin_apply_upgrade(&$db, $trid=false)
{
   /* 'CODEX' var examples:
      a)
      250.3 = #250 for 3 months (10 days)
      CODEX[x]=250.3
      EAFDSS=EPZ12345678
      b)                      select * from `ser_data` where ser_auth='FGG' AND ser_serial like '1802080%'
      250.0.4 = #250 for 4 days
      CODEX[x]=250.3
      EAFDSS=EPZ12345678
   */
   $s11 = $_REQUEST['EAFDSS'];

   foreach ($_REQUEST['CODEX'] as $r1) {
      $ar1=explode('.',$r1);
      if (count($ar1)<2)
         continue;

      $ser_itemid=(int)$ar1[0]; // i.e. 250
      $months=(int)$ar1[1]; // i.e. 3 or 12
      $days=(int)@$ar1[2];

      $query="SELECT ser_expires FROM ser_data WHERE ser_itemid=? AND ser_auth=? AND ser_serial=?";
      $data=array( $ser_itemid, mb_substr($s11,0,3), mb_substr($s11,3) );
      if (($rs=$db->Execute($query,$data))===false) {
         echo "<h6>Error Read ser_data: ".__LINE__.$db->ErrorMsg()."</h6>";
         break;
      }
      $yesterday=date('Y-m-d', time()-86400);
      while ($o2=$rs->FetchNextObject()) {
         if ($o2->SER_EXPIRES==null)
            $expired=$yesterday;
         else {
            $expired=$o2->SER_EXPIRES;
            if (strcmp($expired,$yesterday)<0)
               $expired=$yesterday;
         }

         $expar=explode('-',$expired);
         $newExpiration=mktime( 0, 0, 0, (int)$expar[1]+$months, (int)$expar[2]+$days, (int)$expar[0] );

         $qupd="UPDATE ser_data SET ser_upgrade=NOW(), ser_expires=?, ser_upgtrid=? WHERE ser_itemid=? AND ser_auth=? AND ser_serial=?";
         $data2=array( date('Y-m-d',$newExpiration), $trid, $ser_itemid, mb_substr($s11,0,3), mb_substr($s11,3) );
         if (!$db->Execute($qupd,$data2)) {
            echo "<h6>Error Update ser_data: ".__LINE__.$db->ErrorMsg()."</h6>";
            break;
         }
      }
      $rs->Close();
   }

   $_REQUEST["SER_AUTH"]=mb_substr($s11,0,3);
   $_REQUEST['SER_SERIAL']=mb_substr($s11,3);
   ask_upgrade_2($db);
}
//------------------------------------------------------------------------------
function delete_upgrade(&$db)
{
   $query="UPDATE ser_data SET SER_UPGRADE=NULL, SER_EXPIRES=NULL WHERE SER_AUTH=? AND SER_SERIAL=? AND SER_ITEMID=?";
   $data=array( substr($_REQUEST['S11'],0,3), substr($_REQUEST['S11'],3), $_REQUEST['SER_ITEMID'] );
   if (!$db->Execute($query,$data))
      echo $db->ErrorMsg();
}
//------------------------------------------------------------------------------
function delete_version(&$db)
{
   $query="DELETE FROM ser_version WHERE SER_AUTH=? AND SER_SERIAL=? AND SER_ITEMID=? AND SER_VERSION=? /* AND SER_TRANSID=0 */";
   $data=array( substr($_REQUEST['S11'],0,3), substr($_REQUEST['S11'],3), $_REQUEST['SER_ITEMID'], $_REQUEST['SER_VERSION'] );
   if (!$db->Execute($query,$data))
      echo $db->ErrorMsg();
}
//------------------------------------------------------------------------------
function delete_main_key($db)
{
   $query="UPDATE ser_data SET SER_ACTKEY='' WHERE SER_AUTH=? AND SER_SERIAL=? AND SER_ITEMID=?";
   $data=array( substr($_REQUEST['S11'],0,3), substr($_REQUEST['S11'],3), $_REQUEST['SER_ITEMID'] );
   if (!$db->Execute($query,$data))
      echo $db->ErrorMsg();
}
//------------------------------------------------------------------------------
function some_cleanup(&$db)
{
   $lic=array();
   $query="SELECT SER_AUTH, SER_SERIAL, SER_ITEMID FROM ser_data
      WHERE (SER_ITEMID=250 AND SER_TRANSID=0) OR SER_ITEMID=230 OR SER_ITEMID=240";
   if (($rs=$db->Execute($query))===false) {
      echo __LINE__.$db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $k1=$o1->SER_AUTH.$o1->SER_SERIAL;
      if (array_key_exists($k1, $lic)) {
         $v1=$lic[$k1];
      }
      else {
         $v1=0;
      }

      $v1 |= (($o1->SER_ITEMID==230 || $o1->SER_ITEMID==240)?1:2);
      $lic[$k1]=$v1;
   }
   $rs->Close();

   foreach ($lic as $k1=>$v1) {
      if ($v1>=3) {
         echo "$k1 = $v1<br>";
      }
   }
   echo "<hr>";
}
//------------------------------------------------------------------------------
function do_transfer250to240(&$db)
{
   if (strlen($_REQUEST['S11'])!=11) {
      echo "<h6>S11 not good!</h6>";
      return;
   }

   $auth=substr($_REQUEST['S11'],0,3);
   $s8=substr($_REQUEST['S11'],3);

   $db->StartTrans();

   do {
      $query="DELETE FROM ser_data WHERE ser_itemid=240 AND ser_auth=? AND ser_serial=?";
      $data=array( $auth, $s8 );
      if (!$db->Execute($query,$data)) {
         echo $db->ErrorMsg();
         break;
      }

      $query="UPDATE ser_data SET ser_itemid=240 WHERE ser_itemid=250 AND ser_auth=? AND ser_serial=?";
      $data=array( $auth, $s8 );
      if (!$db->Execute($query,$data)) {
         echo $db->ErrorMsg();
         break;
      }

      $query="DELETE FROM ser_version WHERE ser_itemid=240 AND ser_auth=? AND ser_serial=?";
      $data=array( $auth, $s8 );
      if (!$db->Execute($query,$data)) {
         echo $db->ErrorMsg();
         break;
      }

      $query="UPDATE ser_version SET ser_itemid=240 WHERE ser_itemid=250 AND ser_auth=? AND ser_serial=?";
      $data=array( $auth, $s8 );
      if (!$db->Execute($query,$data)) {
         echo $db->ErrorMsg();
         break;
      }
   } while (false);

   $db->CompleteTrans();
}
//------------------------------------------------------------------------------
function show_s11_complete(&$db)
{
   echo "<div class=MYBOX style=\"width:80%; font-weight:bold;\">".$_REQUEST['S11']."</div>&nbsp;";

   $query="SELECT T1.*, T2.SER_CUSTOMER FROM ser_data T1 ".
      " LEFT JOIN ser_transa T2 ON (T2.SER_TRANSID=T1.SER_TRANSID) ".
      " WHERE T1.ser_auth=? AND T1.ser_serial=? ".
      " ORDER BY T1.SER_TRANSID, T1.SER_DATE";
   $data=array( substr($_REQUEST['S11'],0,3), substr($_REQUEST['S11'],3) );
   if (($rs=$db->Execute($query,$data))===false) {
      echo $db->ErrorMsg();
      return;
   }
   echo "<table>
      <tr class=MYTHEAD>
      <td>Item Id</td>
      <td>Date</td>
      <td>Act.key</td>
      <td>Deltio</td>
      <td>Tim.Pelati</td>
      <td>Trans.Id</td>
      <td>Customer</td>
      <td>Upgrade</td>
      <td>Expires</td>
      <td>SID Count</td>
      <td>Comments</td>
      <td>Last user</td>
      </tr>";
   while ($o1=$rs->FetchNextObject()) {
      $customerName = getCurtomerName($o1->SER_CUSTOMER);

      echo "<tr>
         <td>".$o1->SER_ITEMID."</td>
         <td><pre>".$o1->SER_DATE."</pre></td>
         <td>".$o1->SER_ACTKEY;
      if (!empty($o1->SER_ACTKEY)) {
         echo "\n<a href=\"".myhtml($_SERVER['PHP_SELF'])."?FU=82&S11=".$_REQUEST['S11'].
            "&SER_ITEMID=".$o1->SER_ITEMID."\"><img src=\"../img/cancel_box.png\" border=0\"></a>";
      }
      echo "</td>
         <td>".myhtml($o1->SER_DELTIO)."</td>
         <td>".myhtml($o1->SER_TIM_PEL)."</td>
         <td>".$o1->SER_TRANSID."</td>
         <td>".myhtml($customerName)."</td>
         <td>".$o1->SER_UPGRADE;
      if ($o1->SER_UPGRADE!=null) {
         echo " <a href=\"".myhtml($_SERVER['PHP_SELF'])."?FU=74&S11=".$_REQUEST['S11'].
            "&SER_ITEMID=".$o1->SER_ITEMID."\"><img src=\"../img/cancel_box.png\" border=0></a>";
      }
      echo "</td>
         <td>".$o1->SER_EXPIRES."</td>
         <td>".$o1->SER_COUNT."</td>
         <td>".myhtml($o1->SER_COMMENTS)."</td>
         <td>".myhtml($o1->SER_LASTUSER)."</td>
         </tr>";
   }
   $rs->Close();
   echo "</table>&nbsp;";

   $query="SELECT * FROM ser_version WHERE ser_auth=? AND ser_serial=? ORDER BY SER_TRANSID, SER_DATE";
   $data=array( substr($_REQUEST['S11'],0,3), substr($_REQUEST['S11'],3) );
   if (($rs=$db->Execute($query,$data))===false) {
      echo $db->ErrorMsg();
      return;
   }
   echo "<table>
      <tr class=MYTHEAD>
      <td>Item Id</td>
      <td>Version</td>
      <td>Date</td>
      <td>Trans.Id</td>
      <td>Forever</td>
      </tr>";
   while ($o1=$rs->FetchNextObject()) {
      echo "<tr>
         <td>".$o1->SER_ITEMID."</td>
         <td>".$o1->SER_VERSION."</td>
         <td>".$o1->SER_DATE."</td>
         <td>".$o1->SER_TRANSID."</td>
         <td>".$o1->SER_FOREVER."</td>
         <td><a href=\"".myhtml($_SERVER['PHP_SELF'])."?FU=73&S11=".$_REQUEST['S11'].
            "&SER_ITEMID=".$o1->SER_ITEMID."&SER_VERSION=".$o1->SER_VERSION."\"><img
         src=\"../img/cancel_box.png\" border=0></a></td>
         </tr>";
   }
   $rs->Close();
   echo "</table>";

   echo "<button type=button onclick=\"location.href='".myhtml($_SERVER['PHP_SELF'])."?FU=72';\">Cleanup</button>";
}
//------------------------------------------------------------------------------
function ask_transfer250to240()
{
?>
   <div class=MYBOX style="width:80%"><b>Convert 250 licence to 240</b></div>

   <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method=POST>
   <input type=HIDDEN name="FU" value="76">
   <table>
   <tr>
      <td>Serial (S11)</td>
      <td><input type=text name="S11" maxlength=11></td>
   </tr>
   <tr>
      <td colspan=2 align=right><input type=submit value="Convert"></td>
   </tr>
   </table>
   </form>
<?php
}
//------------------------------------------------------------------------------
function ask_s11_complete()
{
?>
   <div class=MYBOX style="width:80%"><b>Query S11 complete</b></div>

   <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method=POST>
   <input type=HIDDEN name="FU" value="71">
   <table>
   <tr>
      <td>Serial (S11)</td>
      <td><input type=text name="S11" maxlength=11></td>
   </tr>
   <tr>
      <td colspan=2 align=right><input type=submit value="Query"></td>
   </tr>
   </table>
   </form>
<?php
}
//------------------------------------------------------------------------------
function su_execute_query(&$db)
{
   $rs=$db->Execute($_REQUEST['XQUERY']);
   if ($rs===false) {
      echo "<h6>".$db->ErrorMsg()."</h6>";
      return;
   }
   echo "<table>";
   while ($row=$rs->FetchRow()) {
      echo "<tr>";
      foreach ($row as $f1) {
         echo "<td>".myhtml($f1)."</td>";
      }
      echo "</tr>";
   }
   $rs->Close();
   echo "</table>";
}
//------------------------------------------------------------------------------
function su_ask_query()
{
?>
   <div  class=MYBOX style="width:80%"><b>Execute SQL query</b></div>

   <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method=POST>
   <input type=HIDDEN name="FU" value="67">
   <table>
   <tr>
      <td>SQL query</td>
      <td><textarea style="width:640px; height:240px;" name="XQUERY"></textarea></td>
   </tr>
   <tr>
      <td colspan=2 align=right><input type=SUBMIT name="ok" value="Submit"></td>
   </tr>
   </table>
   </form>
<?php
}
//------------------------------------------------------------------------------
function get_input_given()
{
?>
   <table width="80%"><tr class=MYBOX><td><b>Εισαγωγή παλαιών</b></td></tr></table>

   <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method=POST>
   <input type=HIDDEN name="FU" value="2">
   <table>
   <tr>
      <td>Date (YYYYMMDD)</td>
      <td><input type=TEXT name="SER_DATE"></td>
   </tr>
   <tr>
      <td>Ομάδα κωδικών</td>
      <td><textarea name="GROUPCODE" cols=70 rows=20></textarea></td>
   </tr>
   <tr>
      <td colspan=2 align=right><input type=SUBMIT name="ok" value="Submit"></td>
   </tr>
   </table>
   </form>
<?php
}
//------------------------------------------------------------------------------
function get_input_cancel()
{
   global $Groups, $ct;
?>
   <script>
   function checkForm()
   {
      var f1=document.forms[0];
      /*
      if (f1.CANCELGRP.selectedIndex<=0) {
         alert('No group selected!');
         return false;
      }
      else*/ if (f1.GROUPCODE.value.length==0) {
         alert('No codes given!');
         return false;
      }
      if (!f1.WHAT[0].checked && !f1.WHAT[1].checked) {
         alert('At leaset one radio must be checked!');
         return false;
      }
      return true;
   }
   </script>

   <div style="width:80%; font-weight:bold; padding:2px;" class=MYBOX>Ακυρώσεις</div>

   <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method=POST onsubmit="return checkForm()"">
   <input type=HIDDEN name="FU" value="13">
   <table>
   <!-- tr>
      <td>Group</td>
      <td><select name="CANCELGRP">
         <option value="-1">Select...</option>
         <?php
            prAssocSelect($Groups,-1);
         ?></select></td>
   </tr -->
   <tr>
      <td>Τύπος άδειας</td>
      <td><select name="SER_ITEMID">
         <option value="230">ETax Lite Serial (#230)</option>
         <option value="240">ETax Lite Ethernet (#240)</option>

         <option value="250">Κανονική (#250)</option>
         <option value="260">Εκτεταμένη TCP/IP (#260)</option>
         <option value="270">AS400 (#270)</option>
         <option value="280">Native Unix (#280)</option>

         <option value="320">Ηλεκτρονική Διαβίβαση (#320)</option>
         <option value="330">SAP (#330)</option>
         <option value="300">FGA/ SID Xtra (#300)</option>
         <option value="340">E-Xtend (#340)</option>
         <option value="290">E-Invoice Lite (#290)</option>
         <option value="310">Graphics Overdraw (#310)</option>
         <option value="350">Cluster (#350)</option>
         <option value="360">FGA/ IE11 (#360)</option>
         </select></td>
   </tr>
   <tr>
      <td>Είδος</td>
      <td>
         <input id=what1 type=radio name="WHAT" value="1"> <label for=what1>Κανονική άδεια</label>
         <input id=what2 type=radio name="WHAT" value="2"> <label for=what2>Upgrade 3M/12M</label>
      </td>
   </tr>
   <tr>
      <td>Ομάδα κωδικών</td>
      <td><textarea name="GROUPCODE" cols=70 rows=15></textarea></td>
   </tr>
   <tr>
      <td></td>
      <td><input type=SUBMIT name="ok" value="Submit"></td>
   </tr>
   </table>
   </form>
<?php
}
//------------------------------------------------------------------------------
function upd_input_cancel(&$db)
{
   switch (@$_REQUEST['WHAT'])
   {
   case 1:
      cancel_new_lic($db);
      break;
   case 2:
      cancel_upgrade($db);
      break;
   }
}
//------------------------------------------------------------------------------
function cancel_upgrade(&$db)
{
   $ndel3=0;
   $ndel12=0;
   $lines=explode("\n",$_REQUEST["GROUPCODE"]);
   $n=count($lines);

   $db->StartTrans();

   for ($i=0;$i<$n;$i++) {
      $ser11=strtr(trim($lines[$i]),
         'ΑΒΕΖΗΙΚΜΝΟΡΤΥΧ',
         'ABEZHIKMNOPTYX'); // Gr->En
      $ser11=strtr($ser11, array(' '=>'') ); // remove any space
      if (strlen($ser11)!=11) {
         echo "<h6>".myhtml($ser11)." rejected (error in length)</h6>";
         continue;
      }

      $ser_itemid=$_REQUEST["SER_ITEMID"];
      $ser_auth3=mb_substr($ser11,0,3);
      $ser_serial8=mb_substr($ser11,3);

      $query="SELECT ser_ugroup, ser_upgrade, ser_expires FROM ser_data WHERE ser_itemid=? AND ser_auth=? AND ser_serial=?";
      $data=array( $ser_itemid, $ser_auth3, $ser_serial8 );
      if (($rs=$db->Execute($query,$data))===false) {
         echo __LINE__.$db->ErrorMsg();
         continue;
      }
      $o1=$rs->FetchNextObject();
      $rs->Close();
      if ($o1===false) {
         echo "<h6>$ser_auth3 $ser_serial8 not found!</h6>";
         continue;
      }

      if ($o1->SER_UPGRADE==null) {
         echo "<h6>$ser_auth3 $ser_serial8 UPGRADE not ever given!</h6>";
         continue;
      }

      $group = $o1->SER_UGROUP;

      $query="UPDATE ser_data SET ser_upgrade = NULL, ser_expires = NULL WHERE ser_itemid=? AND ser_auth=? AND ser_serial=?";
      $data=array( $ser_itemid, $ser_auth3, $ser_serial8 );
      if (!$db->Execute($query,$data)) {
         echo __LINE__.$db->ErrorMsg();
         break;
      }

      $ar1=explode('-', $o1->SER_EXPIRES);
      $ar2=explode('-', $o1->SER_UPGRADE);
      $dt=( mktime(0,0,0,$ar2[1], $ar2[2], $ar2[0]) - mktime(0,0,0,$ar1[1], $ar1[2], $ar1[0]) )/(24*3600);

      do {
         $query="DELETE FROM ser_version WHERE ser_itemid=? AND ser_auth=? AND ser_serial=? AND ser_date>=?";
         $data=array( $ser_itemid, $ser_auth3, $ser_serial8, $o1->SER_UPGRADE );
         if (!$db->Execute($query,$data)) {
            echo __LINE__.$db->ErrorMsg();
            break;
         }
         else if ($dt<120) {
            $ndel3++;
         }
         else {
            $ndel12++;
         }

      } while (false);

   }

   $deltio=date('YmdHis');

   if ($ndel3>0) {
      $query="INSERT INTO ser_deltia (ser_ugroup, ser_deltio, ser_d_date, ser_itemid, ser_invoice, ser_quantity, ser_given)
            VALUES(?,?,NOW(),?,  ?,?,?)";
      $data=array( $group, $deltio, 1003, 'CANCEL', $ndel3, 0 );
      if (!$db->Execute($query,$data)) {
         echo __LINE__.$db->ErrorMsg();
      }
   }

   if ($ndel12>0) {
      $query="INSERT INTO ser_deltia (ser_ugroup, ser_deltio, ser_d_date, ser_itemid, ser_invoice, ser_quantity, ser_given)
            VALUES(?,?,NOW(),?,  ?,?,?)";
      $data=array( $group/*$_REQUEST['CANCELGRP']*/, $deltio, 1012, 'CANCEL', $ndel12, 0 );
      if (!$db->Execute($query,$data)) {
         echo __LINE__.$db->ErrorMsg();
      }
   }

   $db->CompleteTrans();
}
//------------------------------------------------------------------------------
function cancel_new_lic(&$db)
{
   $in=array('Α', 'Β', 'Ε', 'Ζ', 'Η', 'Ι', 'Κ', 'Μ', 'Ν', 'Ο', 'Ρ', 'Τ', 'Υ', 'Χ'); // Greek UTF-8
   $out=array('A', 'B', 'E', 'Z', 'H', 'I', 'K', 'M', 'N', 'O', 'P', 'T', 'Y', 'X'); // English

   $group = false;
   $ndel=0;
   $lines=explode("\n",$_REQUEST["GROUPCODE"]);
   $n=count($lines);

   $db->StartTrans();

   for ($i=0;$i<$n;$i++) {
      $ser11 = trim($lines[$i]);
      $ser11 = str_replace($in, $out, $ser11); // greek > english
      $ser11 = strtr($ser11, array(' '=>'') ); // remove any space

      if (empty($ser11)) {
         continue;
      }
      else if (strlen($ser11)!=11) {
         echo "<h6>".myhtml($ser11)." rejected (error in length)</h6>";
         continue;
      }

      $ser_itemid=$_REQUEST["SER_ITEMID"];

      do {
         if ($ser_itemid==300) { // convert 300 into 400
            $data = array(substr($ser11,0,3), substr($ser11,3));
            $query = "SELECT T1.ser_count, T2.SER_UGROUP FROM ser_data T1
               INNER JOIN ser_transa T2 ON (T2.ser_transid=T1.ser_transid)
               WHERE T1.ser_itemid=400 AND T1.ser_auth=? AND T1.ser_serial=?";
         }
         else {
            $data=array(substr($ser11,0,3), substr($ser11,3));
            $query="SELECT 1, T2.ser_ugroup FROM ser_version T1
               INNER JOIN ser_transa T2 ON (T2.ser_transid=T1.ser_transid)
               WHERE T1.ser_itemid=$ser_itemid AND T1.ser_auth=? AND T1.ser_serial=? AND T1.ser_forever=1";
         }
         if (($rs=$db->Execute($query, $data))===false) {
            echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
            break;
         }
         $row=$rs->FetchRow();
         $rs->Close();
         if ($row===false) {
            echo "<div style=\"background-color:#e0e0e0\">Did not find record for ${ser11}.
               <h2>Will not do any cancelation.</h2></div>";
            break;
         }

         $ser_count = $row[0];
         if ($ser_itemid==300) {
            echo "<h5>Count $ser_count for $ser_itemid</h5>";
         }

         $group = $row[1];
         echo "<div>$ser11 created by group $group</div>";

         $ser_itemid2 = ($ser_itemid == 300 ? 400 : $ser_itemid);
         $dataX = array($ser_itemid2, substr($ser11,0,3), substr($ser11,3));
         $query2="DELETE FROM ser_data WHERE ser_itemid=? AND ser_auth=? AND ser_serial=?";
         if (!$db->Execute($query2,$dataX)) {
            echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
            break;
         }
         $ndel += $db->affected_rows();

         $query3="DELETE FROM ser_version WHERE ser_itemid=? AND ser_auth=? AND ser_serial=?";
         if (!$db->Execute($query3,$dataX)) {
            echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
            break;
         }

      } while (false);
   }

   do {
      echo "<div>NDEL=$ndel</div>";
      if ($ndel==0)
         break;

      if ($group===false)
         break;

      switch ($ser_itemid)
      {
      case 240:
         $del_id=230;
         break;
      case 260:
      case 270:
      case 280:
         $del_id=250;
         break;
      default:
         $del_id=$ser_itemid;
         break;
      }

      $deltio=date('YmdHis');
      $query="INSERT INTO ser_deltia (ser_ugroup, ser_deltio, ser_d_date, ser_itemid, ".
       " ser_quantity, ser_given, ser_invoice) VALUES (?, ?, ?, ?, ?, 0, ? )";
      $data=array($group/*$_REQUEST['CANCELGRP']*/, $deltio, date('Ymd'), $del_id, $ndel, "CANCEL");
      if (!$db->Execute($query,$data)) {
         echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
         return;
      }
   } while (false);

   $db->CompleteTrans();
}
//------------------------------------------------------------------------------
function upd_given_table(&$db)
// ΕΙΣΑΓΩΓΗ ΠΑΛΙΩΝ (admin)
{
   global $Guname;

   $lines=explode("\n",$_REQUEST["GROUPCODE"]);
   $n=count($lines);

   $remote_host='';
   if (isset($_SERVER["REMOTE_HOST"]))
      $remote_host=$_SERVER["REMOTE_HOST"];

   // insert transaction
   $query1="INSERT INTO ser_transa ".
      " (ser_tr_daytime, ser_ugroup, ser_tr_uname, ser_remote_addr, ser_remote_host, ser_tr_daytime, ser_codex_array, ser_s11_array, ser_version) ".
      " VALUES (NOW(), ?, ?, ?, ?, ?, ?,?,?)";
   $data=array($Guname, $_SESSION['UGROUP'], $_SERVER["REMOTE_ADDR"], $remote_host, $_REQUEST["SER_DATE"], strtr(implode(',', $lines),"\t", " "), 'EPZ', 'Base' );
   if (!$db->Execute($query1,$data)) { // error
      echo "<td colspan=3 class=ERROR>".__LINE__.$db->ErrorMsg()."</td>";
      return;
   }
   $transid=$db->Insert_ID();

?>
   <form name="myform" action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method=POST>
   <input type=HIDDEN name="FU" value="7">
   <input type=HIDDEN name="SER_ITEMID" value="<?php echo $_REQUEST["SER_ITEMID"]; ?>">
   <input type=HIDDEN name="SER_AUTH" value="<?php echo $_REQUEST["SER_AUTH"]; ?>">
   <input type=HIDDEN name="THISNR" value="">
   <input type=HIDDEN name="INVOICE" value="">
   <input type=HIDDEN name="FROMNR" value="<?php echo $_REQUEST["FROMNR"]; ?>">
   <input type=HIDDEN name="TONR" value="<?php echo $_REQUEST["TONR"]; ?>">
   </form>

   <table>
   <tr class=MYTHEAD>
      <td>Τύπος</td>
      <td>Serial</td>
      <td>Action</td>
      <td>Ημ/νία</td>
      <td>Act.key</td>
      <td>Δ/Α</td>
      <td>Τιμ.πελάτη</td>
      <td>Transaction</td>
   </tr>
<?php

   $line=0;
   $query1="SELECT * FROM ser_data WHERE ser_itemid=? AND ser_auth=? AND ser_serial=?";
   for ($i=0;$i<$n;$i++) {
      $line1=trim($lines[$i]);
      if (empty($line1))
         continue;

      $fields=explode("\t",$line1);
      if (count($fields)!=2 || strlen($fields[0])!=11) {
      	// failed by TAB, try by SPACE
			$fields=explode(" ",$line1);
		}
		// check again
		if (count($fields)!=2 || strlen($fields[0])!=11)
         continue;

      $serial=mb_substr($fields[0],3);

      echo "<tr";
      $line++;
      if ($line%3==0)
         echo " class=HILINE";
      echo ">\n".
         "<td>".myhtml('250')."</td>\n".
         "<td>".myhtml('EPZ'.$serial)."</td>\n";

      $fi=false;
      $data=array('250', 'EPZ', $serial);
      if ($rs=$db->Execute($query1,$data)) {
         if ($o1=$rs->FetchNextObject()) {
            $fi=true;
            echo "<td><b>FOUND</b></td>\n".
               "<td>".myhtml($o1->SER_DATE)."</td>\n".
               "<td>".myhtml($o1->SER_ACTKEY)."</td>\n".
               "<td>".myhtml($o1->SER_DELTIO)."</td>\n".
               "<td></td>\n".
               "<td>0</td>";
         }
         $rs->Close();
      }
      else {
         echo "<td colspan=3 class=ERROR>1) ".__LINE__.$db->ErrorMsg()."</td>";
      }

      if ($fi==true)
         continue;

      	// Υπάρχουν ποσότητες για ανάλωση?
         $fi2=false;
         $query2="SELECT ser_deltio, ser_d_date FROM ser_deltia WHERE ser_itemid=? AND ser_quantity > ser_given ".
            " ORDER BY ser_d_date, ser_deltio";
         $data=array('250');
         if ($rs=$db->Execute($query2,$data)) {
            if ($o2=$rs->FetchNextObject()) {
               $fi2=true;
               $deltio=$o2->SER_DELTIO;
            }
            $rs->Close();
         }
         else {
            echo "<td colspan=3 class=ERROR>2) ".__LINE__.$db->ErrorMsg()."</td>";
            break;
         }

         if ($fi2==false) {
            echo "<td colspan=3 class=ASTERISK>Δεν βρέθηκαν Δ/Αποστολής</td>";
            break;
         }

         $ok=false;
         $query2="UPDATE ser_deltia SET ser_given=ser_given+1 WHERE ser_deltio=? AND ser_quantity > ser_given";
         $data=array($deltio);
         if ($db->Execute($query2,$data))
            $ok=true;
         else {
            echo "<td colspan=3 class=ERROR>3) ".__LINE__.$db->ErrorMsg()."</td>";
            break;
         }

         if ($ok) {
            $actkey=$fields[1];
            // update ser_data
            $query2="INSERT INTO ".
               " ser_data (ser_itemid, ser_auth, ser_serial, ser_deltio, ser_date, ser_actkey, ser_transid, ser_lastuser) ".
               " VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            $data=array('250', 'EPZ', $serial, $deltio,
               $_REQUEST["SER_DATE"], $actkey, $transid, $Guname );
            if (!$db->Execute($query2,$data)) { // error
               echo "<td colspan=3 class=ERROR>4) ".__LINE__.$db->ErrorMsg()."</td>";
               break;
            }
            else { // ok.
               echo "<td>New</td>\n".
                  "<td>Σήμερα</td>\n".
                  "<td>".myhtml($actkey)."</td>\n".
                  "<td>".myhtml($deltio)."</td>\n".
                  "<td><a href=\"javascript:GoInvoice('".$serial."')\">Insert</a></td>".
                  "<td><a href=\"".myhtml($_SERVER['SCRIPT_NAME'])."?FU=8&TRID=".$transid."\">".$transid."</a></td>";
            }
         }

      echo "</tr>\n";

   } // for ...

   echo "</table>\n";
}
//------------------------------------------------------------------------------
function input_deltio()
{
   global $Groups;

?>
<script>
$(function(){
   $( 'input[name="SER_D_DATE"]' ).datepicker({ dateFormat: "yymmdd" }); // yymmdd = {YYYY}{MM}{DD}

   $(document.goForm).submit(function(event){
      if ( !$('input:radio[name="SER_UGROUP"]').is(':checked') ) {
         alert('Group not set!');
         event.preventDefault();
      }
      else if ( !$('input:radio[name="PROTYPE"]').is(':checked') ) {
         alert('Program not set!');
         event.preventDefault();
      }
   });
} );

function goInform()
{
   var f1=document.goForm;
   f1.FU.value=55;
   f1.submit();
}
function show_si_body(x)
{
   switch (x)
   {
   case 1: // taxspooler
      $('#ser_itemid_body').show();
      $('#fga_itemid_body').hide();
      break;
   case 2: // taxgate
      $('#ser_itemid_body').hide();
      $('#fga_itemid_body').hide();
      break;
   case 3: // fga
      $('#ser_itemid_body').hide();
      $('#fga_itemid_body').show();
      break;
   }
}
</script>
   <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method=POST name="goForm">
   <input type=HIDDEN name="FU" value="6">
   <table style="border-spacing:0; padding:2px;">
   <tr>
      <td>Group</td>
      <td><?php
         foreach ($Groups as $key=>$val) {
            echo "<label><input type=RADIO name=\"SER_UGROUP\" value=\"$key\">$val</label>&nbsp;&nbsp;";
         }
      ?></td>
   </tr>
   <tr>
      <td>Παραστατικό</td>
      <td><input type=TEXT name="SER_DELTIO" value="<?php echo myhtml(@$_SESSION['SER_DELTIO']); ?>" maxlength=20></td>
   </tr>
   <tr>
      <td>Ημ/νια (ΕΕΕΕΜΜΗΗ)</td>
      <td><input type=TEXT name="SER_D_DATE" value="<?php echo empty($_SESSION['SER_D_DATE']) ? date('Ymd') : myhtml($_SESSION['SER_D_DATE']); ?>" READONLY>
      </td>
   </tr>
   <tr>
      <td>Πρόγραμμα</td>
      <td>
         <input type=radio id=taxsp name="PROTYPE" value="1" onclick="show_si_body(1)"> <label for=taxsp>TaxSpooler</label>
         <input type=radio id=taxfga name="PROTYPE" value="3" onclick="show_si_body(3)"> <label for=taxfga>FGA</label>
         <input type=radio id=taxga name="PROTYPE" value="2" onclick="show_si_body(2)"> <label for=taxga>TaxGate</label>
      </td>
   </tr>

   <tbody id=ser_itemid_body style="display:none">
   <tr style="background-color:#e0e0e0">
      <td>Τύπος άδειας</td>
      <td>
         <label><input type=RADIO name="SER_ITEMID" value="220">FIMAS (#220)</label><br>
         <label><input type=RADIO name="SER_ITEMID" value="230">ETax Lite Serial/ Ethernet (#230 /#240)</label><br>
         <label><input type=RADIO name="SER_ITEMID" value="250">Κανονική #250/ Εκτεταμένη (TCP/IP) #260/ AS400 #270/ Native Unix (#280)</label><br>
         <label><input type=RADIO name="SER_ITEMID" value="320">Ηλεκτρονική Διαβίβαση (#320)</label><br>
         <label><input type=RADIO name="SER_ITEMID" value="330">SAP (#330)</label><br>
         <label><input type=RADIO name="SER_ITEMID" value="300">FGA/ SID Xtra (#300)</label><br>
         <label><input type=RADIO name="SER_ITEMID" value="340">E-Xtend (#340)</label><br>
         <label><input type=RADIO name="SER_ITEMID" value="350">Cluster (#350)</label><br>
         <label><input type=RADIO name="SER_ITEMID" value="360">FGA/ IE11 (#360)</label><br>
         &nbsp;<br>
         <label><input type=RADIO name="SER_ITEMID" value="290">E-Invoice Lite (#290)</label><br>
         <label><input type=RADIO name="SER_ITEMID" value="310">Graphics Overdraw (#310)</label><br>
         &nbsp;<br>
         <label><input type=RADIO name="SER_ITEMID" value="1003">10d Upgrade/ generic</label><br>
         <label><input type=RADIO name="SER_ITEMID" value="1004">10d Upgrade/ SAP</label><br>
         <label><input type=RADIO name="SER_ITEMID" value="1012">12M Upgrade/ generic</label><br>
         <label><input type=RADIO name="SER_ITEMID" value="1013">12M Upgrade/ SAP</label>
      </td>
   </tr>
   </tbody>

   <tr>
      <td>Ποσότητα</td>
      <td><input type=TEXT name="SER_QUANTITY"></td>
   </tr>

   <tbody id=fga_itemid_body style="display:none">
   <tr>
      <td>Designer expires</td>
      <td><input type=text name="DESIGNER_YMD">
         YYYYMMDD/ 1=Never</td>
   </tr>
   <tr>
      <td>Barcode expires</td>
      <td><input type=text name="BARCODE_YMD">
         YYYYMMDD/ 1=Never</td>
   </tr>
   <tr>
      <td>Max. Instances</td>
      <td><input type=text name="MAXSESSIONS">
         3,4...(2 is free)</td>
   </tr>
   <tr>
      <td>Instance expire</td>
      <td><input type=text name="SESSIONS_YMD">
         YYYYMMDD/ 1=Never</td>
   </tr>
   </tr>
   </tbody>

   <tr class=MYNAVBAR>
      <td></td>
      <td>
         <input type=SUBMIT name="ok" value="Submit">
         <input type=BUTTON value="Just inform" onclick="goInform()">
      </td>
   </tr>
   </table>
   </form>
<?php
}
//------------------------------------------------------------------------------
function update_deltio(&$db)
{
   $ar1 = array('SER_DELTIO', 'SER_D_DATE');
   foreach ($ar1 as $k1) {
      $_SESSION[$k1] = $_REQUEST[$k1];
   }

   switch ((int)@$_REQUEST['PROTYPE'])
   {
   case 1: // TaxSpooler licenses
      upd_deltio_taxspl($db);
      show_stat($db);
      break;
   case 2: // TaxGate licenses
      upd_deltio_taxgate($db);
      show_taxgate($db);
      break;
   case 3: // FGA lics.
      upd_deltio_fga();
      show_fgalic();
      break;
   default:
      uerror("Did not select action!");
      show_stat($db);
      break;
   }
}
//------------------------------------------------------------------------------
function upd_deltio_taxspl(&$db)
{
   if (empty($_REQUEST['SER_UGROUP'])) {
      uerror("Did not select group!");
      return;
   }
   else if (empty($_REQUEST['SER_ITEMID'])) {
      uerror("Did not select License type!");
      return;
   }
   else if (empty($_REQUEST['SER_QUANTITY'])) {
      uerror("Did not set quantity!");
      return;
   }

   $query="INSERT INTO ser_deltia (ser_ugroup, ser_deltio, ser_d_date, ser_itemid, ser_quantity) VALUES(?,?,?,  ?,?)";
   $data=array($_REQUEST['SER_UGROUP'], $_REQUEST["SER_DELTIO"], $_REQUEST["SER_D_DATE"], $_REQUEST["SER_ITEMID"], $_REQUEST["SER_QUANTITY"] );
   if ($db->Execute($query,$data)) {
      echo "<h6>Updated!</h6>\n";
   }
   else {
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
      return;
   }

   // on o.k.:
   $ar1=get_qua_left($db, $_REQUEST['SER_UGROUP']);
   if ($ar1!==false) {
      $msg=sprintf("Deltio=%s quantity=%d\r\nLeft:\r\n", $_REQUEST["SER_DELTIO"], $_REQUEST["SER_QUANTITY"]);
      foreach ($ar1 as $k=>$v) {
         if ($k==1003) {
            $k .= " (10 upgrade/ generic)";
         }
         else if ($k==1004) {
            $k .= " (10 upgrade/ SAP)";
         }
         else if ($k==1012) {
            $k .= " (12M upgrade/ generic)";
         }
         else if ($k==1013) {
            $k .= " (12M upgrade/ SAP)";
         }
         else {
            $k .= " (Master license)";
         }

         $msg .= sprintf("Type: %s Quantity: %d\r\n", $k, $v);
      }
      if ($_REQUEST['SER_UGROUP']==1) {
         printf("<h6>Sending email to %s:</h6><pre>%s</pre>", ASSOCIATE1, myhtml($msg));
         mail(ASSOCIATE1, "New license added", $msg  );
      }
      else if ($_REQUEST['SER_UGROUP']==2) {
         printf("<h6>Sending email to %s:</h6><pre>%s</pre>", ASSOCIATE2, myhtml($msg));
         mail(ASSOCIATE2, "New license added", $msg  );
      }
   }
}
//------------------------------------------------------------------------------
function upd_deltio_fga()
{
   global $db;

   if (empty($_REQUEST['SER_UGROUP'])) {
      uerror("Did not select group!");
      return;
   }

   $qcount="SELECT COUNT(*) FROM ser_fgalic WHERE FGA_KEY=?";
   $query="INSERT INTO ser_fgalic (FGA_UGROUP, FGA_KEY, FGA_INV_PURCHASE, FGA_PUR_DATE,
      FGA_DESIGNER_YMD, FGA_BARCODE_YMD, FGA_MAXSESSIONS, FGA_SESSIONS_YMD) VALUES(?,?,?,?,  ?,?,?,?)";

   $good=0;
   for ($i=1; $i<=$_REQUEST['SER_QUANTITY']; $i++) {
      $key=0;
      for ($j=0;$j<10000;$j++) {
         $key=mt_rand(100000,999999);
         $data=array($key);
         if (($rs=$db->Execute($qcount,$data))===false) {
            echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
            break;
         }
         $row=$rs->FetchRow();
         $rs->Close();
         if ($row[0]==0)
            break;
         else
            $key=0; // reset
      }
      if ($key==0) {
         echo "<h6>Could not find a gap for $i element</h6>";
         break;
      }

      $data=array($_REQUEST['SER_UGROUP'], $key, $_REQUEST['SER_DELTIO'], $_REQUEST['SER_D_DATE'],
         $_REQUEST['DESIGNER_YMD'], $_REQUEST['BARCODE_YMD'], (int)$_REQUEST['MAXSESSIONS'], $_REQUEST['SESSIONS_YMD'] );
      if (!$db->Execute($query,$data)) {
         echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
         break;
      }

      $good++;
   }

   echo "<h6>Completed for $good records!</h6>";
}
//------------------------------------------------------------------------------
function upd_deltio_taxgate(&$db)
{
   if (empty($_REQUEST['SER_UGROUP'])) {
      uerror("Did not select group!");
      return;
   }

   $qcount="SELECT COUNT(*) FROM ser_taxgate WHERE tg_key=?";
   $query="INSERT INTO ser_taxgate (tg_ugroup, tg_key, tg_inv_purchase, tg_pur_date) VALUES(?,?,?,?)";

   $good=0;
   for ($i=1; $i<=$_REQUEST['SER_QUANTITY']; $i++) {
      $key=0;
      for ($j=0;$j<10000;$j++) {
         $key=mt_rand(100000,999999);
         $data=array($key);
         if (($rs=$db->Execute($qcount,$data))===false) {
            echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
            break;
         }
         $row=$rs->FetchRow();
         $rs->Close();
         if ($row[0]==0)
            break;
         else
            $key=0; // reset
      }
      if ($key==0) {
         echo "<h6>Could not find a gap for $i element</h6>";
         break;
      }

      $data=array($_REQUEST['SER_UGROUP'], $key, $_REQUEST['SER_DELTIO'], $_REQUEST['SER_D_DATE']);
      if (!$db->Execute($query,$data)) {
         echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
         break;
      }

      $good++;
   }

   echo "<h6>Completed for $good records!</h6>";
}
//--------------------------------------
function inform_reseller(&$db)
{
   if (empty($_REQUEST['SER_UGROUP'])) {
      uerror("Δεν ορίσατε Group!");
      return;
   }

   $ar1=get_qua_left($db, $_REQUEST['SER_UGROUP']);
   if ($ar1===false) {
      echo "<h6>Could not calculate quantity!</h6>";
      return;
   }

   $msg="Qualtity left:\r\n";
   foreach ($ar1 as $k=>$v) {
      if ($k==1003) {
         $k .= " (10d upgrade/ generic)";
      }
      else if ($k==1004) {
         $k .= " (10d upgrade/ SAP)";
      }
      else if ($k==1012) {
         $k .= " (12M upgrade/ generic)";
      }
      else if ($k==1013) {
         $k .= " (12M upgrade/ SAP)";
      }
      else {
         $k .= " (Master license)";
      }

      $msg .= sprintf("Type: %s Quantity: %d\r\n", $k, $v);
   }

   if ($_SESSION['GROUP']==1) {
      $recipient = ASSOCIATE1;
   }
   else if ($_SESSION['GROUP']==2) {
      $recipient = ASSOCIATE2;
   }
   else {
      return;
   }
   printf("<h6>Sending email to %s:</h6><pre>%s</pre>", $recipient, myhtml($msg));
   mail($recipient, "TaxSpooler quantity left", $msg  );
}
//------------------------------------------------------------------------------
function select_lic_type()
{
?>
   <table border=0 cellpadding=10 style="border:1px solid black;">
   <tr>
      <td bgcolor=silver>
         <b>Activation key</b>
      </td>
   </tr>
   <tr>
      <td style="padding:40px;">
         <b><ul>
            <li><a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=3">Νέες άδειες</a>
            <li><a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=68">Πρόσθετες άδειες FGA/SID Xtra &amp; FGA/Instance</a>
            <li><a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=21">Αναβαθμίσεις</a>
         </ul></b>
      </td>
   </tr>
   </table>
<?php
}
//------------------------------------------------------------------------------
function ask_additional_SID_sess()
{
   global $ct;
?>
<form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method=POST name="myform">
<input type=HIDDEN name="FU" value="69">
<table>
<tr>
   <td>Είδος άδειας</td>
   <td><select name="SER_ITEMID">
      <option value="300">#300 FGA/ Station Id (SID) Xtra -- (new #400)</option>
      <option value="470">#370 FGA/ Instance -- (new #470)</option>
   </select></td>
</tr>
<tr>
   <td>Version</td>
   <td>ANY</td>
</tr>
<tr>
   <td>Κωδικός</td>
   <td><SELECT id=ser_auth name="SER_AUTH"></select></td>
</tr>
<tr>
   <td>Αριθμός σειράς</td>
   <td><input type=text name="SER_SERIAL" value="<?php echo myhtml(@$_SESSION['SER_SERIAL']); ?>" maxlength=8></td>
</tr>
<tr>
   <td></td>
   <td class=MYNAVBAR><input type=SUBMIT value="Submit"></td>
</tr>
</table>
</form>
<script>fill_eafdss(document.getElementById('ser_auth'));</script>
<?php
}
//------------------------------------------------------------------------------
function get_input_new()
{
   global $ct, $aLevel;

   $ar1=array();
   get_versions_avail($ar1);
   if (empty($ar1)) {
      return;
   }
//pre($ar1);

   $lics=array();
   foreach ($ct->licTypes as $k=>$v) {
      if ($_SESSION['UGROUP']==2 && ($k==230 || $k==250 || $k==320)) // ICS exclusions
         continue;

      if ($k==300 || $k==400 || $k==370 || $k==470) // Για την #300 (FGA/SID Xtra) και #370 (FGA/Instance) υπάρχει ειδική επιλογή
         continue;

      $lics[$k]=$v;
   }

   //commnt($ar1);
?>
<script>
var versions=[
<?php
   array_walk($ar1, function(&$val, $key){ $val = "'$val'"; } );
   echo implode(', ', $ar1);
?>
];
$(function() {
   ResetSerial1_new();
});

function ResetSerial1_new()
{
   var f=document.myform;
   var i=f.SER_ITEMID.selectedIndex;
   if (i<0) {
      i=0;
      f.SER_ITEMID.selectedIndex=i;
   }
   var ser_itemid=f.SER_ITEMID.options[i].value;
   if (ser_itemid==230 || ser_itemid==240 || ser_itemid==340 || ser_itemid==320 || ser_itemid==330)
      fill_sel_over5();
   else
      fill_sel_all();
}

function fill_sel_over5()
{
   var html='';
   for (var i=0;i<versions.length;i++) {
         if (VersionCompare(versions[i], '2.4.5.0')>=0) {
            html += '<option>'+versions[i]+'</option>';
         }
   }
   $(document.myform.SER_VERSION).html(html);
}

function fill_sel_all()
{
   var html='';
   for (var i=0;i<versions.length;i++) {
      html += '<option>'+versions[i]+'</option>';
   }
   $(document.myform.SER_VERSION).html(html);
}

function uiSelChangedEx()
{
   // perform basic functionallity
   uiSelChanged();
}

function  uiSelChanged()
{
   var f1=document.myform;
   if (f1.ADDNEW.selectedIndex==2) { // old
   	f1.SER_VERSION.selectedIndex=f1.SER_VERSION.length-1;
   }
}

function ResetSerAuth()
{
   $('input[name=SER_AUTH]').val( $('#ser_auth').val() );
}
</script>
   <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method=POST onSubmit="return CheckData(this)" name="myform">
   <input type=HIDDEN name="FU" value="4">
   <input id=hCustomer type=hidden name="CUSTOMER" value="1">
   <table>
   <tr>
      <td>Είδος άδειας</td>
      <td><SELECT name="SER_ITEMID" onChange="ResetSerial1_new()">
         <?php prAssocSelect($lics,0); ?>
         </SELECT></td>
   </tr>
   <tr>
      <td>Version</td>
      <td><SELECT id=vercombo name="SER_VERSION" onchange="uiSelChangedEx()"></SELECT></td>
   </tr>
   <tr>
      <td>Κωδικός</td>
      <td><?php
         if ($aLevel == 1) { // admin
            echo '<input type=text name="SER_AUTH" pattern="[A-Z]{3}" onChange="ResetSerial2()">
               <select id=ser_auth onChange="ResetSerAuth()">
               <option></option>
               </select>';
         }
         else {
            echo '<select id=ser_auth name="SER_AUTH" onChange="ResetSerial2()"></select>';
         }
      ?></td>
   </tr>
   <tr>
      <td>Από αριθμό</td>
      <td><input type=TEXT name="FROMNR" pattern="[0-9]{8}" maxlength=8 title="8 digits please"></td>
   </tr>
   <tr>
      <td>Ως αριθμό</td>
      <td><input type=TEXT name="TONR" pattern="[0-9]{8}" maxlength=8 title="8 digits please"></td>
   </tr>
   <tr>
      <td>Σύνολο κωδικών</td>
      <td><input type=TEXT name="TOTALNR"></td>
   </tr>
   <tr>
      <td>Αρχείο</td>
      <td>
         <select name="ADDNEW" onchange="uiSelChanged()">
         <option value="0">Εμφάνιση μόνο</option>
         <option value="1" SELECTED>Δημιουργία ΝΕΩΝ</option>
         <?php
            if ($_SESSION['UGROUP']==1) { // anelixis
               echo "<option value=\"2\">Αναδημιουργία παλαιών</option>";
            }
         ?>
         </select>
         </td>
   </tr>
   <tr>
      <td></td>
      <td class=MYNAVBAR><input type=SUBMIT name="ok" value="Submit"></td>
   </tr>
   </table>
   </form>
   <script>fill_eafdss(document.getElementById('ser_auth'));</script>

   <p></p>
   <table>
   <tr valign=top>
      <td>Παράδειγμα</td>
      <td class=MYBOX>Για να δημιουργήσετε τα κλειδιά 3000100-3000110 (συνολικά 11) δώστε
         Από αριθμό=3000100, Ως αριθμό=3000110, Σύνολο κωδικών=11, Δημιουργία=ΝΑΙ.
         <BR>Κλειδιά που ήδη υπάρχουν δεν θα ξαναδημιουργηθούν.
         <BR>Ετσι μπορείτε, χωρίς πρόβλημα να ξαναδώσετε ίδιους κωδικούς.</td>
   </tr>
   <tr valign=top>
      <td>Παράδειγμα</td>
      <td>Για να δείτε τα κλειδιά που αντιστοιχούν στους κωδικούς 3000100-3000110
         (συνολικά 11) δώστε
         Από αριθμό=3000100, Ως αριθμό=3000110, Σύνολο κωδικών=11.
         <BR>ΜΗΝ ΤΣΕΚΑΡΕΤΕ την Δημιουργία!</td>
   </tr>
   </table>
<?php
}
//------------------------------------------------------------------------------
function add_additional_SID_sess(&$db)
{
   // will come with
   // 300, 370 -- deprecated
   // 300, 470 -- 300 stands for 400
   //
   // 300 will look for 'as is' (300) in stock, but assign 400
   //
   global $Guname, $aLevel;

   $_SESSION['SER_SERIAL'] = $_REQUEST['SER_SERIAL'];

   // Check if there is a master license
   //
   $countA=0;
   $query="SELECT COUNT(*) FROM ser_data
      WHERE ser_itemid IN (230, 240, 250) AND ser_auth=? AND ser_serial=?";
   $data=array($_REQUEST['SER_AUTH'], $_REQUEST['SER_SERIAL']);
   if (($rs=$db->Execute($query,$data))===false) {
      echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>";
      return;
   }
   if ($row=$rs->FetchRow()) {
      $countA = (int)$row[0];
   }
   $rs->Close();
   if ($countA==0) {
      echo "<h6>Δεν υπάρχει αντίστοιχη βασική άδεια.</h6>";
      return;
   }

   $countA=false; // reset
   $query="SELECT ser_count FROM ser_data
      WHERE ser_itemid=? AND ser_auth=? AND ser_serial=?";
   $ser_itemid2 = $_REQUEST['SER_ITEMID'] == 300 ? 400 : $_REQUEST['SER_ITEMID']; // translated
   $data=array($ser_itemid2, $_REQUEST['SER_AUTH'], $_REQUEST['SER_SERIAL']);
   if (($rs=$db->Execute($query,$data))===false) {
      echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>";
      return;
   }
   if ($row=$rs->FetchRow()) {
      $countA = (int)$row[0];
   }
   $rs->Close();

   // insert transaction
   $remote_host='';
   if (isset($_SERVER["REMOTE_HOST"]))
      $remote_host=$_SERVER["REMOTE_HOST"];

   $query="INSERT INTO ser_transa ".
         " (ser_tr_daytime, ser_ugroup, ser_tr_uname, ser_remote_addr, ser_remote_host, ser_codex_array, ser_s11_array, ser_version) ".
         " VALUES (NOW(), ?,?,?,  ?,?,?,  ?)";
   $data=array($_SESSION['UGROUP'], $Guname, $_SERVER["REMOTE_ADDR"], $remote_host, $ser_itemid2, $_REQUEST['SER_AUTH'].$_REQUEST['SER_SERIAL'], 'All versions');
   if (!$db->Execute($query,$data)) { // error
      echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>";
      return;
   }
   $transid = $db->Insert_ID(); // keep track of record inserted

   $deltio=""; // security
   if ($aLevel != 1) // not superuser
   {
      $query2="SELECT ser_deltio, ser_itemid, ser_d_date FROM ser_deltia
            WHERE ser_ugroup=? AND ser_itemid=? AND ser_quantity > ser_given
            ORDER BY ser_d_date, ser_deltio";
      $data=array($_SESSION['UGROUP'], $_REQUEST['SER_ITEMID']); // use '300', not '400'
      if (($rs=$db->Execute($query2,$data))===false) {
         echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>";
         return;
      }
      if ($o2=$rs->FetchNextObject()) {
         $deltio=$o2->SER_DELTIO;
      }
      $rs->Close();
      if ($o2===false) {
         echo "<h6 class=ASTERISK>Δεν βρέθηκαν Δ/Αποστολής</h6>";
         return;
      }
   }
   else { // superuser
      $deltio="999999";
   }

   $db->StartTrans();

   do {
      if ($aLevel != 1) // not superuser
      {
         $query="UPDATE ser_deltia SET ser_given=ser_given+1
            WHERE ser_ugroup=? AND ser_deltio=? AND ser_itemid=? AND  ser_quantity > ser_given";
         $data=array($_SESSION['UGROUP'], $deltio, $o2->SER_ITEMID); // use '300', not '400'
         if (!$db->Execute($query,$data)) {
            echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>";
            break;
         }
      }

      if ($countA===false) {
         // Insert record
         //
         $query="INSERT INTO ser_data
                   (ser_ugroup, ser_itemid, ser_auth, ser_serial, ser_date, ser_actkey, ser_deltio, ser_transid, ser_count, ser_lastuser)
            VALUES (?,      ?,        ?,        ?,          DATE(NOW()), '',      ?,          ?,           1,         ?)";
         $data=array($_SESSION['UGROUP'], $ser_itemid2, $_REQUEST['SER_AUTH'], $_REQUEST['SER_SERIAL'], $deltio, $transid, $Guname);
      }
      else {
         // Update counter and other fields in existing record; however 'ser_date' remains intact; 'ser_transid' will reflect the latest transaction
         //
         $query="UPDATE ser_data SET ser_deltio=?, ser_transid=?, ser_count=?, ser_lastuser=? WHERE ser_itemid=? AND ser_auth=? AND ser_serial=?";
         $data=array($deltio, $transid, $countA+1, $Guname, $ser_itemid2, $_REQUEST['SER_AUTH'], $_REQUEST['SER_SERIAL']);
      }
      if (!$db->Execute($query,$data)) {
         echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>";
         break;
      }
      else { // o.k.
         if ($_REQUEST['SER_ITEMID']==300) {
            echo "<h6>Incremented FGA/SID license count by one for ".
               $_REQUEST['SER_AUTH'].$_REQUEST['SER_SERIAL'].". Has now extra ".((int)$countA + 1)." SIDS (+1 default = ".((int)$countA + 2)." in total).</h6>";
         }
         else if ($_REQUEST['SER_ITEMID']==370) {
            echo "<h6>Incremented FGA/Instance license count by one for ".
               $_REQUEST['SER_AUTH'].$_REQUEST['SER_SERIAL'].". Has now ".((int)$countA + 1)." (exactly) instances.</h6>";
         }
      }

   } while (false);

   $db->CompleteTrans();
}
//------------------------------------------------------------------------------
function upd_input_new(&$db)
{
   global $Guname, $aLevel;

   $mail_msg='';

   if (!preg_match('/^[0-9]{8}$/', $_REQUEST["FROMNR"]) || !preg_match('/^[0-9]{8}$/', $_REQUEST["TONR"])) {
      uerror("Τα serial numbers πρέπει να είναι ακριβώς 8 ψηφία!");
      return;
   }

   $fromNr=(int)$_REQUEST["FROMNR"];
   $toNr=(int)$_REQUEST["TONR"];

   // Same code (about) in taxspl3.php
   if ($_REQUEST['SER_ITEMID']==230 || $_REQUEST['SER_ITEMID']==240) { // master license
      if ($_REQUEST['SER_AUTH']==='EPZ' && ((int)($fromNr/10000)!=1090 || (int)($toNr/10000)!=1090)) {
         echo "<h5 class=ERROR>Can not get #230/#240/340 license for EPZ.</h5>";
         return;
      }

      $query="SELECT COUNT(*) FROM ser_data WHERE ser_itemid=250 AND ser_auth=? AND ser_serial BETWEEN ? AND ?";
      $data=array($_REQUEST['SER_AUTH'], $fromNr, $toNr);
      if (($rs=$db->Execute($query,$data))===false) {
         echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>";
         return;
      }
      $row=$rs->FetchRow();
      $rs->Close();
      if ($row[0]>0) {
         echo "<h6 class=ERROR>Can not get #240/340 license where already exists #250.</h6>";
         return;
      }
   }
   else if ($_REQUEST['SER_ITEMID']==340) { // E-Xtend: Ανίχνευση στοιχείων του αρχείου Ε, όταν δεν υπάρχει η γραμμή
      if ($_REQUEST['SER_AUTH']==='EPZ' && ((int)($fromNr/10000)!=1090 || (int)($toNr/10000)!=1090)) {
         echo "<h5 class=ERROR>Can not get #230/240/340 license for EPZ.</h5>";
         return;
      }

      $query="SELECT COUNT(*) FROM ser_data WHERE (ser_itemid=230 OR ser_itemid=240) AND ser_auth=? AND ser_serial BETWEEN ? AND ?";
      $data=array($_REQUEST['SER_AUTH'], $fromNr, $toNr);
      if (($rs=$db->Execute($query,$data))===false) {
         echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>";
         return;
      }
      $row=$rs->FetchRow();
      $rs->Close();
      if ($row[0]==0) {
         echo "<h6 class=ERROR>Can not get #340 license if no #230/240 exists.</h6>";
         return;
      }
   }
   else if ($_REQUEST['SER_ITEMID']==320) { // Esend-compete (deprecated)
      $query="SELECT COUNT(*) FROM ser_data WHERE ser_itemid=250 AND ser_auth=? AND ser_serial BETWEEN ? AND ?";
      $data=array($_REQUEST['SER_AUTH'], $fromNr, $toNr);
      if (($rs=$db->Execute($query,$data))===false) {
         echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>";
         return;
      }
      $row=$rs->FetchRow();
      $rs->Close();
      if ($row[0]==0) {
         echo "<h6 class=ERROR>Can not get #320 license if no #250 exists.</h6>";
         return;
      }
   }

   //
   // End of checks: update
   //
   $transid=0;
   $addnew=false;
   $addold=false;
   if ( ((int)@$_REQUEST["ADDNEW"]) > 0 ) {
      if (((int)$_REQUEST["ADDNEW"])==1)
         $addnew=true;
      else if (((int)$_REQUEST["ADDNEW"])==2)
         $addold=true;

      $allowed=array(250,260,270,280);
      if ($addold && !in_array($_REQUEST['SER_ITEMID'], $allowed)) {
         echo "<h6 class=ERROR>Can not get OLD LICENSE for this license type.</h6>";
         return;
      }

      $remote_host='';
      if (isset($_SERVER["REMOTE_HOST"]))
         $remote_host=$_SERVER["REMOTE_HOST"];

      // insert transaction
      $query1="INSERT INTO ser_transa ".
         " (ser_tr_daytime, ser_ugroup, ser_tr_uname, ser_remote_addr, ser_remote_host, ser_codex_array, ser_s11_array, ser_version, ser_customer) ".
         " VALUES (NOW(), ?,?,?,  ?,?,?,  ?,?)";
      $data=array($_SESSION['UGROUP'], $Guname, $_SERVER["REMOTE_ADDR"], $remote_host, $_REQUEST['SER_ITEMID'],
         $_REQUEST['SER_AUTH'].$_REQUEST['FROMNR'].'-'.$_REQUEST['TONR'], $_REQUEST['SER_VERSION'], (int)@$_REQUEST['CUSTOMER'] );
      if (!$db->Execute($query1,$data)) { // error
         echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>";
         return;
      }
      $transid = $db->Insert_ID();
   }

?>
   <form name="myform" action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method=POST>
   <input type=HIDDEN name="FU" value="7">
   <input type=HIDDEN name="SER_ITEMID" value="<?php echo $_REQUEST["SER_ITEMID"]; ?>">
   <input type=HIDDEN name="SER_AUTH" value="<?php echo $_REQUEST["SER_AUTH"]; ?>">
   <input type=HIDDEN name="THISNR" value="">
   <input type=HIDDEN name="INVOICE" value="">
   <input type=HIDDEN name="FROMNR" value="<?php echo $_REQUEST["FROMNR"]; ?>">
   <input type=HIDDEN name="TONR" value="<?php echo $_REQUEST["TONR"]; ?>">
   </form>

   <table>
   <tr class=MYTHEAD>
      <td>Τύπος</td>
      <td>Serial</td>
      <td>Action</td>
      <td>Ημ/νία</td>
      <td>Act.key</td>
      <td>Δ/Α</td>
      <td>Τιμ.πελάτη</td>
      <td>Transaction</td>
   </tr>
<?php

   $line=0;
   $query1="SELECT * FROM ser_data WHERE ser_itemid=? AND ser_auth=? AND ser_serial=?";
   for ($i=$fromNr; $i<=$toNr; $i++) {
      // For each one serial number
      //
      $serial=sprintf("%08d",$i);

      echo "<tr";
      $line++;
      if ($line%3==0)
         echo " class=HILINE";
      echo ">\n".
         "<td>".myhtml($_REQUEST["SER_ITEMID"])."</td>\n".
         "<td>".myhtml($_REQUEST["SER_AUTH"].$serial)."</td>\n";

      $fi=false;
      $done=false;
      $data=array($_REQUEST["SER_ITEMID"], $_REQUEST["SER_AUTH"], $serial);
      if ($rs=$db->Execute($query1,$data)) {
         if ($o1=$rs->FetchNextObject()) {
            //
            // Found an existing (main) record
            //
            $fi=true;
            if (!empty($o1->SER_ACTKEY)) {
            	$done=true;

					echo "<td style=\"background-color:red; color:white;\">FOUND (old)</td>\n".
               	"<td>".myhtml($o1->SER_DATE)."</td>\n".
               	"<td>".myhtml($o1->SER_ACTKEY)."</td>\n".
               	"<td>".myhtml($o1->SER_DELTIO)."</td>\n".
               	"<td><a href=\"javascript:GoInvoice('".$serial."')\">";
            	if(empty($o1->SER_TIM_PEL))
               	echo "Insert";
            	else
               	echo myhtml($o1->SER_TIM_PEL);
            	echo "</a></td>\n".
               	"<td><a href=\"".myhtml($_SERVER['SCRIPT_NAME'])."?FU=8&TRID=".$o1->SER_TRANSID."\">".$o1->SER_TRANSID."</a></td>";
            }
         }
         $rs->Close();
      }
      else {
         echo "<td colspan=3 class=ERROR>".__LINE__.$db->ErrorMsg()."</td>";
      }

      if ($done)
         continue;

      if ($addnew) {
         //
         // Adding new value
         //
         $ser_itemid=$_REQUEST["SER_ITEMID"];
         if ($ser_itemid==230 || $ser_itemid==240) {
            $SID = 230;
         }
         else if ($ser_itemid==250 || $ser_itemid==260 || $ser_itemid==270 || $ser_itemid==280) {
            $SID = 250;
         }
         else {
            $SID = $ser_itemid;
         }

         $o2=false;
         $ugroup=$_SESSION['UGROUP'];
         //if ($ugroup!=99)
         if ($aLevel != 1)
         { // Anelixis - ICS
            $query2="SELECT ser_deltio, ser_itemid, ser_d_date FROM ser_deltia
               WHERE ser_ugroup = ? AND ser_itemid = ? AND ser_quantity > ser_given
               ORDER BY ser_d_date, ser_deltio";
            $data=array($ugroup, $SID);
            if (($rs=$db->Execute($query2, $data))===false) {
               //echo "<!-- $query2 -->";
               echo "<td colspan=3 class=ERROR>".__LINE__.$db->ErrorMsg()."</td>";
               break;
            }
            if ($o2=$rs->FetchNextObject()) {
               $deltio=$o2->SER_DELTIO;
            }
            $rs->Close();
            if ($o2===false) {
               echo "<td colspan=3 class=ASTERISK>Δεν βρέθηκαν Δ/Αποστολής</td>";
               break;
            }

            $ok=false;
            $query2="UPDATE ser_deltia SET ser_given=ser_given+1 WHERE ser_deltio=? AND ser_itemid=? AND ser_quantity > ser_given";
            $data=array($deltio, $SID/*$o2->SER_ITEMID*/);
            if (!$db->Execute($query2,$data)) {
               echo "<td colspan=3 class=ERROR>".__LINE__.$db->ErrorMsg()."</td>";
               break;
            }
            else if ($db->Affected_Rows()==0) {
               echo "<td colspan=3 class=ERROR>Not enough quantity to consume!</td>";
               break;
            }
            $ok=true;
         }
         else { // INCA Hellas
            $deltio=999999;
            $ok=true;
         }
      }
      else if ($addold) {
         $ok=true;
         $deltio='ΠΑΛΙΟ/ΠΑΛΙΟ';
      }

      if ($addnew || $addold) {
         if ($ok) {
            $actkey=make_actkey($_REQUEST["SER_ITEMID"], $_REQUEST["SER_AUTH"].$serial );
            // update ser_data
            if ($fi) {
            	$query2="UPDATE ser_data SET ser_actkey=?, ser_transid=?, ser_date=?, SER_LASTUSER=?
            		WHERE ser_itemid=? AND ser_auth=? AND ser_serial=?";
            	$data=array( $actkey, $transid, date('Ymd'), $Guname, $_REQUEST["SER_ITEMID"], $_REQUEST["SER_AUTH"], $serial );
				}
				else {
            	$query2="INSERT INTO ser_data
                  (ser_ugroup, ser_itemid, ser_auth, ser_serial, ser_deltio, ser_date, ser_actkey, ser_transid, ser_lastuser)
               	VALUES (?, ?, ?, ?,   ?, ?, ?, ?,  ?)";
            	$data=array($_SESSION['UGROUP'], $_REQUEST["SER_ITEMID"], $_REQUEST["SER_AUTH"], $serial, $deltio,
               	date('Ymd'), $actkey, $transid, $Guname );
            }
            if (!$db->Execute($query2,$data)) { // error
               echo "<td colspan=3 class=ERROR>".__LINE__.$db->ErrorMsg()."</td>";
               echo "<!-- ";
               print_r($query2);
               print_r($data);
               echo " -->";
               break;
            }

            if ($_REQUEST['SER_VERSION']!=='2.4.1.1') {
               $tb='ser_version';
               $prim=array('ser_itemid', 'ser_auth', 'ser_serial', 'ser_version');
               $data=array('ser_itemid'=>$_REQUEST["SER_ITEMID"], 'ser_auth'=>$_REQUEST["SER_AUTH"],
                  'ser_serial'=>$serial, 'ser_version'=>$_REQUEST['SER_VERSION'], 'ser_date'=>date('Ymd'),
                  'ser_transid'=>$transid, 'ser_forever'=>1 );
               if (ReplaceEx($db,$tb,$data,$prim)==0) {
                  echo "<td colspan=3 class=ERROR>".__LINE__.$db->ErrorMsg()."</td>";
                  break;
               }
               $dsp=make_lic($_REQUEST["SER_ITEMID"], $_REQUEST["SER_AUTH"].$serial, $_REQUEST['SER_VERSION']);
            }
            else {
               $dsp=$actkey;
            }

            // ok.
            echo "<td>New</td>\n".
               "<td>Σήμερα</td>\n".
               "<td>".myhtml($dsp)."</td>\n".
               "<td>".myhtml($deltio)."</td>\n".
               "<td><a href=\"javascript:GoInvoice('".$serial."')\">Insert</a></td>".
               "<td><a href=\"".myhtml($_SERVER['SCRIPT_NAME'])."?FU=8&TRID=".$transid."\">".$transid."</a></td>";

            $mail_msg .= ($_REQUEST["SER_AUTH"].$serial."\t".$_REQUEST["SER_ITEMID"]."\t".$_REQUEST['SER_VERSION']."\r\n");
         }
      } // if ($addnew)
      else {
         echo "<td colspan=3><b>Δεν βρέθηκε</b></td>";
      }

      echo "</tr>\n";

   } // for ...

   echo "</table>\n";

   if (!empty($mail_msg)) {
      $n2=0;
      $query="SELECT COUNT(*) FROM ser_data WHERE ser_date=? AND ser_transid>0";
      $data=array(date('Ymd'));
      if (($rs=$db->Execute($query,$data))==false) {
         echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>";
      }
      else {
         if ($row=$rs->FetchRow()) {
            $n2=(int)$row[0];
         }
         $rs->Close();
      }

      $mail_msg .= "Transaction Id=$transid AddNew=$addnew AddOld=$addold\r\n";
      $mail_msg .= "Request=".((string)$_REQUEST["ADDNEW"])."\r\n";

      $subject="New TaxSpooler ".date('d M')." sales=".$n2;
      send_mail_to_inca($db, $subject, $mail_msg);
   }
}
//------------------------------------------------------------------------------
function send_mail_to_inca(&$db, $subject, $mail_msg)
{
   global $ct, $aLevel;

   $mail_msg .= "\r\n";

   $ar1=array(
      230=>'ETax Lite Serial/ Ethernet',
      340=>'E-Xtend',
      250=>'Old Base/ TCP/IP/ AS400',
      320=>'ESend-Complete',
      300=>'FGA/SID Xtra',
      330=>'SAP',
      290=>'E-Invoice Lite',
      1003=>'10d Upgrade/ generic',
      1004=>'10d Upgrade/ SAP',
      1012=>'12M Upgrade/ generic',
      1013=>'12M Upgrade/ SAP'
      );

   $gt=array();

   $data=array();
   $query="SELECT SER_ITEMID, SUM(SER_QUANTITY) FQUA, SUM(SER_GIVEN) FGIV FROM ser_deltia ";
   //if ($_SESSION['UGROUP']!=99)
   if ($aLevel != 1)
   {
      $query .= " WHERE SER_UGROUP=?";
      $data[] = $_SESSION['UGROUP'];
   }
   $query .= " GROUP BY SER_ITEMID ORDER BY SER_UGROUP, SER_ITEMID";
   if (($rs=$db->Execute($query, $data))===false) {
      echo "<h6>".__LINE__.$db->ErrorMsg()."</h6>\n";
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      if (array_key_exists($o1->SER_ITEMID, $ar1))
         $k=$o1->SER_ITEMID;
      else
         $k=250;

      $gt[$k] = (int)@$gt[$k] + $o1->FQUA - $o1->FGIV;
   }
   $rs->Close();

   $mail_msg2='';

   foreach ($ar1 as $k=>$v) {
      $s1=(string)@$gt[$k];
      if (strlen($s1)==1) { $s1 = ' '.$s1; }
      $mail_msg .= "Left $s1 for $k: $v\r\n";
      if (array_key_exists($k, $gt) /* && $gt[$k]<10 */) { // shortage
         $mail_msg2 .= "Attention! TaxSpooler keys left for $k - $v = $gt[$k]\r\n";
      }
   }

   mail("inca@incahellas.com", $subject, $mail_msg);

   if (!empty($mail_msg2)) {
      if ($_SESSION['UGROUP']==1)
         $recipient = ASSOCIATE1;
      else if ($_SESSION['UGROUP']==2)
         $recipient = ASSOCIATE2;
      else
         return;

      @mail("$recipient, inca@incahellas.com", "TaxSpooler license shortage", $mail_msg2);
   }
}
//------------------------------------------------------------------------------
function getSubInfo(&$db, $transid)
{
   $query="SELECT COUNT(*) F1,
      MIN( CONCAT(T2.ser_auth, T2.ser_serial) ) N1,
      MAX( CONCAT(T2.ser_auth, T2.ser_serial) ) N2
      FROM ser_data T2
      WHERE ser_transid=?
      GROUP BY ser_transid"; // inca 28/2/2008
   $data=array($transid);
   if (($rs=$db->Execute($query,$data))===false) {
      echo __LINE__.$db->ErrorMsg();
      return false;
   }
   $o2=$rs->FetchNextObject();
   $rs->Close();

   return $o2;
}
//--------------------------------------
function ask_edit_fga_sales(&$db)
{
   $key=(int)$_REQUEST['FGA_KEY'];
   $query="SELECT * FROM ser_fgalic WHERE FGA_KEY=?";
   $data=array( $key );
   if (($rs=$db->Execute($query,$data))===false) {
      echo __LINE__.$db->ErrorMsg();
      return;
   }
   $o1=$rs->FetchNextObject();
   $rs->Close();
   if ($o1===false) {
      echo "<h6>Δεν βρέθηκε τέτοια εγγραφή (key=$key)!</h6>";
      return;
   }
?>
<form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method=POST target=_parent>
<input type=hidden name="FU" value="81">
<input type=hidden name="FGA_KEY" value="<?php echo $key; ?>">
<table>
<tr>
   <td>Key</td>
   <td><?php echo myhtml($key); ?></td>
</tr>
<tr>
   <td>Τιμολόγιο αγοράς</td>
   <td><?php echo myhtml($o1->FGA_INV_PURCHASE); ?></td>
</tr>
<tr>
   <td>Ημερομηνία αγοράς</td>
   <td><?php echo GrDate($o1->FGA_PUR_DATE); ?></td>
</tr>
<tr>
   <td>MAC address</td>
   <td><?php echo myhtml($o1->FGA_MACADDRESS); ?></td>
</tr>
<tr>
   <td>Τιμολόγιο πώλησης</td>
   <td><input type=text name="FGA_INV_SALES" value="<?php echo myhtml($o1->FGA_INV_SALES); ?>" maxlength=20></td>
</tr>
<tr>
   <td>Ημερομηνία καταχώρισης</td>
   <td><?php if ($o1->FGA_SAL_DATE!=null) { echo GrDateTime($o1->FGA_SAL_DATE); } ?></td>
</tr>
<tr>
   <td></td>
   <td><input type=submit value="Ενημέρωση"></td>
</tr>
</table>
</form>
<?php
}
//--------------------------------------
function ask_edit_tg_sales(&$db)
{
   $key=(int)$_REQUEST['TG_KEY'];
   $query="SELECT * FROM ser_taxgate WHERE TG_KEY=?";
   $data=array( $key );
   if (($rs=$db->Execute($query,$data))===false) {
      echo __LINE__.$db->ErrorMsg();
      return;
   }
   $o1=$rs->FetchNextObject();
   $rs->Close();
   if ($o1===false) {
      echo "<h6>Δεν βρέθηκε τέτοια εγγραφή (key=$key)!</h6>";
      return;
   }
?>
<form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method=POST target=_parent>
<input type=hidden name="FU" value="58">
<input type=hidden name="TG_KEY" value="<?php echo $key; ?>">
<table>
<tr>
   <td>Key</td>
   <td><?php echo myhtml($key); ?></td>
</tr>
<tr>
   <td>Τιμολόγιο αγοράς</td>
   <td><?php echo myhtml($o1->TG_INV_PURCHASE); ?></td>
</tr>
<tr>
   <td>Ημερομηνία αγοράς</td>
   <td><?php echo GrDate($o1->TG_PUR_DATE); ?></td>
</tr>
<tr>
   <td>MAC address</td>
   <td><?php echo myhtml($o1->TG_MACADDRESS); ?></td>
</tr>
<tr>
   <td>Τιμολόγιο πώλησης</td>
   <td><input type=text name="TG_INV_SALES" value="<?php echo myhtml($o1->TG_INV_SALES); ?>" maxlength=20></td>
</tr>
<tr>
   <td>Ημερομηνία καταχώρισης</td>
   <td><?php if ($o1->TG_SAL_DATE!=null) { echo GrDateTime($o1->TG_SAL_DATE); } ?></td>
</tr>
<tr>
   <td></td>
   <td><input type=submit value="Ενημέρωση"></td>
</tr>
</table>
</form>
<?php
}
//--------------------------------------
function smooth_ser_data(&$db)
{
   $query="UPDATE ser_data SET SER_COMMENTS=?, SER_LASTUSER=? WHERE SER_AUTH=? AND SER_SERIAL=? AND SER_UPGRADE IS NOT NULL";
   $data=array( $_REQUEST['COMMENTS'], $_REQUEST['LASTUSER'], mb_substr($_REQUEST['S11'],0,3), mb_substr($_REQUEST['S11'],3) );
   if (!$db->Execute($query,$data))
      echo $db->ErrorMsg();
   else
      echo "<h5>Records affected: ".$db->Affected_Rows()."</h5>";
}
//--------------------------------------
function zoom_ser_data(&$db)
{
   $lastuser='';
   $comments='';

   $query="SELECT SER_ITEMID, SER_AUTH, SER_SERIAL, SER_DATE, SER_UPGRADE, SER_EXPIRES,
      SER_LASTUSER, SER_COMMENTS FROM ser_data
      WHERE SER_AUTH=? AND SER_SERIAL=?
      ORDER BY SER_ITEMID";
   $data=array( mb_substr($_REQUEST['S11'],0,3), mb_substr($_REQUEST['S11'],3) );
   if (($rs=$db->Execute($query,$data))===false) {
      echo $db->ErrorMsg();
      return;
   }
   echo "<table>
      <tr class=MYTHEAD>
      <td>Lic. type</td>
      <td>Serial</td>
      <td>Initial date</td>
      <td>Upgrade given</td>
      <td>Expires</td>
      <td>Last user</td>
      <td>Comments</td>
      </tr>";
   $nc=0;
   while ($o1=$rs->FetchNextObject()) {
      if (empty($comments)) {
         $comments=$o1->SER_COMMENTS;
      }

      if (empty($lastuser)) {
         $lastuser=$o1->SER_LASTUSER;
      }

      echo "<tr";
      if ($nc++%2>0) {
         echo " class=HILINE";
      }
      echo ">
         <td>".myhtml($o1->SER_ITEMID)."</td>
         <td>".myhtml($o1->SER_AUTH.$o1->SER_SERIAL)."</td>
         <td>".GrDate($o1->SER_DATE)."</td>
         <td>".GrDate($o1->SER_UPGRADE)."</td>
         <td>".GrDateTime($o1->SER_EXPIRES)."</td>
         <td>".myhtml($o1->SER_LASTUSER)."</td>
         <td>".myhtml($o1->SER_COMMENTS)."</td>
         </tr>";
   }
   $rs->Close();
   echo "</table>";
?>
   <h5>Apply comments and last user to all</h5>
   <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>">
   <input type=hidden name="FU" value="53">
   <input type=hidden name="S11" value="<?php echo $_REQUEST['S11']; ?>">
   <table>
   <tr>
      <td>Commments</td>
      <td><input type=TEXT name="COMMENTS" value="<?php echo myhtml($comments); ?>"></td>
   </tr>
   <tr>
      <td>Last user</td>
      <td><input type=TEXT name="LASTUSER" value="<?php echo myhtml($lastuser); ?>"></td>
   </tr>
   <tr>
      <td></td>
      <td><input type=submit value="Apply"></td>
   </tr>
   </table>
   </form>
<?php
}
//--------------------------------------
function total_upgrades(&$db)
{
   $query="SELECT COUNT(*) FROM ser_data
      WHERE SER_UPGRADE>='2009-01-20' AND SER_UPGRADE<'2011-05-09' AND SER_EXPIRES>SER_UPGRADE
   	AND (SER_LASTUSER IS NULL OR SER_LASTUSER!='inca')
      AND DATEDIFF(SER_EXPIRES, SER_UPGRADE) < 80";
   if (($rs=$db->Execute($query))===false) {
      echo $db->ErrorMsg();
      return;
   }
   $row=$rs->FetchRow();
   $nc1=$row[0];
   $rs->Close();

   $query="SELECT COUNT(*) FROM ser_data
      WHERE SER_UPGRADE>='2009-01-20' AND SER_UPGRADE<'2011-05-09' AND SER_EXPIRES>SER_UPGRADE
   	AND (SER_LASTUSER IS NULL OR SER_LASTUSER!='inca')
      AND DATEDIFF(SER_EXPIRES, SER_UPGRADE) >= 80 AND DATEDIFF(SER_EXPIRES, SER_UPGRADE) < 300";
   if (($rs=$db->Execute($query))===false) {
      echo $db->ErrorMsg();
      return;
   }
   $row=$rs->FetchRow();
   $nc3=$row[0];
   $rs->Close();

   $query="SELECT COUNT(*) FROM ser_data
      WHERE SER_UPGRADE>='2009-01-20' AND SER_UPGRADE<'2011-05-09' AND SER_EXPIRES>SER_UPGRADE
   	AND (SER_LASTUSER IS NULL OR SER_LASTUSER!='inca')
      AND DATEDIFF(SER_EXPIRES, SER_UPGRADE) >= 300";
   if (($rs=$db->Execute($query))===false) {
      echo $db->ErrorMsg();
      return;
   }
   $row=$rs->FetchRow();
   $nc12=$row[0];
   $rs->Close();

   echo "<h4><span style=\"color:gray;\">Upgrades from 20/1/2009 to 8/5/2011, 1-month:</span> $nc1,
      <span style=\"color:gray;\">3-months:</span> $nc3
      <span style=\"color:gray;\">12-months:</span> $nc12</h4>
      <b>
      <a href=\"".myhtml($_SERVER['PHP_SELF'])."?FU=47&QUA=1&NOTINV=1\" target=_parent>Details (1-month)</a> |
      <a href=\"".myhtml($_SERVER['PHP_SELF'])."?FU=47&QUA=3&NOTINV=1\" target=_parent>Details (3-months)</a> |
      <a href=\"".myhtml($_SERVER['PHP_SELF'])."?FU=47&QUA=12&NOTINV=1\" target=_parent>Details (12-months)</a>
      </b>";
}
//--------------------------------------
function cond_list_upgrades(&$db)
{
   global $aLevel;

   $pg=(int)@$_REQUEST['RSPAGE'];
   if ($pg<1) $pg=1;
   $pgsz=25;

   $qua=(int)@$_REQUEST['QUA'];

   $notinv = (int)@$_REQUEST['NOTINV'];
   if ($notinv) {
      echo "<div style=\"color:red;\">Ατιμολόγητα 20/1/2009 - 8/5/2011</div>";
   }

   $orderby=(int)@$_REQUEST['ORDERBY'];

   $query="SELECT SER_UGROUP, SER_ITEMID, SER_AUTH, SER_SERIAL, SER_DATE, SER_UPGRADE, SER_EXPIRES,
      DATEDIFF(SER_EXPIRES, SER_UPGRADE) F1, SER_LASTUSER, SER_COMMENTS FROM ser_data
      WHERE SER_EXPIRES>=SER_UPGRADE ";
   //if ($_SESSION['UGROUP']!=99) {
   if ($aLevel != 1) {
      $query .= " AND SER_UGROUP=".$_SESSION['UGROUP'];
   }
   if ($aLevel!=1 || /*$qua>0*/ $notinv) {
   	// Not admin
   	$query .= " AND (SER_LASTUSER IS NULL OR SER_LASTUSER!='inca') ";
	}
	if ($notinv) {
	  $query .= " AND SER_UPGRADE>='2009-01-20' AND SER_UPGRADE<'2011-05-09' ";
	}
   if ($qua>0) {
      if ($qua==1)
         $query .= " AND DATEDIFF(SER_EXPIRES, SER_UPGRADE) < 80";
      else if ($qua==12)
         $query .= " AND DATEDIFF(SER_EXPIRES, SER_UPGRADE) >= 300";
      else
         $query .= " AND DATEDIFF(SER_EXPIRES, SER_UPGRADE) >= 80 AND DATEDIFF(SER_EXPIRES, SER_UPGRADE) < 300";
   }
   $query .= " ORDER BY ".($orderby==0?" SER_UPGRADE DESC":" SER_AUTH, SER_SERIAL, SER_ITEMID");
   $data=false;
   if (($rs=$db->PageExecute($query,$pgsz,$pg,$data))===false) {
      echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>\n";
      return;
   }
?>
   <script>
function zoomLost()
{
   var url=location.pathname + '?FU=54';
   document.getElementById('zoomframe').src=url;
   $('#zoomdlg').dialog({modal:true, width:652}).dialog('open'); // content width + 32 (+2x16)
}
function zoomS11(o1)
{
   var url=location.pathname + '?FU=52&S11=' + $(o1).text();
   document.getElementById('zoomframe').src=url;
   $('#zoomdlg').dialog({modal:true, width:652}).dialog('open'); // content width + 32 (+2x16)
}
function editLastUser(o1)
{
   var a1=$(o1).text();
   var a2=window.prompt('Last User value', a1 );
   if (a2 && a2!=a1) {
      var co1=$(o1).parent().children();
      var url = location.pathname+'?FU=48&RID='+$(co1).slice(0,2).text()+'&LASTUSR='+escape(a2);
      $.get(url, function(data){
         var key='update_lastuser:';
         var i=data.indexOf(key);
         if (i>=0) {
            if (data.substr(i+key.length, 4)=='o.k.') {
               $(o1).text(a2);
               $(o1).css('color', a2=='inca'?'red':'');
            }
            else {
               window.alert(data.substr(i));
            }
         }
      } );
   }
}
function setQua(x)
{
   var f1=document.goForm;
   f1.QUA.value=x;
   f1.submit();
}
function setOrderBy(x)
{
   var f1=document.goForm;
   f1.ORDERBY.value=x;
   f1.submit();
}
$(function(){
   $('#zoomdlg').dialog({autoOpen:false});
});
   </script>
   <form method=POST action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" name="goForm">
   <input type=HIDDEN name="RSPAGE">
   <input type=HIDDEN name="FU" value="47">
   <input type=HIDDEN name="QUA" value="<?php echo $qua; ?>">
   <input type=HIDDEN name="NOTINV" value="<?php echo $notinv; ?>">
   <input type=HIDDEN name="ORDERBY" value="<?php echo $orderby; ?>">
   <table>
   <tr class=MYTHEAD>
      <td></td>
      <td>Lic. type</td>
      <td>Serial</td>
      <td>Initial date</td>
      <td>Upgrade given</td>
      <td>Expires</td>
      <td>Duration days</td>
      <td>Dur. month</td>
      <td>Last user</td>
      <td>Comments</td>
   </tr>
<?php
   $nc=0;
   while ($o1=$rs->FetchNextObject()) {
      echo "<tr";
      if ($nc++%2>0) {
         echo " class=HILINE";
      }
      echo ">";

      $aa=($pg-1)*$pgsz+$nc;

      echo "<td class=linenum>$aa</td>
         <td>".myhtml($o1->SER_ITEMID)."</td>
         <td";
      if ($aLevel==1) {
         echo " style=\"cursor:pointer;\" onclick=\"zoomS11(this)\"";
      }
      echo ">".myhtml($o1->SER_AUTH.$o1->SER_SERIAL)."</td>
         <td>".GrDate($o1->SER_DATE)."</td>
         <td>".GrDate($o1->SER_UPGRADE)."</td>
         <td>".GrDateTime($o1->SER_EXPIRES)."</td>
         <td>".myhtml($o1->F1)."</td>
         <td>".floor(($o1->F1+1)/30.0+0.5)."</td>
         <td";
      if ($aLevel==1) {
         // Admin
         echo " style=\"cursor:pointer; ";
         if ($o1->SER_LASTUSER=='inca') {
            echo "color:red;";
         }
         echo "\" onclick=\"editLastUser(this)\"";
      }
      echo ">".myhtml($o1->SER_LASTUSER)."</td>
         <td>".myhtml($o1->SER_COMMENTS)."</td>
         </tr>";
   }
   $epage=$rs->LastPageNo();
   $rs->Close();
   echo "</table>
      <div class=MYNAVBAR>";
   print_page_nav2($pg,$epage,47);
	echo "&nbsp;<b><a href=\"javascript:zoomLost()\">Zoom total</a> |
      <a href=\"javascript:setQua(1)\">1-month only</a> |
      <a href=\"javascript:setQua(3)\">3-months only</a> |
      <a href=\"javascript:setQua(12)\">12-months only</a> |
      Order by <a href=\"javascript:setOrderBy(0)\">Date</a> / <a href=\"javascript:setOrderBy(1)\">EAFDSS</a>
      </b>
      </div></form>";

	echo "<div id=zoomdlg title=\"Zoom\"><iframe id=zoomframe width=620 height=300></iframe></div>";
}
//------------------------------------------------------------------------------
function ResetSerCustomer(&$db)
{
   global $aLevel;

   if ($aLevel != 1) // not admin
      return;

   if (!empty($_REQUEST['NEWCUSTOMER']) && $_REQUEST['NEWCUSTOMER'] !== 'OTE') {
      uerror('Ακατάλληλη αξία!');
      return;
   }

   $query = 'UPDATE ser_transa SET SER_CUSTOMER=? WHERE SER_TRANSID=?';
   $data = array((empty($_REQUEST['NEWCUSTOMER']) ? 1 : 3), (int)$_REQUEST['TRID']);
   if (!$db->Execute($query,$data)) {
      uerror( __LINE__.' '.$db->ErrorMsg() );
   }
}
//------------------------------------------------------------------------------
function list_files(&$db)
{
   global $aLevel;

   if ($aLevel != 1) // not admin
      return;

   echo '<h5>Export tables</h5>';

   $ar1 = $db->metaTables('TABLES');
   echo '<ul>';
   foreach ($ar1 as $f1) {
      echo '<li><a href="'.myhtml($_SERVER['SCRIPT_NAME']).'?FU=85&TABLE='.$f1.'">'.$f1.'</a></li>';
   }
   echo '</ul>';
}
//------------------------------------------------------------------------------
function export_table(&$db)
{
   global $aLevel, $ADODB_FETCH_MODE;

   if ($aLevel != 1) // not admin
      return;

   $f1 = $_REQUEST['TABLE'];

   echo '<h5>Export table '.$f1.'</h5>';

   $ADODB_FETCH_MODE = ADODB_FETCH_NUM;

   /*
   $ar1 = $db->metaColumns($f1);
   foreach ($ar1 as $field) {
      pre($field);
   }
   */

   $query="SELECT * FROM $f1";
   if (($rs=$db->Execute($query))===false) {
      return;
   }
   echo '<pre>';
   while ($row=$rs->FetchRow()) {
      echo "INSERT INTO $f1 VALUES(";
      $n = count($row);
      for ($i=0; $i<$n; $i++) {
         if ($i>0) echo ', ';
         if (is_null($row[$i]))
            echo 'NULL';
         else if (is_numeric($row[$i]))
            echo $row[$i];
         else
            echo "'$row[$i]'";
      }
      echo ");\n";
   }
   echo '</pre>';
   $rs->Close();
}
//------------------------------------------------------------------------------
function show_all_transid(&$db)
{
	global $aLevel;

   $pg=(int)@$_REQUEST['RSPAGE'];
   if ($pg<1) $pg=1;
   $pgsz=30;

   $T1=0;

	$data=array();
	$whereFilter = false;
   $details=false;
   $query="SELECT T1.*, T2.ser_itemid FROM ser_transa T1
   	LEFT JOIN ser_data T2 ON (T2.ser_transid=T1.ser_transid)
      WHERE 1=1 ";
   if ($aLevel !=1 ) {
   	// Not admin
   	$query .= " AND SER_TR_UNAME != 'inca'  AND T1.SER_UGROUP=".$_SESSION['UGROUP'];
   	$whereFilter = true;
	}

   if (isset($_REQUEST[$k1='USRFILTER'])) {
      $_SESSION[$k1] = $_REQUEST[$k1];
   }
   if (!empty($_SESSION[$k1])) {
		$query .= " AND SER_TR_UNAME=? ";
   	$data[]=$_SESSION[$k1]; // string
	}

   if (isset($_REQUEST[$k1='IIDFILTER'])) {
      $_SESSION[$k1] = $_REQUEST[$k1];
   }
   if (!empty($_SESSION[$k1])) {
		$query .= " AND SER_ITEMID=? ";
   	$data[]=(int)$_SESSION[$k1];
	}

   if (isset($_REQUEST[$k1='S11FILTER'])) {
      $_SESSION[$k1] = $_REQUEST[$k1];
   }
   if (!empty($_SESSION[$k1])) {
		$query .= " AND SER_S11_ARRAY LIKE ? ";
      $filter = $_SESSION[$k1];
      if (strpos($filter, '%') === false) { $filter .= '%'; }
   	$data[] = $filter;
	}

   if (isset($_REQUEST[$k1 = 'VERFILTER'])) {
      $_SESSION[$k1] = $_REQUEST[$k1];
   }
   if (!empty($_SESSION[$k1])) {
		$query .= " AND SER_VERSION=? ";
   	$data[]=(int)$_SESSION[$k1];
	}

   if (isset($_REQUEST[$k1='CUSTFILTER'])) {
      $_SESSION[$k1] = $_REQUEST[$k1];
   }
   if (isset($_SESSION[$k1]) && strlen($_SESSION['CUSTFILTER'])>0) { // do not use 'empty()'; may be '0'
		$query .= " AND SER_CUSTOMER=? ";
   	$data[]=(int)$_SESSION[$k1];
	}

   $query .= " GROUP BY T1.ser_transid
      ORDER BY T1.ser_transid DESC";

   echo "<!-- $query ";
   print_r($data);
   echo " -->";
   if ($rs=$db->PageExecute($query,$pgsz,$pg,$data)) {
?>
<script>
function askNewCustomer(ohref, trid)
{
   var newval = window.prompt( 'New customer', $(ohref).text() );
   if (newval !== null)
   {
      var url = document.location.pathname + '?FU=83&TRID=' + trid + '&NEWCUSTOMER=' + encodeURIComponent(newval);
      location.href = url;
   }
}
</script>
   <form method=POST action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" name="goForm">
   <input type=HIDDEN name="RSPAGE">
   <input type=HIDDEN name="FU" value="11">
   <table>
   <tr class=MYTHEAD>
      <td>Transid</td>
      <td>Ημ/νία</td>
      <td>User</td>
      <td>Remote Host</td>
      <td>Remote Addr.</td>
      <td>Serials</td>
      <td>Type</td><!-- 28/2/2008 -->
      <td>Min</td>
      <td>Max</td>
      <td>Codex</td>
      <td>Serial(s)</td>
      <td>Version</td>
      <td>Customer</td>
   </tr>
<?php
      while ($o1=$rs->FetchNextObject()) {
         if (($o2=getSubInfo($db, $o1->SER_TRANSID))===false)
            $o2=(object)array('F1'=>0, 'N1'=>'', 'N2'=>'');

         $T1 += $o2->F1;
         $datestr=GrDateTime($o1->SER_TR_DAYTIME);
         $customerName = getCurtomerName($o1->SER_CUSTOMER);

         echo "<tr>\n".
            "<td><a href=\"".myhtml($_SERVER['SCRIPT_NAME'])."?FU=8&TRID=".$o1->SER_TRANSID."\">".$o1->SER_TRANSID."</a></td>\n".
            "<td>".$datestr."</td>\n".
            "<td>".myhtml($o1->SER_TR_UNAME)."</td>\n".
            "<td>".myhtml($o1->SER_REMOTE_HOST)."</td>\n".
            "<td>".myhtml($o1->SER_REMOTE_ADDR)."</td>\n".
            "<td>".myhtml($o2->F1)."</td>\n".
            // inca 28/2/2008
            "<td>".myhtml(@$o1->SER_ITEMID)."</td>\n".
            "<td>".myhtml($o2->N1)."</td>\n".
            "<td>".myhtml($o2->N2)."</td>\n".
            "<td>".myhtml($o1->SER_CODEX_ARRAY)."</td>\n".
            "<td>".myhtml($o1->SER_S11_ARRAY)."</td>\n".
            "<td>".myhtml($o1->SER_VERSION)."</td>\n".
            "<td>";
      if ($aLevel == 1 && ((int)$o1->SER_TRANSID)>0) { // admin
         echo '<a href="#" onclick="javascript:askNewCustomer(this, '.$o1->SER_TRANSID.')">'.myhtml($customerName).'</a>';
      }
      else {
         echo myhtml($customerName);
      }
      echo "</td>\n".
            "</tr>\n";
      }
      $epage=$rs->LastPageNo();
      $rs->Close();

      echo "<tr>\n".
            "<td></td>\n".
            "<td>Total</td>\n".
            "<td></td>\n".
            "<td></td>\n".
            "<td></td>\n".
            "<td>$T1</td>\n".
            "</tr>\n";

      echo "</table>
         <div class=MYNAVBAR style=\"width:80%\">
         <div>
         <span style=\"border:1px solid black; padding:4px\">Φίλτρα:
         User<input type=text name=\"USRFILTER\" value=\"".myhtml(@$_SESSION['USRFILTER'])."\" size=5>
         Τύπος άδειας<input type=text name=\"IIDFILTER\" value=\"".myhtml(@$_SESSION['IIDFILTER'])."\" size=3 maxlength=3>
         S11%<input type=text name=\"S11FILTER\" value=\"".myhtml(@$_SESSION['S11FILTER'])."\" size=11 maxlength=12>
         Version<input type=text name=\"VERFILTER\" value=\"".myhtml(@$_SESSION['VERFILTER'])."\" size=5>
         Customer<input type=text name=\"CUSTFILTER\" value=\"".myhtml(@$_SESSION['CUSTFILTER'])."\" size=5>
         </span><input type=submit value=\"Refresh\">
         </div>";
   	print_page_nav2($pg,$epage,11);
	   echo "</div>
         </form>";
   }
   else {
      echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>\n";
   }

   echo "<h5>Current server time: ".date('d-m-Y H:i:s')."</h5>";
}
//------------------------------------------------------------------------------
function remove_version(&$db)
{
	global $aLevel;

	if ($aLevel!=1) { // not admin
		echo "<h6>Not administrator!</h6>";
		return;
	}

	$query="delete FROM ser_version WHERE ser_itemid=? AND ser_auth=? AND ser_serial=? AND ser_version=?";
	$data=array( (int)$_REQUEST['SER_ITEMID'], $_REQUEST['SER_AUTH'], $_REQUEST['SER_SERIAL'], $_REQUEST['SER_VERSION']);
	if (!$db->Execute($query,$data))
		echo __LINE__.$db->ErrorMsg();
}
//------------------------------------------------------------------------------
function statistics_by_mon(&$db)
{
	$query="SELECT EXTRACT(YEAR_MONTH FROM T1.SER_TR_DAYTIME) F1, COUNT(*) F2 FROM ser_transa T1
		LEFT JOIN ser_data T2 ON (T2.SER_TRANSID=T1.SER_TRANSID)
		WHERE T2.SER_TRANSID IS NOT NULL
		GROUP BY F1
		ORDER BY T1.SER_TRANSID DESC LIMIT 100";
	$data=array();
	if (($rs=$db->Execute($query,$data))===false) {
		echo __LINE__.$db->ErrorMsg();
		return;
	}
	echo "<table>
		<tr class=MYTHEAD>
		<td>Date</td>
		<td>Count</td>
		</tr>";
	while ($o1=$rs->FetchNextObject()) {
		echo "<tr>
			<td>".substr($o1->F1,0,4).'-'.substr($o1->F1,4,2)."</td>
			<td align=right>".$o1->F2."</td>
			</tr>";
	}
	$rs->Close();
	echo "</table>
		</p></p>";
}
//------------------------------------------------------------------------------
function show_stats_allyear(&$db)
{
   include_plot_js();

   $cdata=array();
   $maxc=0;

   // whole year
   $query="SELECT EXTRACT(YEAR FROM T1.SER_TR_DAYTIME) F1, COUNT(*) F2 FROM ser_transa T1
		LEFT JOIN ser_data T2 ON (T2.SER_TRANSID=T1.SER_TRANSID)
		WHERE T2.SER_TRANSID IS NOT NULL
		GROUP BY F1
		ORDER BY F1";
   $data=false;
   if (($rs=$db->Execute($query,$data))===false) {
		echo $db->ErrorMsg();
		return;
	}
   while ($o1=$rs->FetchNextObject()) {
      $cdata[$o1->F1]=array(0, $o1->F2);
      if ($o1->F2>$maxc) {
         $maxc=$o1->F2;
      }
   }
   $rs->Close();

   $m=(int)date('n'); // month as 1,2,...

   // partial
   $query="SELECT EXTRACT(YEAR FROM T1.SER_TR_DAYTIME) F1, COUNT(*) F2 FROM ser_transa T1
		LEFT JOIN ser_data T2 ON (T2.SER_TRANSID=T1.SER_TRANSID)
		WHERE EXTRACT(MONTH FROM T1.SER_TR_DAYTIME)<=? AND T2.SER_TRANSID IS NOT NULL
		GROUP BY F1
		ORDER BY F1";
   $data=array($m);
   if (($rs=$db->Execute($query,$data))===false) {
		echo $db->ErrorMsg();
		return;
	}
   while ($o1=$rs->FetchNextObject()) {
      $cdata[$o1->F1][0]=$o1->F2;
      if ($o1->F2>$maxc) {
         $maxc=$o1->F2;
      }
   }
   $rs->Close();

   // non-connected
   $query="SELECT COUNT(*) FROM ser_data T1
      LEFT JOIN ser_transa T2 ON (T2.SER_TRANSID=T1.SER_TRANSID)
      WHERE T2.SER_TRANSID IS NULL";
   $data=false;
   if (($rs=$db->Execute($query,$data))===false) {
		echo $db->ErrorMsg();
		return;
	}
   $row=$rs->FetchRow();
   $nc=$row[0];
   $rs->Close();

   $gt=0;
   foreach ($cdata as $v) {
      $gt += $v[1];
   }

   $step=get_step($maxc);
?>
<div id="big" style="height:400px;width:800px; border:1px solid #c0c0c0; padding:10px;">
   <div id=chartdiv style="height:100%; width:100%;"></div>
</div>
<script>
<?php
  echo "var ticks=[ ";
   $i=0;
   foreach ($cdata as $k=>$v) {
      if ($i++>0) { echo ", "; }
      echo " '$k'";
   }
   echo " ];\n";

   echo "var s1=[ ";
   $i=0;
   foreach ($cdata as $v) {
      if ($i++>0) { echo ", "; }
      echo " '$v[0]'";
   }
   echo " ];\n";

   echo "var s2=[ ";
   $i=0;
   foreach ($cdata as $v) {
      if ($i++>0) { echo ", "; }
      echo " '$v[1]'";
   }
   echo " ];\n";

   echo "var ticksY=[ ";
   for ($i=0;$i<=5;$i++) {
      if ($i>0) { echo ", "; }
      echo $step*$i;
   }
   echo " ];\n";
?>
//myChart.setBarColor('#FF9933', 1);
//myChart.setBarColor('#ff0f0f', 2);
var plot1 = $.jqplot('chartdiv', [s1, s2], {
      title:'Ετήσιες πωλήσεις',
      axesDefaults: {
         labelRenderer: $.jqplot.CanvasAxisLabelRenderer
      },
      axes: {
         // options for each axis are specified in seperate option objects.
         xaxis: {
            label: "Ημερομηνίες",
            // Turn off "padding".  This will allow data point to lie on the
            // edges of the grid.  Default padding is 1.2 and will keep all
            // points inside the bounds of the grid.
            renderer: $.jqplot.CategoryAxisRenderer,
            ticks: ticks
         },
         yaxis: {
            label: "Αδειες",
            pad: 1.0,
            tickOptions: {formatString: '%d'},
            ticks: ticksY
         }
      },
      seriesDefaults:{
         renderer:$.jqplot.BarRenderer,
         pointLabels: { show: true, location: 'n'/*, edgeTolerance: -15*/ },
         rendererOptions: {fillToZero: true},
         useNegativeColors: false
      },
      series:[
         {label:'<?php echo $m; ?>μηνο', color:'#FF9933'},
         {label:'Ετος', color:'#FF0000'} // red
      ],
      legend: {
         show: true,
         placement: 'outsideGrid'
      }
   });

$('#big').resizable( {stop:function(){
   plot1.replot();
   } } );
</script>
<div style="background-color:#d0d0d0; width:80%; padding:2px;">
<b>
   <?php draw_chart_menu(61); ?> ||
   Grand total = <?php echo $gt." + ".$nc; ?>
</b>
</div>
<?php
}
//------------------------------------------------------------------------------
function version_analysis(&$db)
{
   if (version_compare($_REQUEST['VERSION'], '2.4.1.1')==0) {
      echo "<h6>Information for base version not available!</h6>";
      return;
   }
?>
<script>
function queryS11(s11)
{
   var url = 'https://www.metafuture.biz/myweb/taxspl2.php?SER_AUTH=' + s11.substr(0,3) + '&SER_SERIAL=' + s11.substr(3);
   window.open(url,'query','resizable=yes,scrollbars=yes,status=yes');
}
</script>
<?php
   $query="SELECT ser_auth, ser_serial FROM ser_version
      WHERE ser_version=? AND (ser_forever IS NULL OR ser_forever=1)
      ORDER BY ser_auth, ser_serial";
   $data=array($_REQUEST['VERSION']);
   if (($rs=$db->Execute($query,$data))===false) {
		echo $db->ErrorMsg();
		return;
	}
   echo "<table>";
   while ($o1=$rs->FetchNextObject()) {
      $s11=$o1->SER_AUTH.$o1->SER_SERIAL;

      echo "<tr>
         <td>".myhtml($_REQUEST['VERSION'])."</td>
         <td><a href=\"javascript:queryS11('$s11')\">$s11</a></td>
         </tr>";
   }
   $rs->Close();
   echo "</table>";
?>
<div style="background-color:#d0d0d0; width:80%; padding:2px;">
<b>
   <a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=63">Εκδόσεις</a>
</b>
</div>
<?php
}
//------------------------------------------------------------------------------
function show_stats_version(&$db)
{
   include_plot_js();
   $lics=array(); // s11:itemid->max_version
   $cdata=array(); // version->count

   $query="SELECT T1.ser_auth, T1.ser_serial, T1.ser_itemid, T2.ser_version, T2.ser_forever FROM ser_data T1
      LEFT JOIN ser_version T2 ON(T2.ser_itemid=T1.ser_itemid AND T2.ser_auth=T1.ser_auth AND T2.ser_serial=T1.ser_serial)";
      //WHERE T2.ser_forever IS NULL OR T2.ser_forever=1";
   if (($rs=$db->Execute($query))===false) {
		echo $db->ErrorMsg();
		return;
	}
   while ($o1=$rs->FetchNextObject()) {
      if ($o1->SER_FOREVER==0) {
         $version="2.4.1.1";
      }
      else {
         $version=(string)$o1->SER_VERSION;
         $ar1=explode('.',$version);
         if (count($ar1)!=4) {
            $version="2.4.1.1";
         }
         else if (version_compare($version, '2.4.5.0')>=0) {
            $version='2.4.5.1';
         }
      }

      $key=$o1->SER_AUTH.$o1->SER_SERIAL.':'.$o1->SER_ITEMID;
      if (!array_key_exists($key,$lics)) {
         $lics[$key] = $version;
      }
      else if (version_compare($version, $lics[$key])>0) {
         $lics[$key] = $version;
      }
   }
   $rs->Close();         echo count($lics);

   foreach ($lics as $version) {
      $key=$version;

      if (array_key_exists($key,$cdata)) {
         $cdata[ $key ] = $cdata[ $key ] + 1;
      }
      else {
         $cdata[ $key ] = 1;
      }
   }
   $rs->Close();

   uksort($cdata, 'version_compare');

   $maxc=0;
   $gt=0;
   foreach ($cdata as $val) {
      if ($val>$maxc) {
         $maxc=$val;
      }
      $gt += $val;
   }
   $step=get_step($maxc);
?>
<div id="big" style="height:400px;width:800px; border:1px solid #c0c0c0; padding:10px;">
   <div id=chartdiv style="height:100%; width:100%;"></div>
</div>
<script>
<?php
   echo "var ticks=[ ";
   $i=0;
   foreach ($cdata as $k=>$v) {
      if ($i++>0) { echo ", "; }
      echo " '$k'";
   }
   echo " ];\n";

   echo "var s1=[ ";
   $i=0;
   foreach ($cdata as $v) {
      if ($i++>0) { echo ", "; }
      echo " $v";
   }
   echo " ];\n";

   echo "var ticksY=[ ";
   for ($i=0;$i<=5;$i++) {
      if ($i>0) { echo ", "; }
      echo $step*$i;
   }
   echo " ];\n";
?>
var plot1 = $.jqplot('chartdiv', [s1], {
      title:'Κατανομή εκδόσεων',
      axesDefaults: {
         labelRenderer: $.jqplot.CanvasAxisLabelRenderer
      },
      axes: {
         // options for each axis are specified in seperate option objects.
         xaxis: {
            label: "Εκδόσεις",
            // Turn off "padding".  This will allow data point to lie on the
            // edges of the grid.  Default padding is 1.2 and will keep all
            // points inside the bounds of the grid.
            renderer: $.jqplot.CategoryAxisRenderer,
            ticks: ticks,
            tickRenderer: $.jqplot.CanvasAxisTickRenderer ,
            tickOptions: {
               angle: -40,
               fontSize: '10pt'
            }
         },
         yaxis: {
            label: "Αδειες",
            pad: 1.0,
            tickOptions: {formatString: '%d'},
            ticks: ticksY
         }
      },
      seriesDefaults:{
         renderer:$.jqplot.BarRenderer,
         pointLabels: { show: true, location: 'n'/*, edgeTolerance: -15*/ },
         rendererOptions: {fillToZero: true},
         useNegativeColors: false
      }
   });

$('#big').resizable( {stop:function(){
   plot1.replot();
   } } );

function go_analysis()
{
   location.href = location.pathname+'?FU=64&VERSION='+$('#version').val();
}
</script>
<div style="background-color:#d0d0d0; width:80%; padding:2px;">
<b>
   <?php draw_chart_menu(63); ?> || Grand total = <?php echo $gt; ?> ||
</b>
Ανάλυση <select id=version><?php
   foreach ($cdata as $key=>$val) {
      echo "<option>".myhtml($key)."</option>";
   }
?></select><button  style="height:25px; width:25px;" onclick="go_analysis()"><img src="/img/go_right.png"></button>
</div>
<?php
}
//------------------------------------------------------------------------------
function show_stats_daily(&$db)
{
   include_plot_js();

   $nowt=getdate(); // year, mon (1..12), mday (1..31)
   $mon=$nowt['mon'];
   $mdy=$nowt['mday']-1;
   $d1=mktime(0,0,0,$mon-1,1,$nowt['year']);
   $d1s=date('Y-m-d H:i:s',$d1);

   // last day of prev. month:
   $d2=date('d', mktime(0,0,0,$mon,0,$nowt['year']));

   $cdata=array();
   for ($i=1;$i<=31;$i++) {
      $cdata[$i]=array(0,0);
   }
   $cdata['μ.ο.']=array(0,0);

   $maxfc=0;
   $gt=array(0,0);

   $query="SELECT EXTRACT(MONTH FROM T1.SER_TR_DAYTIME) FMON, EXTRACT(DAY FROM T1.SER_TR_DAYTIME) FDAY, COUNT(*) FC FROM ser_transa T1
		LEFT JOIN ser_data T2 ON (T2.SER_TRANSID=T1.SER_TRANSID)
		WHERE SER_TR_DAYTIME >= ? AND T2.SER_TRANSID IS NOT NULL
		GROUP BY FMON, FDAY";
	$data=array( $d1s );
	if (($rs=$db->Execute($query,$data))===false) {
		echo $db->ErrorMsg();
		return;
	}
   while ($o1=$rs->FetchNextObject()) {
      $m=$o1->FMON;
      $d=$o1->FDAY;
      if ($m==$mon) {
         $cdata[$d][0]=$o1->FC;
         if ($d<$mdy) {
            $gt[0]=$gt[0]+$o1->FC;
         }
      }
      else {
         $cdata[$d][1]=$o1->FC;
         $gt[1]=$gt[1]+$o1->FC;
      }

      if ($o1->FC > $maxfc) {
         $maxfc=$o1->FC;
      }
   }
   $rs->Close();

   if ($mdy>1) {
      $cdata['μ.ο.'][0]=$gt[0]/($mdy-1);
   }
   $cdata['μ.ο.'][1]=$gt[1]/$d2;

   $step=get_step($maxfc);
?>
<div id="big" style="height:400px;width:800px; border:1px solid #c0c0c0; padding:10px;">
   <div id=chartdiv style="height:100%; width:100%;"></div>
</div>
<script>
<?php
   echo "var ticks=[ ";
   $i=0;
   foreach ($cdata as $k=>$v) {
      if ($i++>0) { echo ", "; }
      echo " '$k'";
   }
   echo " ];\n";

   echo "var s1=[ ";
   $i=0;
   foreach ($cdata as $v) {
      if ($i++>0) { echo ", "; }
      echo " '$v[0]'";
   }
   echo " ];\n";

   echo "var s2=[ ";
   $i=0;
   foreach ($cdata as $v) {
      if ($i++>0) { echo ", "; }
      echo " '$v[1]'";
   }
   echo " ];\n";

   echo "var ticksY=[ ";
   for ($i=0;$i<=5;$i++) {
      if ($i>0) { echo ", "; }
      echo $step*$i;
   }
   echo " ];\n";
?>
var plot1 = $.jqplot('chartdiv', [s1, s2], {
      title:'Ημερήσιες πωλήσεις',
      axesDefaults: {
         labelRenderer: $.jqplot.CanvasAxisLabelRenderer
      },
      axes: {
         // options for each axis are specified in seperate option objects.
         xaxis: {
            label: "Ημερομηνίες",
            // Turn off "padding".  This will allow data point to lie on the
            // edges of the grid.  Default padding is 1.2 and will keep all
            // points inside the bounds of the grid.
            renderer: $.jqplot.CategoryAxisRenderer,
            ticks: ticks
         },
         yaxis: {
            label: "Αδειες",
            pad: 1.0,
            tickOptions: {formatString: '%d'},
            ticks: ticksY
         }
      },
      seriesDefaults:{
         renderer:$.jqplot.BarRenderer,
         pointLabels: { show: true, location: 'n'/*, edgeTolerance: -15*/ },
         rendererOptions: {fillToZero: true},
         useNegativeColors: false
      },
      series:[
         {label:'Τρέχων μήνας', color:'#008000'},
         {label:'Προηγ. μήνας', color:'#FF0000'} // red
      ],
      legend: {
         show: true,
         placement: 'outsideGrid'
      }
   });

$('#big').resizable( {stop:function(){
   plot1.replot();
   } } );
</script>
<div style="background-color:#d0d0d0; width:80%; padding:2px;">
<b>
   <?php draw_chart_menu(62); ?>
</b>
</div>
<?php
}
//------------------------------------------------------------------------------
function get_step($i)
{
   $xe=$i*1.15;
   $x2=round($xe/5.0);
   if ($x2==0) {$x2=1;}
   if (($m=$x2%5)>0) { $x2 += 5-$m; }

   return $x2; // step
}
//------------------------------------------------------------------------------
function draw_chart_menu($j)
{
   if ($j==62) {
      echo "Ημερήσιες";
   }
   else {
      echo "<a href=\"".myhtml($_SERVER['PHP_SELF'])."?FU=62\">Ημερήσιες</a>";
   }
   echo " | ";

   if ($j==60) {
      echo "Μηνιαίες";
   }
   else {
      echo "<a href=\"".myhtml($_SERVER['PHP_SELF'])."?FU=60\">Μηνιαίες</a>";
   }
   echo " | ";

   if ($j==61) {
      echo "Ολα τα έτη";
   }
   else {
      echo "<a href=\"".myhtml($_SERVER['PHP_SELF'])."?FU=61\">Ολα τα έτη</a>";
   }
   echo " | ";

   if ($j==63) {
      echo "Εκδόσεις";
   }
   else {
      echo "<a href=\"".myhtml($_SERVER['PHP_SELF'])."?FU=63\">Εκδόσεις</a>";
   }
   echo " | ";

   if ($j==65) {
      echo "Upgrades";
   }
   else {
      echo "<a href=\"".myhtml($_SERVER['PHP_SELF'])."?FU=65\">Upgrades</a>";
   }
}
//------------------------------------------------------------------------------
function show_stats_upd(&$db)
{
   $today=time();
   $expires=array();

   $query="SELECT ser_itemid, ser_auth, ser_serial, ser_date, ser_upgrade, ser_expires, ser_comments FROM ser_data
      WHERE SER_UPGRADE IS NOT NULL AND SER_EXPIRES > NOW()";
   if (($rs=$db->Execute($query,$data))===false) {
		echo $db->ErrorMsg();
		return;
	}
   echo "<table>
      <tr class=MYTHEAD>
      <td>Λήξη σε ημέρες</td>
      <td>Πλήθος</td>
      </tr>";
   while ($o1=$rs->FetchNextObject()) {
      do {
         $ar1=explode(" ",$o1->SER_EXPIRES);
         if (count($ar1)<2)
            break;

         $ar2=explode("-",$ar1[0]);
         if (count($ar2)<3)
            break;

         $t1=mktime(0,0,0,$ar2[1],$ar2[2],$ar2[0]); // m,d,y
         $x=(int)floor(($t1 - $today)/24/3600);
         if (!array_key_exists($x, $expires)) {
            $expires[$x]=1;
         }
         else {
            $expires[$x] = $expires[$x]+1;
         }

      } while (false);
   }
   $rs->Close();

   ksort($expires);
   $nrec=0;
   $tn=0;
   foreach ($expires as $days=>$n) {
      echo "<tr";
      if ($nrec++%2>0) { echo " class=HILINE"; }
      echo ">
         <td>$days</td>
         <td>$n</td>
         </tr>";
      $tn += $n;
   }
   echo "<tr";
   if ($nrec++%2>0) { echo " class=HILINE"; }
   echo " style=\"font-weight:bold\">
      <td>Σύνολο</td>
      <td>$tn</td>
      </tr>
      </table>";
?>
<div style="background-color:#d0d0d0; width:80%; padding:2px;">
<b>
   <?php draw_chart_menu(65); ?>
</b>
</div>
<?php
}
//------------------------------------------------------------------------------
function show_stats_thisyear(&$db)
{
   include_plot_js();

   $cdata=array();

   $y=date('Y');
   $y2=$y-1;
   $maxc=0;

   // this year
   $query="SELECT EXTRACT(YEAR_MONTH FROM T1.SER_TR_DAYTIME) F1, COUNT(*) F2 FROM ser_transa T1
		LEFT JOIN ser_data T2 ON (T2.SER_TRANSID=T1.SER_TRANSID)
		WHERE SER_TR_DAYTIME >= ? AND T2.SER_TRANSID IS NOT NULL
		GROUP BY F1
		ORDER BY F1";
	$data=array( "$y-01-01" );
	if (($rs=$db->Execute($query,$data))===false) {
		echo $db->ErrorMsg();
		return;
	}
   while ($o1=$rs->FetchNextObject()) {
      $k=substr($o1->F1,4);
      $cdata[$k]=array($o1->F2, 0);
      if ($o1->F2>$maxc) {
         $maxc=$o1->F2;
      }
   }
   $rs->Close();

   // last year
   $query="SELECT EXTRACT(YEAR_MONTH FROM T1.SER_TR_DAYTIME) F1, COUNT(*) F2 FROM ser_transa T1
		LEFT JOIN ser_data T2 ON (T2.SER_TRANSID=T1.SER_TRANSID)
		WHERE SER_TR_DAYTIME >= ? AND SER_TR_DAYTIME < ? AND T2.SER_TRANSID IS NOT NULL
		GROUP BY F1
		ORDER BY F1";
	$data=array( "$y2-01-01", "$y-01-01" );
	if (($rs=$db->Execute($query,$data))===false) {
		echo $db->ErrorMsg();
		return;
	}
   while ($o1=$rs->FetchNextObject()) {
      $k=substr($o1->F1,4);
      if (array_key_exists($k,$cdata)) {
         $cdata[$k][1]=$o1->F2;
      }
      else {
         $cdata[$k]=array(0, $o1->F2);
      }
      if ($o1->F2>$maxc) {
         $maxc=$o1->F2;
      }
   }
   $rs->Close();

   $step=get_step($maxc);
?>
<div id="big" style="height:400px;width:800px; border:1px solid #c0c0c0; padding:10px;">
   <div id=chartdiv style="height:100%; width:100%;"></div>
</div>
<script>
<?php
   echo "var ticks=[ ";
   $i=0;
   foreach ($cdata as $k=>$v) {
      if ($i++>0) { echo ", "; }
      echo " '$k'";
   }
   echo " ];\n";

   echo "var s1=[ ";
   $i=0;
   foreach ($cdata as $v) {
      if ($i++>0) { echo ", "; }
      echo " '$v[0]'";
   }
   echo " ];\n";

   echo "var s2=[ ";
   $i=0;
   foreach ($cdata as $v) {
      if ($i++>0) { echo ", "; }
      echo " '$v[1]'";
   }
   echo " ];\n";

   echo "var ticksY=[ ";
   for ($i=0;$i<=5;$i++) {
      if ($i>0) { echo ", "; }
      echo $step*$i;
   }
   echo " ];\n";
?>
var plot1 = $.jqplot('chartdiv', [s1, s2], {
      title:'Μηνιαίες πωλήσεις',
      axesDefaults: {
         labelRenderer: $.jqplot.CanvasAxisLabelRenderer
      },
      axes: {
         // options for each axis are specified in seperate option objects.
         xaxis: {
            label: "Μήνες",
            // Turn off "padding".  This will allow data point to lie on the
            // edges of the grid.  Default padding is 1.2 and will keep all
            // points inside the bounds of the grid.
            renderer: $.jqplot.CategoryAxisRenderer,
            ticks: ticks
         },
         yaxis: {
            label: "Αδειες",
            pad: 1.0,
            tickOptions: {formatString: '%d'},
            ticks: ticksY
         }
      },
      seriesDefaults:{
         renderer:$.jqplot.BarRenderer,
         pointLabels: { show: true, location: 'n'/*, edgeTolerance: -15*/ },
         rendererOptions: {fillToZero: true},
         useNegativeColors: false
      },
      series:[
         {label:'Φέτος', color:'#008000'},
         {label:'Πέρσυ', color:'#FF0000'} // red
      ],
      legend: {
         show: true,
         placement: 'outsideGrid'
      }
   });

$('#big').resizable( {stop:function(){
   plot1.replot();
   } } );
</script>
<div style="background-color:#d0d0d0; width:80%; padding:2px;">
<b>
   <?php draw_chart_menu(60); ?>
</b>
</div>
<?php
}
function OLD_CODE()
{
?>
<div id="chart1"></div>
<script src="/script/jscharts.js"></script>
<script>
<?php
   echo "var myData=[ ";
   $i=0;
   foreach ($cdata as $k=>$v) {
      if ($i++>0) { echo ", "; }
      echo "['$k',$v[0],$v[1] ]";
   }
   echo " ];";
?>
var myChart = new JSChart('chart1', 'bar');
myChart.setDataArray(myData);
myChart.setSize(640, 400);
myChart.setAxisNameX('Ημερομηνίες');
myChart.setAxisNameY('Αδειες');
myChart.setBarColor('#008000', 1);
myChart.setBarColor('#ff0f0f', 2);
myChart.setTitle('Μηνιαίες πωλήσεις');

myChart.setAxisPaddingBottom(40);
myChart.setAxisPaddingLeft(50);

myChart.setLegendShow(true);
myChart.setLegendPosition('right top');
myChart.setLegendForBar(1, 'Φέτος');
myChart.setLegendForBar(2, 'Πέρσυ');

myChart.setGraphExtend(true);
myChart.draw();
</script>
<?php
}
//------------------------------------------------------------------------------
function show_orphans(&$db)
{
   global $aLevel;

	$query="SELECT T1.*, TX.ser_version TRV FROM ser_version T1
		LEFT JOIN ser_data T2 ON (T2.ser_itemid=T1.ser_itemid AND T2.ser_auth=T1.ser_auth AND T2.ser_serial=T1.ser_serial)
		LEFT JOIN ser_version TX ON (TX.ser_itemid=T2.ser_itemid AND TX.ser_auth=T2.ser_auth AND TX.ser_serial=T2.ser_serial AND TX.ser_transid=T2.ser_transid)
		WHERE T1.ser_forever=1 /* AND T1.ser_itemid!=300 */ AND T1.ser_transid=0 AND T2.ser_upgrade IS NULL
		ORDER BY T1.ser_auth, T1.ser_serial, T1.ser_itemid";
	if (($rs=$db->Execute($query))===false) {
		echo __LINE__.$db->ErrorMsg();
		return;
	}
	echo "<table>
		<tr class=MYTHEAD>
		<td></td>
		<td>Serial</td>
		<td>Τύπος</td>
		<td>Version</td>
		<td>Cre.date</td>
		<td>Τransid</td>
		<td>Διάρκεια</td>
		<td>TR/Ver.</td>
		</tr>";
	$nrec=0;
	while ($o1=$rs->FetchNextObject()) {
		if (version_compare($o1->SER_VERSION, $o1->TRV)<0)
			continue;

		echo "<tr>
			<td>".(++$nrec)."</td>
			<td><a href=\"".myhtml($_SERVER['PHP_SELF'])."?FU=40&SER_AUTH=".$o1->SER_AUTH.
			"&SER_SERIAL=".$o1->SER_SERIAL."\" style=\"font-weight:bold;\" title=\"Eafdss records\">".myhtml($o1->SER_AUTH.$o1->SER_SERIAL)."</a></td>
			<td>".myhtml($o1->SER_ITEMID)."</td>
			<td>".myhtml($o1->SER_VERSION)."</td>
			<td>".myhtml($o1->SER_DATE)."</td>
			<td>".myhtml($o1->SER_TRANSID)."</td>
			<td>".($o1->SER_FOREVER==1?'Για πάντα':'Για 1 μήνα')."</td>
			<td>".myhtml($o1->TRV)."</td>";
		if ($aLevel==1) { // admin
			echo "<td><a href=\"".myhtml($_SERVER['PHP_SELF'])."?FU=43&SER_ITEMID=".$o1->SER_ITEMID.
				"&SER_AUTH=".$o1->SER_AUTH."&SER_SERIAL=".$o1->SER_SERIAL."&SER_VERSION=".$o1->SER_VERSION."\">Remove</a></td>";
		}
		echo "</tr>";
	}
	$rs->Close();
	echo "</table></p></p>";
}
//------------------------------------------------------------------------------
function show_eafdss(&$db)
{
	global $aLevel;

	//
	// Show master data
	//
	$query="SELECT * FROM ser_data WHERE ser_auth=? AND ser_serial=?";
	$data=array( $_REQUEST['SER_AUTH'], $_REQUEST['SER_SERIAL'] );
	if (($rs=$db->Execute($query,$data))===false) {
		echo __LINE__.$db->ErrorMsg();
		return;
	}
	echo "<table>
		<tr class=MYTHEAD>
		<td>Serial</td>
		<td>Τύπος</td>
		<td>Cre.date</td>
		<td>Activation key</td>
		<td>Δελτίο</td>
		<td>Τιμολόγιο</td>
		<td>Τransid</td>
		<td>Upgrade date</td>
		<td>Exp.date</td>
		<td>Σχόλια</td>
		</tr>";
	while ($o1=$rs->FetchNextObject()) {
		echo "<tr>
			<td>".myhtml($o1->SER_AUTH.$o1->SER_SERIAL)."</td>
			<td>".myhtml($o1->SER_ITEMID)."</td>
			<td>".myhtml($o1->SER_DATE)."</td>
			<td>".myhtml($o1->SER_ACTKEY)."</td>
			<td>".myhtml($o1->SER_DELTIO)."</td>
			<td>".myhtml($o1->SER_TIM_PEL)."</td>";
		if ($o1->SER_TRANSID>0) {
			echo "<td><a href=\"".myhtml($_SERVER['SCRIPT_NAME'])."?FU=8&TRID=".myhtml($o1->SER_TRANSID)."\">".myhtml($o1->SER_TRANSID)."</a></td>";
		}
		else {
			echo "<td>".myhtml($o1->SER_TRANSID)."</td>";
		}
		echo "<td>".myhtml($o1->SER_UPGRADE)."</td>
			<td>".myhtml($o1->SER_EXPIRES)."</td>
			<td>".myhtml($o1->SER_COMMENTS)."</td>
			</tr>";
	}
	$rs->Close();
	echo "</table><p></p>";

	//
	// Show details
	//
	$query="SELECT * FROM ser_version WHERE ser_auth=? AND ser_serial=? ORDER BY ser_itemid, ser_version";
	$data=array( $_REQUEST['SER_AUTH'], $_REQUEST['SER_SERIAL'] );
	if (($rs=$db->Execute($query,$data))===false) {
		echo __LINE__.$db->ErrorMsg();
		return;
	}
	echo "<table>
		<tr class=MYTHEAD>
		<td>Serial</td>
		<td>Τύπος</td>
		<td>Version</td>
		<td>Cre.date</td>
		<td>Τransid</td>
		<td>Διάρκεια</td>
		</tr>";
	while ($o1=$rs->FetchNextObject()) {
		echo "<tr>
			<td>".myhtml($o1->SER_AUTH.$o1->SER_SERIAL)."</td>
			<td>".myhtml($o1->SER_ITEMID)."</td>
			<td>".myhtml($o1->SER_VERSION)."</td>
			<td>".myhtml($o1->SER_DATE)."</td>";
		if ($o1->SER_TRANSID>0) {
			echo "<td><a href=\"".myhtml($_SERVER['SCRIPT_NAME'])."?FU=8&TRID=".myhtml($o1->SER_TRANSID)."\">".myhtml($o1->SER_TRANSID)."</a></td>";
		}
		else {
			echo "<td>".myhtml($o1->SER_TRANSID)."</td>";
		}
		echo "<td>".($o1->SER_FOREVER==1?'Για πάντα':'Για 1 μήνα')."</td>";
		if ($aLevel==1) { // admin
			echo "<td><a href=\"".myhtml($_SERVER['PHP_SELF'])."?FU=41&SER_ITEMID=".$o1->SER_ITEMID.
				"&SER_AUTH=".$o1->SER_AUTH."&SER_SERIAL=".$o1->SER_SERIAL."&SER_VERSION=".$o1->SER_VERSION."\">Remove</a></td>";
		}
		echo "</tr>";
	}
	$rs->Close();
	echo "</table></p></p>";

	echo "<form action=\"".myhtml($_SERVER['SCRIPT_NAME'])."\">
      <input type=hidden name=\"FU\" value=\"40\">
		<table class=MYNAVBAR>
		<tr>
		<td><a href=\"".myhtml($_SERVER['PHP_SELF'])."?FU=40&SER_AUTH=".$_REQUEST['SER_AUTH'].
			"&SER_SERIAL=".$_REQUEST['SER_SERIAL']."\" style=\"font-weight:bold;\" title=\"Eafdss records\">Requery<a/></td>
		<td width=10>&nbsp;</td>
		<td>Ask another</td>
		<td><select id=ser_auth name=\"SER_AUTH\"></select></td>
		<td><input type=TEXT name=\"SER_SERIAL\" MAXLENGTH=8></td>
		<td><input type=submit value=\"Query\"></td>
		</tr>
		</table>
		</form>
      <script>fill_eafdss(document.getElementById('ser_auth'));</script>";
}
//------------------------------------------------------------------------------
function show_transid(&$db)
{
	global $aLevel;

   $details=false;
   $query="SELECT ser_transa.*, COUNT(ser_data.ser_transid) as T1 FROM ser_transa
      LEFT JOIN ser_data USING (ser_transid)
      WHERE ser_transa.ser_transid=?
      GROUP BY ser_transa.ser_transid";
   $data=array((int)$_REQUEST["TRID"]);
   if ($rs=$db->Execute($query,$data)) {
?>
   <table>
   <tr class=MYTHEAD>
      <td>Transid</td>
      <td>Ημ/νία</td>
      <td>User</td>
      <td>Remote Host</td>
      <td>Remote Addr.</td>
      <td>Serials</td>
   </tr>
<?php
      if ($o1=$rs->FetchNextObject()) {
         $datestr=$o1->SER_TR_DAYTIME;

         echo "<tr>\n".
            "<td>".$o1->SER_TRANSID."</td>\n".
            "<td>".$datestr."</td>\n".
            "<td>".myhtml($o1->SER_TR_UNAME)."</td>\n".
            "<td>".myhtml($o1->SER_REMOTE_HOST)."</td>\n".
            "<td>".myhtml($o1->SER_REMOTE_ADDR)."</td>\n".
            "<td>".myhtml($o1->T1)."</td>\n".
         	"</tr>\n";
         $details=true;
      }

      echo "</table>\n";

      $rs->Close();
   }
   else {
      echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>\n";
   }

   if ($details==false)
      return;

   //
	// show details
	//
   $query="SELECT ser_itemid, ser_auth, ser_serial, ser_actkey FROM ser_data
      WHERE ser_transid=?";
   $data=array((int)$_REQUEST["TRID"]);
   if ($rs=$db->Execute($query,$data)) {
?>
   <p></p>
   <table>
   <tr class=MYTHEAD>
   	<td>Transid</td>
      <td>Τύπος</td>
      <td>Serial</td>
      <td>Act.key</td>
   </tr>
<?php
      $line=0;
      while ($o2=$rs->FetchNextObject()) {
         $x=(int)$o2->SER_SERIAL;
         echo "<tr";
         $line++;
         if ($line%3==0)
            echo " class=HILINE";
         echo ">\n".
         	"<td>".myhtml($_REQUEST["TRID"])."</td>".
            "<td>".$o2->SER_ITEMID."</td>".
            "<td><a href=\"".myhtml($_SERVER['SCRIPT_NAME'])."?FU=40&SER_AUTH=".$o2->SER_AUTH."&SER_SERIAL=".$o2->SER_SERIAL."\">".
				myhtml($o2->SER_AUTH.$o2->SER_SERIAL)."</a></td>".
            "<td>".myhtml($o2->SER_ACTKEY)."</td>".
            "</tr>\n";
      }

      echo "</table>\n";

      $rs->Close();
   }
   else {
      echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>\n";
   }

   //
   // Show versions (other than basic)
   //
   $query="SELECT * FROM ser_version
      WHERE ser_transid=?";
   $data=array((int)$_REQUEST["TRID"]);
   if ($rs=$db->Execute($query,$data)) {
      echo "<p></p>
         <table>
         <tr class=MYTHEAD>
         	<td>Transid</td>
         	<td>Τύπος</td>
         	<td>Serial</td>
         	<td>Version</td>
         	<td>Ημ/νία</td>
         	<td>Για πάντα</td>
         </tr>";
      while ($o1=$rs->FetchNextObject()) {
         echo "<tr>
         	<td>".myhtml($_REQUEST["TRID"])."</td>
            <td>".$o1->SER_ITEMID."</td>
	         <td>".$o1->SER_AUTH.$o1->SER_SERIAL."</td>
   	      <td>".$o1->SER_VERSION."</td>
   	      <td>".$o1->SER_DATE."</td>
			   <td>".($o1->SER_FOREVER==1?'YES':'No')."</td>";
			if ($aLevel==1) { // admin
         	echo "<td><a href=\"".myhtml($_SERVER['PHP_SELF'])."?FU=39&TRID=".$_REQUEST["TRID"]."&SER_ITEMID=".$o1->SER_ITEMID.
					"&SER_AUTH=".$o1->SER_AUTH."&SER_SERIAL=".$o1->SER_SERIAL."&SER_VERSION=".$o1->SER_VERSION."\">Remove</a></td>";
			}
         echo "</tr>";
      }
      $rs->Close();
      echo "</table>";
   }
   else {
      echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>\n";
   }
}
//------------------------------------------------------------------------------
function upd_invoice(&$db)
{
   $query="UPDATE ser_data SET ser_tim_pel=? ".
      " WHERE ser_itemid=? AND ser_auth=? AND ser_serial=?";
   $data=array(trim($_REQUEST["INVOICE"]), $_REQUEST["SER_ITEMID"],
      $_REQUEST["SER_AUTH"], $_REQUEST["THISNR"] );
   if (!$db->Execute($query,$data))
      echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>\n";
}
//------------------------------------------------------------------------------
function get_inverse_query()
{
?>
   <table width="80%"><tr class=MYBOX><td><b>Ερώτηση για άδεια χρήσης που χορηγήθηκε</b></td></tr></table>

   <table>
   <form method=POST action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>">
   <input type=HIDDEN name="FU" value="15">
   <tr>
      <td>Αδεια χρήσης</td>
      <td><input type=TEXT name="SER_ACTKEY" size=50 MAXLENGTH=36></td>
   </tr>
   <tr>
      <td></td>
      <td><input type=SUBMIT name="ok" value="Ερώτηση"></td>
   </tr>
   </form>
   </table>

<?php
}
//------------------------------------------------------------------------------
function do_inverse_query(&$db)
{
   echo "<table width=\"80%\"><tr class=MYBOX><td>Aδεια χρήσης <b>".
      $_REQUEST["SER_ACTKEY"]."</b></td></tr></table>\n";

   $n=false;
   $query="SELECT * FROM ser_data WHERE ser_actkey=?";
   $data=array($_REQUEST["SER_ACTKEY"]);
   if ($rs=$db->Execute($query,$data)) {
      while ($o1=$rs->FetchNextObject()) {
         if (!$n) {
            $n=true;
            echo "<table><tr class=MYTHEAD>\n".
               "<td>Τύπος</td>\n".
               "<td>Σειριακός αρ.</td>\n".
               "<td>Δημιουργία</td>\n".
               "<td>Δ/Α</td>\n".
               "<td>Transaction</td>\n".
               "</tr>\n";
         }

         echo "<tr>\n".
            "<td>".$o1->SER_ITEMID."</td>\n".
            "<td>".$o1->SER_AUTH.$o1->SER_SERIAL."</td>\n".
            "<td>".$o1->SER_DATE."</td>\n".
            "<td>".$o1->SER_DELTIO."</td>\n".
            "<td><a href=\"".myhtml($_SERVER['SCRIPT_NAME'])."?FU=8&TRID=".$o1->SER_TRANSID."\">".$o1->SER_TRANSID."</a></td>\n".
            "</tr>\n";
      }
      $rs->Close();
   }
   if (!$n)
      echo "<h6>Δεν βρέθηκαν εγγραφές</h6>\n";
   else
      echo "</table>\n";
}
//------------------------------------------------------------------------------
function get_input_passwd()
{
   global $Guname;

?>
   <table>
   <form method=POST action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" onSubmit="return CheckPass(this)">
   <input type=HIDDEN name="FU" value="10">
   <tr>
      <td>User</td>
      <td><kbd><?php echo myhtml($Guname); ?></kbd></td>
   </tr>
      <td>New Password (min. 4 chars.)</td>
      <td><input type=PASSWORD name="UPASS" MAXLENGTH=25></td>
   <tr>
   </tr>
      <td>Verify (please repeat)</td>
      <td><input type=PASSWORD name="UPVER" MAXLENGTH=25></td>
   <tr>
   <tr class=MYNAVBAR>
      <td colspan=2 align=right><input type=SUBMIT name="ok" value="Submit"></td>
   </tr>
   </tr>
   </table>
<?php
}
//--------------------------------------
function inspect_files(&$db)
{
?>
<script>
function goExport(tname)
{
   location.assign('taxspl_out.php?FU=1&TABLE='+tname);
}
</script>
<?php
   echo "<h5>Inspect tables</h5>";

   $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_NUM;
   $query="SHOW TABLE STATUS";
   if (($rs=$db->Execute($query))===false) {
      echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>\n";
      return;
   }
   echo "<table><tr class=MYTHEAD>";
   // header
   $n=$rs->FieldCount();
   for ($i=0;$i<$n;$i++) {
      $fo=$rs->FetchField($i);
      echo "<td>".myhtml($fo->name)."</td>";
   }
   echo "</tr>";
   // records
   $nrec=0;
   while ($row=$rs->FetchRow()) {
      echo "<tr>";
      echo "<td><a href=\"javascript:goExport('".$row[0]."')\">".myhtml($row[0])."</a></td>";
      for ($i=1;$i<$n;$i++) {
         echo "<td>".myhtml($row[$i])."</td>";
      }
      echo "</tr>";
   }
   echo "</table>";

   $rs->Close();
}
//------------------------------------------------------------------------------
function show_table_status(&$db)
{
   $query="SHOW TABLE STATUS";
}
//------------------------------------------------------------------------------
function convert_charset(&$db)
{
   $done=0;

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

   foreach ($tables as $t1) {
      echo "<h4>$t1</h4>";

      $cfields=array();
      $flds=$db->MetaColumns($t1);
      foreach ($flds as $f1) {
         if ($db->MetaType($f1->type)=='C') {
            $cfields[]=strtoupper($f1->name);
         }
      }

      if (!empty($cfields)) {
         $pks=$db->MetaPrimaryKeys($t1);

         $query="SELECT ".implode(',', $cfields);
         foreach ($pks as $pk1) {
            $pk2=strtoupper($pk1);
            if (!in_array($pk2, $cfields)) {
               $query .= ", ".$pk2;
            }
         }
         $query .= " FROM $t1";
         $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_ASSOC;
         if (($rs=$db->Execute($query))===false) {
            echo $db->ErrorMsg();
            continue;
         }
         while ($row=$rs->FetchRow()) {
            $fupd=array();

            $n=count($cfields);
            for ($i=0;$i<$n;$i++) {
               $s1=trim($row[$cfields[$i]]);
               if (!mb_check_encoding($s1)) {
                  $s2=ToUtf8($s1);
                  if ($s2!=$row[$i]) {
                     $fupd[$cfields[$i]]=$s2;
                  }
               }
            }

            if (!empty($fupd)) {
               $query="UPDATE $t1 SET ";
               $i=0;
               $data=array();
               foreach ($fupd as $k1=>$v1) {
                  if ($i++>0) {
                     $query .= ", ";
                  }
                  $query .= $k1."=?";
                  $data[]=$v1;
               }
               $query .= " WHERE ";
               $i=0;
               foreach ($pks as $pk1) {
                  $pk2=strtoupper($pk1);
                  if ($i++>0) {
                     $query .= " AND ";
                  }
                  $query .= " $pk2=? ";
                  $data[]=$row[$pk2];
               }

               if (!$db->Execute($query, $data)) {
                  echo $db->ErrorMsg()."<br>";
                  pre($query);
                  pre($data);
               }
               else {
                  echo (++$done).' ';
               }
            }
         }
         $rs->Close();
      }
   }
}
//------------------------------------------------------------------------------
function update_lastuser(&$db)
{
   $query="UPDATE ser_data SET SER_LASTUSER=? WHERE SER_ITEMID=? AND SER_AUTH=? AND SER_SERIAL=?";
   $data=array( $_REQUEST['LASTUSR'], mb_substr($_REQUEST['RID'],0,3), mb_substr($_REQUEST['RID'],3,3),
      mb_substr($_REQUEST['RID'],6) );
   if ($db->Execute($query,$data))
      echo "update_lastuser:o.k.";
   else {
      echo "update_lastuser:".__LINE__.$db->ErrorMsg();
      print_r($data);
   }
}
//------------------------------------------------------------------------------
function upd_passwd(&$db)
{
   global $Guname;

   if ($_REQUEST['UPASS']!==$_REQUEST['UPVER']) {
      uerror("Λάθος στο password, επαναλάβετε!");
      return get_input_passwd();
   }

   $query="UPDATE ser_users SET ser_upass=? WHERE ser_uname=?";
   $data=array($_POST["UPASS"], $Guname );
   if ($db->Execute($query,$data))
      echo "<h6>Updated</h6>\n";
   else
      echo "<h6 class=ERROR>".__LINE__.$db->ErrorMsg()."</h6>\n";
}
//--------------------------------------
function print_page_nav2($pg,$epage,$fu=0)
{
 	if ($epage<0)
	 	$epage=0;

   echo "<button type=BUTTON ".
		" title=\"Move to 1st page\" class=NavButton ";
 	if ($pg>1) {
		echo " onClick=\"goMovePageEx(".$fu.",1)\">";
   }
	else {
		echo " DISABLED>";
   }
   echo "&lt;&lt;</button>";

	echo "<button type=BUTTON ".
		" title=\"Move to previous page\" class=NavButton ";
 	if ($pg>1) {
		echo " onClick=\"goMovePageEx(".$fu.','.($pg-1).")\">";
   }
	else {
		echo " DISABLED>";
   }
   echo "&lt;</button>";

	echo "<button type=BUTTON ".
		" title=\"Move to next page\" class=NavButton ";
	if ($pg<$epage) {
		echo " onClick=\"goMovePageEx(".$fu.','.($pg+1).")\">";
   }
	else {
		echo " DISABLED>";
   }
   echo "&gt;</button>";

	echo "<button type=BUTTON ".
		" title=\"Move to last page\" class=NavButton ";
	if ($pg<$epage) {
		echo " onClick=\"goMovePageEx(".$fu.','.$epage.")\">";
   }
	else {
		echo " DISABLED>";
   }
   echo "&gt;&gt;</button>";

   echo "<button type=BUTTON ".
		" title=\"Refresh\" class=NavButton onclick=\"goMovePageEx($fu, $pg)\">re</button>";

   if ($epage>1) {
   	echo "\n<a href=\"javascript:xtdPage($pg, $epage)\">Page</a> ".
	      "<span id=xtdpgNo> $pg/$epage</span>".
         "<span id=xtdpgSel style=\"display:none;\"></span>\n";
   }
   else {
      echo " Page $pg/$epage\n";
   }
}
//------------------------------------------------------------------------------
function export_sql_cre(&$db)
{
   $tbl = $_REQUEST['TABLE'];

   $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_NUM;
   $query="SELECT * FROM ?";
   $data=array($tbl);
   if (($rs=$db->Execute($query, $data))===false) {
      uerror($db->ErrorMsg());
      return;
   }
   echo "TRUNCATE TABLE $tbl;
      INSERT INTO $tbl VALUES ";
   $nrec=0;
   while ($row=$rs->FetchRow()) {
      if ($nrec++>0)
         echo ", ";

      $str1=false;
      foreach ($row as $f1) {
         if ($str1===false) {
            $str1="('$f1'";
         }
         else {
            $str1 .= ", '$f1'";
         }
      }
      $str1 .= ")";
      echo $str1;
   }
   $rs->Close();
}
//------------------------------------------------------------------------------
function ask_sql()
{
   echo "max file size allowed = ".ini_get('upload_max_filesize')."<br><br>";
?>
<form method=POST enctype="multipart/form-data" action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" name="goForm">
<input type=hidden name="FU" value="79">
File <input type=file name="SQLFILE"> <input type=submit>
</form>
<?php
}
//------------------------------------------------------------------------------
function execute_sql(&$db)
{
   if (!isset($_FILES['SQLFILE'])) {
      uerror("MIssing data file!");
      return;
   }
   else if (!empty($_FILES['SQLFILE']['error'])) {
      uerror("Error ".$_FILES['SQLFILE']['error']." while uploading file!");
      return;
   }
   else if (($query=file_get_contents($_FILES['SQLFILE']['tmp_name']))===false) {
      uerror("Could not read file");
      return;
   }

   if (!$db->Execute($query))
      echo $db->ErrorMsg();
   else
      echo "OK. Affected rows: ".$db->Affected_Rows();
}
//------------------------------------------------------------------------------
function pr_user_menu()
{
?>
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=0">Main (TaxSpooler)</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=59">FGA</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=56">TaxGate</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=20">ACTIVATION</a> |
<a href=<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=11">Transactions</a> |
<a href=<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=47&QUA=0">Upgrades</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=14">Requery</a> |
<a href="#" FU="60"></a>Statistics |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=9">Αλλαγή Password</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=-10">Logout</a>
<?php
}
//------------------------------------------------------------------------------
function pr_su_nav_bar()
{
?>
<p></p>
<div class=BOTNAVBAR>
<?php pr_user_menu(); ?>
<hr />
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=5">Εισαγωγή Δ/Α</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=1">Εισαγωγή παλαιών</a> |
<a href=<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=12">Cancelations</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=16">Admin upgrade</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=24">Licenses</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=26">Upgrades</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=30">Reassign_upgrades</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=75">250 -&gt; 240</a>
<br />
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=70">Query S11</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=42">Orphan versions</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=-1">Recheck files</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=49">Inspect files</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=78">Execute SQL</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=50">Convert charset</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=66">Execute query</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=19">Users</a> |
<a href="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>?FU=84">List files</a>
</div>
<?php
}
//------------------------------------------------------------------------------
function pr_norm_nav_bar()
{
?>
<p></p>
<div class=BOTNAVBAR>
<?php pr_user_menu(); ?>
</div>
<?php
}
//------------------------------------------------------------------------------
function repeat_login()
{
?>
<p>&nbsp;</b>
<div class=ASTERISK>Logout success or Authentication error</div>
<b>Παρακαλούμε <b><a href="javascript:repeat_login()">επαναλάβετε!</a></b>
<p></p>
<b><a href="https://www.metafuture.biz/metafuture/nsp_buy.php">Επιστροφή στο site</a></b>
<div id=repeat_login title="Επανάληψη login"  style="display:none;">
   <form method=POST action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>">
   <table>
   <tr>
      <td>User</td>
      <td><input type=text name="UNAME"></td>
   </tr>
   <tr>
      <td>Password</td>
      <td><input type=password name="UPASS"></td>
   </tr>
   <tr>
      <td></td>
      <td><input type=submit name="ok" value="Login"></td>
   </tr>
   </table>
   </form>
</div>
<script>

function repeat_login()
{
   $('#repeat_login').dialog({modal:true}).dialog('open');
}
</script>
<?php
}
//------------------------------------------------------------------------------
?>

</head>

<body>

<table width=100%>
<tr class=MYTHEAD>
   <td>TaxSpooler Maintenance<?php
      if (VERBOSE) {
         echo ' VERBOSE';
      }
   ?></td>
</tr>
</table>
<p></p>
<?php

$fu=(int)@$_REQUEST["FU"];
if ($fu == -10) {
   $_SESSION=array();
   session_destroy();
   // reset
   $aLevel=0;
   $fu=0;
}
else if ($fu == -1) {
   $aLevel=1; // superuser
}
else {
   $aLevel = authenticate($db);
   if ($aLevel==0/* authentication failed */ && $fu>0)
      $fu=0; // reset
}

echo "<!-- -------------- FUNCTION $fu --------------- -->";

//
// Start and special selections
//
switch ($aLevel)
{
case 1:
   //
   // superuser
   //
   echo "User group: <b>".(@$Groups[ $_SESSION['UGROUP'] ])." (admin.)</b><BR>&nbsp;\n";

   switch ($fu)
   {
   /*
   case -2:
      adjust_tables($db);
      break;
   */
   case -1:
      make_files($db);
      check_innodb($db);
      break;
   case 1:
      get_input_given();
      break;
   case 2:
      upd_given_table($db);
      echo "<p></p>\n";
      show_stat($db);
      break;
   case 5:
      input_deltio();
      break;
   case 6:
      update_deltio($db);
      break;
   case 12:
      get_input_cancel($db);
      break;
   case 13:
      upd_input_cancel($db);
      echo "<p></p>\n";
      show_stat($db);
      break;
   case 16:
      ask_upgrade_1($db);
      break;
   case 17:
      ask_upgrade_2($db);
      break;
   case 18:
      admin_apply_upgrade($db);
      break;
   case 19:
      show_users($db);
      break;
   case 24:
      show_licenses($db);
      break;
   case 25:
      add_user($db);
      show_users($db);
      break;
   case 26:
      show_upgrades($db);
      break;
   case 27:
      upd_comments($db);
      show_upgrades($db);
      break;
   case 28:
      show_grp_bydate($db);
      break;
   case 29:
      show_grp_analysis($db);
      break;
   case 30:
      su_ask_reassign($db);
      break;
   case 31:
      su_do_reassign($db);
      break;
   case 32:
      su_upd_ser_deltio($db);
      show_stat($db);
      break;
   case 33:
      ask_admin_upgrade($db);
      break;
   case 34:
      do_admin_upgrade($db);
      ask_admin_upgrade($db);
      break;
   case 35:
   	ask_group_license($db);
   	break;
   case 36:
   	apply_group_license($db);
   	break;
   case 37:
   	ask_group_upgrade($db);
   	break;
   case 38:
   	apply_group_upgrade($db);
   	show_stat($db);
   	break;
   case 39:
   	remove_version($db);
   	show_transid($db);
   	break;
   case 42:
   	show_orphans($db);
   	break;
   case 43:
   	remove_version($db);
   	show_orphans($db);
   	break;
   case 44:
      del_user($db);
      show_users($db);
      break;
	case 46:
      su_del_ser_deltio($db);
      show_stat($db);
      break;
   case 48:
      update_lastuser($db);
      break;
   case 49:
      inspect_files($db);
      break;
   case 50:
      convert_charset($db);
      break;
   case 52:
      zoom_ser_data($db);
      break;
   case 53:
      smooth_ser_data($db);
      zoom_ser_data($db);
      break;
   case 55:
      inform_reseller($db);
      break;
   case 66:
      su_ask_query();
      break;
   case 67:
      su_execute_query($db);
      //show_stat($db);
      break;
   case 70:
      ask_s11_complete();
      break;
   case 71:
      show_s11_complete($db);
      break;
   case 72:
      some_cleanup($db);
      break;
   case 73:
      delete_version($db);
      show_s11_complete($db);
      break;
   case 74:
      delete_upgrade($db);
      show_s11_complete($db);
      break;
   case 75:
      ask_transfer250to240();
      break;
   case 76:
      do_transfer250to240($db);
      show_s11_complete($db);
      break;
   case 77:
      export_sql_cre($db);
      break;
   case 78:
      ask_sql();
      break;
   case 79:
      execute_sql($db);
      break;
   case 82:
      delete_main_key($db);
      show_s11_complete($db);
      break;
   case 83:
      ResetSerCustomer($db);
      show_all_transid($db);
      break;
   case 84:
      list_files($db);
      break;
   case 85:
      export_table($db);
      break;
   }

   break;
case 2:
   //
   // normal user
   //
   echo "User group: <b>".(@$Groups[ $_SESSION['UGROUP'] ])."</b><BR>&nbsp;\n";
   break;
}

//
// All authenticated users (both super + normal)
//
if ($aLevel==1 || $aLevel==2) {
   switch ($fu)
   {
   case 0:
      show_stat($db);
      break;
   case 3:
      get_input_new();
      break;
   case 4:
      upd_input_new($db);
      echo "<p></p>\n";
      show_stat($db);
      break;
   case 7:
      upd_invoice($db);
      upd_input_new($db);
      echo "<p></p>\n";
      show_stat($db);
      break;
   case 8:
      show_transid($db);
      break;
   case 9:
      get_input_passwd();
      break;
   case 10:
      upd_passwd($db);
      break;
   case 11:
      show_all_transid($db);
      break;
   case 14: // inverse query
      get_inverse_query();
      break;
   case 15:
      do_inverse_query($db);
      break;
   case 20:
      select_lic_type();
      break;
   case 21:
      ask_upgrade_1($db);
      break;
   case 22:
      ask_upgrade_2($db);
      break;
   case 23:
      user_apply_upgrade($db);
      break;
   case 40:
   	show_eafdss($db);
   	break;
   case 41:
   	remove_version($db);
   	show_eafdss($db);
   	break;
   case 45:
      show_stat($db, true);
      break;
   case 47:
      cond_list_upgrades($db);
      break;
   case 54:
      total_upgrades($db);
      break;
   case 56:
      show_taxgate($db);
      break;
   case 57:
      ask_edit_tg_sales($db);
      break;
   case 58:
      update_tg_sales($db);
      show_taxgate($db);
      break;
   case 59:
      show_fgalic();
      break;
   case 60:
      show_stats_thisyear($db);
		break;
   case 61:
      show_stats_allyear($db);
		break;
   case 62:
      show_stats_daily($db);
		break;
   case 63:
      show_stats_version($db);
		break;
   case 64:
      version_analysis($db);
      break;
   case 65:
      show_stats_upd($db);
      break;
   case 68:
      ask_additional_SID_sess();
      break;
   case 69:
      add_additional_SID_sess($db);
      echo "<div><button type=button onclick=\"location.assign(location.pathname + '?FU=68')\">Επανάληψη</button></div>
         <p></p>";
      show_stat($db);
      break;
   case 80:
      ask_edit_fga_sales($db);
      break;
   case 81:
      /*
      update_tg_sales($db);
      show_taxgate($db);
      */
      update_fga_sales();
      show_fgalic();
      break;
   }
}

//
// Endup
//
$noToolbar=array(52,53,54,57);
if (!in_array($fu, $noToolbar)) {
   switch ($aLevel)
   {
   case 1: // superuser
      pr_su_nav_bar();
      break;
   case 2: // normal user
      pr_norm_nav_bar();
      break;
   default: // failure
      repeat_login();
      break;
   }
}

$db->Close();
?>
</body>
</html>
