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

include_once ("../include/mcglobal.inc.php");
include_once ("../include/inc_job.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 = "automailer4";
$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
     // $stationArray = getAutoMailerStations(5);
     $stationArrayNoPhoto = getAutoMailerStations(5);
     $stationArrayWithPhoto = getAutoMailerStations(5,1);
     $stationArray = array_merge($stationArrayNoPhoto, $stationArrayWithPhoto);     
// print_r($stationArray); echo "\n\n"; die();
     $lenStationArray = count($stationArray);

     // Loop all stations
     for ($i = 0; $i < $lenStationArray; $i++) :

         if ($i > 0) : sleep(1); endif;

         // Init for each job
         $jbMailAttachements = array();

         // Current station and mail address
         $job_id = $stationArray[$i][0];
         $tour_sort = $stationArray[$i][1];
         $f_email = trim($stationArray[$i][2]);
         $f_email = str_replace(" ", "", $f_email);
         $job_crSid = $stationArray[$i][3];
         $currentHqId = $stationArray[$i][4];
         $takeCscMailAdress = $stationArray[$i][5];
         $f_email_csc = $stationArray[$i][6];
         $f_email_csc = str_replace(" ", "", $f_email_csc);
         $trId = $stationArray[$i][7];
         $jbOrdertime = $stationArray[$i][8];

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

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

         // Initiate switch for the mail text according to the caller mode for new jobs (= 8) [or (= 9), it is ok]
         $mailTextJobStatus = "ALL";

         // Standalone process
         $automailer = "1";

         if ($job_id != "" && $tour_sort != "" && $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","tr","sp_obj_id",$trId,"sp_fieldname",$semaphorKey))) :
               insertStmt("phoenix_log.semaphor", array("sp_obj_type", "tr", "sp_obj_id", $trId, "sp_fieldname", $semaphorKey, "sp_content", "", "sp_context", 'FALLBACK'));
               die();  // Terminate here after INSERT (!!!!)
            endif;

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

               // **** MAIL BEGIN ****************************

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

               if (checkEmailFormat($f_email)) :
               
                  $jobData = array();
                  getDBData("tour", $job_id);  // Get station data
               
                  $tmpSignPath = "../temp/signs/";
                  $constSignPath = getParameterValue("0", "SIGNS_PATH", $currentHqId);
                  if ($constSignPath == "") : $constSignPath = getParameterValue("0", "SIGNS_PATH", "0"); endif;
                  if ($constSignPath != "") : $tmpSignPath = $constSignPath; endif;
               
                  // Generate sign image
                  $rawCoord = splitRawCoordinates ($jobData["tour"][$tour_sort]["tr_sign"]);
                  $maxCoord = checkMaxCoordinates($rawCoord);
                  $imgFilename = $tmpSignPath . $job_id . "_" . $tour_sort . ".png";
                  $imgFilenames[] = $imgFilename;
                  $im = createSignImage($rawCoord);
                  imagepng ($im, $imgFilename);
               
                  // Generate mail object
                  $mailObj = new htmlMimeMail();
               
                  $mailCssFontType = getParameterValue("0", "MAIL_CSS_FONT_TYPE", $currentHqId);
                  if ($mailCssFontType == "") : $mailCssFontType = "Verdana, Arial, Helvetica, sans-serif"; endif;
               
                  $mailtext  = "<html><head><meta text/html>";
                  $mailtext .= "<style type=\"text/css\">";
                  $mailtext .= ".f8np1 { font-family: " . $mailCssFontType . "; font-size: 8pt; font-weight: normal; padding: 1px}";
                  $mailtext .= ".f8bp1 { font-family: " . $mailCssFontType . "; font-size: 8pt; font-weight: bold; padding: 1px}";
                  $mailtext .= ".f10np1 { font-family: " . $mailCssFontType . "; font-size: 10pt; font-weight: normal; padding: 1px}";
                  $mailtext .= ".f10bp1 { font-family: " . $mailCssFontType . "; font-size: 10pt; font-weight: bold; padding: 1px}";
                  $mailtext .= ".f8np1_red { font-family: " . $mailCssFontType . "; font-size: 8pt; font-weight: normal; padding: 1px; color: #FF0000;}";
                  $mailtext .= "</style>";
                  $mailtext .= "</head><body><h4>";
               
                  $trFinishtime =  $jobData["tour"][$tour_sort]["tr_finishtime"];
                  // $trFinishtime = substr($trFinishtime,8,2) . "." . substr($trFinishtime,5,2) . "." . substr($trFinishtime,0,4) . " " . substr($trFinishtime,11,2) . ":" . substr($trFinishtime,14,2);
                  $trFinishtime =  substr($trFinishtime,11,2) . ":" . substr($trFinishtime,14,2) . " " . getLngt("Uhr") . " [" . substr($trFinishtime,8,2) . "." . substr($trFinishtime,5,2) . "." . substr($trFinishtime,0,4) . "]";
               
                  // BEGIN station data
                  $jobtext = "";
               
                  // Definition of the output place of the job data
                  $mailJobData = getParameterValue("0", "MAIL_JOBDATA", "0");
                  if ($mailJobData == "") : $mailJobData = "0"; endif;
               
                  // Transport date or current date
                  $mailJobDate = getParameterValue("0", "MAIL_JOBDATE", "0");
               
                  if ($mailJobDate == "1") :
                     $jobtext .= "<div class=\"f10bp1\">" . getLngt("Transportdatum:") . " " . formatOutput($jbOrdertime, "datetime", 4) . "</div>";
                  else :
                     $jobtext .= "<div class=\"f10bp1\">" . getLngt("Transportdatum:") . " " . getDateTime(5) . "</div>";
                  endif;
                  $jobtext .= "<div style=\"width:100%; height:10px;\"> </div>";
               
                  $tmpHeight = "20";
                  $jobtext .= "<table class=\"f8np1\">";
                  $jobtext .= "<tr style=\"height:" . $tmpHeight . "px;\"><td valign=\"top\"><span class=\"f8bp1\">" . getLngt("AUFTRAG:") . " " . $job_id . "</span></td></tr>";
                  $jobtext .= "<tr style=\"height:" . $tmpHeight . "px;\"><td valign=\"top\"><span class=\"f8bp1\">" . getLngt("KOMMISSIONSNUMMER:") . " " . $jobData["tour"][$tour_sort]["tr_commission_no"] . "</span></td></tr>";
                  $jobtext .= "<tr style=\"height:" . $tmpHeight . "px;\"><td valign=\"top\"><span class=\"f8bp1\">" . getLngt("ERLEDIGUNGSZEITPUNKT:") . " " . $trFinishtime . " " . "</span></td></tr>";
                  $jobtext .= "<tr style=\"height:" . $tmpHeight . "px;\"><td valign=\"top\"><span class=\"f8bp1\">" . getLngt("ERLEDIGTE STATION:") . "</span>" . "</td></tr>";
                  $jobtext .= "<tr><td>" . $jobData["tour"][$tour_sort]["tr_comp"] . " " . $jobData["tour"][$tour_sort]["tr_comp2"] . "</td></tr>";
                  $jobtext .= "<tr><td>" . "- " . getLngt("Annahme") . ": " . $jobData["tour"][$tour_sort]["tr_signname"] . " -" . "</td></tr>";
                  $jobtext .= "<tr><td>" . $jobData["tour"][$tour_sort]["ad_street"] . " " . $jobData["tour"][$tour_sort]["tr_hsno"] . "</td></tr>";
                  $jobtext .= "<tr><td>" . $jobData["tour"][$tour_sort]["ad_zipcode"] . " " . $jobData["tour"][$tour_sort]["ad_city"] . "</td></tr>";                              
                  $jobtext .= "</table>";
               
                  // $jobtext .= "<table class=\"f8np1\">" . $jobentry . "</table><br>";
                  // $jobtext .= "</td><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td><td valign=\"top\">";
                  // if ($courierentry != "" && $mailTextJobStatus != "0" && $mailTextJobStatus != "8" && $mailTextJobStatus != "9") :
                  //    $jobtext .= "<span class=\"f8bp1\">" . getLngt("TRANSPORTEUR:") . "</span><br>";
                  //    $jobtext .= "<table class=\"f8np1\">" . $courierentry . "</table><br>";
                  // endif;
               
                  // Display events if activated
                  $cscIdPayer = getFieldValueFromId("job", "jb_id", $job_id, "csc_id_payer");
                  $csIdPayer = getFieldValueFromId("costcenter", "csc_id", $cscIdPayer, "cs_id");
                  $csJbstatusmailFields = getFieldValueFromId("customer","cs_id",$csIdPayer,"cs_jbstatusmail_fields");
                  $constMaskStationsPodScanEvents = getParameterValue("0", "MASK_JOBDETAILS_STATIONS_POD_SCAN_EVENTS", $hq_id);
                  if ($constMaskStationsPodScanEvents == "") : $constMaskStationsPodScanEvents = getParameterValue("0", "MASK_JOBDETAILS_STATIONS_POD_SCAN_EVENTS", "0"); endif;
                  if ($constMaskStationsPodScanEvents == "1" && substr($csJbstatusmailFields, 8, 1) == "1") : 
                     $jobtext .= "<table>";
                     $jobtext .= "<tr style=\"height:15px;\"><td valign=\"top\">";
                     $eventBemerkung = "";
                     $tmpEventState = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_obj_id = '" . $trId . "' AND gdc_gen_fieldname = 'del_code'");
                     if ($tmpEventState != "" && is_numeric($tmpEventState)) :
                        $eventBemerkung .= $deliveryCodeArray[$tmpEventState] . "&nbsp;&nbsp;&nbsp;&nbsp;";
                     endif;
                     // Get scan event remark
                     $tmpEventRemark = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_obj_id = '" . $trId . "' AND gdc_gen_fieldname = 'del_rem'");
                     if ($tmpEventRemark != "") :
                        $eventBemerkung .= $tmpEventRemark;
                     endif;
                     // Output scan barcodes
                     // $eventBemerkung .= getOutputJobTratArticleData($job_id, "1", "1", "1", "1", $jobData["tour"][$tour_sort]["tr_sort"]);
                     $jobtext .= "<span class=\"f8bp1\">" . getLngt("EVENT-BEMERKUNG:") . " " . $eventBemerkung . "</span><br>";
                     $jobtext .= "</td></tr></table>";
                  endif;
                  // END station data
               
                  $mailCssFontClass = getParameterValue("0", "MAIL_CSS_FONT_CLASS", $currentHqId);
                  if ($mailCssFontClass == "") : $mailCssFontClass = "f8bp1"; endif;
               
                  $mailPreSalutationText = getParameterValue("0", "MAIL_PRE_SALUTATION_TEXT", $currentHqId);
                  if ($mailPreSalutationText == "") : $mailPreSalutationText = getLngt("Sehr geehrte Damen und Herren,"); endif;
                  $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailPreSalutationText . "</div>";
                  $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
                  $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . getLngt("die Erledigung der Station erfolgte.") . "</div>";
               
                  // $mailTextJobdata = getParameterValue("0", "MAIL_TEXT_JOBDATA", $currentHqId);
                  // if ($mailTextJobdata == "") : $mailTextJobdata = getLngt("Anbei übersenden wir Ihnen die Auftragsdaten."); endif;
                  // $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailTextJobdata . "</div>";
                  // $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
               
                  if ($mailJobData == "1") :
                     $mailtext .= "<div style=\"width:100%; height:30px;\"> </div>";
                     $mailtext .= $jobtext;
                     $mailtext .= "<div style=\"width:100%; height:20px;\"> </div>";
                  endif;
               
                  // Signature
                  $mailTextRegards = getParameterValue("0", "MAIL_TEXT_REGARDS", $currentHqId);
                  if ($mailTextRegards == "") : $mailTextRegards = getLngt("Mit freundlichem Gruß,"); endif;
                  $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailTextRegards . "</div>";
                  $mailSalutationText = getParameterValue("0", "MAIL_SALUTATION_TEXT", $currentHqId);
                  $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . getLngt($mailSalutationText) . "</div>";
                  $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
               
                  // HOMEPAGE
                  $mailFooterWebPage = getParameterValue("0", "MAIL_FOOTER_WEB_PAGE", $currentHqId);
               
                  // LOGO
                  $logoName = getParameterValue("0", "IMG_LOGO_NAME", $currentHqId);
                  $logoHeight = getParameterValue("0", "IMG_LOGO_HEIGHT", $currentHqId);
                  $logoWidth = getParameterValue("0", "IMG_LOGO_WIDTH", $currentHqId);
                  if ($logoName != "" && $logoHeight != "" && $logoWidth != "") :
                     $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
                     if ($mailFooterWebPage != "") : 
                        $mailtext .= "<div><a href=\"http://" . $mailFooterWebPage . "\"><img src=\"../images/external/" . $logoName . "\" border=\"0\" height=\"" . $logoHeight . "\" width=\"" . $logoWidth . "\"></a></div>";
                     else :
                        $mailtext .= "<div><img src=\"../images/external/" . $logoName . "\" border=\"0\" height=\"" . $logoHeight . "\" width=\"" . $logoWidth . "\"></div>";
                     endif;
                     $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
                  endif;
               
               
                  $mailFooterEnabled = getParameterValue("0", "MAIL_FOOTER_ENABLED", $currentHqId);
                  if ($mailFooterEnabled == "1") :
                     $mailFooterAddress = getParameterValue("0", "MAIL_FOOTER_ADDRESS", $currentHqId);
                     if ($mailFooterAddress != "") :
                        $mailtext .= "<table style=\"font-family: Arial; font-size: 10pt; font-weight: normal; padding: 1px; color: #000000;\">";
                        $mailtext .= $mailFooterAddress;
                        $mailtext .= "</table>";
                        $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
                     endif;
                     $mailFooterContact = getParameterValue("0", "MAIL_FOOTER_CONTACT", $currentHqId);
                     if ($mailFooterContact != "") :                  
                        if ($mailDisplayModeEmployeeData == "1" && ($mailEmployeeData[2] != "" || $mailEmployeeData[3] != "" || $mailEmployeeData[4] != "")) :
                           $mailtext .= "<table>";
                           if ($mailEmployeeData[2] != "") : 
                              $mailtext .= "<tr><td><span class=\"" . $mailCssFontClass . "\">" . getLngt("Telefon") . ": " . $mailEmployeeData[2] . "</span></td></tr>";
                           endif;
                           if ($mailEmployeeData[4] != "") : 
                              $mailtext .= "<tr><td><span class=\"" . $mailCssFontClass . "\">" . getLngt("Fax") . ": " . $mailEmployeeData[4] . "</span></td></tr>";
                           endif;
                           if ($mailEmployeeData[3] != "") : 
                              $mailtext .= "<tr><td><span class=\"" . $mailCssFontClass . "\">" . getLngt("Email") . ": " . $mailEmployeeData[3] . "</span></td></tr>";
                           endif;
                           // $mailFooterWebPage = getParameterValue("0", "MAIL_FOOTER_WEB_PAGE", $currentHqId);
                           if ($mailFooterWebPage != "") : 
                              // $mailtext .= "<tr><td><span class=\"" . $mailCssFontClass . "\">" . $mailFooterWebPage . "</span></td></tr>";
                              $mailtext .= "<tr><td><span class=\"" . $mailCssFontClass . "\"><a href=\"http://" . $mailFooterWebPage . "\">" . $mailFooterWebPage . "</a></span></td></tr>";
                           endif;
                           $mailtext .= "</table>";
                        else :
                           $mailtext .= "<table style=\"font-family: Arial; font-size: 10pt; font-weight: normal; padding: 1px; color: #000000;\">";
                           $mailtext .= $mailFooterContact;
                           $mailtext .= "</table>";
                        endif;                  
                        $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
                     endif;
                     $mailFooterImpressum = getParameterValue("0", "MAIL_FOOTER_IMPRESSUM", $currentHqId);
                     if ($mailFooterImpressum != "") :
                        $mailtext .= "<table style=\"font-family: Arial; font-size: 7pt; font-weight: normal; padding: 1px; color: #000000;\">";
                        $mailtext .= $mailFooterImpressum;
                        $mailtext .= "</table>";
                        $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
                     endif;
                     $mailFooterResponsibility = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY", $currentHqId);
                     if ($mailFooterResponsibility == "") : $mailFooterResponsibility = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY", "0"); endif;
                     if ($mailFooterResponsibility != "") : 
                        $mailtext .= "<div style=\"font-family: Arial; font-size: 7pt; font-weight: normal; padding: 1px; color: #000000;\">" . $mailFooterResponsibility . "</div>";
                        // Extended text
                        $mailFooterResponsibility2 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_2", $currentHqId);
                        if ($mailFooterResponsibility2 == "") : $mailFooterResponsibility2 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_2", "0"); endif;
                        if ($mailFooterResponsibility2 != "") : 
                           $mailtext .= "<div style=\"font-family: Arial; font-size: 7pt; font-weight: normal; padding: 1px; color: #000000;\">" . $mailFooterResponsibility2 . "</div>";
                           $mailFooterResponsibility3 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_3", $currentHqId);
                           if ($mailFooterResponsibility3 == "") : $mailFooterResponsibility3 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_3", "0"); endif;
                           if ($mailFooterResponsibility3 != "") : 
                              $mailtext .= "<div style=\"font-family: Arial; font-size: 7pt; font-weight: normal; padding: 1px; color: #000000;\">" . $mailFooterResponsibility3 . "</div>"; 
                              $mailFooterResponsibility4 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_4", $currentHqId);
                              if ($mailFooterResponsibility4 == "") : $mailFooterResponsibility4 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_4", "0"); endif;
                              if ($mailFooterResponsibility4 != "") : 
                                 $mailtext .= "<div style=\"font-family: Arial; font-size: 7pt; font-weight: normal; padding: 1px; color: #000000;\">" . $mailFooterResponsibility4 . "</div>";
                                 $mailFooterResponsibility5 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_5", $currentHqId);
                                 if ($mailFooterResponsibility5 == "") : $mailFooterResponsibility5 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_5", "0"); endif;
                                 if ($mailFooterResponsibility5 != "") : 
                                    $mailtext .= "<div class=\"" . $mailFooterImpressum . "\">" . $mailFooterResponsibility5 . "</div>";
                                 endif;
                              endif;
                           endif;
                           $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
                        endif;
                     endif;
                     $mailFooterThinkGreen = getParameterValue("0", "MAIL_FOOTER_THINK_GREEN", $currentHqId);
                     if ($mailFooterThinkGreen != "") :
                        $mailtext .= $mailFooterThinkGreen;
                        $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
                     endif;
                     $mailtext .= "<div style=\"width:100%; height:30px;\"> </div>";               
                  endif;
               
                  if ($mailJobData == "0") :
                     $mailtext .= "</br>" . $jobtext;
                  endif;
               
                  $mailtext .= "</body></html>";
               
                  $mailObj->setSubject(getLngt("Station") . " " . $tour_sort . " " . getLngt("des Transportauftrags!") . " " . $job_id . " " . getLngt("wurde erledigt!"));
               
                  $mailObj->setHtml($mailtext, null, "./");
                  // $mailObj->setHtml($mailtext);
               
                  // Set From address
                  $mailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $currentHqId);
                  if ($mailSenderAddress == "" || !checkEmailFormat($mailSenderAddress)) : 
                     $mailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", "0");
                  endif;
                  $mailObj->setFrom($mailSenderAddress);
               
                  // Set Cc address
                  $mailCcAddress = getParameterValue("0", "MAIL_CC_ADDRESS", $currentHqId);
                  if ($mailCcAddress == "" || !checkEmailFormat($mailCcAddress)) :
                     $mailCcAddress = getParameterValue("0", "MAIL_CC_ADDRESS", "0");
                  endif;                        
                  if ($mailCcAddress != "" && checkEmailFormat($mailCcAddress)) :
                     $mailObj->setCc($mailCcAddress);
                  endif;
               
                  // Set Bcc address
                  $mailBccAddress = getParameterValue("0", "MAIL_BCC_STATION_ADDRESS", "0");
                  if ($mailBccAddress == "" || !checkEmailFormat($mailBccAddress)) :               
                     $mailBccAddress = getParameterValue("0", "MAIL_BCC_ADDRESS", $currentHqId);
                     if ($mailBccAddress == "" || !checkEmailFormat($mailBccAddress)) :
                        $mailBccAddress = getParameterValue("0", "MAIL_BCC_ADDRESS", "0");
                     endif;                        
                  endif;
// $mailBccAddress = ($mailBccAddress != "" ? $mailBccAddress . "," : "") . "mv@assecutor.de";
                  if ($mailBccAddress != "" && checkEmailFormat($mailBccAddress)) :
                     $mailObj->setBcc($mailBccAddress);
                  endif;
               
                  // Generate PDF if enabled for customer            
                  /*
                  $csJbstatusmailPdf = getFieldValueFromId("customer","cs_id",$csIdPayer,"cs_jbstatusmail_pdf");
                  if ($csJbstatusmailPdf == "1" && $job_status == "2") :
                     $tmpPdfPath = "../temp/pdf/";
               
                     $includePDFGeneric = "1";
                     $f_act = "generatePDFJob";
                     $storeAsFile = "1";
                     $jbId = $job_id;
                     $pdfFile = "Auftrag_" . $job_id . ".pdf";
                     include_once ("../admin/pdf_generic.php");
               
                     if (file_exists($tmpPdfPath . $pdfFile)) :
                        $attachment = $mailObj->getFile($tmpPdfPath . $pdfFile);
                        $mailObj->addAttachment($attachment, $pdfFile, 'application/pdf');
                     endif;
                  endif;
                  */
               
                  $mailResult = $mailObj->send(array($f_email), 'smtp');
// $mailResult = $mailObj->send(array("admin@assecutor.de"), 'smtp');
               
                  if ($mailResult) :
                     $mailsendStatus = getLngt("Die Nachricht für die Station " . $tour_sort . " wurde versandt!");
               
                     // Write logdata into log database
                     writeToLogDB("22",$currentHqId,$job_id,$currentSessionUsrId,"","","",$f_email . "|STATION");
                  else :
                     $mailsendStatus = getLngt("Die Nachricht für die Station " . $tour_sort . " konnte nicht gesendet werden!");
               
                     // Write logdata into log database
                     writeToLogDB("23",$currentHqId,$job_id,$currentSessionUsrId,"","","",$f_email . "|STATION");
                  endif;
               
                  // $mailObj->free();
                  $mailObj = NULL;
               
                  // Remove stored temporary images on the filesystem
                  $imgFilenamesLen = count($imgFilenames);
                  for ($im = 0; $im < $imgFilenamesLen; $im++) :
                      if (file_exists($tmpSignPath . $imgFilenames[$im])) :
                         unlink($tmpSignPath . $imgFilenames[$im]);
                      endif;
                  endfor;
               
                  // Remove stored temporary pdf documents on the filesystem
                  // if (file_exists($tmpPdfPath . $pdfFile)) :
                  //    unlink($tmpPdfPath . $pdfFile);
                  // endif;
               else :
                  $mailsendStatus = getLngt("Die eingegebene Emailadresse ist syntaktisch nicht korrekt!");
               endif;
               
               // **** MAIL END ****************************
               
               // *** Mail was sent => Update genericdatacontainer ***
               
               // Get current mail status
               $trAutomailsent = getFieldValueFromClause("genericdatacontainer","gdc_content","gdc_obj_id = '" . $trId . "' AND gdc_gen_fieldname = 'auto_mail_station'");
               if ($trAutomailsent == "" || !is_numeric($trAutomailsent)) : $trAutomailsent = 0; endif;
               
               if ($mailResult) :
                  if (existsEntry("genericdatacontainer",array("gdc_obj_type","tr","gdc_obj_id",$trId,"gdc_gen_fieldname","auto_mail_station"))) :
                     updateStmt("genericdatacontainer","gdc_obj_type","tr",array("gdc_content", "999", "gdc_context", ""),"gdc_obj_id = '" . $trId . "' AND gdc_gen_fieldname = 'auto_mail_station'");
                  else :
                     insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trId, "gdc_gen_fieldname", "auto_mail_station", "gdc_content", "999", "gdc_context", ""));
                  endif;
                  $statusSent = "OK";
               else :
                  $statusSent = "NOT OK";
                  $trAutomailsent++;
               
                  // Check for maximum of 2 fault trials. If reached then finalize with error code
                  if ($trAutomailsent > "2") :
                     $trAutomailsent = "998";
                  endif;
               
                  if (existsEntry("genericdatacontainer",array("gdc_obj_type","tr","gdc_obj_id",$trId,"gdc_gen_fieldname","auto_mail_station"))) :
                     updateStmt("genericdatacontainer","gdc_obj_type","tr",array("gdc_content", $trAutomailsent, "gdc_context", ""),"gdc_obj_id = '" . $trId . "' AND gdc_gen_fieldname = 'auto_mail_station'");
                  else :
                     insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trId, "gdc_gen_fieldname", "auto_mail_station", "gdc_content", $trAutomailsent, "gdc_context", ""));
                  endif;
               endif;
               
               // Write logdata into log file
               writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . $currentTime . "] [From: " . $mailSenderAddress . "] [To: " . $f_email . "] [SID: " . $job_crSid . "] [Erledigung Station " . $tour_sort . "] [Status: " . $statusSent . "]");
               
            else :

               // Check semaphore to be unlocked
               $spCreatetime = getFieldValueFromClause("phoenix_log.semaphor", "sp_createtime", "sp_obj_type = 'tr' AND sp_obj_id = '" . $trId . "' AND sp_fieldname = '" . $semaphorKey . "'");
               $spSecDiff = strtotime($currentTime) - strtotime($spCreatetime);
               if ($spSecDiff > $semaphorLiveTime) :
                  updateStmt("phoenix_log.semaphor", "sp_obj_id", $trId, array("sp_content", "", "sp_createtime", $currentTime), "sp_obj_type = 'tr' 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 != "" && $tour_sort != "" && $currentHqId != "") :

               if (existsEntry("genericdatacontainer",array("gdc_obj_type","tr","gdc_obj_id",$trId,"gdc_gen_fieldname","auto_mail_station"))) :
                  updateStmt("genericdatacontainer","gdc_obj_type","tr",array("gdc_content", "998", "gdc_context", ""),"gdc_obj_id = '" . $trId . "' AND gdc_gen_fieldname = 'auto_mail_station'");
               else :
                  insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trId, "gdc_gen_fieldname", "auto_mail_station", "gdc_content", "998", "gdc_context", ""));
               endif;

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

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

     endfor;  // Loop all stations     
  endif;  // AUTOMAILER_ENABLED

//   sleep(30);

// endwhile;  // Endless loop
?>
