<?php
/*=======================================================================
 *
 * automailer6.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_6", "0");
if ($logFile == "") : $logFile = "../log/automailer6.log"; endif;

$gdcJobJamKey = "jb_job_jam";
$semaphorKey = "automailer6";
$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 = getAutoMailerJobsByJobJam(5);

     // Loop all jobs (default one)
     $lenJobArray = count($jobArray);
if ($lenJobArray > 0) :
   // writeToFile("../log/automailer6.log", "lenJobArray = " .$lenJobArray . " :: Jobs: " . $jobArray[0][0] . " " . $jobArray[1][0] . " " . $jobArray[2][0] . " " . $jobArray[3][0] . " " . $jobArray[4][0]);
endif;
     for ($i = 0; $i < $lenJobArray; $i++) :

         // 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);
         $csIdPayer = $jobArray[$i][6];
         $jbOrdertime = $jobArray[$i][7];
// writeToFile("../log/automailer6.log", "job_id = " .$job_id);
         // 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_6", "0");
         if ($logFile == "") : $logFile = "../log/automailer6.log"; endif;
         $constMailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $currentHqId);

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

         // Initiate switch for the mail text according to the caller mode for taken jobs (= 1)
         $mailTextJobStatus = "1";

         // Standalone process
         $automailer = "1";
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// $f_email = "va@assecutor.de,mv@assecutor.de";
// $f_email = "ingo.kublenz@stadtbote.de,va@assecutor.de,mv@assecutor.de";
         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");
// *****************
               // Check language by payer for sending email and take customer parameter
               $csLanguageMail = getParameterValue("0", "JOBDETAILS_EMAIL_LANGUAGE_" . $csIdPayer, "0");
               if ($csLanguageMail == "") : $csLanguageMail = "0"; endif;
               $remLanguageSelected = "";
               if ($languageSelected != $csLanguageMail) :
                  $remLanguageSelected = $languageSelected;
                  $languageSelected = $csLanguageMail;
                  getLanguage(__FILE__);
               endif;
               
               $mailSubject = getLngt("Verzögerung bei Ihrem Auftrag Nr.: ") . " " . $job_id;

               // $mailContent = getLngt("Der Transportauftrag") . " " . $job_id . " ". getLngt("befindet sich noch in der Vermittlung!");               
               $mailContent = getLngt("wir möchten Sie darüber informieren, dass es bei Ihrem aktuellen Auftrag geplant für") . " " . formatOutput($jbOrdertime, "datetime", "14") . " "
                            . getLngt("zu einer Verzögerung in der Vermittlung kommt.") . "<br>"
                            . getLngt("Unser Team arbeitet aktiv daran, einen verfügbaren Boten für Ihren Auftrag zu finden. Wir prüfen alle Optionen, um Ihre Lieferung schnellstmöglich zu vermitteln.") . "<br>"
                            . getLngt("Sobald Ihr Auftrag erfolgreich vermittelt wurde, werden wir Sie per Mail informieren.") . "<br><br>"
                            . getLngt("Wir hoffen auf Ihr Verständnis und bedanken uns für Ihr Vertrauen in STADTBOTE.") . "<br><br>";
               $mailContent = "<div class=\"f8np1\">" . $mailContent . "</div>";

               $mailResult = sendExternalMailExtended($mailContent, $mailSubject, $f_email);
               // $mailResult = sendExternalMailExtended($mailContent, $mailSubject, $f_email, "EMPTY", "EMPTY", "mv@assecutor.de");

               // Reset language
               if ($remLanguageSelected != "") :
                  $languageSelected = $remLanguageSelected;
                  getLanguage(__FILE__);
               endif;               
// *****************

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

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

               if ($mailResult) :
                  // updateStmt("job", "jb_id", $job_id, array("jb_automailsent6", "999"));
                  updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "MAIL_SENT"),"gdc_obj_type = 'jb' AND gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcJobJamKey . "'");

                  // Insert into GDC to check job jam order wil be mediated within n minutes
                  $constAmStarttimeInMinutes = getParameterValue("0", "CS_JB_JAM_WAITTIME_CTRL", $currentHqId);
                  if ($constAmStarttimeInMinutes == "") : $constAmStarttimeInMinutes = getParameterValue("0", "CS_JB_JAM_WAITTIME_CTRL", "0"); endif;
                  if ($constAmStarttimeInMinutes == "") : $constAmStarttimeInMinutes = 10; endif;
                  $execTime = getDateTime("datetime_plus_offset", array(0,$constAmStarttimeInMinutes,0,0,0,0), "Y-m-d H:i:s");
                  insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $job_id, "gdc_gen_fieldname", "jb_job_jam_ctrl", "gdc_content", $execTime, "gdc_context", ""));

                  $statusSent = "SENT";
               else :
                  $statusSent = "NOT SENT";
                  $jbAutomailsent++;

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

               // Write logdata into log database
               writeToLogDB("188",$currentHqId,$job_id,"","","","","MAIL_STATE=" . $statusSent . "|MAIL_TO=" . $f_email);

               // Write logdata into log file
               writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . $f_email . "] [SID: " . $job_crSid . "] [Vermittlungsstau] [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_type = 'jb' AND gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = '" . $gdcJobJamKey . "'");

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

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

//   sleep(30);

// endwhile;  // Endless loop
?>
