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


error_reporting(E_ALL ^ (E_DEPRECATED | E_NOTICE));

include_once ("../include/mcglobal.inc.php");
// include_once ("../include/auth.inc.php");
include_once ("../include/inc_filters.inc.php");
include_once ("../include/inc_vehicle.inc.php");
include_once ("../include/html.inc.php");
include_once ("../include/inc_html2pdf.inc.php");


// Check global parameter for executing CRON process
$globalCronEnabled = getParameterValue("0", "GLOBAL_CRON_ENABLED", "0");

// Check parameter for executing CRON process for CARTAGE NOTE
$cronCartageNoteEnabled = getParameterValue("0", "CRON_CARTAGE_NOTE_ENABLED", "0");


if ($globalCronEnabled == "1" && $cronCartageNoteEnabled == "1") :

   // Execution-Time for script
   set_time_limit(0);
   
   // Get current day
   $currDay = getDateTime("3");
   $currentDayTime = getDateTime("0");
   
   // Clock time now
   $currClockTime = getDateTime("4");
   $currClockHourMinute = substr($currClockTime,0,5);  // E.g. "19:30"
   
   // Get path to doc root
   $dirName = dirname(__FILE__);
   $dirName = str_replace("\\", "/", $dirName);
   $lastSlashPos = strrpos($dirName,"/");
   $path = substr($dirName, 0, $lastSlashPos);
   
   // Log file
   $logFile = getParameterValue("0", "AUTOMAILER_CARTAGE_NOTE_LOGFILE", "0");
   if ($logFile == "") : $logFile = "../log/automailer_cartage_note.log"; endif;
   // writeToFile($logFile, "LOG=START|");
   
   
   // Get ALL customers (of ALL headquarters) belonging to the "STATIC" groups !!!!
   $sqlquery = "SELECT cs.cs_id"
             . "  FROM customer AS cs, company AS cmp"
             . "  WHERE (cs.cs_group LIKE '%,1,%' OR cs.cs_group LIKE '%,2,%' OR cs.cs_group LIKE '%,3,%' OR cs.cs_group LIKE '%,4,%' OR cs.cs_group LIKE '%,5,%' OR cs.cs_group LIKE '%,6,%' OR cs.cs_group LIKE '%,7,%' OR cs.cs_group LIKE '%,8,%' OR cs.cs_group LIKE '%,11,%' OR cs.cs_group LIKE '%,12,%' OR cs.cs_group LIKE '%,13,%') AND "
             . "         cmp.cmp_id = cs.cmp_id AND cmp.cmp_comp != 'EXTERN' AND cs.cs_id_parent != '0' AND NOT isnull(cs.cs_id_parent)";
   $result = $db->query($sqlquery);
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
   $csIdArray = array();
   while ($row = $result->fetch_assoc()):
         $csIdArray[] = $row["cs_id"];
   endwhile;
   $result->free();
   $csIdArrayLen = count($csIdArray);
   
   // !!!! TEST !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   // $csIdArray = array("1");
   // $csIdArrayLen = count($csIdArray);
   // !!!! TEST !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


   // Iterate all customers
   for ($i = 0; $i < $csIdArrayLen; $i++) :

       $csId = $csIdArray[$i];

       // $csHqId = getFieldValueFromId("customer","cs_id",$csId,"hq_id");  // Get hq_id if the carrier
       $parDayOffset = getObjectBasedParameterValue("AUTOMAILER_CARTAGE_NOTE_DAY_OFFSET", $csId, "", "", "1");
       if ($parDayOffset != "" && is_numeric($parDayOffset) && $parDayOffset > 0) :
          // Overwrite execution date
          $currDay = getDateTime("date_plus_offset", array(0,$parDayOffset,0), "Y-m-d");
       endif;
   
       // Check cartage note has been sent for the customer
       $gdcContextCartage = getFieldValueFromClause("genericdatacontainer", "gdc_context", "gdc_obj_type = 'cs' AND gdc_obj_id = '" . $csId . "' AND gdc_gen_fieldname = 'mail_cartage_note' AND gdc_content = '" . $currDay . "'");
       if (true || $gdcContextCartage == "") :

          // Check cartage note time setting for customer
          $mtCartageTime = getFieldValueFromClause("metatype","mt_mapped_value","mt_type = 'cartage_time' AND mt_sort = '0' AND mt_objtype = 'cs' AND mt_objid = '" . $csId . "'");
          if ($mtCartageTime == "") : 
             // Get default value
             $mtCartageTime = getFieldValueFromClause("metatype","mt_mapped_value","mt_type = 'cartage_time' AND mt_sort = '0' AND mt_objtype = '' AND mt_objid = '0'");
          endif;
          // if ($mtCartageTime != "" && $mtCartageTime >= $currClockHourMinute) :
          if (true) :

             // Get mail address data for the related customer. (No global parameter checks !!!!)
             $parMailToAddresses = getObjectBasedParameterValue("MAIL_CARTAGE_NOTE_MAIL_TO", $csId, "", "", "1");
             $parMailCcAddresses = getObjectBasedParameterValue("MAIL_CARTAGE_NOTE_MAIL_CC", $csId, "", "", "1");
             $parMailBccAddresses = getObjectBasedParameterValue("MAIL_CARTAGE_NOTE_MAIL_BCC", $csId, "", "", "1");
             $parMailSenderAddress = getObjectBasedParameterValue("MAIL_CARTAGE_NOTE_MAIL_SENDER", $csId, "", "", "1");

             if ($parMailSenderAddress != "") :

                // Get the vehicles for the current customer
                $crvhList = array();
                $sqlquery = getStmtCustomerVehicleRelation("", $csId);
                $result = $db->query($sqlquery);
                if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
                while ($row = $result->fetch_assoc()):
                      $crvhList[] = $row["crvh_id"];
                endwhile;
                $result->free();
                $crvhListLen = count($crvhList);
   
   
   // !!!! TEST !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   // $crvhList = array("10");
   // $crvhListLen = count($crvhList);
   // !!!! TEST !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   
   
                // Iterate all vehicles of the related customer
                for ($v = 0; $v < $crvhListLen; $v++) :
   
                    $crvhId = $crvhList[$v];

                    // Check for vehicle is NOT in disposition of a courier !!!!
                    $crvhBlockedState = crvhBlockedState($crvhId, $currDay);
                    if (true || ($crvhBlockedState & 2) != 2) :

                       if ($crvhId != "" && is_numeric($crvhId) && $currDay != "") :

                          // Get courier ID of the current vehicle
                          $crvhSid = getFieldValueFromId("couriervehicle","crvh_id",$crvhId,"crvh_sid");   // Get SID, needed for "fake" courier for the vehicle !!!!
                          $crId = getFieldValueFromId("courier","cr_sid",$crvhSid,"cr_id");                // Get "fake" courier ID
                          $crHqId = getFieldValueFromId("courier","cr_id",$crId,"hq_id");                  // Get hq_id if the carrier
   
                          // Get mail address of the courier of the vehicle
                          $usrMailAddressOfVehicleOwner = "";
                          $crIdVehicleOwner = getFieldValueFromId("couriervehicle","crvh_id",$crvhId,"cr_id");
                          if ($crIdVehicleOwner != "") :
                             $usrIdOfVehicleOwner = getFieldValueFromId("courier","cr_id",$crIdVehicleOwner,"usr_id");
                             if ($usrIdOfVehicleOwner != "") :
                                $usrMailAddressOfVehicleOwner = getFieldValueFromId("user","usr_id",$usrIdOfVehicleOwner,"usr_email");
                             endif;
                          endif;
                          $tmpParMailToAddresses = $parMailToAddresses;  // Init for output
                          if ($usrMailAddressOfVehicleOwner != "") :
                             if ($tmpParMailToAddresses != "") : $tmpParMailToAddresses .= ","; endif;
                             $tmpParMailToAddresses .= $usrMailAddressOfVehicleOwner;  // Add special courier mail address from master data
                          endif;

                          if ($tmpParMailToAddresses != "") :

                             // Title, mail subject and mail text !!!!
                             $title = "ROLLKARTE " . $crvhSid . " " . $currDay;
                             
                             // Configure system command parameters
                             //            auth             log_group    f_act                         title            hqId     iln. dwl. typ pgs pth functionName       par_01          par_02
                             $cmdParStr = "acapella7890 \"" . $crvhSid . "\" calculateAndSendMailPDF \"" . $title . "\" " . $crHqId . " 0 0 pdf \"\" \"\" getCartageNote " . $crvhId . " " . $currDay . " ";
                             //            par_03 ....                       par_10
                             $cmdParStr .= "\"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" ";
                             //            mail_to                          file       mail_sbj       mail_text att_file_typ     mail_cc                         mail_bcc                         mail_sender                 parKeyForLogFile                objId cascadingObjType
                             $cmdParStr .= "\"" . $tmpParMailToAddresses . "\" \"\" \"" . $title . "\" \"" . $title . "\" pdf \"" . $parMailCcAddresses . "\" \"" . $parMailBccAddresses . "\" \"" . $parMailSenderAddress . "\" AUTOMAILER_CARTAGE_NOTE_LOGFILE \"\" \"\"";
                             
                             $system_result = "";
                             $cmd = "php " . $path . "/admin/pdf_generic_function.php " . $cmdParStr . " >" . $path . "/log/auto_cartage_note.stdout+err 2>&1 &";
                             $ausgabe = system($cmd, $system_result);
                             // echo $system_result . "<br>";
                             
                             
                             // Get all jobs associated to the current vehicle for the current day and send them to the mobile device
                             $jbIdArray = getColVectorFromDB2ArrayByClause("vehicledisposition", "jb_id", "crvh_id = '" . $crvhId . "' AND LEFT(vhd_timeslot, 10) = '" . $currDay . "' AND jb_id != '0'", "", "", "DISTINCT");
                             $jbIdArrayLen = count($jbIdArray);
                             
                             if ($jbIdArrayLen > 0) :
                             
                                TA("B");            
                             
                                for ($j = 0; $j < $jbIdArrayLen; $j++) :
                             
                                   // Update job
                                   // According to be TA-safe the WHERE-Clause depends on the current list the user is in
                                   $res = updateStmt("job", "jb_id", $jbIdArray[$j], array("cr_id", $crId, "cr_id_order", $crId, "jb_status", "1", "cr_sid", $crvhSid, "jb_taketime", $currentDayTime, "jb_globaljob", "0", "jb_autoranking", "0"), "(jb_status = '9' OR jb_status = '0') AND jb_offer = '0'");

                                   if ($db->affected_rows > 0) :
                             
                                      // Insert PDA command to remove job (take cr_id/cr_id_order before changing)
                                      // $currentTimePDA = getDateTime("datetime_plus_offset", array(0,0,30,0,0,0), $formatStr = "Y-m-d H:i:s");
                                      // if ($crIdCurrent != "" && $crIdCurrent != "0") :
                                      //    insertPDACommand($jbHqId, $crIdCurrent, "4", "1", $f_jb_id, $currentTimePDA, "");
                                      // endif;
                                      // if ($crIdOrderCurrent != "" && $crIdOrderCurrent != "0" && $crIdOrderCurrent != $crIdCurrent) :
                                      //    insertPDACommand($jbHqId, $crIdOrderCurrent, "4", "1", $f_jb_id, $currentTimePDA, "");
                                      // endif;
                             
                                      // Write logdata into log database
                                      // writeToLogDB("x",$jbHqId,$f_jb_id,$currentSessionUsrId,$cr_id,$f_cr_sid,"","LOST_RANKING=" . ($arLooseRanking == "1" ? "YES" : "NO"));
                             
                                      // Update "vehicledisposition" and remove jobs
                                      // updateStmt("vehicledisposition", "jb_id", $jbIdArray[$j], array("jb_id", "0"));
                                   endif;
                                endfor;
                             
                                TA("C");
                                TA("E");
                             endif;
                          endif;
                       endif;
                    endif;
                endfor;
             else :
                // No sender address and/or no mail receiver
             endif;
   
             // Log all cartage notes have been sent for customer
             $gdcText = getLngt("CARTAGE_NOTE_SENT");
             if (existsEntry("genericdatacontainer",array("gdc_obj_type","cs","gdc_obj_id",$csId,"gdc_gen_fieldname","mail_cartage_note","gdc_content",$currDay))) :
                updateStmt("genericdatacontainer","gdc_obj_type","cs",array("gdc_content", $currDay, "gdc_context", $gdcText),"gdc_obj_id = '" . $csId . "' AND gdc_gen_fieldname = 'mail_cartage_note'");
             else :
                insertStmt("genericdatacontainer", array("gdc_obj_type", "cs", "gdc_obj_id", $csId, "gdc_gen_fieldname", "mail_cartage_note", "gdc_content", $currDay, "gdc_context", $gdcText));
             endif;
          endif;
       endif;
   endfor;
endif;
?>
