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

error_reporting(E_ALL ^ (E_DEPRECATED | E_NOTICE));

include_once ("../include/mcglobal.inc.php");
// include_once ("../include/auth.inc.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 SERVICE ACCEPTANCE PROTOCOL
$cronServiceAcceptanceProtocolEnabled = getParameterValue("0", "CRON_SERVICE_ACCEPTANCE_PROTOCOL_ENABLED", "0");


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

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

   // Absolute system path
   $path = getAbsoluteSystemPath();

   // Endless loop
   // while (TRUE):

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

     // $constAmStarttimeInDays = getParameterValue("0", "AUTO_RESPONSE_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");

     // Get ALL JOBS can be processed to send mails of SERVICE ACCEPTANCE PROTOCOLS 
     $sqlquery = "SELECT jb.jb_id"
               . "  FROM job AS jb, costcenteraddress AS cscad, tour AS tr"
               . "  WHERE jb.jb_finishtime > '" . $startTime . "'      AND"
               . "        (ISNULL(jb.jb_storno) OR jb.jb_storno = '0') AND"
               . "        jb.jb_status = '2'                           AND"
               . "        jb.jb_offer = '0'                            AND"
               . "        (jb.jb_service & 2) = 2                      AND"
               . "        tr.jb_id = jb.jb_id                          AND"
               . "        tr.tr_sort = '2'                             AND"
               . "        tr.tr_sign != ''                             AND"
               . "        (NOT ISNULL(tr.tr_sign))                     AND"
               . "        cscad.csc_id = jb.csc_id_payer               AND"
               . "        cscad.adt_id = '2'                           AND"
               . "        cscad.cscad_email != ''                      AND"
               . "        (NOT EXISTS (SELECT * FROM phoenix.genericdatacontainer AS gdc WHERE gdc.gdc_obj_id = jb.jb_id AND gdc.gdc_obj_type = 'jb' AND gdc.gdc_gen_fieldname = 'mail_srv_acc_prot'))";

     $result = $db->query($sqlquery);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     $jbIdArray = array();
     $gdcContentArray = array();
     $gdcContextArray = array();
     while ($row = $result->fetch_assoc()):
           $jbIdArray[] = $row["jb_id"];
     endwhile;
     $result->free();
     $jbIdArrayLen = count($jbIdArray);

     // Iterate all jobs
     for ($i = 0; $i < $jbIdArrayLen; $i++) :

         $jbId = $jbIdArray[$i];

         // Set semaphore for this job
         insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbId, "gdc_gen_fieldname", "mail_srv_acc_prot", "gdc_content", "", "gdc_context", "SEND_IN_PROGRESS"));
         if (true) :

            $jbCscIdRelated = getFieldValueFromId("job", "jb_id", $jbId, "csc_id_related");
            if ($jbCscIdRelated != "") :

               $jbCsId = getFieldValueFromId("costcenter", "csc_id", $jbCscIdRelated, "cs_id");
               if ($jbCsId != "") :

                  $jbHqId = getFieldValueFromId("job", "jb_id", $jbId, "hq_id");            // Get "hq_id" from "jb_id"
                  $tmpGroups = getFieldValueFromId("customer","cs_id",$jbCsId,"cs_group");  // Get "grp_id" from "cs_id"
                  $tmpGroups = spliti(",", $tmpGroups);
                  $jbCsGrpId = $tmpGroups[1];

                  // * Get mail addresses *
                  // Mail TO
                  $mailToAddresses = getObjectBasedParameterValue("AUTOMAILER_ACCEPTANCE_PROTOCOL_MAIL_TO_CS", $jbCsId, $hq_id, "", "1");
                  if ($mailToAddresses == "") :
                     if ($jbCsGrpId != "" && is_numeric($jbCsGrpId)) :
                        $mailToAddresses = getObjectBasedParameterValue("AUTOMAILER_ACCEPTANCE_PROTOCOL_MAIL_TO_GRP", $jbCsGrpId, $hq_id, "", "1");
                     endif;
                     if ($mailToAddresses == "") :
                        $mailToAddresses = getParameterValue("0", "AUTOMAILER_ACCEPTANCE_PROTOCOL_MAIL_TO", "0");
                        if ($mailToAddresses == "") :
                           // $mailToAddresses = "support@assecutor.de";  // Extreme fallback !!!!
                        endif;
                     endif;                  
                  endif;

                  // Mail CC
                  $mailCcAddresses = getObjectBasedParameterValue("AUTOMAILER_ACCEPTANCE_PROTOCOL_MAIL_CC_CS", $jbCsId, $hq_id, "", "1");
                  if ($mailCcAddresses == "") :
                     if ($jbCsGrpId != "" && is_numeric($jbCsGrpId)) :
                        $mailCcAddresses = getObjectBasedParameterValue("AUTOMAILER_ACCEPTANCE_PROTOCOL_MAIL_CC_GRP", $jbCsGrpId, $hq_id, "", "1");
                     endif;
                     if ($mailCcAddresses == "") :
                        $mailCcAddresses = getParameterValue("0", "AUTOMAILER_ACCEPTANCE_PROTOCOL_MAIL_CC", "0");
                     endif;
                  endif;

                  // Mail BCC
                  $mailBccAddresses = getObjectBasedParameterValue("AUTOMAILER_ACCEPTANCE_PROTOCOL_MAIL_BCC_CS", $jbCsId, $hq_id, "", "1");
                  if ($mailBccAddresses == "") :
                     if ($jbCsGrpId != "" && is_numeric($jbCsGrpId)) :
                        $mailBccAddresses = getObjectBasedParameterValue("AUTOMAILER_ACCEPTANCE_PROTOCOL_MAIL_BCC_GRP", $jbCsGrpId, $hq_id, "", "1");
                     endif;
                     if ($mailBccAddresses == "") :
                        $mailBccAddresses = getParameterValue("0", "AUTOMAILER_ACCEPTANCE_PROTOCOL_MAIL_BCC", "0");
                     endif;
                  endif;

                  // Get end customer mail address
                  $cscIdPayer = getFieldValueFromId("job", "jb_id", $jbId, "csc_id_payer");
                  $csMailAddress = getFieldValueFromClause("costcenteraddress","cscad_email","csc_id = '" . $cscIdPayer . "' AND adt_id = '4'");  // Delivery address
                  if ($csMailAddress == "") :
                     $csMailAddress = getFieldValueFromClause("costcenteraddress","cscad_email","csc_id = '" . $cscIdPayer . "' AND adt_id = '2'");  // Invoice address
                     if ($csMailAddress == "") :
                        $csMailAddress = getFieldValueFromClause("costcenteraddress","cscad_email","csc_id = '" . $cscIdPayer . "' AND adt_id = '3'");  // Invoice special address
                         if ($csMailAddress == "") :
                            $csMailAddress = getFieldValueFromClause("costcenteraddress","cscad_email","csc_id = '" . $cscIdPayer . "' AND adt_id = '1'");  // Main address
                         endif;
                     endif;
                  endif;
                  if ($csMailAddress != "") :
                     if ($mailToAddresses != "") : $mailToAddresses .= ","; endif;
                     $mailToAddresses .= $csMailAddress;
                  endif;

                  // Check against "gdc_content" should not be empty AND the protocol of the job is ready (prefix == "OK") to be sent
                  // if (substr($gdcContext,0,11) == "SEND_PLEASE") :

                     // Call with arguments: password, category, objId, objType, title, mailTo, mailCc, mailBcc
                     // https://htm.assecutor.de/htm/admin/metafield_special_cron.php?category=300&objId=167342&mailToAdresses=mv@assecutor.de&specialPageTitle=ABNAHMEPROTOKOLL&sendToClientFileDownload=1
                     $system_result = "";
// $mailToAddresses = "support@assecutor.de";
// $mailCcAddresses = "";
// $mailBccAddresses = "";
                     $cmdParStr = "acapella7890 300 " . $jbId . " jb \"" . getLngt("ABNAHMEPROTOKOLL") . "\" \"" . $mailToAddresses . "\" \"" . $mailCcAddresses . "\" \"" . $mailBccAddresses . "\" &";
                     // exec($cmd . " > /dev/null &");
                     $cmd = "php " . $path . "/admin/metafield_special_cron.php " . $cmdParStr . " >" . $path . "/log/auto_service_acceptance_protocol.stdout+err 2>&1 &";
                     $ausgabe = system($cmd, $system_result);
                  // endif;
               endif;
            endif;
         else :
            // Unlock semaphore if necessary (e.g. mail has not been sent)
            $res = updateStmt("genericdatacontainer", "gdc_obj_id", $jbId, array("gdc_context", "SEND_PLEASE"), "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'mobile_photos' AND gdc_context LIKE '%SEND_IN_PROGRESS%'");
         endif;
// if ($i == 0) : break; endif;
         sleep(3);
     endfor;

   // sleep(30)

   // endwhile;  // Endless loop
endif;
?>