<?php
/*=======================================================================
 *
 * auto_response.php
 *
 * Autor: Marc Vollmann
 *
  =======================================================================*/

error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);

include_once ("../include/mcglobal.inc.php");
include_once ("../include/inc_file.inc.php");
include_once ("../include/image.inc.php");


$autoMode = false;
if (!isset($argv[1]) || $argv[1] == "") :
   $isCron = false;
//   include_once ("../include/auth.inc.php");
   getSecHttpVars("1",array("f_act", "csId"));
   $autoMode = true;
//   $usrAccessArray["hq"] = "1"; $usrAccessArray["cs"] = "1";
//   authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
//   authCheckEmployeeRights($emp_id, "1", "1");
else :
   // Init parameters
   $f_act = ""; $title = ""; 

   $isCron = true;
   if ($argv[1] == "acapella7890") : $autoMode = true; endif;
   if ($autoMode) :
      if (isset($argv[2]) && $argv[2] != "") : $csId = $argv[2]; endif;
   endif;
endif;


// Set timezone
// date_default_timezone_set('Europe/Berlin');

// Execution-Time for script
set_time_limit(240);


// START SCRIPT

$path = getAbsoluteSystemPath();
$systemPath = "..";
$tmpSignPath = "../temp/signs/";
$hq_id = "";
$numOfStations = 30;

$logFile = getParameterValue("0", "AUTO_RESPONSE_LOGFILE", "0");
if ($logFile == "") : $logFile = "../log/auto_response.log"; endif;


// Get jobs for auto_response
function getOpenJobsOfCustomer($csId, $sendSign) {
  global $db, $logFile, $numOfStations;
  $retArray = array();

  // $constAmStarttimeInDays = getParameterValue("0", "AUTO_RESPONSE_STARTTIME_IN_DAYS", "0");  // "Meta-Global" <=> hq_id = 0
  $constAmStarttimeInDays = 3;

  $startTime = getDateTime("datetime_plus_offset", array(0,0,0,0,-($constAmStarttimeInDays),0), "Y-m-d H:i:s");
  // $currentTime = getDateTime("0");


  // Get jobs of the specified customer
  $sqlquery = "SELECT jb.jb_id, jb.jb_status, jb.cr_id, jb.cr_sid, jb.hq_id, tr1.tr_commission_no, gdc.gdc_content, gdc.gdc_context,"
            . "       gdc_info_0.gdc_content AS gdc_info_0_content, gdc_info_1.gdc_content AS gdc_info_1_content, gdc_info_2.gdc_content AS gdc_info_2_content,"
            . "       gdc_info_3.gdc_content AS gdc_info_3_content, gdc_info_4.gdc_content AS gdc_info_4_content,";            
  for ($i = 1; $i <= $numOfStations; $i++) :
      $sqlquery .= "  tr" . $i . ".tr_id AS tr" . $i . "_id, tr" . $i . ".tr_status AS tr" . $i . "_status, "
                 . "  tr" . $i . ".tr_finishtime AS tr" . $i . "_finishtime, tr" . $i . ".tr_signname AS tr" . $i . "_signname, ";
      if ($sendSign) :
          $sqlquery .= " tr" . $i . ".tr_sign AS tr" . $i . "_sign";
      else :
          $sqlquery .= " '' AS tr" . $i . "_sign";
      endif;
      if ($i < $numOfStations) :
         $sqlquery .= ",";
      endif;
  endfor;
  $sqlquery .= " FROM job AS jb ";
  for ($i = 1; $i <= $numOfStations; $i++) :
      $sqlquery .= "      LEFT JOIN tour AS tr" . $i . " ON tr" . $i . ".jb_id = jb.jb_id AND tr" . $i . ".tr_sort = '" . $i . "'";
  endfor;
  $sqlquery .= "          LEFT JOIN genericdatacontainer AS gdc ON gdc.gdc_obj_id = jb.jb_id AND gdc.gdc_obj_type = 'jb' AND gdc.gdc_gen_fieldname = 'auto_response'"
             . "          LEFT JOIN genericdatacontainer AS gdc_info_0 ON gdc_info_0.gdc_obj_id = jb.jb_id AND gdc_info_0.gdc_obj_type = 'jb' AND gdc_info_0.gdc_gen_fieldname = 'info_0'"
             . "          LEFT JOIN genericdatacontainer AS gdc_info_1 ON gdc_info_1.gdc_obj_id = jb.jb_id AND gdc_info_1.gdc_obj_type = 'jb' AND gdc_info_1.gdc_gen_fieldname = 'info_1'"
             . "          LEFT JOIN genericdatacontainer AS gdc_info_2 ON gdc_info_2.gdc_obj_id = jb.jb_id AND gdc_info_2.gdc_obj_type = 'jb' AND gdc_info_2.gdc_gen_fieldname = 'info_2'"
             . "          LEFT JOIN genericdatacontainer AS gdc_info_3 ON gdc_info_3.gdc_obj_id = jb.jb_id AND gdc_info_3.gdc_obj_type = 'jb' AND gdc_info_3.gdc_gen_fieldname = 'info_3'"
             . "          LEFT JOIN genericdatacontainer AS gdc_info_4 ON gdc_info_4.gdc_obj_id = jb.jb_id AND gdc_info_4.gdc_obj_type = 'jb' AND gdc_info_4.gdc_gen_fieldname = 'info_4',"
             . "       costcenter AS csc, customer AS cs, employee AS emp, user AS usr"
             . " WHERE jb.jb_ordertime > '" . $startTime . "'       AND"
             . "       (ISNULL(jb.jb_storno) OR jb.jb_storno = '0') AND"
             . "       (jb.jb_status = '1' OR jb.jb_status = '2')   AND"
             . "       jb.jb_offer = '0'                            AND"
             . "       jb.csc_id_payer = csc.csc_id                 AND"
             . "       csc.cs_id = cs.cs_id                         AND"
             . "       cs.cs_id = '" . $csId . "'                   AND"
             . "       cs.cs_admin = emp.emp_id                     AND"
             . "       emp.usr_id = usr.usr_id"
             . " ORDER BY jb.jb_finishtime";
// echo $sqlquery . "<br><br>\n\n"; die();
  $result = $db->query($sqlquery);
  // $result = $db->query($sqlquery . " UNION " . $sqlquery2);
  if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
  while ($row = $result->fetchRow()):
        if ($row["gdc_context"] != 'JOB_DONE') :
           $retArray[$row["jb_id"]]["jb_status"]          = $row["jb_status"];
           $retArray[$row["jb_id"]]["tr_commission_no"]   = $row["tr_commission_no"];
           $retArray[$row["jb_id"]]["cr_id"]              = $row["cr_id"];
           $retArray[$row["jb_id"]]["cr_sid"]             = $row["cr_sid"];
           $retArray[$row["jb_id"]]["hq_id"]              = $row["hq_id"];
           $retArray[$row["jb_id"]]["gdc_content"]        = $row["gdc_content"];
           $retArray[$row["jb_id"]]["gdc_context"]        = $row["gdc_context"];
           $retArray[$row["jb_id"]]["gdc_info_0_content"] = $row["gdc_info_0_content"];
           $retArray[$row["jb_id"]]["gdc_info_1_content"] = $row["gdc_info_1_content"];
           $retArray[$row["jb_id"]]["gdc_info_2_content"] = $row["gdc_info_2_content"];
           $retArray[$row["jb_id"]]["gdc_info_3_content"] = $row["gdc_info_3_content"];
           $retArray[$row["jb_id"]]["gdc_info_4_content"] = $row["gdc_info_4_content"];
           for ($i = 1; $i <= $numOfStations; $i++) :
               $retArray[$row["jb_id"]]["tr" . $i . "_id"] = $row["tr" . $i . "_id"];
               $retArray[$row["jb_id"]]["tr" . $i . "_status"] = $row["tr" . $i . "_status"];
               $retArray[$row["jb_id"]]["tr" . $i . "_finishtime"] = $row["tr" . $i . "_finishtime"];
               $retArray[$row["jb_id"]]["tr" . $i . "_signname"] = $row["tr" . $i . "_signname"];
               $retArray[$row["jb_id"]]["tr" . $i . "_sign"] = $row["tr" . $i . "_sign"];
           endfor;
        endif;
  endwhile;
  $result->free();
  return $retArray;
} 


function array_to_json( $array ){

    if( !is_array( $array ) ){
        return false;
    }

    $associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
    if( $associative ){

        $construct = array();
        foreach( $array as $key => $value ){

            // We first copy each key/value pair into a staging array,
            // formatting each key and value properly as we go.

            // Format the key:
            if( is_numeric($key) ){
                $key = "key_$key";
            }
            $key = '"'.addslashes($key).'"';

            // Format the value:
            if( is_array( $value )){
                $value = array_to_json( $value );
            } else if( !is_numeric( $value ) || is_string( $value ) ){
                $value = '"'.addslashes($value).'"';
            }

            // Add to staging array:
            $construct[] = "$key: $value";
        }

        // Then we collapse the staging array into the JSON form:
        $result = "{ " . implode( ", ", $construct ) . " }";

    } else { // If the array is a vector (not associative):

        $construct = array();
        foreach( $array as $value ){

            // Format the value:
            if( is_array( $value )){
                $value = array_to_json( $value );
            } else if( !is_numeric( $value ) || is_string( $value ) ){
                $value = '"'.addslashes($value).'"';
            }

            // Add to staging array:
            $construct[] = $value;
        }

        // Then we collapse the staging array into the JSON form:
        $result = "[ " . implode( ", ", $construct ) . " ]";
    }

    return $result;
}


/**
 * Send a POST requst using cURL
 */
function curl_post($requestConfigArray) {
	global $logFile;

  $logDebug = true;
  if ($logDebug) :
     writeToFile($logFile, $requestConfigArray["CURLOPT_URL"]);
     // writeToFile($logFile, $requestConfigArray["CURLOPT_USERPWD"]);
     writeToFile($logFile, "REQUEST:");
     writeToFile($logFile, $requestConfigArray["CURLOPT_POSTFIELDS"]);
     // writeToFile($logFile, "------------------------------------------------------------------------------------");
  endif;

  $result = "ERR:NO_CURL_DATA";

  if ($requestConfigArray["CURLOPT_URL"] != "" && $requestConfigArray["CURLOPT_POSTFIELDS"] != "") :

     $headers = array(
                  "Content-type: application/json;charset=\"utf-8\"",
                  "Accept: application/json",
                  "Cache-Control: no-cache",
                  "Pragma: no-cache",
                  "Content-length: " . strlen($requestConfigArray["CURLOPT_POSTFIELDS"]),
              );

     // PHP cURL  for https connection with auth
     $ch = curl_init();

     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
     curl_setopt($ch, CURLOPT_URL, $requestConfigArray["CURLOPT_URL"]);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, $requestConfigArray["CURLOPT_RETURNTRANSFER"]);
     if ($requestConfigArray["CURLOPT_USERPWD"] != "") :
        curl_setopt($ch, CURLOPT_USERPWD, $requestConfigArray["CURLOPT_USERPWD"]);  // Authenticate the user using basic auth $username and $password
     endif;
     curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
     curl_setopt($ch, CURLOPT_TIMEOUT, 300);
     curl_setopt($ch, CURLOPT_POST, true);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $requestConfigArray["CURLOPT_POSTFIELDS"]); // The SOAP request
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
     if ($logDebug) :
        // curl_setopt($ch, CURLINFO_HEADER_OUT, true);
     endif;

     // converting
     $result = curl_exec($ch); 

     $errNo = curl_errno($ch);
     $errMsg = curl_error($ch);
     $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);     

     if ($logDebug) :
        writeToFile($logFile, "RESPONSE:");
        writeToFile($logFile, $result);
        writeToFile($logFile, "HTTP-STATUS: " . $httpStatus);
        writeToFile($logFile, "------------------------------------------------------------------------------------");
     endif;

     // fclose($fh);
     curl_close($ch);

     return $result;
  endif;
}

/**
 * Send a GET requst using cURL
 */
function curl_get($requestConfigArray) {
	global $logFile;

  $result = "ERR:NO_CURL_DATA";
  $requestConfigArrayLen = count($requestConfigArray);

  writeToFile($logFile, $requestConfigArray["CURLOPT_URL"]);

  if ($requestConfigArrayLen > 0) :

     $ch = curl_init();

     curl_setopt($ch, CURLOPT_URL, $requestConfigArray["CURLOPT_URL"]);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, $requestConfigArray["CURLOPT_RETURNTRANSFER"]);

     $result = curl_exec($ch);

     $errNo = curl_errno($ch);
     $errMsg = curl_error($ch);
     $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     writeToFile($logFile, "HTTP : " . $httpStatus);

     curl_close($ch);

     if ($errNo != "" && $errNo != "0") :
        $result = "ERR:" . $errNo . ":" . $errMsg;
     else :
        $result = "OK:" . $errNo . ":" . $errMsg;
     endif;
  endif;
  return $result;
} 

/**
 * Send a PUT requst using cURL
 */
function curl_put($requestConfigArray) {
	global $logFile;

  $result = "ERR:NO_CURL_DATA";
  $requestConfigArrayLen = count($requestConfigArray);

  if ($requestConfigArrayLen > 0) :

     $ch = curl_init();
     $fh = tmpfile();
     fwrite($fh, $requestConfigArray["CURLOPT_POSTFIELDS"]);
     fseek($fh, 0);
     curl_setopt($ch, CURLOPT_HTTPHEADER, $requestConfigArray["CURLOPT_HTTPHEADER"]);
     // curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
     // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     // curl_setopt($ch, CURLOPT_HEADER, true);  // Do you want CURL to output the headers? Set to FALSE to hide them
     curl_setopt($ch, CURLOPT_URL, $requestConfigArray["CURLOPT_URL"]);
     curl_setopt($ch, CURLOPT_PUT, true);
     if ($requestConfigArray["CURLOPT_USERPWD"] != "") :
        curl_setopt($session, CURLOPT_USERPWD, $requestConfigArray["CURLOPT_USERPWD"]);  // Authenticate the user using basic auth $username and $password
     endif;
     curl_setopt($ch, CURLOPT_INFILE, $fh);
     curl_setopt($ch, CURLOPT_INFILESIZE, strlen($requestConfigArray["CURLOPT_POSTFIELDS"]));


     writeToFile($logFile, $requestConfigArray["CURLOPT_URL"]);
     writeToFile($logFile, $requestConfigArray["CURLOPT_HTTPHEADER"][0]);
     writeToFile($logFile, $requestConfigArray["CURLOPT_HTTPHEADER"][1]);
     writeToFile($logFile, $requestConfigArray["CURLOPT_HTTPHEADER"][2]);
     writeToFile($logFile, $requestConfigArray["CURLOPT_POSTFIELDS"]);
     // writeToFile($logFile, $requestConfigArray["CURLOPT_INFILE"]);

     $result = curl_exec($ch);
     $errNo = curl_errno($ch);
     $errMsg = curl_error($ch);
     $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     writeToFile($logFile, "HTTP : " . $httpStatus);

     fclose($fh);
     curl_close($ch);

     if ($errNo != "" && $errNo != "0") :
        $result = "ERR:" . $errNo . ":" . $errMsg;
     else :
        $result = "OK:" . $errNo . ":" . $errMsg;
     endif;
  endif;

  return $result;
}


function connectResponse($completeReq) {
  global $server, $port, $logFile;
  $response = "ERR:NO_SERVER";
  $errno = "";
  $errstr = "";
  $fp = fsockopen($server, substr($port, 1), $errno, $errstr, 10);
  if ($server != "") :
     if (!$fp) {
         $response = "ERR: $errstr ($errno)";
     } else {
         fputs($fp, $completeReq);
         if (fflush($fp)) :
             // Read header
             $httpHeader = "";
             $httpBodyLength = 0;
             if (!feof($fp)) :
                 $line = trim(fgets($fp, 1024));
                 $httpHeader .= trim($line);
                 while (!feof($fp) && $line != "") {
                     $line = trim(fgets($fp, 1024));
                     $httpHeader .= $line;
                     if (!(strpos($line, "Content-Length: ") === FALSE)) :
                         $httpBodyLength = trim(substr($line, 16));
                     endif;
                 }
             endif;
             // writeLocatingLog($logFile, "::: " . $httpHeader . "\r\n");
             // writeLocatingLog($logFile, "::: " . $httpBodyLength . "\r\n");
             $count = 0;
             while (!feof($fp) && $count < $httpBodyLength) {
                 $line = trim(fgets($fp, 2));
                 $response .= $line;
                 $count++;
             }
         // writeLocatingLog($logFile, ":# Loops: " . $count . "\r\n");
         else :
             $response = "ERR: " . $errno . " " . $errstr;
         endif;
         fclose($fp);
     }
  endif;
  return $response;
}


// Interface for function defined in included file accorting to customer ID
function sendResponseInterface($stateEvent, $timestamp, $jbId, $trId, $trSort, $tr1CommissionNo = "", $crId = "", $crSid = "", $trSignName, $trSign, $gdc_01 = "", $gdc_02 = "", $gdc_03 = "", $gdc_04 = "", $gdc_05 = "") {
	global $logFile, $sendMode;

if ($jbId == "19656841") :    
   echo "-------------\n";
   echo "stateEvent = " . $stateEvent . "\n";
   echo "jbId = " . $jbId . "\n";
   echo "trId = " . $trId . "\n";
   echo "trSort = " . $trSort . "\n";
   echo "tr1CommissionNo = " . $tr1CommissionNo . "\n";
   echo "crId = " . $crId . "\n";
   echo "crSid = " . $crSid . "\n";
   echo "gdc_01 = " . $gdc_01 . "\n";
   echo "gdc_02 = " . $gdc_02 . "\n";
   echo "gdc_03 = " . $gdc_03 . "\n";
   echo "gdc_04 = " . $gdc_04 . "\n";
   echo "-------------\n";
endif;

  $retVal = "ERR:NO_CONNECT";
  if ($sendMode == "") : $sendMode = "PUT"; endif;
  
  $requestConfigArray = array();
  if (function_exists("sendResponse")) :
     // $request = sendResponse($stateEvent, $timestamp, $tr1CommissionNo, $gdc_01, $gdc_02, $gdc_03, $gdc_04, $gdc_05);
if ($jbId == "19656841") :    
echo "BEFORE! \n";
endif;
     $requestConfigArray = sendResponse($stateEvent, $timestamp, $jbId, $trId, $trSort, $tr1CommissionNo, $crId, $crSid, $trSignName, $trSign, $gdc_01, $gdc_02, $gdc_03, $gdc_04, $gdc_05);     
if ($jbId == "19656841") :    
echo "AFTER! \n";
endif;
  endif;
  $requestConfigArrayLen = count($requestConfigArray);

/*
  if ($request != "") :
     $retVal = connectResponse($request);
  endif;
*/
  if ($requestConfigArrayLen > 0) :
     if ($sendMode == "GET") :
        $retVal = curl_get($requestConfigArray);
     endif;
     if ($sendMode == "POST") :
        $retVal = curl_post($requestConfigArray);
     endif;
     if ($sendMode == "PUT") :
        $retVal = curl_put($requestConfigArray);
     endif;
     if ($sendMode == "EXTERNAL") :
        $retVal = $requestConfigArray["SEND_STATE"];
     endif;
  endif;
if ($jbId == "19656841") :    
   echo "retVal = " . $retVal . "\n";
endif;
  return $retVal;
}



// Get script name of the requested customer
if ($csId != "" && is_numeric($csId) && $csId > "0") :
   
   // Include special function for the customer
   $getIncludeFileNameSuffix = getParameterValue("0", "AUTO_RESPONSE_INCLUDE_FILENAME_SUFFIX_CS_" . $csId, "0");
   if ($getIncludeFileNameSuffix == "") : $getIncludeFileNameSuffix = $csId; endif;
   include ("../tools/auto_response_" . $getIncludeFileNameSuffix . ".php");
   
   // Get configuration parameters of the customer
   $sendSign = false;
   $parAutoResponseParameterArray = array();
   $parAutoResponseParameters = getParameterValue("0", "AUTO_RESPONSE_PARAMETERS_CS_" . $csId, "0");  // E.g. "1,0,0,1,...." <=> "par1_enabled,par2_disabled,par3_disabled,...." <=> "Send_sign_enabled,...."
   if ($parAutoResponseParameters != "") :
      $parAutoResponseParameterArray = spliti(",", $parAutoResponseParameters);
      if ($parAutoResponseParameterArray[0] == "1") :
         $sendSign = true;
      endif;
   endif;


   if ($csId != "" && is_numeric($csId)) :
   
      // Set execution time for keepalive
      $currentTime = getDateTime("0");
      // updateStmt("keepalive", "ka_process", "automailer", array("ka_lastexecutiontime", $currentTime),"");
         
      // ********************************
      // *** Send mails automatically ***
      // ********************************
   
      // $constAutoResponseEnabled = getParameterValue("0", "AUTO_RESPONSE_ENABLED", "0");
      $constAutoResponseEnabled = "1";
      if ($constAutoResponseEnabled == '1') :

         $jbArr = getOpenJobsOfCustomer($csId, $sendSign);
         $jbkArr = array_keys($jbArr);
         $jbkArrLen = count($jbkArr);

         for ($i = 0; $i < $jbkArrLen; $i++) :

             $jbId = $jbkArr[$i];
             $trSortMaxVal = getMaxOfField("tour", "tr_sort", "jb_id = '" . $jbId . "'");            

             $gdcContent = $jbArr[$jbId]["gdc_content"];
             $gdcContext = $jbArr[$jbId]["gdc_context"];

             $crId = $jbArr[$jbId]["cr_id"];
             $crSid = $jbArr[$jbId]["cr_sid"];
             $tr1CommissionNo = $jbArr[$jbId]["tr_commission_no"];
             // $gdc_01 = $jbArr[$jbId]["gdc_info_0_content"];
             // $gdc_02 = $jbArr[$jbId]["gdc_info_1_content"];
             // $gdc_03 = $jbArr[$jbId]["gdc_info_2_content"];
             // $gdc_04 = $jbArr[$jbId]["gdc_info_3_content"];
             // $gdc_05 = $jbArr[$jbId]["gdc_info_4_content"];

             $gdcEntryExists = false;
             if ($gdcContent != "") :
                 $gdcEntryExists = true;
             else : 
                 $gdcContent = 0;
                 $response = sendResponseInterface("0", $currentTime, $jbId, "", "", $tr1CommissionNo, $crId, $crSid, "", "", $jbArr[$jbId]["gdc_info_0_content"], $jbArr[$jbId]["gdc_info_1_content"], $jbArr[$jbId]["gdc_info_2_content"], $jbArr[$jbId]["gdc_info_3_content"], $jbArr[$jbId]["gdc_info_4_content"]);  // "0" <=> "ACCEPT"
             endif;

             // Iterate stations, generate bit representation for done job
             $bitString = "0";  // First bit has no representation of tr_sort, because tr_sort starts with "1"
             for ($j = 1; $j <= $trSortMaxVal; $j++) :
                 $bitString = "1" . $bitString;  // Generate bit string for complete job

                 // Pickup and delivery only
                 if ($gdcEntryExists) :

                    // If station is finished AND response has NOT(!) been sent then send !!!!
                    if ($jbArr[$jbId]["tr" . $j . "_status"] == "1" && ($gdcContent & (pow(2,$j))) == "0") :

                       // Encode sign
                       $encodedSign = $jbArr[$jbId]["tr" . $j . "_sign"];  // Init with NO encoding
                       if ($sendSign && $encodedSign != "") :

                          // Set unique image filename for the sign
                          $imgFilename = $jbId . "_" . $j . ".png";

                          // Generate image file
                          $tmpImg = saveImageToFile($encodedSign, $imgFilename, $systemPath);
                          
                          // Check for success generating the image file
                          if ($tmpImg == "") : 
                             $encodedSign = ""; 
                          else :
                             // Read image path, convert to base64 encoding
                             $encodedSign = base64_encode(file_get_contents($tmpSignPath . $imgFilename));
                          endif;

                          // Remove stored temporary images (signs) on the filesystem
                          if (file_exists($tmpSignPath . $imgFilename)) :
                             unlink($tmpSignPath . $imgFilename);
                          endif;
                       endif;

                       // Contact remote system
                       if ($j == 1) :
                          $response = sendResponseInterface("1", $jbArr[$jbId]["tr" . $j . "_finishtime"], $jbId, $jbArr[$jbId]["tr" . $j . "_id"], $j, $tr1CommissionNo, $crId, $crSid, $jbArr[$jbId]["tr" . $j . "_signname"], $encodedSign, $jbArr[$jbId]["gdc_info_0_content"], $jbArr[$jbId]["gdc_info_1_content"], $jbArr[$jbId]["gdc_info_2_content"], $jbArr[$jbId]["gdc_info_3_content"], $jbArr[$jbId]["gdc_info_4_content"]);  // "0" <=> "PICKUP"
                       else :
                          $response = sendResponseInterface("2", $jbArr[$jbId]["tr" . $j . "_finishtime"], $jbId, $jbArr[$jbId]["tr" . $j . "_id"], $j, $tr1CommissionNo, $crId, $crSid, $jbArr[$jbId]["tr" . $j . "_signname"], $encodedSign, $jbArr[$jbId]["gdc_info_0_content"], $jbArr[$jbId]["gdc_info_1_content"], $jbArr[$jbId]["gdc_info_2_content"], $jbArr[$jbId]["gdc_info_3_content"], $jbArr[$jbId]["gdc_info_4_content"]);  // "0" <=> "DELIVERY" (equals "JOB_DONE")
                       endif;

                       if (true || $sendResponseOk) :
                          $gdcContent = ($gdcContent | (pow(2,$j)));  // Add 
                       else :
                          // Try again later.... !!!!
                       endif;
                    endif;
                 endif;
             endfor;

             // Log response
             // $sendResponseOk = false;
             // if ($response == "OK") :
             //    $sendResponseOk = true;
             // endif;
             
             // Check success of operation
             if (substr($response,0,4) != "ERR:") :
                // Comparable bitstring for "JOB_DONE"
                $jbCompletedDecRepresentation = bindec($bitString);
                
                $jobCompleted = false;
                $gdcContext = "";
                if (($jbCompletedDecRepresentation & $gdcContent) == $jbCompletedDecRepresentation) :
                   $jobCompleted = true;
                   $gdcContext = "JOB_DONE";
                endif;
                
                if ($gdcEntryExists) :
                   updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_content", $gdcContent, "gdc_context", $gdcContext),"gdc_obj_id = '" . $jbId . "' AND gdc_gen_fieldname = 'auto_response'");
                else :
                   insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbId, "gdc_gen_fieldname", "auto_response", "gdc_content", $gdcContent, "gdc_context", $gdcContext));
                endif;
             endif;

             if ($response != "") :
                writeToFile($logFile, "JOB=" . $jbId . "|STATION_BINDEC=" . $gdcContent . "|DATETIME=" . $currentTime);
                writeToFile($logFile, $response);
                writeToFile($logFile, "-------------------------------------------------------------------------------------------------------------------");
             endif;
         endfor;  // Loop all jobs
      endif;  // AUTO_RESPONSE_ENABLED
   endif;
else :
     writeToFile($logFile, "ERR: UNKNOWN CUSTOMER" . " " . $csId);
     writeToFile($logFile, "-------------------------------------------------------------------------------------------------------------------");
endif;


/*

**** PROCEDURE INSERTION OF NEW CUSTOMER ****

[1.] Call special script "../sysadmin/mcInsertObjIntoMetaobjectInstance.php" to insert a new customer in meta objects 

[2.] Insert parameter for customer individual script file name suffix in table "parameter"
     $getIncludeFileNameSuffix = getParameterValue("0", "AUTO_RESPONSE_INCLUDE_FILENAME_SUFFIX_CS_" . $csId, "0");

[3.] Add customer call in CRON list

*/
?>
