<?php
/*=======================================================================
 *
 * automailer.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", "0");

$semaphorKey = "automailer";
$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
     $jobArrayNoPhoto = getAutoMailerJobs(4);
     $jobArrayWithPhoto = getAutoMailerJobs(4,1);
     $jobArray = array_merge($jobArrayNoPhoto, $jobArrayWithPhoto);     
// print_r($jobArray); echo "\n\n"; die();
     // 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];
         $takeCscMailAdress = $jobArray[$i][4];
         $f_email_csc = $jobArray[$i][5];
         $f_email_csc = str_replace(" ", "", $f_email_csc);
         
         // Take email address stored to costcenter (invoice address) if activated
         if ($f_email_csc != "" && $takeCscMailAdress == "1") :
            $f_email = $f_email_csc;
         endif;
         
         // Define constants
         $logFile = getParameterValue("0", "AUTOMAILER_LOGFILE", $currentHqId);
         $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) :

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

               // *** Mail was sent => Update jb_automailsent ***

               // Get current mail status
               $jbAutomailsent = getFieldValueFromId("job","jb_id",$job_id,"jb_automailsent");
               if ($jbAutomailsent == "" || !is_numeric($jbAutomailsent)) : $jbAutomailsent = 0; endif;            

               if ($mailResult) :
                  updateStmt("job", "jb_id", $job_id, array("jb_automailsent", "999"));
                  $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("job", "jb_id", $job_id, array("jb_automailsent", "998"),"jb_automailsent != '999'");
                  else :
                     updateStmt("job", "jb_id", $job_id, array("jb_automailsent", $jbAutomailsent),"jb_automailsent != '999'");
                  endif;
               endif;

               // Write logdata into log file
               writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . $f_email . "] [SID: " . $job_crSid . "] [Erledigung] [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("job", "jb_id", $job_id, array("jb_automailsent", "998"));

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