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

include_once ("../include/mcglobal.inc.php");
$hq_id = HQ_ID_DEFAULT;
include_once ("../include/image.inc.php");
include_once ('../include/email/htmlMimeMail.php');
include_once ("../include/jb_detail_history.inc.php");
include_once ("../include/inc_html2pdf.inc.php");
include_once ("../include/inc_automailer_related.inc.php");
include_once ("../include/inc_metafield.inc.php");


// 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_RELATED", "0");

// Endless loop
// while (TRUE):

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


  // ********************************
  // *** Send mails 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 = getAutoMailerJobs(1,"csc_id_related");

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

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

         // 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_RELATED", $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 != "") :

            $tmpPdfPath = "../temp/pdf/";
            $jbMailAttachements = array();

            // **** Acceptance protocol ****

            $hq_id = $currentHqId;
            $category = "300";
            $objId = $job_id;
            $cascadingObjType = "jb";

            $gHqId = true;
            $constFormSingleHQ = getParameterValue("0", "SYSTEM_FORM_SINGLE_HQ_" . $category, "0");
            if ($constFormSingleHQ != "" && $constFormSingleHQ != "0") :
               $gHqId = false;
            else :
               $constFormSingleHQ = getParameterValue("0", "SYSTEM_FORM_SINGLE_HQ", "0");
               if ($constFormSingleHQ != "" && $constFormSingleHQ != "0") :
                  $gHqId = false;
               endif;
            endif;
            initMetaFieldStructure();

            $pathAndFilename = generateMetafieldPDF($tmpPdfPath);
            // $filename = substr($pathAndFilename, strlen($tmpPdfPath));
            $filename = "Abnahmeprotokoll_" . $job_id . ".pdf";

            $jbMailAttachements[0][0] = $pathAndFilename;
            $jbMailAttachements[0][1] = $filename;

            // ****************************************************************
                
            // **** Customer service protocol ****

            $hq_id = $currentHqId;
            $category = "306";
            $objId = $job_id;
            $cascadingObjType = "jb";

            $gHqId = true;
            $constFormSingleHQ = getParameterValue("0", "SYSTEM_FORM_SINGLE_HQ_" . $category, "0");
            if ($constFormSingleHQ != "" && $constFormSingleHQ != "0") :
               $gHqId = false;
            else :
               $constFormSingleHQ = getParameterValue("0", "SYSTEM_FORM_SINGLE_HQ", "0");
               if ($constFormSingleHQ != "" && $constFormSingleHQ != "0") :
                  $gHqId = false;
               endif;
            endif;
            initMetaFieldStructure();
            
            $pathAndFilename = generateMetafieldPDF($tmpPdfPath);
            // $filename = substr($pathAndFilename, strlen($tmpPdfPath));
            $filename = "Kundendienstaufnahme_" . $job_id . ".pdf";

            $jbMailAttachements[1][0] = $pathAndFilename;
            $jbMailAttachements[1][1] = $filename;


            include_once ("../admin/jb_detail.php");
            // $output = getJobMailText($currentHqId, $job_id, "2");







            // *** 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"));
               else :
                  updateStmt("job", "jb_id", $job_id, array("jb_automailsent", $jbAutomailsent));
               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 . "] [RELATED]");

            // $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] [RELATED]");
            endif;
         endif;
         
         $job_id = "";
         $f_email = "";

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

//   sleep(30);

// endwhile;  // Endless loop
?>
