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

include_once ("../include/mcglobal.inc.php");
include_once ("../include/image.inc.php");
include_once ('../include/email/htmlMimeMail.php');
include_once ("../include/inc_automailer.inc.php");


if (isRunning(5)):
  exit();
endif;

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

$logFile = getParameterValue("0", "AUTOMAILER_LOGFILE_5", "0");

$gdcCashpayerMailKey = "jb_cashpayer_mail";
$semaphorKey = "automailer5";
$semaphorLiveTime = 120;


// Endless loop
// while (TRUE):

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

  // ********************************
  // *** Send emails automatically ***
  // ********************************

  $constAutomailerEnabled = getParameterValue("0", "AUTOMAILER_ENABLED", "0");  // "Meta-Global" <=> hq_id = 0
  if ($constAutomailerEnabled == '1') :

     // Get next job(s) to send per mail to the customer
     $jobArray = getAutoMailerJobsGdc(1);

     // Loop all jobs (default one)
     $lenJobArray = count($jobArray);

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

         if ($i > 0) : sleep(1); endif;
         
         // Init for each job
         $jbMailAttachements = array();

         // Current job and mail address
         $job_id = $jobArray[$i][0];
         $f_email = trim($jobArray[$i][1]);
         $f_email = str_replace(" ", "", $f_email);
         $job_crSid = $jobArray[$i][2];
         $currentHqId = $jobArray[$i][3];
         $job_mode = $jobArray[$i][4];

         // Define constants
         $logFile = getParameterValue("0", "AUTOMAILER_LOGFILE_5", $currentHqId);
         if ($logFile == "") : $logFile = getParameterValue("0", "AUTOMAILER_LOGFILE_5", "0"); endif;
         $constMailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $currentHqId);

         // Set action parameters
         $f_act = "mailsend";
         $mailResult = FALSE;

         // Standalone process
         $automailer = "1";

         if ($job_id != "" && $f_email != "" && $currentHqId != "") :

            // The semaphore basically has to be generated by inserting a new job. 
            // Here the existence will be checked finally, but the code should not be executed (!!!!)
            if (!existsEntry("phoenix_log.semaphor",array("sp_obj_type","jb","sp_obj_id",$job_id,"sp_fieldname",$semaphorKey))) :
               insertStmt("phoenix_log.semaphor", array("sp_obj_type", "jb", "sp_obj_id", $job_id, "sp_fieldname", $semaphorKey, "sp_content", "", "sp_context", 'FALLBACK'));
               die();
            endif;

            // Try to lock semaphore
            $res = updateStmt("phoenix_log.semaphor", "sp_obj_id", $job_id, array("sp_content", "LOCKED", "sp_createtime", $currentTime), "sp_obj_type = 'jb' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = ''");
            if ($db->affected_rows > 0) :

               // Initiate switch for the mail text according to the caller mode for taken jobs (= 1)
               $gdcContextCurr = getFieldValueFromClause("genericdatacontainer", "gdc_context", "gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcCashpayerMailKey . "'");
               if ($gdcContextCurr == "" || !is_numeric($gdcContextCurr)) :
                  $gdcContextCurr = 1024;
               endif;
               $mailTextJobStatus = "";
               $gdcContextNewValue = 1024;
               switch ($job_mode) {
                 case "1": 
                   $mailTextJobStatus = "8";
                   $gdcContextNewValue = ($gdcContextCurr | 1025);
                   $jbStatusText = "Erfassung";
                   break;
                 case "2": 
                   $mailTextJobStatus = "1";
                   $gdcContextNewValue = ($gdcContextCurr | 1026);
                   $jbStatusText = "Abholung";
                   break;
                 case "3": 
                   $gdcContextNewValue = ($gdcContextCurr | 1028);
                   $jbStatusText = "Erledigung";
                   break;
               }

               include ("../admin/jb_detail.php");

               // Get current mail status
               // $jbAutomailsent = getFieldValueFromClause("genericdatacontainer", "gdc_context", "gdc_obj_type = 'jb' AND gdc_gen_fieldname = '" . $gdcCashpayerMailKey . "' AND gdc_obj_id = '" . $job_id . "'");
               // if ($jbAutomailsent == "" || !is_numeric($jbAutomailsent)) : $jbAutomailsent = 0; endif;            

               if ($mailResult) :
                  // updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "MAIL_SENT"),"gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcCashpayerMailKey . "'");
                  updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", $gdcContextNewValue) ,"gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcCashpayerMailKey . "'");
                  $statusSent = "OK";
               else :

                  $statusSent = "NOT OK";
                  // $jbAutomailsent++;

                  // Check for maximum of 5 fault trials. If reached then finalize with error code
                  // if ($jbAutomailsent > "5") :
                     // updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "MAIL_NOT_SENT"),"gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcCashpayerMailKey . "'");
                     updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", $gdcContextNewValue) ,"gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcCashpayerMailKey . "'");
                  // else :
                  //    updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", $jbAutomailsent),"gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcCashpayerMailKey . "'");
                  // endif;
               endif;

               // Write logdata into log file
               writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . $f_email . "] [SID: " . $job_crSid . "] [" . $jbStatusText . "] [Status: " . $statusSent . "]");
            else :

               // Check semaphore to be unlocked
               $spCreatetime = getFieldValueFromClause("phoenix_log.semaphor", "sp_createtime", "sp_obj_type = 'jb' AND sp_obj_id = '" . $job_id . "' AND sp_fieldname = '" . $semaphorKey . "'");
               $spSecDiff = strtotime($currentTime) - strtotime($spCreatetime);
               if ($spSecDiff > $semaphorLiveTime) :
                  updateStmt("phoenix_log.semaphor", "sp_obj_id", $job_id, array("sp_content", "", "sp_createtime", $currentTime), "sp_obj_type = 'jb' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = 'LOCKED'");
               endif;
            endif;

            // $mailObj.dispose();
         else :
            // If email address is empty then set sent status to NOT OK
            if ($f_email == "" && $job_id != "" && $currentHqId != "") :

               updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "MAIL_NOT_SENT"),"gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcCashpayerMailKey . "'");

               // Write logdata into log file
               writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . "_EMPTY_" . "] [SID: " . $job_crSid . "] [Erledigung] [Status: NOT OK]");
            endif;
         endif;

         $job_id = "";
         $f_email = "";

     endfor;  // Loop all jobs     
  endif;  // AUTOMAILER_ENABLED

//   sleep(30);

// endwhile;  // Endless loop
?>
