<?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");


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


// Get jobs for automailer
function getAutoMailerJobs_MC($limit) {
  global $db, $logFile;

  // Try to connect request server because of performance
  global $db2;
  getDb2Connection();

  $retArray = array();

  // Limit    
  if (is_numeric($limit) && $limit > 0) :
     $limit = "LIMIT 0," . $limit;
  else :
     $limit = "";     
  endif;
$limit = "";
  
  // Exclude jobs with special vehicles (E.g.: Do not generate a mail if internal job is generated with vehicle SID=1888)
  $excludedVehicles = getParameterValue("0", "EMAIL_CRVHSID_NO_MAIL", "0");  // "Meta-Global" <=> hq_id = 0
  $whereClauseExcludedVehicles = "";
  if ($excludedVehicles != "") :
     $tmp = spliti(",",$excludedVehicles);
     $lenTmp = count($tmp);
     for ($i = 0; $i < $lenTmp; $i++) {  
        $whereClauseExcludedVehicles .= " jb.cr_sid != '" . $tmp[$i] . "' AND ";
     };
  endif;

  $constAmStarttimeInDays = getParameterValue("0", "AUTOMAILER_STARTTIME_IN_DAYS", "0");  // "Meta-Global" <=> hq_id = 0
  $startTime = getDateTime("datetime_plus_offset", array(0,0,0,0,-($constAmStarttimeInDays),0), "Y-m-d H:i:s");
  // $currentTime = getDateTime("0");

  // jb.jb_automailsent = '999' <=> Mail was sent correctly
  // jb.jb_automailsent = '998' <=> Mail was NOT sent correctly. Process iteration terminated!
  // jb.jb_automailsent = '997' <=> Mail will never be sent because it is a batch job
  // Otherwise number is equal to the number of faults.
  $sqlquery = "SELECT jb.jb_id, usr.usr_email, jb.cr_sid, jb.hq_id, cs.cs_jbstatusmail2csc, cscad.cscad_email, cs.cs_eid, cmp.cmp_comp, cs.cs_jbstatusmail_pdf, jb.jb_finishtime, jb.jb_automailsent"
            . " FROM job AS jb, costcenter AS csc, customer AS cs, costcenteraddress AS cscad, employee AS emp, user AS usr, tour AS tr, company AS cmp"
            . " WHERE jb.jb_status = '2'                                     AND"
            . "       jb.jb_finishtime > '" . $startTime . "'                AND"
            . "       jb.jb_automailsent != '997'                            AND"
            . "       jb.jb_automailsent != '998'                            AND"
            . "       jb.jb_automailsent != '999'                            AND"
            .         $whereClauseExcludedVehicles
            . "       (ISNULL(jb.jb_storno) OR jb.jb_storno = '0')           AND"            
            . "       jb.csc_id_payer = csc.csc_id                           AND"
            . "       csc.cs_id = cs.cs_id                                   AND"
            . "       cs.cs_jbstatusmail = '1'                               AND"
            . "       cmp.cmp_id = cs.cmp_id                                 AND"
            . "       cs.cs_admin = emp.emp_id                               AND"
            . "       emp.usr_id = usr.usr_id                                AND"
            . "       csc.csc_id = cscad.csc_id                              AND"
            . "       cscad.adt_id = '2'                                     AND"
            . "       jb.jb_id = tr.jb_id                                    AND"
            . "       tr.tr_sort = '1'                                       AND"
            . "       tr.tr_status = '1'                                        "
            . " ORDER BY jb.jb_finishtime " . $limit;
            
  $sqlquery2 = "SELECT jb.jb_id, usr.usr_email, jb.cr_sid, jb.hq_id, cs.cs_jbstatusmail2csc, cscad.cscad_email, cs.cs_eid, cmp.cmp_comp, cs.cs_jbstatusmail_pdf, jb.jb_finishtime, jb.jb_automailsent"
            . " FROM job AS jb, costcenter AS csc, customer AS cs, costcenteraddress AS cscad, employee AS emp, user AS usr, tour AS tr, company AS cmp"
            . " WHERE jb.jb_status = '2'                                     AND"
            . "       jb.jb_finishtime > '" . $startTime . "'                AND"
            . "       jb.jb_automailsent != '997'                            AND"
            . "       jb.jb_automailsent != '998'                            AND"
            . "       jb.jb_automailsent != '999'                            AND"
            .         $whereClauseExcludedVehicles
            . "       (ISNULL(jb.jb_storno) OR jb.jb_storno = '0')           AND"
            . "       jb.csc_id_payer_cash = csc.csc_id                      AND"
            . "       csc.cs_id = cs.cs_id                                   AND"
            . "       cs.cs_jbstatusmail = '1'                               AND"
            . "       cmp.cmp_id = cs.cmp_id                                 AND"
            . "       cs.cs_admin = emp.emp_id                               AND"
            . "       emp.usr_id = usr.usr_id                                AND"
            . "       csc.csc_id = cscad.csc_id                              AND"
            . "       cscad.adt_id = '2'                                     AND"
            . "       jb.jb_id = tr.jb_id                                    AND"
            . "       tr.tr_sort = '1'                                       AND"
            . "       tr.tr_status = '1'                                        "
            . " ORDER BY jb.jb_finishtime " . $limit;
// echo "(" . $sqlquery . ") UNION (" . $sqlquery2 . ")"; die();
  $result = $db2->query("(" . $sqlquery . ") UNION (" . $sqlquery2 . ")");
  // $result = $db2->query($sqlquery . " UNION " . $sqlquery2);
  if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
  while ($row = $result->fetch_assoc()):
        $retArray[] = array($row["jb_id"], $row["usr_email"], $row["cr_sid"], $row["hq_id"], $row["cs_jbstatusmail2csc"], $row["cscad_email"], $row["cs_eid"], $row["cmp_comp"], $row["cs_jbstatusmail_pdf"], $row["jb_finishtime"], $row["jb_automailsent"]);
  endwhile;
  $result->free();
  return $retArray;
}  


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


// Endless loop
// while (TRUE):

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

  // ********************************
  // *** Send mails automatically ***
  // ********************************

  $output = "";

  $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_MC(1);

     // Loop all jobs (default one)
     $lenJobArray = count($jobArray);
     $output .= "<table>";
     $output .= "<tr>";
     $output .= "<td>AUFTRAG</td>";
     $output .= "<td>ERLEDIGUNGSZEIT</td>";     
     $output .= "<td>KURIER</td>";
     $output .= "<td>HQ</td>";
     $output .= "<td>EID</td>";
     $output .= "<td>FIRMA</td>";
     $output .= "<td>PDF JA_NEIN</td>";     
     $output .= "<td>AUTOMAILSENT_STATE</td>";
     $output .= "<td>MAIL (CS)</td>";
     $output .= "<td>MAIL_CSC?</td>";
     $output .= "<td>MAIL (CSC)</td>";
     $output .= "</tr>";
     $count = 0;
     for ($i = 0; $i < $lenJobArray; $i++) :

         // Current job and mail address
         $job_id = $jobArray[$i][0];
         $f_jb_finishtime = $jobArray[$i][9];
         $job_crSid = $jobArray[$i][2];
         $currentHqId = $jobArray[$i][3];
         $takeCscMailAdress = $jobArray[$i][4];
         $f_cs_eid = $jobArray[$i][6];
         $f_cmp_comp = $jobArray[$i][7];
         $f_cs_jbstatusmail_pdf = $jobArray[$i][8];         
         $f_jb_automailsent = $jobArray[$i][10];         
         $f_email = trim($jobArray[$i][1]);
         $f_email = str_replace(" ", "", $f_email);
         $f_email_csc = $jobArray[$i][5];
         $f_email_csc = str_replace(" ", "", $f_email_csc);
         

         $output .= "<tr>";
         $output .= "<td>" . $job_id . "</td>";
         $output .= "<td>" . $f_jb_finishtime . "</td>";         
         $output .= "<td>" . $job_crSid . "</td>";
         $output .= "<td>" . $currentHqId . "</td>";
         $output .= "<td>" . $f_cs_eid . "</td>";
         $output .= "<td>" . $f_cmp_comp . "</td>";
         $output .= "<td>" . $f_cs_jbstatusmail_pdf . "</td>";         
         $output .= "<td>" . $f_jb_automailsent . "</td>";
         $output .= "<td>" . $f_email . "</td>";
         $output .= "<td>" . $takeCscMailAdress . "</td>";
         $output .= "<td>" . $f_email_csc . "</td>";
         $output .= "</tr>";
         
         $count++;
     endfor;  // Loop all jobs
     $output .= "</table>";
  endif;  // AUTOMAILER_ENABLED

//   sleep(30);

// endwhile;  // Endless loop

echo $count;
echo "<br><br><br><br>";
echo $output

?>
