<?php
/*=======================================================================
 *
 * inc_automailer.inc.php
 *
 * Autor: Marc Vollmann
 *
  =======================================================================*/


// Get jobs for automailer
function getAutoMailerJobs($limit, $delayInMinutes = 0) {
  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;

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

  // Delay
  $fromClauseDelay = " LEFT JOIN genericdatacontainer AS gdc_pls ON gdc_pls.gdc_obj_id = jb.jb_id AND gdc_pls.gdc_obj_type = 'jb' AND gdc_pls.gdc_gen_fieldname = 'photos_last_station'";
  $whereClauseDelay = " (ISNULL(gdc_pls.gdc_content) OR LENGTH(TRIM(gdc_pls.gdc_content)) = 0 OR TRIM(gdc_pls.gdc_content) = '0')";
  if (is_numeric($delayInMinutes) && $delayInMinutes > 0) :
     $endTime = getDateTime("datetime_plus_offset", array(0,-($delayInMinutes),0,0,0,0), "Y-m-d H:i:s");
     $whereClauseDelay = " jb.jb_finishtime < '" . $endTime . "' AND"
                       . " (NOT ISNULL(gdc_pls.gdc_content))     AND"
                       . " LENGTH(TRIM(gdc_pls.gdc_content)) > 0 AND"
                       . " TRIM(gdc_pls.gdc_content) > '0'          ";
  endif;

  // 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"
            . " FROM job AS jb" . $fromClauseDelay . ", costcenter AS csc, customer AS cs, costcenteraddress AS cscad, employee AS emp, user AS usr, tour AS tr"
            . " 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"
            . "       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'                                     AND"
            .         $whereClauseDelay
            . " 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"
            . " FROM job AS jb" . $fromClauseDelay . ", costcenter AS csc, customer AS cs, costcenteraddress AS cscad, employee AS emp, user AS usr, tour AS tr"
            . " 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"
            . "       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'                                     AND"
            .         $whereClauseDelay
            . " ORDER BY jb.jb_finishtime " . $limit;

  $result = $db2->dbQ("(" . $sqlquery . ") UNION (" . $sqlquery2 . ")");
  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"]);
  endwhile;
  $result->free();
  return $retArray;
}  


// Get jobs for automailer
function getAutoMailerJobs2($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;

  // 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_PICKUP_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");
  // $startTime = getDateTime("3") . " 00:00:00";

  // jb.jb_automailsent2 = '999' <=> Mail was sent correctly
  // jb.jb_automailsent2 = '998' <=> Mail was NOT sent correctly. Process iteration terminated!
  // 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"
            . " FROM job AS jb, costcenter AS csc, customer AS cs, costcenteraddress AS cscad, employee AS emp, user AS usr, tour AS tr"
            . " WHERE jb.jb_status = '1'                                     AND"
            . "       jb.jb_taketime > '" . $startTime . "'                  AND"
            . "       jb.jb_automailsent2 != '998'                           AND"
            . "       jb.jb_automailsent2 != '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_jbstatusmail2 = '1'                              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"
            . "       ((usr.usr_email != '' AND cs.cs_jbstatusmail2csc = '0') OR"
            . "        (cscad.cscad_email != '' AND cs.cs_jbstatusmail2csc = '1')) AND"
            . "       jb.jb_id = tr.jb_id                                    AND"
            . "       tr.tr_sort = '1'                                       AND"
            . "       tr.tr_status = '1'                                        "
            . " ORDER BY jb.jb_taketime " . $limit;
            
  $sqlquery2 = "SELECT jb.jb_id, usr.usr_email, jb.cr_sid, jb.hq_id, cs.cs_jbstatusmail2csc, cscad.cscad_email"
            . " FROM job AS jb, costcenter AS csc, customer AS cs, costcenteraddress AS cscad, employee AS emp, user AS usr, tour AS tr"
            . " WHERE jb.jb_status = '1'                                     AND"
            . "       jb.jb_taketime > '" . $startTime . "'                  AND"
            . "       jb.jb_automailsent2 != '998'                           AND"
            . "       jb.jb_automailsent2 != '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_jbstatusmail2 = '1'                              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"
            . "       ((usr.usr_email != '' AND cs.cs_jbstatusmail2csc = '0') OR"
            . "        (cscad.cscad_email != '' AND cs.cs_jbstatusmail2csc = '1')) AND"
            . "       jb.jb_id = tr.jb_id                                    AND"
            . "       tr.tr_sort = '1'                                       AND"
            . "       tr.tr_status = '1'                                        "
            . " ORDER BY jb.jb_taketime " . $limit;

  $result = $db2->dbQ("(" . $sqlquery . ") UNION (" . $sqlquery2 . ")");
  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"]);
  endwhile;
  $result->free();
  return $retArray;
}  


// Get jobs for automailer
function getAutoMailerJobs3($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;

  // Exclude jobs with special vehicles (E.g.: Do not generate a mail if internal job is generated with vehicle SID=1888)
  $whereClauseExcludedVehicles = "";
  /*
  $excludedVehicles = getParameterValue("0", "EMAIL_CRVHSID_NO_MAIL", "0");  // "Meta-Global" <=> hq_id = 0
  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(-2,0,0,0,0,0), "Y-m-d H:i:s");
  // $startTime = getDateTime("3") . " 00:00:00";

  // jb.jb_automailsent3 = '999' <=> Mail was sent correctly
  // jb.jb_automailsent3 = '998' <=> Mail was NOT sent correctly. Process iteration terminated!
  // 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"
            . " FROM job AS jb, costcenter AS csc, customer AS cs, costcenteraddress AS cscad, employee AS emp, user AS usr"
            . " WHERE (jb.jb_status = '8' OR jb.jb_status = '9' OR jb.jb_status = '0' OR jb.jb_status = '1') AND"
            . "       jb.jb_ordertime > '" . $startTime . "'                 AND"
            . "       (ISNULL(jb.jb_offer) OR jb.jb_offer = '0')             AND"
            . "       jb.jb_automailsent3 != '998'                           AND"
            . "       jb.jb_automailsent3 != '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_jbstatusmail3 = '1'                              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"
            . "       ((usr.usr_email != '' AND cs.cs_jbstatusmail2csc = '0') OR"
            . "        (cscad.cscad_email != '' AND cs.cs_jbstatusmail2csc = '1'))"
            . " ORDER BY jb.jb_ordertime " . $limit;
            
  $sqlquery2 = "SELECT jb.jb_id, usr.usr_email, jb.cr_sid, jb.hq_id, cs.cs_jbstatusmail2csc, cscad.cscad_email"
            . " FROM job AS jb, costcenter AS csc, customer AS cs, costcenteraddress AS cscad, employee AS emp, user AS usr"
            . " WHERE (jb.jb_status = '8' OR jb.jb_status = '9' OR jb.jb_status = '0' OR jb.jb_status = '1') AND"
            . "       jb.jb_ordertime > '" . $startTime . "'                 AND"
            . "       (ISNULL(jb.jb_offer) OR jb.jb_offer = '0')             AND"
            . "       jb.jb_automailsent3 != '998'                           AND"
            . "       jb.jb_automailsent3 != '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_jbstatusmail3 = '1'                              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"
            . "       ((usr.usr_email != '' AND cs.cs_jbstatusmail2csc = '0') OR"
            . "        (cscad.cscad_email != '' AND cs.cs_jbstatusmail2csc = '1'))"
            . " ORDER BY jb.jb_ordertime " . $limit;

  $result = $db2->dbQ("(" . $sqlquery . ") UNION (" . $sqlquery2 . ")");
  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"]);
  endwhile;
  $result->free();
  return $retArray;
}


// Get jobs for automailer
function getAutoMailerStations($limit, $delayInMinutes = 0) {
  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;

  // 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
  $constAmStarttimeInDays = 1;
  $startTime = getDateTime("datetime_plus_offset", array(0,0,0,0,-($constAmStarttimeInDays),0), "Y-m-d H:i:s");
  // $currentTime = getDateTime("0");

  // Delay
  $fromClauseDelay = " LEFT JOIN genericdatacontainer AS gdc_tr_photo ON gdc_tr_photo.gdc_obj_id = tr.tr_id AND gdc_tr_photo.gdc_obj_type = 'tr' AND gdc_tr_photo.gdc_gen_fieldname = 'tr_photo'";
  $whereClauseDelay = " (ISNULL(gdc_tr_photo.gdc_content) OR LENGTH(TRIM(gdc_tr_photo.gdc_content)) = 0) AND";
  if (is_numeric($delayInMinutes) && $delayInMinutes > 0) :
     $endTime = getDateTime("datetime_plus_offset", array(0,-($delayInMinutes),0,0,0,0), "Y-m-d H:i:s");
     $whereClauseDelay = " tr.tr_finishtime < '" . $endTime . "' AND"
                       . " (NOT ISNULL(gdc_tr_photo.gdc_content)) AND"
                       . " LENGTH(SUBSTRING(TRIM(gdc_tr_photo.gdc_content), 1, (INSTR(gdc_tr_photo.gdc_content, '|') - 1))) > 0 AND"
                       . " SUBSTRING(gdc_tr_photo.gdc_content, 1, (INSTR(gdc_tr_photo.gdc_content, '|') - 1)) > 0 AND";
  endif;

  // gdc.gdc_content = '999' <=> Mail was sent correctly
  // gdc.gdc_content = '998' <=> Mail was NOT sent correctly. Process iteration terminated!
  // gdc.gdc_content = '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, tr.tr_id, tr.tr_sort, usr.usr_email, jb.jb_ordertime, jb.cr_sid, jb.hq_id, cs.cs_jbstatusmail2csc, cscad.cscad_email, IFNULL(gdc.gdc_content,'') AS gdc_content"
            . " FROM job AS jb, costcenter AS csc, customer AS cs, costcenteraddress AS cscad, employee AS emp, user AS usr,"
            . "      tour AS tr LEFT JOIN genericdatacontainer AS gdc ON gdc.gdc_obj_id = tr.tr_id AND gdc.gdc_obj_type = 'tr' AND gdc.gdc_gen_fieldname = 'auto_mail_station'" . $fromClauseDelay
            . " WHERE jb.jb_status = '1'                             AND"
            . "       jb.jb_ordertime >= '" . $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"
            . "       SUBSTRING(cs.cs_jbstatusmail_fields,5,1) = '1' 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_status = '1'                             AND"
            . "       tr.tr_finishtime > '" . $startTime . "'        AND"
            .         $whereClauseDelay
            . "       (usr_email != '' OR cscad_email != '') AND"
            . "       (NOT EXISTS (SELECT * FROM genericdatacontainer AS gdc WHERE gdc.gdc_obj_id = tr.tr_id AND gdc.gdc_obj_type = 'tr' AND gdc.gdc_gen_fieldname = 'auto_mail_station'))"
            . " ORDER BY tr.tr_finishtime " . $limit;

  $sqlquery2 = "SELECT jb.jb_id, tr.tr_id, tr.tr_sort, usr.usr_email, jb.jb_ordertime, jb.cr_sid, jb.hq_id, cs.cs_jbstatusmail2csc, cscad.cscad_email, IFNULL(gdc.gdc_content,'') AS gdc_content"
            . " FROM job AS jb, costcenter AS csc, customer AS cs, costcenteraddress AS cscad, employee AS emp, user AS usr,"
            . "      tour AS tr LEFT JOIN genericdatacontainer AS gdc ON gdc.gdc_obj_id = tr.tr_id AND gdc.gdc_obj_type = 'tr' AND gdc.gdc_gen_fieldname = 'auto_mail_station'" . $fromClauseDelay
            . " WHERE jb.jb_status = '1'                             AND"
            . "       jb.jb_ordertime >= '" . $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"
            . "       SUBSTRING(cs.cs_jbstatusmail_fields,5,1) = '1' 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_status = '1'                             AND"
            . "       tr.tr_finishtime > '" . $startTime . "'        AND"
            .         $whereClauseDelay
            . "       (usr_email != '' OR cscad_email != '') AND"
            . "       (NOT EXISTS (SELECT * FROM genericdatacontainer AS gdc WHERE gdc.gdc_obj_id = tr.tr_id AND gdc.gdc_obj_type = 'tr' AND gdc.gdc_gen_fieldname = 'auto_mail_station'))"
            . " ORDER BY tr.tr_finishtime " . $limit;

  $result = $db2->dbQ("(" . $sqlquery . ") UNION (" . $sqlquery2 . ")");
  while ($row = $result->fetch_assoc()):
        $retArray[] = array($row["jb_id"], $row["tr_sort"], $row["usr_email"], $row["cr_sid"], $row["hq_id"], $row["cs_jbstatusmail2csc"], $row["cscad_email"], $row["tr_id"], $row["jb_ordertime"]);
  endwhile;
  $result->free();
  return $retArray;
}

// Get jobs for automailer
function getAutoMailerJobsGdc($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;

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

  // Finished jobs
  $sqlquery = "SELECT jb.jb_id, gdc.gdc_content, jb.cr_sid, jb.hq_id, '3' AS job_mode"
            . " FROM job AS jb, tour AS tr, genericdatacontainer AS gdc, costcenter AS csc, customer AS cs"
            . " WHERE jb.jb_status = '2'                                     AND"
            . "       jb.jb_finishtime > '" . $startTime . "'                AND"
            . "       (ISNULL(jb.jb_storno) OR jb.jb_storno = '0')           AND"
            . "       jb.csc_id_payer = csc.csc_id                           AND"
            . "       cs.cs_id = csc.cs_id                                   AND"
            . "       cs.cs_jbstatusmail = '1'                               AND"
            . "       gdc.gdc_obj_id = jb.jb_id                              AND"
            . "       gdc.gdc_obj_type = 'jb'                                AND"
            . "       gdc.gdc_gen_fieldname = 'jb_cashpayer_mail'            AND"
            . "       gdc.gdc_content != ''                                  AND"
            . "       gdc.gdc_context != 'MAIL_SENT'                         AND"
            . "       gdc.gdc_context != 'MAIL_NOT_SENT'                     AND"
            . "       (IF (gdc.gdc_context REGEXP '^[0-9]+$', 
                         gdc.gdc_context + 0,
                         1024
                      ) & 1028) != 1028                                      AND"
            . "       jb.jb_id = tr.jb_id                                    AND"
            . "       tr.tr_sort = '1'                                       AND"
            . "       tr.tr_status = '1'                                        "
            . " ORDER BY jb.jb_finishtime " . $limit;

  // Picked jobs
  $sqlquery2 = "SELECT jb.jb_id, gdc.gdc_content, jb.cr_sid, jb.hq_id, '2' AS job_mode"
            . " FROM job AS jb, tour AS tr, genericdatacontainer AS gdc, costcenter AS csc, customer AS cs"
            . " WHERE jb.jb_status = '1'                                     AND"
            . "       jb.jb_taketime > '" . $startTime . "'                  AND"
            . "       (ISNULL(jb.jb_storno) OR jb.jb_storno = '0')           AND"
            . "       jb.csc_id_payer = csc.csc_id                           AND"
            . "       cs.cs_id = csc.cs_id                                   AND"
            . "       cs.cs_jbstatusmail2 = '1'                              AND"
            . "       gdc.gdc_obj_id = jb.jb_id                              AND"
            . "       gdc.gdc_obj_type = 'jb'                                AND"
            . "       gdc.gdc_gen_fieldname = 'jb_cashpayer_mail'            AND"
            . "       gdc.gdc_content != ''                                  AND"
            . "       gdc.gdc_context != 'MAIL_SENT'                         AND"
            . "       gdc.gdc_context != 'MAIL_NOT_SENT'                     AND"
            . "       (IF (gdc.gdc_context REGEXP '^[0-9]+$', 
                         gdc.gdc_context + 0,
                         1024
                      ) & 1026) != 1026                                      AND"
            . "       jb.jb_id = tr.jb_id                                    AND"
            . "       tr.tr_sort = '1'                                       AND"
            . "       tr.tr_status = '1'                                        "
            . " ORDER BY jb.jb_taketime " . $limit;

  // Created jobs
  $sqlquery3 = "SELECT jb.jb_id, gdc.gdc_content, jb.cr_sid, jb.hq_id, '1' AS job_mode"
            . " FROM job AS jb, genericdatacontainer AS gdc, costcenter AS csc, customer AS cs"
            . " WHERE (jb.jb_status = '8' OR jb.jb_status = '9' OR jb.jb_status = '0' OR jb.jb_status = '1') AND"
            . "       jb.jb_ordertime > '" . $startTime . "'                 AND"
            . "       (ISNULL(jb.jb_storno) OR jb.jb_storno = '0')           AND"
            . "       jb.csc_id_payer = csc.csc_id                           AND"
            . "       cs.cs_id = csc.cs_id                                   AND"
            . "       cs.cs_jbstatusmail3 = '1'                              AND"
            . "       gdc.gdc_obj_id = jb.jb_id                              AND"
            . "       gdc.gdc_obj_type = 'jb'                                AND"
            . "       gdc.gdc_gen_fieldname = 'jb_cashpayer_mail'            AND"
            . "       gdc.gdc_content != ''                                  AND"
            . "       gdc.gdc_context != 'MAIL_SENT'                         AND"
            . "       gdc.gdc_context != 'MAIL_NOT_SENT'                     AND"
            . "       (IF (gdc.gdc_context REGEXP '^[0-9]+$', 
                         gdc.gdc_context + 0,
                         1024
                      ) & 1025) != 1025                                         "
            . " ORDER BY jb.jb_ordertime " . $limit;
  
  $result = $db2->dbQ("(" . $sqlquery . ") UNION (" . $sqlquery2 . ") UNION (" . $sqlquery3 . ")");
  while ($row = $result->fetch_assoc()):
        $retArray[] = array($row["jb_id"], $row["gdc_content"], $row["cr_sid"], $row["hq_id"], $row["job_mode"]);
  endwhile;
  $result->free();
  return $retArray;
}

// Get jobs for job jam
function getAutoMailerJobsByJobJam ($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;

  // 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
  // $constAmStarttimeInDays = 0;  // Jobs with order time from today only
  // $startTime = getDateTime("datetime_plus_offset", array(0,0,0,0,-($constAmStarttimeInDays),0), "Y-m-d H:i:s");
  $startTime = getDateTime("3") . " 00:00:00";
  $currentTime = getDateTime("0");

  // Job jam of "ad hoc" jobs AND "reservations"  
  $sqlquery = "SELECT jb.jb_id, usr.usr_email, jb.cr_sid, jb.hq_id, jb.jb_ordertime, cs.cs_jbstatusmail2csc, cscad.cscad_email, cs.cs_id"
            . " FROM job AS jb, costcenter AS csc, customer AS cs, costcenteraddress AS cscad, employee AS emp, user AS usr, genericdatacontainer AS gdc,"
            . "      tour AS tr LEFT JOIN genericdatacontainer AS gdc_arr_tour ON gdc_arr_tour.gdc_obj_id = tr.tr_id AND gdc_arr_tour.gdc_obj_type = 'tr' AND gdc_arr_tour.gdc_gen_fieldname = 'arr_tour'"
            . " WHERE jb.jb_status != '1'                                          AND"
            . "       jb.jb_status != '2'                                          AND"
            . "       jb.jb_ordertime > '" . $startTime . "'                       AND"
            . "       (ISNULL(jb.jb_offer) OR jb.jb_offer = '0')                   AND"
            . "       (ISNULL(jb.jb_automailsent) OR jb.jb_automailsent = '0')     AND"
            . "       (ISNULL(jb.jb_automailsent2) OR jb.jb_automailsent2 = '0')   AND"
            .         $whereClauseExcludedVehicles
            . "       (ISNULL(jb.jb_storno) OR jb.jb_storno = '0')                 AND"
            . "       gdc.gdc_obj_id = jb.jb_id                                    AND"
            . "       gdc.gdc_obj_type = 'jb'                                      AND"
            . "       gdc.gdc_gen_fieldname = 'jb_job_jam'                         AND"
            . "       gdc.gdc_content != ''                                        AND"
            . "       gdc.gdc_content <= '" . $currentTime . "'                    AND"
            . "       gdc.gdc_context != 'MAIL_SENT'                               AND"
            . "       gdc.gdc_context != 'MAIL_NOT_SENT'                           AND"
            . "       jb.csc_id_payer = csc.csc_id                                 AND"
            . "       csc.cs_id = cs.cs_id                                         AND"
            . "       cs.cs_jb_jam_waittime > '0'                                  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"
            . "       ((usr.usr_email != '' AND cs.cs_jbstatusmail2csc = '0') OR"
            . "        (cscad.cscad_email != '' AND cs.cs_jbstatusmail2csc = '1')) AND"
            . "       jb.jb_id = tr.jb_id                                          AND"
            . "       tr.tr_sort = '1'                                             AND"
            . "       tr.tr_status != '1'                                          AND"
            . "       ( (LEFT(gdc_arr_tour.gdc_content,14) = '') OR"
            . "         (STR_TO_DATE(LEFT(gdc_arr_tour.gdc_content,14), '%Y%m%d%H%i%s') IS NULL) OR "
            . "         (STR_TO_DATE(LEFT(gdc_arr_tour.gdc_content,14), '%Y%m%d%H%i%s') = '0000-00-00 00:00:00')"
            . "       )"
            . " ORDER BY jb.jb_ordertime " . $limit;

  $result = $db2->dbQ($sqlquery);
  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_id"], $row["jb_ordertime"]);
  endwhile;
  $result->free();
  return $retArray;
}

// Get job jam jobs where emails were sent to the customers have to be checked regarding mediation the next n minutes
function getAutoMailerJobJamControl ($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;

  // $constAmStarttimeInDays = getParameterValue("0", "AUTOMAILER_STARTTIME_IN_DAYS", "0");  // "Meta-Global" <=> hq_id = 0
  // $constAmStarttimeInDays = 0;  // Jobs with order time from today only
  // $startTime = getDateTime("datetime_plus_offset", array(0,0,0,0,-($constAmStarttimeInDays),0), "Y-m-d H:i:s");
  $startTime = getDateTime("3") . " 00:00:00";
  $currentTime = getDateTime("0");

  // Job jam of "ad hoc" jobs AND "reservations"  
  $sqlquery = "SELECT jb.jb_id, usr.usr_email, jb.cr_sid, jb.hq_id, jb.jb_ordertime, cs.cs_jbstatusmail2csc, cscad.cscad_email, cs.cs_id"
            . " FROM job AS jb LEFT JOIN genericdatacontainer AS gdc_job_jam ON gdc_job_jam.gdc_obj_id = jb.jb_id AND gdc_job_jam.gdc_obj_type = 'jb' AND gdc_job_jam.gdc_gen_fieldname = 'jb_job_jam',"
            . "      costcenter AS csc, customer AS cs, costcenteraddress AS cscad, employee AS emp, user AS usr, genericdatacontainer AS gdc"
            . " WHERE jb.jb_status = '1'                                           AND"
            . "       jb.jb_ordertime > '" . $startTime . "'                       AND"
            . "       (ISNULL(jb.jb_storno) OR jb.jb_storno = '0')                 AND"
            . "       gdc.gdc_obj_id = jb.jb_id                                    AND"
            . "       gdc.gdc_obj_type = 'jb'                                      AND"
            . "       gdc.gdc_gen_fieldname = 'jb_job_jam_ctrl'                    AND"
            . "       gdc.gdc_content != ''                                        AND"
            . "       '" . $currentTime . "' <= gdc.gdc_content                    AND"
            . "       gdc.gdc_context != 'MAIL_SENT'                               AND"
            . "       gdc.gdc_context != 'MAIL_NOT_SENT'                           AND"
            . "       gdc_job_jam.gdc_context = 'MAIL_SENT'                        AND"
            . "       jb.csc_id_payer = csc.csc_id                                 AND"
            . "       csc.cs_id = cs.cs_id                                         AND"
            . "       cs.cs_jb_jam_waittime > '0'                                  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"
            . "       ((usr.usr_email != '' AND cs.cs_jbstatusmail2csc = '0') OR"
            . "        (cscad.cscad_email != '' AND cs.cs_jbstatusmail2csc = '1'))    "
            . " ORDER BY jb.jb_ordertime " . $limit;

  $result = $db2->dbQ($sqlquery);
  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_id"], $row["jb_ordertime"]);
  endwhile;
  $result->free();
  return $retArray;
}

// Get stations with end customer email addresses for automailer
function getAutoMailerTracking($limit = 0) {
  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;

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

  $sqlquery = "SELECT jb.jb_id, tr.tr_id, tr.tr_sort, jb.jb_ordertime, jb.cr_sid, jb.hq_id, jb.csc_id_payer, cs.cs_id AS cs_id_payer,"
            . "       IFNULL(gdc.gdc_content,'') AS gdc_content, IFNULL(gdc.gdc_context,'') AS gdc_context"
            . " FROM job AS jb, costcenter AS csc, customer AS cs,"
            . "      tour AS tr, tour AS tr_pickup, genericdatacontainer AS gdc"
            . " WHERE jb.jb_status = '1'                             AND"
            . "       jb.jb_ordertime >= '" . $startTime . "'        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_tracking = '1'                           AND"
            . "       jb.jb_id = tr_pickup.jb_id                     AND"
            . "       tr_pickup.tr_sort = '1'                        AND"
            . "       tr_pickup.tr_status = '1'                      AND"
            . "       jb.jb_id = tr.jb_id                            AND"
            . "       tr.tr_id = gdc.gdc_obj_id                      AND"
            . "       gdc.gdc_obj_type = 'tr'                        AND"
            . "       gdc.gdc_gen_fieldname = 'tr_tracking'          AND"
            . "       gdc.gdc_content != ''                          AND"
            . "       gdc.gdc_context != 'SENT_OK'                   AND"
            . "       gdc.gdc_context != 'SENT_NOK'                     "
            . " ORDER BY jb.jb_id, tr.tr_sort " . $limit;
// echo $sqlquery . "\n\n";
  $result = $db2->dbQ($sqlquery);
  while ($row = $result->fetch_assoc()):
        $retArray[] = array($row["jb_id"], $row["tr_id"], $row["tr_sort"], $row["gdc_content"], $row["gdc_context"], $row["hq_id"], $row["csc_id_payer"], $row["cs_id_payer"], $row["jb_ordertime"], $row["cr_sid"]);
  endwhile;
  $result->free();
  return $retArray;
}
?>