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

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


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


$constAutomailerEnabled = getParameterValue("0", "AUTOMAILER_ENABLED", "0");
$parAutomailer2TrackingEnabled = getParameterValue("0", "AUTOMAILER_2_TRACKING_ENABLED", "0");

if ($constAutomailerEnabled == '1' && $parAutomailer2TrackingEnabled == '1') :

   if ($argv[1] == "acapella7890") :

      // Error reporting
      error_reporting(E_ERROR | E_WARNING | E_PARSE);
   
      $dirName = dirname(__FILE__);
      $dirName = str_replace("\\", "/", $dirName);
      $lastSlashPos = strrpos($dirName,"/");
      $path = substr($dirName, 0, $lastSlashPos);

      $currentTime = getDateTime("0");

      $logFile = getParameterValue("0", "AUTOMAILER_LOGFILE_7", "0");
      // if ($logFile == "") : $logFile = $path . "/log/automailer7.log"; endif;
      if ($logFile == "") : $logFile = "../log/automailer7.log"; endif;

      $semaphorKey = "automailer7";
      $semaphorLiveTime = 120;

      $jobArray = getAutoMailerTracking();

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

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

          // Current job and mail address
          $job_id = $jobArray[$i][0];
          $tr_id = $jobArray[$i][1];
          $tr_sort = $jobArray[$i][2];
          $gdc_content = $jobArray[$i][3];
          $gdc_context = $jobArray[$i][4];
          $currentHqId = $jobArray[$i][5];
          $jbCscIdPayer = $jobArray[$i][6];
          $jbCsIdPayer = $jobArray[$i][7];
          $jb_ordertime = $jobArray[$i][8];
          $job_crSid = $jobArray[$i][9];          

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

             // Get tracking state
             // $jbCscIdPayer = getFieldValueFromId("job","jb_id",$job_id,"csc_id_payer");
             if ($jbCscIdPayer > 0) :

                // $jbCsIdPayer = getFieldValueFromId("costcenter","csc_id",$jbCscIdPayer,"cs_id");
                if ($jbCsIdPayer > 0) :

                   $tmpGdcContent = trim($gdc_content);
                   $tmpGdcContentArr = explode("|", $tmpGdcContent);
                   $f_email = $tmpGdcContentArr[0];
                   $f_email = str_replace(" ", "", $f_email);

                   // Define constants
                   $constMailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $currentHqId);

                   // Set action parameters
                   $mailResult = FALSE;

                   // Standalone process
                   $automailer = "1";

                   // if ($tr_sort > 1) :
                   
                      if ($f_email != "" && $currentHqId != "") :
                      
                         if (!existsEntry("phoenix_log.semaphor",array("sp_obj_type","jb","sp_obj_id",$job_id,"sp_fieldname",$semaphorKey,"sp_content",$f_email))) :
                      
                            // Insert tracking link into 
                            $constGlobalDbInstNo = getParameterValue("0", "GLOBAL_UNIQUE_DB_INSTANCE_NO", "0", "0");
                            // $tmpArray = insertMetaTrackingItem($constGlobalDbInstNo, "tracking_tr", $tr_id);
                            $tmpArray = insertTrackingItems("", $tr_id, "", "", "", "SINGLE_TR");
                      
                            $trackingLink = getParameterValue("0", "GLOBAL_URL", $currentHqId);
                            if ($trackingLink == "") : $trackingLink = getParameterValue("0", "GLOBAL_URL", "0"); endif;
                            if ($trackingLink == "") : 
                               // Send info mail to sysop
                               sendInternalMail("Parameter for URL of instance not specified!");
                               die();
                            endif;
                            $trackingLink .= "/tracking/tracking_ADSG.php?trackingID=";
                      
                            $parLogoFile = getParameterValue("0", "IMG_LOGO_NAME_EMAIL", $currentHqId, "0");
                            $parLogoHeight = getParameterValue("0", "IMG_LOGO_HEIGHT", $currentHqId, "0");
                            $parLogoWidth = getParameterValue("0", "IMG_LOGO_WIDTH", $currentHqId, "0");
                            $parCssBackground = getParameterValue("0", "IMG_LOGO_BGCOL_EMAIL", $currentHqId, "0");
                            $parLogoArr = array($parLogoFile, $parLogoHeight, $parLogoWidth, $parCssBackground);

                            $jbCsBlurMarkupTimePayer = getFieldValueFromId("customer","cs_id",$jbCsIdPayer,"cs_blur_markup_time");
                            if ($jbCsBlurMarkupTimePayer == "") : $jbCsBlurMarkupTimePayer = 0; endif;
                            $jbCmpIdPayer = getFieldValueFromId("customer","cs_id",$jbCsIdPayer,"cmp_id");
                            $jbCmpCompPayer = getFieldValueFromId("company","cmp_id",$jbCmpIdPayer,"cmp_comp");

                            $trComp = getFieldValueFromId("tour","tr_id",$tr_id,"tr_comp");
                            // $trComp2 = getFieldValueFromId("tour","tr_id",$tr_id,"tr_comp2");
                            $adId = getFieldValueFromId("tour","tr_id",$tr_id,"ad_id");
                            $adStreet = getFieldValueFromId("address","ad_id",$adId,"ad_street");
                            $adHsno = getFieldValueFromId("tour","tr_id",$tr_id,"tr_hsno 	");
                            $adZipcode = getFieldValueFromId("address","ad_id",$adId,"ad_zipcode");
                            $adCity = getFieldValueFromId("address","ad_id",$adId,"ad_city");
                            $currAddress = $adStreet . " " . $adHsno . " in " . $adZipcode . " " . $adCity;

                            // ETA
                            $etaOut = "";
                            $etaOffset = get_tour_duration($tr_id);
                            $roundToXMinutes = 5;
                            $sendEmail = true;

                            if (is_numeric($etaOffset)) :
                               if ($etaOffset != -1) :

                                  // ETA
                                  $currUnixTimestamp = time();
                                  if ($roundToXMinutes != "" && is_numeric($roundToXMinutes) && $roundToXMinutes > 1) :
                                     $eta = (floor(($currUnixTimestamp + $etaOffset) / 60) - (floor(($currUnixTimestamp + $etaOffset) / 60) % $roundToXMinutes)) * 60;  // Full x minutes (e.g. 5)
                                  else :
                                     $eta = floor(($currUnixTimestamp + $etaOffset) / 60) * 60;  // Full minute
                                  endif;
                                  $etaTime = date("H:i", $eta);

                                  if ($jbCsBlurMarkupTimePayer > 0) :

                                     // Time window
                                     $etaTimeLowerRange = date("H:i", $eta - ($jbCsBlurMarkupTimePayer * 60));
                                     $etaTimeUpperRange = date("H:i", $eta + ($jbCsBlurMarkupTimePayer * 60));
                                     
                                     $etaOut .= getLngt("Ihre Sendung von") . " " . $jbCmpCompPayer . " " . getLngt("wird voraussichtlich zwischen") . "<br><br>";
                                     $etaOut .= "<span class=\"f12bp1_blue\">" . $etaTimeLowerRange . " " . getLngt("Uhr") . " " . getLngt("und") . " " . $etaTimeUpperRange . " " . getLngt("Uhr") . "</span><br><br>";
                                     $etaOut .= getLngt("bei") . " " . $trComp . " " . "<br><br>";
                                     $etaOut .= "<b>" . $currAddress . " </b><br><br>";
                                     $etaOut .= getLngt("eintreffen") . "." . "<br><br>";
                                  else :
                                  
                                     $etaOut .= getLngt("Ihre Sendung von") . " " . $jbCmpCompPayer . " " . getLngt("wird voraussichtlich um ca.") . "<br><br>";
                                     $etaOut .= "<span class=\"f12bp1_blue\">" . $etaTime . " " . getLngt("Uhr") . "</span><br><br>";
                                     $etaOut .= getLngt("bei") . " " . $trComp . " " . "<br><br>";
                                     $etaOut .= "<b>" . $currAddress . " </b><br><br>";
                                     $etaOut .= getLngt("eintreffen") . "." . "<br><br>";
                                  endif;
                               else :

                                  // updateStmt("genericdatacontainer","gdc_obj_type","tr",array("gdc_context", "SENT_NOK"),"gdc_obj_id = '" . $tr_id . "' AND gdc_gen_fieldname = 'tr_tracking'");
                                  // sendExternalMail ("[DEBUG] [JB: " . $job_id . "] [TR: " . $tr_id . "] [Time: " . $currentTime . "] [ETA_OFFSET: " . $etaOffset . "] [TO: " . $f_email . "] [LR: " . $etaTimeLowerRange . "] [UR: " . $etaTimeUpperRange . "]", "Tracking_Internal", "mv@assecutor.de", "", "", "", "", "", "");
                                  // $sendEmail = false;

                                  $etaOut .= getLngt("Ihre Sendung von") . " " . $jbCmpCompPayer . "<br><br>";
                                  $etaOut .= getLngt("an") . " " . $trComp . " " . "<br><br>";
                                  $etaOut .= "<b>" . $currAddress . " </b><br><br>";
                                  $etaOut .= getLngt("ist unterwegs") . "." . "<br><br>";
                                  $sendEmail = true;
                               endif;
                            endif;

                            // Send tracking email. "array($tmpArray)" equals "array(array(...))" !!!!
                            if ($sendEmail) :

                               $mailSubject = getLngt("Ihre Sendung ist auf dem Weg zu Ihnen!");                            
                               $emailResArr = sendTrackingHTMLMail($f_email, $tmpArray, $constGlobalDbInstNo, $job_id, $trackingLink, $currentHqId, "0", $parLogoArr, $etaOut, $mailSubject);

                               // Get current mail status                                     
                               $statusSent = "NOT OK";

                               if ($emailResArr[0] == "0") :

                                  $mailResult = ($emailResArr[1] == "1" ? true : false);

                                  if ($mailResult) :
                                     // updateStmt("job", "jb_id", $job_id, array("jb_automailsent6", "999"));
                                     updateStmt("genericdatacontainer","gdc_obj_type","tr",array("gdc_context", "SENT_OK"),"gdc_obj_type = 'tr' AND gdc_obj_id = '" . $tr_id . "' AND gdc_gen_fieldname = 'tr_tracking'");
                                     $statusSent = "OK";
                                  else :
                                     // Get number of tries and increment
                                     $trEmailSentCount = getFieldValueFromClause("phoenix.genericdatacontainer", "gdc_context", "gdc_obj_type = 'tr' AND gdc_obj_id = '" . $tr_id . "' AND gdc_gen_fieldname = 'tr_tracking'");
                                     if ($trEmailSentCount == "") : $trEmailSentCount = 0; endif;
                                     $trEmailSentCount++;
                                  
                                     // Check for maximum of 3 fault trials. If reached then finalize with error code
                                     if ($trEmailSentCount > 3) :
                                        updateStmt("genericdatacontainer","gdc_obj_type","tr",array("gdc_context", "SENT_NOK"),"gdc_obj_id = '" . $tr_id . "' AND gdc_gen_fieldname = 'tr_tracking'");
                                     else :
                                        updateStmt("genericdatacontainer","gdc_obj_type","tr",array("gdc_context", $trEmailSentCount),"gdc_obj_id = '" . $tr_id . "' AND gdc_gen_fieldname = 'tr_tracking'");
                                     endif;
                                  endif;
                               else :                                        
                                  updateStmt("genericdatacontainer","gdc_obj_type","tr",array("gdc_context", "SENT_NOK"),"gdc_obj_id = '" . $tr_id . "' AND gdc_gen_fieldname = 'tr_tracking'");
                               endif;

                               // Write logdata into log file
                               writeToFile($logFile, "[JB: " . $job_id . "] [TR: " . $tr_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . $f_email . "] [End_customer] [Status: " . $statusSent . "] [Err: " . ($emailResArr[0] != "0" ? $emailResArr[2] : "NO") . "]");
                            else :

                               // Write logdata into log file
                               $statusSent = "NOT OK";
                               writeToFile($logFile, "[JB: " . $job_id . "] [TR: " . $tr_id . "] [Time: " . $currentTime . "] [From: " . $constMailSenderAddress . "] [To: " . $f_email . "] [End_customer, no email sent!] [Status: " . $statusSent . "] [Err: " . ($emailResArr[0] != "0" ? $emailResArr[2] : "NO") . "]");
                            endif;
                         else :
                      
                            // Check semaphor to be removed
                            $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) :
                               deleteStmt("phoenix_log.semaphor","sp_obj_type = 'jb' AND sp_obj_id = '" . $job_id . "' AND sp_fieldname = '" . $semaphorKey . "'");
                            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", "SENT_NOK"),"gdc_obj_type = 'tr' AND gdc_obj_id = '" . $tr_id . "' AND gdc_gen_fieldname = 'tr_tracking'");
                         
                            // 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;
                   // else :
                   //    updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "SENT_NOK"),"gdc_obj_type = 'tr' AND gdc_obj_id = '" . $tr_id . "' AND gdc_gen_fieldname = 'tr_tracking'");
                   // endif;  // tr_sort
                          
                   sleep(1);
                else :   
                   writeToFile($logFile, "[" . $currentTime . "] " . "[" . $job_id . "] " . "No Customer ID!");
                endif;  // cs_id
             else :   
                writeToFile($logFile, "[" . $currentTime . "] " . "[" . $job_id . "] " . "No invoice payer!");
             endif;  // csc_id_payer
          else :   
             writeToFile($logFile, "[" . $currentTime . "] " . "[" . $job_id . "] " . "Called without job!");
          endif;  // $job_id

      endfor;  // Loop jobs

   endif;  // $argv[1]

endif; // AUTOMAILER_ENABLED && AUTOMAILER_2_TRACKING_ENABLED
?>
