<?php
// 1st things first
$verbose=false;
if (php_sapi_name()==='cli')
{
   parse_str(implode('&', $argv), $_REQUEST);
   
   if (!empty($argv)) { // running as CLI
      chdir(dirname($argv[0]));
   }

   if (count($argv)>=2 && strcasecmp($argv[1], "/v")==0) {
      $verbose=true;
   }
}

$logfileTest = 'E:/tmp/tax/'.date('H_i_s').'.txt';
//file_put_contents($logfileTest, 'Starting', FILE_APPEND|LOCK_EX);

// continue as CGI
include("../lib/ado/adodb.inc.php");
include("../lib/generic.inc.php");
include("../ishop/ishop_all.inc.php");
include("../ishop/ishop.inc.php");
include("taxinfo.inc.php");

class cS11
{
   public $s11;
   public $mtype;
   public $location;

   function __construct($xs11, $xmtype, $xlocation=false)
   {
      $this->s11 = $xs11;
      $this->mtype = $xmtype;
      $this->location = $xlocation;
   }
}

/* commented 4-11-2021
header("Content-type: text/html; charset=utf-8"); 
*/
$now=time();

$ret=false; // default
date_default_timezone_set('Europe/Athens');
$dm100=array('DCD', 'DLD', 'DSK', 'EPZ', 'EKX', 'EPT', 'FBD', 'FGG', 'QWR'); 


$db = &db_open(); // fill 'TAX_Catalog'
if (empty($_SESSION['TAX_Catalog'])) {
	generic_log("TAX_Catalog found empty");
   $db->Close(); // no more needed
   exit();
}

generic_log("Start");

if ($verbose) {
  echo "About to open ".$_SESSION['TAX_Catalog']."\n";
}
$iterator=false;
try {
   $iterator = new DirectoryIterator($_SESSION['TAX_Catalog']);
}
catch (Exception $e) {
	generic_log( "Exception: ".$e->getMessage() );
   exit();
}
$nrec=0;
$ndata=0;
$ndel=0;
foreach ($iterator as $fileinfo) {

   if (!$fileinfo->isDir() || $fileinfo->isDot())
      continue;

   if ((time() - $now)>=900) { // max 15 minutes
      generic_log("Max.time reached, aborting...");
      break;
   }

   //
   // process only directories
   //
   $dir1 = $fileinfo->getFilename();
   if (strcasecmp($dir1, "err")==0 || strcasecmp($dir1, "save")==0)
      continue;

   $fulldir = $fileinfo->getPathname();

   if (($now - $fileinfo->getMTime())>3600) { // more then an hour old
      remove_dir( $fulldir ); // local function
      rmdir( $fulldir );      // PHP native function
      $ndel++;
      continue;
   }

   $ext = pathinfo($dir1, PATHINFO_EXTENSION);
   if ($ext==='err')
      continue;

   $logfile = $fulldir.".error";
   if (file_exists($logfile)) { // already some error occured
      move_data_err($dir1);
      continue;
   }

   $fok = $fulldir."\\OK";
   if (!file_exists($fok)) {
      echo "$fok not found!\n";
      continue;
   }

   $frequest = $fulldir."\\REQUEST";
   if (!file_exists($frequest)) {
      echo "$frequest not found!\n";
      continue;
   }
   
   //echo "Processing $fulldir\n";

	try {
		$data = file_get_contents($frequest);
	}
	catch (Exception $e) {}

   unset($_REQUEST);
   $_REQUEST = unserialize($data);
   process_files();
   $nrec++;
   $ndata += strlen($data);
}
$db->Close(); // no more needed
generic_log("Nrec=$nrec, Ndata=$ndata, Ndel=$ndel");
exit();
//--------------------------------------
function respond($msg)
{
   // this function is different in taxinfo.php and taxinfoload.php
   save_log($msg);
}
//--------------------------------------
function generic_log($msg)
{
   if (($fp=@fopen($_SESSION['TAX_Catalog']."\\logfile.txt", "a"))===false)
      return;

   $line = date('Y-m-d H:i:s')." $msg\r\n";
   fwrite($fp,$line);
   fclose($fp);
}
//--------------------------------------
function remove_dir($dir1)
{
   $iterator = new DirectoryIterator($dir1);
   foreach ($iterator as $fileinfo) {
      if ($fileinfo->isFile()) {
         $path1=$fileinfo->getPathname() ;
         echo "About to unlink $path1\n";
         if (!unlink( $path1 )) {
            echo "Failed to unlink $path1\n";
         }
      }
   }
}
//--------------------------------------
function move_data_err($dir1)
{
   global $verbose;

   $err_dir = $_SESSION['TAX_Catalog']."\\err";
   if (!file_exists($err_dir)) {
      mkdir($err_dir);
      if (!file_exists($err_dir)) { // security
         return;
      }
   }

   $old_dir = $_SESSION['TAX_Catalog']."\\$dir1";
   $new_dir = $err_dir."\\${dir1}.err";
   if (!rename($old_dir, $new_dir)) {
      return;
   }
   else if ($verbose) {
      echo "Moved $old_dir into $new_dir\n";
   }

   $old_file = $old_dir.".error";
   $new_file = $new_dir."\\ERROR";
   if (rename($old_file, $new_file) && $verbose) {
      echo "Moved $old_file into $new_file\n";
   }
}
//--------------------------------------
function process_files()
{
   global $fulldir;

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

   // RUN program
   switch ($fu)
   {
   case 0:
      $ret=process_std();
      break;
   case 1:
      $ret=process_wmic();
      break;
   default:
      //echo "Undefined function $fu\n";
      $ret=false;
      break;
   }

   if ($ret) {
      unlink($fulldir."\\OK");
      unlink($fulldir."\\REQUEST");
      @unlink($fulldir."\\WMICFILE"); // maybe it does not exist
      rmdir($fulldir);
      //echo "UNLINK $fulldir\n";
   }
}
//--------------------------------------
function process_wmic()
{
   global $fulldir;
   $wmicfile = $fulldir."\\WMICFILE";

   if (($agentid=authenticate_user())===false) {
      return false;
   }

   if (!file_exists($wmicfile)) {
      return false;
   }

   if (($fp = @gzopen( $wmicfile, 'r'))===false) {
      return false;
   }
   $wmics=array();
   while (($sret=gzgets($fp))!==false) {
      $ar2=explode("\t", trim($sret)); // attention php syntax: \t must be in double quotes, not single
      array_unshift($ar2, '', '');
      $wmics[]=$ar2;
   }
   gzclose($fp);
   
   cleanup_log($agentid);

   return update_wmic($agentid, $wmics, false);
}
//--------------------------------------
?>