<?php
/*=======================================================================
 *
 * cron_sms.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/inc_job.inc.php");
include_once ("../include/email/htmlMimeMail.php");


// Check for authentication access and granted rights
// $usrAccessArray["hq"] = "1";
// authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
// authCheckEmployeeRights($emp_id, "1", "1");


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

// Check parameter for executing CRON process for SMS
$cronSmsEnabled = getParameterValue("0", "CRON_SMS_ENABLED", "0");

$logFile = getParameterValue("0", "SMS_LOGFILE", "0");
if ($logFile == "") : $logFile = "../log/sms.log"; endif;

$logExecutionState = "SCRIPT_CALLED";

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

   $logExecutionState .= "::PARAMETERS_ACTIVED";

   // http://gateway.smstrade.de/?key=CMhUVpZ078ea4f55aXSMm35&to=491729914851&message=Hello+World&route=basic&from=ADSG
   $url = "http://gateway.smstrade.de";   // URL des Gateways
   $adsgKey = "CMhUVpZ078ea4f55aXSMm35";  // Key
   $smsFrom = "mv@assecutor.de";          // Sender (Default)
   $smsFromSpecial = "AUFTRAG";           // Sender (Default)
   $smsRoute = "gold";                    // "basic", "gold", "direct"
   $minLengthOfPhoneNo = 10;              // Minimum length of the end customers phone number
   $smsDebug = "1";                       // Debug mode enabled <=> "1"
   $mode = "2";                           // mode = "1" <=> Request per HTTP, mode = "2" <=> Request per Mail
   
   // Execution-Time for script
   set_time_limit(0);
   
   // Current day and tomorrow
   $selDay = getDateTime("day");
   $selMonth = getDateTime("month");
   $selYear = getDateTime("year");
   $dayTomorrow = getDateTime("day_tomorrow");
   $monthTomorrow = getDateTime("month_tomorrow");
   $yearTomorrow = getDateTime("year_tomorrow");
   $tomorrowDate = $yearTomorrow . "-" . $monthTomorrow . "-" . $dayTomorrow;
   $executionDate = $dayTomorrow . "." . $monthTomorrow . "." . $yearTomorrow;
   
   // Clock time now
   $currClockTime = getDateTime("4");
   $currClockHourMinute = substr($currClockTime,0,5);  // E.g. "19:30"
   
   
   if ($logFile == "") : $logFile = getParameterValue("0", "SMS_LOGFILE", "0"); endif;
   if ($logFile == "") : $logFile = "../log/sms.log"; endif;
   
   
   // Get ALL customers (of ALL headquarters) belonging to the "STATIC" groups !!!!
   // **** Presently IKEA only !!!! ****
   $sqlquery = "SELECT cs.cs_id"
             . "  FROM customer AS cs, company AS cmp"
             . "  WHERE (cs.cs_group LIKE '%,1,%') 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)";
             // . "  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,%') AND "
             // . "  WHERE (cs.cs_group LIKE '%,1,%' OR cs.cs_group LIKE '%,11,%') AND "
   $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);

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

       $csId = $csIdArray[$i];
       
       $logExecutionState .= "::[CS=" . $csId;
   
       // Check SMS time setting for customer
       $mtSmsTime = getFieldValueFromClause("metatype","mt_mapped_value","mt_type = 'sms_time' AND mt_sort = '0' AND mt_objtype = 'cs' AND mt_objid = '" . $csId . "'");
       if ($mtSmsTime == "") : 
          // Get default value
          $mtSmsTime = getFieldValueFromClause("metatype","mt_mapped_value","mt_type = 'sms_time' AND mt_sort = '0' AND mt_objtype = '' AND mt_objid = '0'");
       endif;
       // if ($mtSmsTime != "" && $mtSmsTime >= $currClockHourMinute) :
       if (true) :
   
          // 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);

          // Check for each vehicle displayed the existence of entries in "vehicledisposition", "vehicleavailability" and "vehicleavailabilitytimeunits".
          // If it does not exist then generate it to handle the drag and dropping the jobs etc.
          for ($v = 0; $v < $crvhListLen; $v++) :
              $crvhId = $crvhList[$v];
              
              $logExecutionState .= "::[CRVH=" . $crvhId;
   
              // Check for vehicle is NOT in disposition of a courier !!!!
              $crvhBlockedState = crvhBlockedState($crvhId, $tomorrowDate);
              if (true || ($crvhBlockedState & 2) != 2) :
   
                 // Get job data from all jobs tomorrow taken by vehicle. ALL jobs associated in "vehicledisposition" !!!!
                 $checkForParentJob = true;
                 if (true) :
                    // Installations only
                    $jbArray = getVehicleJobList($crvhId, $tomorrowDate, "", "0", " jb.jb_offer = '0' AND jb.jb_status != '2' AND jb.jb_service IN (6, 18) AND ");
                    $checkForParentJob = false;
                 else :
                    // DEFAULT: ALL jobs (delivery AND installation)
                    $jbArray = getVehicleJobList($crvhId, $tomorrowDate, "", "0", " jb.jb_offer = '0' AND jb.jb_status != '2' AND ");
                 endif;
                 $jbArrayLen = count($jbArray);

                 if ($jbArrayLen > 0) :

                    for ($j = 0; $j < $jbArrayLen; $j++) :

                        // Get job data
                        $jbId = $jbArray[$j]["jb_id"];

                       	$doContinue = true;
                        if ($doContinue) :

                           $logExecutionState .= "::[JB=" . $jbId;

                           // Check SMS has been sent for the job. 
                           $gdcContextSms = getFieldValueFromClause("genericdatacontainer", "gdc_context", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $jbId . "' AND gdc_gen_fieldname = 'sms'");
                           if ($gdcContextSms == "") :

                              $jbHqId = $jbArray[$j]["hq_id"];
                              $jbOrderTime = $jbArray[$j]["jb_ordertime"];
                              $jbFreetext1 = $jbArray[$j]["jb_freetext_1"];

                              // Get parent ID and check for parent had to be sent a sms at the same day
                              $sendSMS = true;
                              $deliveryAndInstallationOnAnotherDay = false;
                              $jbIdParent = $jbArray[$j]["jb_id_parent"];
                              if ($jbIdParent > "0") :
                                 $jbOrdertimeOfParent = getFieldValueFromId("job", "jb_id", $jbIdParent, "jb_ordertime");  // Ordertime of the parent
                                 // Check for current job and its parent job having the same orderdate
                                 if (substr($jbOrderTime,0,10) == substr($jbOrdertimeOfParent,0,10)) :
                                    $deliveryAndInstallationOnAnotherDay = true;
                                    if (existsEntry("genericdatacontainer",array("gdc_obj_type","jb","gdc_obj_id",$jbIdParent,"gdc_gen_fieldname","sms"))) :
                                       $gdcContextSmsOfParent = getFieldValueFromClause("genericdatacontainer", "gdc_context", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $jbIdParent . "' AND gdc_gen_fieldname = 'sms'");
                                       if ($gdcContextSmsOfParent == "SMS_SENT=OK") :
                                          // If mode "send_SMS_for_ALL_jobs" then disable SMS if had been sent for parent (delivery) the same day
                                          // [$checkForParentJob == true <==> ALL jobs, $checkForParentJob == false <==> Installations only]
                                          if ($checkForParentJob) :
                                             $sendSMS = false;
                                          endif;
                                       endif;
                                    endif;
                                 endif;
                              endif;

                              $logExecutionState .= "::[JB_PARENT=" . $jbIdParent;

                              if ($sendSMS) :

                                 // Overwrite sender from headquarter of the job
                                 $smsFromSpecialHQ = getParameterValue("0", "SMS_MAIL_FROM", $jbHqId);
// ******                  
// PROPR.                  
                                 if ($jbHqId == 1020)
                                   $smsFromSpecialHQ = "*" . getParameterValue("0", "SMS_MAIL_FROM", $jbHqId);
// ******                  
                                 if ($smsFromSpecialHQ == "") : $smsFromSpecialHQ = getParameterValue("0", "SMS_MAIL_FROM", "0"); endif;
                                 $smsFromSpecialHQ = trim($smsFromSpecialHQ);
                                 if ($smsFromSpecialHQ != "") :
                                    $smsFromSpecial = $smsFromSpecialHQ;
                                 endif;

                                 // Use daytime and no time offset for time interval
                                 $smsDaytimeAndNoTimeOffset = getParameterValue("0", "SMS_USE_DAYTIME_AND_NO_TIME_OFFSET", $jbHqId);
                                 if ($smsDaytimeAndNoTimeOffset == "") : $smsDaytimeAndNoTimeOffset = getParameterValue("0", "SMS_USE_DAYTIME_AND_NO_TIME_OFFSET", "0"); endif;

                                 // Phone no of the end customer
                                 $phoneNo = $jbArray[$j]["tr2_phone"];

                                 $phoneNo = eregPhoneNo($phoneNo);
                                 // Set Country phone prefix
                                 $parCountryPhonePrefix = getParameterValue("0", "COUNTRY_FON_PREFIX", $jbHqId);
                                 if ($parCountryPhonePrefix == "") :
                                    $parCountryPhonePrefix = getParameterValue("0", "COUNTRY_FON_PREFIX", "0");
                                    if ($parCountryPhonePrefix == "") :
                                       $parCountryPhonePrefix = "49";
                                    endif;
                                 endif;
                                 $phoneNo = "+" . $parCountryPhonePrefix . $phoneNo;
//$phoneNo = "+491706340122";  // $phoneNo = "+491736289234";
                                 $logExecutionState .= "::PHONE=" . $phoneNo;
                                 
                                 if ($phoneNo != "" && strlen($phoneNo) >= $minLengthOfPhoneNo) :
                                 
                                    // Try to get sender address
                                    $parMailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $jbHqId);
                                    if ($parMailSenderAddress == "") : getParameterValue("0", "MAIL_SENDER_ADDRESS", "0"); endif;
                                    if ($parMailSenderAddress != "") :
                                       $smsFrom = "support@assecutor.de";
                                    endif;
                                 
                                    // Define time interval for SMS
                                    $gdcContentSms = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $jbId . "' AND gdc_gen_fieldname = 'sms_time'");
                                    $smsUseStandardInterval = true;
                                    if ($gdcContentSms != "") :
                                       // Special entry does exist
                                       $smsUseStandardInterval = false;
                                       $tmpStartIntervalArray = spliti(":",$gdcContentSms);
                                       // $tmpSmsStartHour = substr($gdcContentSms,0,2);
                                       // $tmpSmsStartMinute = substr($gdcContentSms,3,2);
                                       $tmpSmsStartHour = $tmpStartIntervalArray[0];
                                       $tmpSmsStartMinute = $tmpStartIntervalArray[1];
                                       if ($tmpSmsStartHour == "" || !is_numeric($tmpSmsStartHour) || $tmpSmsStartMinute == "" || !is_numeric($tmpSmsStartMinute)) :
                                          $smsUseStandardInterval = true;  // Start time for SMS is NOT OK. Take standard interval regarding to the job data.
                                       else :
                                          // $timeIntervalText = substr($jbFreetext1,0,10) . " [" . $gdcContentSms . " - "  . ($tmpSmsStartHour + 2) . ":" . $tmpSmsStartMinute . "]";
                                          $tmpSmsStartHour = pad($tmpSmsStartHour,2);
                                          $tmpSmsStartMinute = pad($tmpSmsStartMinute,2);
                                          $timeIntervalText = $executionDate . " [" . $gdcContentSms . " - "  . ($tmpSmsStartHour + 2) . ":" . $tmpSmsStartMinute . "]";
                                       endif;
                                    endif;
                                    if ($smsUseStandardInterval) :
                                       $timeIntervalText = $jbFreetext1;  // Init with standard interval for the customer (e.g. [16.00 - 20.00] OR "ganztägig")
                                       if ($jbOrderTime != "" && substr($jbOrderTime,11,8) != "00:00:01") :
                                          if ($smsDaytimeAndNoTimeOffset == "1" && substr($jbFreetext1,-9) != "ganztägig") :
                                             $jbDayTimeInterval = getDaytimeTimeInterval($jbOrderTime, $csId);
                                             if ($jbDayTimeInterval != "") :
                                                $timeIntervalText = $executionDate . " [" . $jbDayTimeInterval . "]";
                                             endif;
                                          else :
                                             // Compute time interval to be sent to the end customer
                                             $intervalArray = getComputedTimeInterval($jbOrderTime, $csId);
                                             if (count($intervalArray) > 0) :
                                                // $timeIntervalText = substr($jbFreetext1,0,10) . " [" . $intervalArray[0] . " - "  . $intervalArray[1] . "]";
                                                $timeIntervalText = $executionDate . " [" . $intervalArray[0] . " - "  . $intervalArray[1] . "]";
                                             endif;
                                          endif;
                                       endif;
                                    endif;

                                    if ($checkForParentJob) :
                                       $smsSubject = "Sehr geehrter Kunde! Die morgige Anfahrt avisieren wir für das Zeitfenster: " . $timeIntervalText . " Vielen Dank.";
                                    else :
                                       if (!(strpos($timeIntervalText, "ganz") === false)) :
                                          $smsSubject = "IKEA Auftr.Nr.: " . getJobIdOutput($jbId) . " - Hej lieber Kunde, wir treffen morgen bei Ihnen für Ihre " . ($deliveryAndInstallationOnAnotherDay ? "Lieferung und " : "") . "Montage ein. Fa. Hansetrans";
                                       else :
                                          $smsSubject = "IKEA Auftr.Nr.: " . getJobIdOutput($jbId) . " - Hej lieber Kunde, wir treffen morgen zwischen " . substr($timeIntervalText, -14, 13) . " Uhr bei Ihnen für Ihre " . ($deliveryAndInstallationOnAnotherDay ? "Lieferung und " : "") . "Montage ein. Fa. Hansetrans";
                                       endif;
                                    endif;
                                    // $smsSubject = utf8_encode($smsSubject);
                                 
                                    $smsSMessage = "#" . $adsgKey . "#" . $smsRoute . "#" . $smsFromSpecial . "#";     // Special commands (Steuerbefehle)
                                 
                                    // Check for status regarding the SMS is sent or not
                                    $gdcContentSms = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $jbId . "' AND gdc_gen_fieldname = 'sms'");
                                    $gdcContextSms = getFieldValueFromClause("genericdatacontainer", "gdc_context", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $jbId . "' AND gdc_gen_fieldname = 'sms'");
                                 
                                    if ($gdcContentSms == "" && $gdcContextSms == "") :
                                 
                                       // **** Send request per HTTP ****
                                       if ($mode == "1") :
                                       
                                          $logExecutionState .= "::SEND_MODE=" . $mode;
                                 
                                          $request = "";                          // Request Variable initialisieren
                                          $param["key"] = $adsgKey;               // Gateway Key
                                          $param["to"] = $phoneNo;                // Empfänger der SMS
                                          $param["message"] = "";                 // Inhalt der Nachricht
                                          $param["route"] = $smsRoute;            // Modus (besic, gold, direct)
                                          $param["from"] = $smsFrom;              // Absender der SMS
                                          $param["cost"] = "1";                   // SMS-Kostenüberwachung aktiviert = "1"
                                          // $param["senddate"] = "1";            // Versetzes Sendedatum (Unix-Timestamp)
                                          $param["debug"] = $smsDebug;            // SMS wird nicht versendet - Testmodus = "1"
                                 
                                          foreach($param as $key=>$val)           // Alle Parameter durchlaufen
                                          {
                                            $request.= $key."=".urlencode($val);  // Werte müssen url-encoded sein
                                            $request.= "&";                       // Trennung der Parameter mit &
                                          }
                                 
                                          // SMS kann jetzt versendet werden
                                          $response = @file($url."?".$request);   // Request absetzen                    
                                          $response_code = intval($response[0]);  // Responsecode auslesen
                                          $gdcText = "SMS_SENT=" . $response_code;
                                       endif;
                                 
                                       // **** Send request MAIL ****
                                       if ($mode == "2") :
                                 
                                          $logExecutionState .= "::SEND_MODE=" . $mode;
                                 
                                          // Send mail to admin@assecutor.de
                                          $mailObj = new htmlMimeMail();
                                          $mailObj->setFrom("support@assecutor.de");
                                          // $mailObj->setCc("");
                                          // $mailObj->setBcc($mailBccAddress);
                                 
                                 
                                          $mailObj->setSubject($smsSubject);
                                          $mailtext .= $crashdumpdata;
                                          $mailObj->setText($smsSMessage);
                                 
                                          $mailResult = $mailObj->send(array($phoneNo . "@email2sms.smstrade.de"), 'smtp');
                                 
                                          $currentTimestamp = getDateTime("0");
                                 
                                          // Write logdata into log file
                                          if ($mailResult) :
                                             writeToFile($logFile, "DATETIME=" . $currentTimestamp . "|PHONE=" . $phoneNo . "|JOB=" . $jbId . "|TEXT=" . $timeIntervalText . "|STATUS=OK");
                                             $gdcText = "SMS_SENT=OK";
                                             $logExecutionState .= "::SMS_SENT=OK";
                                          else :
                                             writeToFile($logFile, "DATETIME=" . $currentTimestamp . "|PHONE=" . $phoneNo . "|JOB=" . $jbId . "|TEXT=" . $timeIntervalText . "|STATUS=NOT_OK");
                                             $gdcText = "SMS_SENT=NOT_OK";
                                             $logExecutionState .= "::SMS_SENT=NOT_OK";
                                          endif;
                                          $mailObj = NULL;
                                       endif;
                                 
                                       if (existsEntry("genericdatacontainer",array("gdc_obj_type","jb","gdc_obj_id",$jbId,"gdc_gen_fieldname","sms"))) :
                                          updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_content", $phoneNo, "gdc_context", $gdcText),"gdc_obj_id = '" . $jbId . "' AND gdc_gen_fieldname = 'sms'");
                                       else :
                                          insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbId, "gdc_gen_fieldname", "sms", "gdc_content", $phoneNo, "gdc_context", $gdcText));
                                       endif;
                                    endif;
                                 endif;
                              endif;  // Check for SMS had been sent for parent on the same day
                              $logExecutionState .= "]";
                           endif;
                           $logExecutionState .= "]";
                        endif;  // SPECIAL CENTIROCHECK
//die();
                    endfor;
                 endif;
              endif;
              $logExecutionState .= "]";
          endfor;
       endif;
       $logExecutionState .= "]";
   endfor;
endif;

// Enter final log state
if ($logExecutionState != "") :
   writeToFile($logFile, "LOG_STATE=" . $logExecutionState);
   writeToFile($logFile, "--------------------------------------------------------------------------------------------------------------");
endif;
?>