<?php
/*=======================================================================
 *
 * auto_response_job_new.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", "jbId", "numOfCalls"));
   $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;
      if (isset($argv[3]) && $argv[3] != "") : $jbId = $argv[3]; endif;
      if (isset($argv[4]) && $argv[4] != "") : $numOfCalls = $argv[4]; endif;
   endif;
endif;

// Check num of calls
$maxNumOfCalls = 5;
if (!isset($numOfCalls) || $numOfCalls == "" || !is_numeric($numOfCalls)) :
   $numOfCalls = 1;
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_JOB_NEW_LOGFILE", "0");
if ($logFile == "") : $logFile = "../log/auto_response_job_new.log"; endif;


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

  // 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_job_new'"
             . "          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_id = '" . $jbId . "'                   AND"
             . "       (ISNULL(jb.jb_storno) OR jb.jb_storno = '0') 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";
// echo $sqlquery . "<br><br>"; die();
  $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_NEW_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;
} 


/**
 * Send a POST requst using cURL
 */
function curl_post($url, array $post = NULL, array $options = array()) {
  global $logFile;
  $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
 */
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();
/*  
     // [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);
     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;
}


// 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;

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

  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;
  endif;

  return $retVal;
}



// Get script name of the requested customer
if ($csId != "" && is_numeric($csId) && $csId > "0" && $jbId != "" && is_numeric($jbId) && $jbId > "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_job_new_" . $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;
   */
   $sendSign = false;


   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 = getNewJobOfCustomer($csId, $jbId);
         $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"];

             $response = sendResponseInterface("0", $currentTime, $jbId, "", "", $tr1CommissionNo, $crId, $crSid, "", "", $gdc_01, $gdc_02, $gdc_03, $gdc_04, $gdc_05);  // "0" <=> "STORED"

             // Check success of operation
             if (substr($response,0,4) != "ERR:") :

                $gdcContext = "JOB_NEW_DONE";
                
                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_job_new'");
                else :
                   insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbId, "gdc_gen_fieldname", "auto_response_job_new", "gdc_content", $gdcContent, "gdc_context", $gdcContext));
                endif;

                // Write "Accept" e.g. for "timematters" (!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!)
                if ($getIncludeFileNameSuffix == "timematters") :
                   insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbId, "gdc_gen_fieldname", "auto_response", "gdc_content", "0", "gdc_context", ""));
                endif;

                writeToFile($logFile, "CS=" . $csId . "|JB=" . $jbId . "|STATUS=OK|DATETIME=" . $currentTime);
             else :
                writeToFile($logFile, "CS=" . $csId . "|JB=" . $jbId . "|STATUS=NOT_OK|DATETIME=" . $currentTime);

                $errMsg = "Autoresponse failed after order request. Try again in 3 minutes automatically. ";
                sendInternalMail($errMsg . " [CS_ID:" . $csId . "] " . " [JB_ID:" . $jbId . "] ");

                sleep(180);

                // Call autoresponder for the new job if enabled for the customer
                $numOfCalls++;
                if ($numOfCalls <= $maxNumOfCalls) :
                   $cmd = "php " . $path . "/tools/auto_response_job_new.php acapella7890 " . $csId . " " . $jbIdNew . " " . $numOfCalls . " &";
                   system($cmd);
                else : 
                   $errMsg = "Autoresponse failed " . $maxNumOfCalls . " times after order request.";
                   sendInternalMail($errMsg . " [CS_ID:" . $csId . "] " . " [JB_ID:" . $jbId . "] ");
                endif;
             endif;
   
             if ($response != "") :
                writeToFile($logFile, $response);
             endif;
             writeToFile($logFile, "-------------------------------------------------------------------------------------------------------------------");
         endfor;  // Loop all jobs
      endif;  // AUTO_RESPONSE_ENABLED
   endif;
else :
     writeToFile($logFile, "ERR: UNKNOWN CUSTOMER OR JOB NOT SPECIFIED" . " [CS:" . $csId . "][JB: " . $jbId . "]");
     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

*/
?>
