<?php     

include_once ("../tools/co2e_sendReq.php");



// Get jobs for auto_response
function getJobsWithoutCO2e($startDay) {
  global $db, $logFile;
  $retArray = array();

  $startTime = getDateTime("datetime_plus_offset", array(0,0,0,0,-($startDay),0), "Y-m-d H:i:s");
  $currentTime = getDateTime("0");
  $numOfStations = 1;

  // Get jobs of the specified customer
  $sqlquery = "SELECT jb.jb_id, jb.hq_id, jb.jb_status, jb.jb_finishtime, jb.cr_id, jb.cr_sid, crvh.crvh_payload, jbprc_11.jbprc_price AS jbprc_price_11, jbprc_12.jbprc_price AS jbprc_price_12"
            . "  FROM job AS jb LEFT JOIN jobprice AS jbprc_11 ON jbprc_11.jb_id = jb.jb_id AND jbprc_11.mt_sort = '11'"
            . "                 LEFT JOIN jobprice AS jbprc_12 ON jbprc_12.jb_id = jb.jb_id AND jbprc_12.mt_sort = '12',"
            . "       tour AS tr, couriervehicle AS crvh"
            . "  WHERE jb.jb_finishtime > '" . $startTime . "'      AND"
            . "        jb.jb_finishtime <= '" . $currentTime . "'   AND"
            . "        (ISNULL(jb.jb_storno) OR jb.jb_storno = '0') AND"
            . "        jb.jb_status = '2'                           AND"
            . "        jb.jb_id = tr.jb_id                          AND"
            . "        tr.tr_sort = '1'                             AND"
            . "        tr.tr_status = '1'                           AND"
            . "        jb.cr_sid = crvh.crvh_sid                    AND"
            . "        crvh.crvh_payload > 0                           "
            . " ORDER BY jb.jb_id";
// echo $sqlquery . "\n\n"; 
// die();
  $result = $db->query($sqlquery);
  // $result = $db->query($sqlquery . " UNION " . $sqlquery2);
  if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
  while ($row = $result->fetchRow()):
        if ($row["jbprc_price_12"] == "" || $row["jbprc_price_12"] == 0) :
           $retArray[$row["jb_id"]]["jb_status"]          = $row["jb_status"];           
           $retArray[$row["jb_id"]]["cr_id"]              = $row["cr_id"];
           $retArray[$row["jb_id"]]["cr_sid"]             = $row["cr_sid"];
           $retArray[$row["jb_id"]]["hq_id"]              = $row["hq_id"];
           $retArray[$row["jb_id"]]["crvh_payload"]       = $row["crvh_payload"];
           $retArray[$row["jb_id"]]["jbprc_price_11"]     = $row["jbprc_price_11"];
           $retArray[$row["jb_id"]]["jbprc_price_12"]     = $row["jbprc_price_12"];
           for ($i = 1; $i <= $numOfStations; $i++) :
               $retArray[$row["jb_id"]]["tr" . $i . "_id"] = $row["tr" . $i . "_id"];
               $retArray[$row["jb_id"]]["tr" . $i . "_status"] = $row["tr" . $i . "_status"];
               $retArray[$row["jb_id"]]["tr" . $i . "_finishtime"] = $row["tr" . $i . "_finishtime"];
               $retArray[$row["jb_id"]]["tr" . $i . "_signname"] = $row["tr" . $i . "_signname"];
               $retArray[$row["jb_id"]]["tr" . $i . "_sign"] = $row["tr" . $i . "_sign"];
           endfor;
        endif;
  endwhile;
  $result->free();
  return $retArray;
} 


if ($argv[1] == "acapella7890") :

   // Error reporting
   error_reporting(E_ERROR | E_WARNING | E_PARSE);

   $directCall = (strtoupper($argv[2]) == "DC");  // DC = Direct call

   $path = getAbsoluteSystemPath();
   $passwd = "acapella7890";
   $logFile = $path . "/log/co2e_cron.log";
   $logDebug = true;
   $emptyArgument = "\"\"";
   $currDatetime = getDateTime("0");  // Format: "YmdHi"
   $maxNumOfDays = 9;

   $numOfDays = $argv[3];
   if ($numOfDays == "" || !is_numeric($numOfDays) || $numOfDays <= 0  | $numOfDays > $maxNumOfDays) :
      $numOfDays = 2;
   endif;

   // Get jobs 
   $jbArr = getJobsWithoutCO2e($numOfDays);
   $jbkArr = array_keys($jbArr);
   $jbkArrLen = count($jbkArr);
   for ($i = 0; $i < $jbkArrLen; $i++) :

       $jbId = $jbkArr[$i];
       $km  = $jbArr[$jbId]["jbprc_price_11"];
       if ($km == "" || !is_numeric($km)) : $km = 0; endif;
       $co2_old = $jbArr[$jbId]["jbprc_price_12"];
       $callMode = "NO";

       // if ($km > "0" && ($co2_old == "" || !is_numeric($co2_old) || $co2_old <= 0)) :       
       // if ($co2_old == "" || !is_numeric($co2_old) || $co2_old <= 0) :
       if (true) :
          // Send request
          // if (($km != "" && $km > 0) || $directCall) :
          if (false) :
             $rspArr = sendReqCO2($jbId);  // array($jbprcPrice, $response, $rspArr, $jbId, $logDescription);
             $callMode = "sendReqCO2()";
          else :
             // if ($km == "") :
             if (true) :
                $cmd = "php " . $path . "/tools/get_job_distance.php " . $jbId . " &";
                // echo $cmd . "\n";
                $cmdOutput = null;
                exec($cmd, $cmdOutput);
                $callMode = "get_job_distance";
             endif;
             $rspArr = array();
          endif;
// echo $jbId . "\n";
          sleep(1);
       endif;

       if ($logDebug) :
          // Get (new) KM and CO2 values
          $km_new = getFieldValueFromClause("jobprice","jbprc_price","jb_id = '" . $jbId . "' AND mt_sort = '11'");
          $co2_new = getFieldValueFromClause("jobprice","jbprc_price","jb_id = '" . $jbId . "' AND mt_sort = '12'");

          writeToFile($logFile, $currDatetime . " :: callMode =" . $callMode . " :: jb_id=" . $jbId . " :: km_old=" . $km . " :: km_new=" . $km_new . " :: co2_old=" . $co2_old . " :: co2_new=" . $co2_new);
          // writeToFile($logFile, $rspArr[1]);
          // writeToFile($logFile, $rspArr[2]);
          // writeToFile($logFile, "------------------------------------------------------------------------------------");
       endif;
   
       /*
       $trSortMaxVal = getMaxOfField("tour", "tr_sort", "jb_id = '" . $jbId . "'");
       
       $gdcContent = $jbArr[$jbId]["gdc_content"];
       $gdcContext = $jbArr[$jbId]["gdc_context"];

       $crId = $jbArr[$jbId]["cr_id"];
       $crSid = $jbArr[$jbId]["cr_sid"];
       $tr1CommissionNo = $jbArr[$jbId]["tr_commission_no"];
       */
   endfor;
endif;

?>



