<?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 = "";

$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;
  $retArray = array();

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

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

  $fieldClause = "";
  if ($sendSign) :
     $fieldClause .= ", tr1.tr_sign AS tr1_sign, tr2.tr_sign AS tr2_sign, tr3.tr_sign AS tr3_sign, tr4.tr_sign AS tr4_sign, tr5.tr_sign AS tr5_sign,"
                   . "  tr6.tr_sign AS tr6_sign, tr7.tr_sign AS tr7_sign, tr8.tr_sign AS tr8_sign, tr9.tr_sign AS tr9_signname";
  else :
     $fieldClause .= ", '' AS tr1_sign, '' AS tr2_sign, '' AS tr3_sign, '' AS tr4_sign, '' AS tr5_sign, '' AS tr6_sign, '' AS tr7_sign, '' AS tr8_sign, '' AS tr9_signname";
  endif;

  // 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,"
            . "       tr1.tr_status AS tr1_status, tr2.tr_status AS tr2_status, tr3.tr_status AS tr3_status, tr4.tr_status AS tr4_status, tr5.tr_status AS tr5_status,"
            . "       tr6.tr_status AS tr6_status, tr7.tr_status AS tr7_status, tr8.tr_status AS tr8_status, tr9.tr_status AS tr9_status,"
            . "       tr1.tr_finishtime AS tr1_finishtime, tr2.tr_finishtime AS tr2_finishtime, tr3.tr_finishtime AS tr3_finishtime, tr4.tr_finishtime AS tr4_finishtime, tr5.tr_finishtime AS tr5_finishtime,"
            . "       tr6.tr_finishtime AS tr6_finishtime, tr7.tr_finishtime AS tr7_finishtime, tr8.tr_finishtime AS tr8_finishtime, tr9.tr_finishtime AS tr9_finishtime,"
            . "       tr1.tr_signname AS tr1_signname, tr2.tr_signname AS tr2_signname, tr3.tr_signname AS tr3_signname, tr4.tr_signname AS tr4_signname, tr5.tr_signname AS tr5_signname,"
            . "       tr6.tr_signname AS tr6_signname, tr7.tr_signname AS tr7_signname, tr8.tr_signname AS tr8_signname, tr9.tr_signname AS tr9_signname"
            .         $fieldClause
            . " FROM job AS jb LEFT JOIN tour AS tr1 ON tr1.jb_id = jb.jb_id AND tr1.tr_sort = '1'"
            . "                LEFT JOIN tour AS tr2 ON tr2.jb_id = jb.jb_id AND tr2.tr_sort = '2'"
            . "                LEFT JOIN tour AS tr3 ON tr3.jb_id = jb.jb_id AND tr3.tr_sort = '3'"
            . "                LEFT JOIN tour AS tr4 ON tr4.jb_id = jb.jb_id AND tr4.tr_sort = '4'"
            . "                LEFT JOIN tour AS tr5 ON tr5.jb_id = jb.jb_id AND tr5.tr_sort = '5'"
            . "                LEFT JOIN tour AS tr6 ON tr6.jb_id = jb.jb_id AND tr6.tr_sort = '6'"
            . "                LEFT JOIN tour AS tr7 ON tr7.jb_id = jb.jb_id AND tr7.tr_sort = '7'"
            . "                LEFT JOIN tour AS tr8 ON tr8.jb_id = jb.jb_id AND tr8.tr_sort = '8'"
            . "                LEFT JOIN tour AS tr9 ON tr9.jb_id = jb.jb_id AND tr9.tr_sort = '9'"
            . "                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";

  $result = $db->query($sqlquery);
  // $result = $db->query($sqlquery . " UNION " . $sqlquery2);
  if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
  while ($row = $result->fetch_assoc()):
        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 <= 9; $i++) :                
               $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
 * @param string $url to request
 * @param array $post values to send
 * @param array $options for cURL
 * @return string
 */
/*
function curl_post($url, array $post = NULL, array $options = array())
{
    $defaults = array(
        CURLOPT_POST => 1,
        CURLOPT_HEADER => 0,
        CURLOPT_URL => $url,
        CURLOPT_FRESH_CONNECT => 1,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_FORBID_REUSE => 1,
        CURLOPT_TIMEOUT => 4,
        CURLOPT_POSTFIELDS => http_build_query($post)
    );

    $ch = curl_init();
    curl_setopt_array($ch, ($options + $defaults));
    if( ! $result = curl_exec($ch))
    {
        trigger_error(curl_error($ch));
    }
    curl_close($ch);
    return $result;
}
*/

/**
 * Send a GET requst using cURL
 * @param string $url to request
 * @param array $get values to send
 * @param array $options for cURL
 * @return string
 */
/*
function curl_get($url, array $get = NULL, array $options = array())
{   
    $defaults = array(
        CURLOPT_URL => $url. (strpos($url, '?') === FALSE ? '?' : ''). http_build_query($get),
        CURLOPT_HEADER => 0,
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_TIMEOUT => 4
    );
   
    $ch = curl_init();
    curl_setopt_array($ch, ($options + $defaults));
    if( ! $result = curl_exec($ch))
    {
        trigger_error(curl_error($ch));
    }
    curl_close($ch);
    return $result;
} 
*/

function curl_put($requestConfigArray) {
	global $logFile;

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

  if ($requestConfigArrayLen > 0) :

     $ch = curl_init();
/*  
     // [1.]
     curl_setopt($ch, CURLOPT_URL, $requestConfigArray["CURLOPT_URL"]);
     // curl_setopt($ch, CURLOPT_USERAGENT, $requestConfigArray["CURLOPT_USERAGENT"]);
     curl_setopt($ch, CURLOPT_HTTPHEADER, $requestConfigArray["CURLOPT_HTTPHEADER"]);
     // curl_setopt($ch, CURLOPT_VERBOSE, $requestConfigArray["CURLOPT_VERBOSE"]);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, $requestConfigArray["CURLOPT_RETURNTRANSFER"]);
     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $requestConfigArray["CURLOPT_CUSTOMREQUEST"]); 
     curl_setopt($ch, CURLOPT_POSTFIELDS, $requestConfigArray["CURLOPT_POSTFIELDS"]);
     // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $requestConfigArray["CURLOPT_SSL_VERIFYPEER"]);
     // curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $requestConfigArray["CURLOPT_FOLLOWLOCATION"]);
     // curl_setopt($ch, CURLOPT_MAXREDIRS, $requestConfigArray["CURLOPT_MAXREDIRS"]);
     // curl_setopt($ch, CURLOPT_PUT, $requestConfigArray["CURLOPT_PUT"]);
     // curl_setopt($ch, CURLINFO_HEADER_OUT, "1");

     // [2.]
     $fp = fopen('php://temp/maxmemory:256000', 'w');
     if (!$fp) { die('could not open temp memory data'); }
     fwrite($fp, $requestConfigArray["CURLOPT_INFILE"]);
     fseek($fp, 0); 
     curl_setopt($ch, CURLOPT_URL, $requestConfigArray["CURLOPT_URL"]);
     curl_setopt($ch, CURLOPT_USERAGENT, $requestConfigArray["CURLOPT_USERAGENT"]);
     curl_setopt($ch, CURLOPT_HTTPHEADER, $requestConfigArray["CURLOPT_HTTPHEADER"]);
     // curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $requestConfigArray["CURLOPT_CUSTOMREQUEST"]); 
     curl_setopt($ch, CURLOPT_PUT, $requestConfigArray["CURLOPT_PUT"]);
     // curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
     curl_setopt($ch, CURLOPT_INFILE, $fp); // file pointer
     // curl_setopt($ch, CURLOPT_INFILE, $requestConfigArray["CURLOPT_INFILE"]);
     curl_setopt($ch, CURLOPT_INFILESIZE, $requestConfigArray["CURLOPT_INFILESIZE"]); 
*/
     // [3.]
     $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);
     // curl_setopt($session, CURLOPT_USERPWD, $username.":".$password );  // Authenticate the user using basic auth $username and $password
     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, $tr1CommissionNo = "", $crId = "", $crSid = "", $trSignName, $trSign, $gdc_01 = "", $gdc_02 = "", $gdc_03 = "", $gdc_04 = "", $gdc_05 = "") {
	global $logFile, $sendMode;

  $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);
     $requestConfigArray = sendResponse($stateEvent, $timestamp, $tr1CommissionNo, $crId, $crSid, $trSignName, $trSign, $gdc_01, $gdc_02, $gdc_03, $gdc_04, $gdc_05);     
  endif;
  $requestConfigArrayLen = count($requestConfigArray);

/*
  if ($request != "") :
     $retVal = connectResponse($request);
  endif;
*/
  if ($requestConfigArrayLen > 0) :
     if ($sendMode == "PUT") :
        $retVal = curl_put($requestConfigArray);
     endif;
  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, $tr1CommissionNo, $crId, $crSid, "", "", $gdc_01, $gdc_02, $gdc_03, $gdc_04, $gdc_05);  // "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 < $trSortMaxVal) :
                          $response = sendResponseInterface("1", $jbArr[$jbId]["tr" . $j . "_finishtime"], $tr1CommissionNo, $crId, $crSid, $jbArr[$jbId]["tr" . $j . "_signname"], $encodedSign, $gdc_01, $gdc_02, $gdc_03, $gdc_04, $gdc_05);  // "0" <=> "PICKUP"
                       else :
                          $response = sendResponseInterface("2", $jbArr[$jbId]["tr" . $j . "_finishtime"], $tr1CommissionNo, $crId, $crSid, $jbArr[$jbId]["tr" . $j . "_signname"], $encodedSign, $gdc_01, $gdc_02, $gdc_03, $gdc_04, $gdc_05);  // "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;
   
             writeToFile($logFile, "JOB=" . $jbId . "|STATION_BINDEC=" . $gdcContent . "|DATETIME=" . $currentTime);
             if ($response != "") :
                writeToFile($logFile, $response);
             endif;
             writeToFile($logFile, "-------------------------------------------------------------------------------------------------------------------");
         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

*/
?>
