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

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


$autoMode = false;
if (!isset($argv[1]) || $argv[1] == "") :
   $isCron = false;
//   include_once ("../include/auth.inc.php");
   getSecHttpVars("1",array("f_act", "csId", "sendMode"));
   $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] != "") : $sendMode = $argv[3]; endif;
   endif;
endif;

// Error reporting
error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);

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

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


// START SCRIPT

// $path = getParameterValue("0", "PATH_DOCROOT", "0");
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);
$hq_id = "";

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


// Get jobs for auto_export
function getDoneJobsOfCustomer($csId) {
  global $db, $logFile;
  $retArray = array();

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

  $startTime = getDateTime("datetime_plus_offset", array(0,0,0,0,-($constAmStarttimeInDays),0), "Y-m-d") . " 00:00:00";
  $endTime =   getDateTime("datetime_plus_offset", array(0,0,0,0,-1,0), "Y-m-d") . " 23:59:59";
  // $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,"
            . "       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"
            . " 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_export'"
            . "                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_finishtime >= '" . $startTime . "'     AND"
            . "       jb.jb_finishtime <= '" . $endTime . "'       AND"
            . "       (ISNULL(jb.jb_storno) OR jb.jb_storno = '0') AND"
            . "       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_EXPORTED') :
           $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"];
           endfor;
        endif;
  endwhile;
  $result->free();
  return $retArray;
} 


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_URL, $requestConfigArray["CURLOPT_URL"]);
     curl_setopt($ch, CURLOPT_PUT, true);
     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"]);

     $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, $jbArr) {
	global $logFile, $sendMode;

  $retVal = "ERR:NO_CONNECT";
  if ($sendMode == "") : $sendMode = "FILE::CSV"; endif;
  
  $requestConfigArray = array();
  if (function_exists("sendResponse")) :
     $requestConfigArray = sendResponse($stateEvent, $timestamp, $jbArr);
  endif;
  $requestConfigArrayLen = count($requestConfigArray);

/*
  if ($request != "") :
     $retVal = connectResponse($request);
  endif;
*/
  if ($requestConfigArrayLen > 0) :
     if ($sendMode == "FILE::CSV") :
        $retVal = curl_put($requestConfigArray);
     endif;
     if ($sendMode == "REST::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_EXPORT_INCLUDE_FILENAME_SUFFIX_CS_" . $csId, "0");
   if ($getIncludeFileNameSuffix == "") : $getIncludeFileNameSuffix = $csId; endif;
   include ("../tools/auto_export_" . $getIncludeFileNameSuffix . ".php");


   if ($csId != "" && is_numeric($csId)) :

      // Set execution time for keepalive
      $currentTime = getDateTime("0");
      // updateStmt("keepalive", "ka_process", "autoexport", array("ka_lastexecutiontime", $currentTime),"");

      // ********************************
      // *** Send mails automatically ***
      // ********************************

      // $constAutoExportEnabled = getParameterValue("0", "AUTO_EXPORT_ENABLED", "0");
      $constAutoExportEnabled = "1";
      if ($constAutoExportEnabled == '1') :

         $jbArr = getDoneJobsOfCustomer($csId);
         $jbkArr = array_keys($jbArr);
         $jbkArrLen = count($jbkArr);

         // [1.] Iterate jobs for generating export file
         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, $jbArr);  // Call interface function
             endif;

             
             // Check success of operation
             $gdcContext = "JOB_EXPORTED";
             if (substr($response,0,4) == "ERR:") :
                $gdcContext = "JOB_EXPORT_FAILED";
             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_export'");
             else :
                insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbId, "gdc_gen_fieldname", "auto_export", "gdc_content", $gdcContent, "gdc_context", $gdcContext));
             endif;

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


         // [2.] Send process
         
         
         // [3.] Iterate jobs for generating "JOB_EXPORTED" state
         
         
      endif;  // AUTO_EXPORT_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_EXPORT_INCLUDE_FILENAME_SUFFIX_CS_" . $csId, "0");

[3.] Add customer call in CRON list

*/
?>
