<?php
/*=======================================================================
 *
 * auto_response_ups.php
 *
 * CUSTOMER: UPS [Loginext]
 *
  =======================================================================*/

// Clear cache
// clearstatcache(true, "../include/extern/loginext/LN_loginext_include.php");
// clearstatcache(true, "LN_loginext_include.php");
// include_once ("../include/extern/loginext/LN_loginext_include.php");
include_once ("../service/LN_374893028394/LN_loginext_include.php");


// Special implementation for customer
function sendResponse($stateEvent, $timestamp, $jbId, $trId, $trSort, $tr1CommissionNo = "", $crId = "", $crSid, $trSignName, $trSign, $gdc_01 = "", $gdc_02 = "", $gdc_03 = "", $gdc_04 = "", $gdc_05 = "") {
  global $server, $port, $sendMode, $currentTime, $logFile;

  $sendMode = "EXTERNAL";  // Do NOT send from autoresponder
 
  // $crEid = "";
  // if ($crId != "" && $crId != "0") :
  //    $crEid = getFieldValueFromId("courier","cr_id",$crId,"cr_eid");
  // endif;

  // Init
  $xxxx_01 = $gdc_01;
  $xxxx_02 = $gdc_02;
  $imei = $gdc_03;
  $orderReferenceId = $gdc_04;
  $xxxx_05 = $gdc_05;

if (false) :
   echo "---------------------------------------- \n";
   echo "---------------------------------------- \n";
   echo "stateEvent = " . $stateEvent . "\n";
   echo "jbId = " . $jbId . "\n";
   echo "trId = " . $trId . "\n";
   echo "trSort = " . $trSort . "\n";
   echo "tr1CommissionNo = " . $tr1CommissionNo . "\n";
   echo "crId = " . $crId . "\n";
   echo "crSid = " . $crSid . "\n";
   echo "gdc_01 = " . $gdc_01 . "\n";
   echo "gdc_02 = " . $gdc_02 . "\n";
   echo "gdc_03 = " . $gdc_03 . "\n";
   echo "gdc_04 = " . $gdc_04 . "\n";
   echo "gdc_05 = " . $gdc_05 . "\n";
   echo "orderReferenceId = " . $orderReferenceId . "\n";
   echo "---------------------------------------- \n";
   echo "---------------------------------------- \n";
endif;

/*
  // Convert timestamp from localtime to UTC
  $timestamp = gmdate("Y-m-d H:i:s", mktime(substr($timestamp, 11, 2), substr($timestamp, 14,2), substr($timestamp, 17, 2), substr($timestamp, 5, 2), substr($timestamp, 8,2), substr($timestamp, 0, 4)));
  $timestamp = substr($timestamp,0,10). "T" . substr($timestamp,11) . "Z";

  // Location zipcode
  $adId = getFieldValueFromId("tour","tr_id",$trId,"ad_id");
  $adZipcode = getFieldValueFromId("address","ad_id",$adId,"ad_zipcode");

  // Taketime "job" (UTC)
  $jbTaketime = getFieldValueFromId("job","jb_id",$jbId,"jb_taketime");
  $jbTaketime = gmdate("Y-m-d H:i:s", mktime(substr($jbTaketime, 11, 2), substr($jbTaketime, 14,2), substr($jbTaketime, 17, 2), substr($jbTaketime, 5, 2), substr($jbTaketime, 8,2), substr($jbTaketime, 0, 4)));
  $jbTaketime = substr($jbTaketime,0,10). "T" . substr($jbTaketime,11) . "Z";

  // Finishtime "tour" (UTC)
  $trFinishtime = getFieldValueFromId("tour","tr_id",$trId,"tr_finishtime");
  $trFinishtime = gmdate("Y-m-d H:i:s", mktime(substr($trFinishtime, 11, 2), substr($trFinishtime, 14,2), substr($trFinishtime, 17, 2), substr($trFinishtime, 5, 2), substr($trFinishtime, 8,2), substr($trFinishtime, 0, 4)));
  $trFinishtime = substr($trFinishtime,0,10). "T" . substr($trFinishtime,11) . "Z";
*/

  // Check order is a b2b order
  if ($gdc_01 == "") :  // Equals "info_0" (!!!!)
     $gdc_01 = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'info_0' AND gdc_obj_id = '" . $jbId . "'");
  endif;

  if ($gdc_01 != "") :

     // Get CHECK-IN data from GDC (arrival time) depending on the state
     $arrivalTime = $currentTime;
     if ($stateEvent == "1" || $stateEvent == "2") :
     
        // Get arrival time from GDC
        $arrTour = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_gen_fieldname = 'arr_tour' AND gdc_obj_id = '" . $trId . "'");
        $arrivalTime = substr($arrTour, 0, 14);
        // Convert 20210111225604 => 2021-01-11 22:56:04
        $arrivalTime = substr($arrivalTime, 0, 4) . "-" . substr($arrivalTime, 4, 2) . "-" . substr($arrivalTime, 6, 2) . " " . substr($arrivalTime, 8, 2) . ":" . substr($arrivalTime, 10, 2) . ":" . substr($arrivalTime, 12, 2);
     endif;
     
     // Get data for log history
     $trSortMaxVal = 0;
     if ($jbId != "") : 
        $hqId = getFieldValueFromId("job", "jb_id", $jbId, "hq_id");
        $jbStatus = getFieldValueFromId("job", "jb_id", $jbId, "jb_status");
        $trStatusOfPickUpStation = getFieldValueFromClause("tour", "tr_status", "jb_id = '" . $jbId . "' AND tr_sort = '1'");
        $trSortMaxVal = getMaxOfField("tour", "tr_sort", "jb_id = '" . $jbId . "'");
        $trStatusOfTrSortMaxVal = getFieldValueFromClause("tour", "tr_status", "jb_id = '" . $jbId . "' AND tr_sort = '" . $trSortMaxVal . "'");
     endif;
     if ($crId != "") : 
        $crGpsLong = getFieldValueFromId("courier", "cr_id", $crId, "cr_gps_long");
        $crGpsLat = getFieldValueFromId("courier", "cr_id", $crId, "cr_gps_lat");
     endif;

/*
Folgendermaßen kann jetzt der Status eines Auftrags gesetzt werden.
Als “status” kann Folgendes übergeben werden: PICKEDUP, NOTPICKEDUP, DELIVERED, NOTDELIVERED.
Es wird je nachdem, ob es PICKEUP oder DELIVERY der benötigte Checkin automatisch vorher durchgeführt.

orderReferenceId	=> Pflicht (“938a928824b34a768223e968e1d26ea4”)
status			=> Pflicht (PICKEDUP, NOTPICKEDUP, DELIVERED, NOTDELIVERED)
updateTime 		=> optional (UTC Beispiel: 2018-02-08T09:30:00Z)
reasonCd 		=> optional (“REASON”)

$orderStatusData = array(
    "orderReferenceId" => “938a928824b34a768223e968e1d26ea4”,
    "status" => "DELIVERED",
    "updateTime" => "2021-02-08 9:30:00",
    "reasonText" => "REASON"
    "reasonCd" => "CODE"
);

lnUpdateOrderStatus($orderStatusData);
*/

     if ($stateEvent == "0") :

        // **** ACCEPT ****
        $resultCallOrderState = true;  // Request had been sent!!!!
        writeToFile($logFile, "ACCEPTED: " . "[jbId=" . $jbId . "][orderReferenceId=" . $orderReferenceId . "]");

     elseif ($stateEvent == "1") :

        // **** CHECK-IN PICKUP ****
        // $orderPickedUp = array($orderReferenceId, $arrivalTime);
        // lnUpdateOrderStatus($orderPickedUp);


        // **** PICKEDUP ****
        // Check for order is picked
        $resultCallOrderState = true;
        $pickedState = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'auto_response' AND gdc_obj_id = '" . $jbId . "'");

        if ($pickedState < "2") :
           $resultCallOrderState = false;           
           $trFinishtime = getFieldValueFromId("tour","tr_id",$trId,"tr_finishtime");
           $crUsrId = "";
           if ($crId != "" && is_numeric($crId)) :
              $crUsrId = getFieldValueFromId("courier","cr_id",$crId,"usr_id");
           endif;

           // **** PICKEDUP ****
     	     // Get event state from GDC
     	     $eventCode = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_gen_fieldname = 'del_code' AND gdc_obj_id = '" . $trId . "'");
     	     $eventRemark = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_gen_fieldname = 'del_rem' AND gdc_obj_id = '" . $trId . "'");

           // Init delivery state           
     	     $pickupState = "PICKEDUP";
     	     $eventText = "";

           if ($eventCode != "" && $eventCode != "1") :
              if ($eventRemark != "") :
                 $eventText = $eventRemark;
              endif;
              $pickupState = "NOTPICKEDUP";
           endif;

           $orderStatusData = array(
               "orderReferenceId" => $orderReferenceId,
               "status" => $pickupState,
               "updateTime" => $trFinishtime,
               "reasonText" => $eventText,
               "reasonCd" => $eventCode,
               "recipientName" => "",
               "crID" => $crId,
               "crUsrID" => $crUsrId,
               "vehicle" => $gdc_03,
               "crGpsLong" => $crGpsLong,
               "crGpsLat" => $crGpsLat
           );

           // Write logdata into log database
           $gdcJbLogWritten = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'db_log' AND gdc_obj_id = '" . $jbId . "'");
           if ($gdcJbLogWritten == "" && $trStatusOfPickUpStation == "1") :
           
              writeToFile($logFile, "PICKEDUP (Begin): " . "[currentTime=" . getDateTime("0") . "][jbId=" . $jbId . "][orderReferenceId=" . $orderReferenceId . "][trFinishtime=" . $trFinishtime . "]");
              // $resultCallOrderState = lnUpdateOrderStatus($orderReferenceId, "PICKEDUP", $trFinishtime, "", "");

              $resultCallOrderState = lnUpdateOrderStatus($orderStatusData);
              writeToFile($logFile, "PICKEDUP (End): " . "[currentTime=" . getDateTime("0") . "][jbId=" . $jbId . "][orderReferenceId=" . $orderReferenceId . "][trFinishtime=" . $trFinishtime . "][resultCallOrderState=" . $resultCallOrderState . "]");

              writeToLogDB("172",$hqId,$jbId,"",$crId,$crSid,"","LONG=" . $crGpsLong . "|LAT=" . $crGpsLat . "|INFO_2=" . $gdc_03 . "|RES=" . $resultCallOrderState);
              insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbId, "gdc_gen_fieldname", "db_log", "gdc_content", "172", "gdc_context", ""));
           endif;
        endif;

     elseif ($stateEvent == "2") :

        // **** CHECK-IN DELIVERY ****
        // $orderDelivered = array($orderReferenceId, $arrivalTime);
        // lnUpdateOrderStatus($orderDelivered);


        // Check for order is picked
        // $resultCallOrderState = false;
        // $pickedState = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'auto_response' AND gdc_obj_id = '" . $jbId . "'");

        // if ($pickedState >= "2") :           

           // **** DELIVERED ****
     	     // Get event state from GDC
     	     $eventCode = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_gen_fieldname = 'del_code' AND gdc_obj_id = '" . $trId . "'");
     	     $eventRemark = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_gen_fieldname = 'del_rem' AND gdc_obj_id = '" . $trId . "'");
           
           // Init delivery state
     	     $deliveryState = "DELIVERED";
     	     $eventText = "";

           if ($eventCode != "" && $eventCode != "1") :
              if ($eventRemark != "") :
                 $eventText = $eventRemark;
              endif;
              $deliveryState = "NOTDELIVERED";
           endif;

           $trFinishtime = getFieldValueFromId("tour","tr_id",$trId,"tr_finishtime");
           $tr_signname = getFieldValueFromId("tour","tr_id",$trId,"tr_signname");
           $crUsrId = "";
           if ($crId != "" && is_numeric($crId)) :
              $crUsrId = getFieldValueFromId("courier","cr_id",$crId,"usr_id");
           endif;
           $orderStatusData = array(
               "orderReferenceId" => $orderReferenceId,
               "status" => $deliveryState,
               "updateTime" => $trFinishtime,
               "reasonText" => $eventText,
               "reasonCd" => $eventCode,
               "recipientName" => $tr_signname,
               "crID" => $crId,
               "crUsrID" => $crUsrId,
               "vehicle" => $gdc_03,
               "crGpsLong" => $crGpsLong,
               "crGpsLat" => $crGpsLat
           );
           
           // Write logdata into log database
           $gdcJbLogWritten = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'db_log' AND gdc_obj_id = '" . $jbId . "'");
           if ($gdcJbLogWritten == "172" && ($jbStatus == "2" || $trStatusOfTrSortMaxVal == "1")) :
           
              writeToFile($logFile, $deliveryState . " (Begin): " . "[currentTime=" . getDateTime("0") . "][jbId=" . $jbId . "][orderReferenceId=" . $orderReferenceId . "][trFinishtime=" . $trFinishtime . "][deliveryState=" . $deliveryState . "]");

              // $resultCallOrderState = lnUpdateOrderStatus($orderReferenceId, $deliveryState, $trFinishtime, $eventText, $eventCode);
              $resultCallOrderState = lnUpdateOrderStatus($orderStatusData);
              writeToFile($logFile, $deliveryState . " (End): " . "[currentTime=" . getDateTime("0") . "][jbId=" . $jbId . "][orderReferenceId=" . $orderReferenceId . "][trFinishtime=" . $trFinishtime . "][deliveryState=" . $deliveryState . "][resultCallOrderState=" . $resultCallOrderState . "]");
           
              writeToLogDB("174",$hqId,$jbId,"",$crId,$crSid,"","LONG=" . $crGpsLong . "|LAT=" . $crGpsLat . "|INFO_2=" . $gdc_03 . "|RES=" . $resultCallOrderState);
              updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_content", "174", "gdc_context", ""),"gdc_obj_id = '" . $jbId . "' AND gdc_gen_fieldname = 'db_log'");
           endif;
        // endif;
     endif;
  endif;

  $requestConfigArray = array();
  if ($resultCallOrderState) :
     $requestConfigArray["SEND_STATE"] = "OK:0:";
  else :
     $requestConfigArray["SEND_STATE"] = "ERR:no:msg";
  endif;


  return $requestConfigArray;
}

/*
---------------------------------------------------------------

LIVE-SERVER

cs_id    cs_eid       emp_id   usr_id
123456   STH911739    123456   123456
123456   STH911740    123456   123456
123456   STF910972    123456   123456
123456   STS920307    123456   123456
123456   STS920308    123456   123456
123456   STS920315    123456   123456


    
-----------------------------------------------------------------
    
TEST-SERVER

cs_id    cs_eid       emp_id   usr_id
123456   STH911739    123456   123456
123456   STH911740    123456   123456
123456   STF910972    123456   123456
123456   STS920307    123456   123456
123456   STS920308    123456   123456
123456   STS920315    123456   123456

<auth>
  <customer>STF910972</customer>
  <account>STF910972</account>
  <password>F92184</password>
  <session_id>0e143c3bef0f7759c230664c4dc905f8e4da3b7fbbce2345d7772b0674a318d51dde48a31c101b2feb6c5e598654d88d3f694af5242fcf7dffe7129497871797</session_id>
  <costcenter_name></costcenter_name>
</auth>

<auth>
  <customer>STH911739</customer>
  <account>STH911739</account>
  <password>H85450</password>
  <session_id>5067ed417ec5779207a81178c50017b4a87ff679a2f3e71d9181a67b7542122c74e6497fd22dd8eafa58e21abe4b371bf72642f12aa2d1a323334db941c0f145</session_id>
  <costcenter_name></costcenter_name>
</auth>

<auth>
  <customer>STH911740</customer>
  <account>STH911740</account>
  <password>H63474</password>
  <session_id>fe709c654eac84d5239d1a12a4f71877a87ff679a2f3e71d9181a67b7542122c618b8800517a6c10f8f27a7c48166ea392433abdf2a5a3badf45c990fc732aff</session_id>
  <costcenter_name></costcenter_name>
</auth>

<auth>
  <customer>STS920307</customer>
  <account>STS920307</account>
  <password>S68031</password>
  <session_id>dc363817786ff182b7bc59565d8645236512bd43d9caa6e02c990b0a82652dca2ab855e70e04711a44aea6555af30f10ab1a2d9401e4ae7fe5acff76e5f10420</session_id>
  <costcenter_name></costcenter_name>
</auth>

<auth>
  <customer>STS920308</customer>
  <account>STS920308</account>
  <password>S27196</password>
  <session_id>f096d3da9f8797e053edd854335413ab6512bd43d9caa6e02c990b0a82652dcaf5bea4fc2cbc9766f98b8d8fd28d597c3485aa0e07dfb703721627b6edf1759e</session_id>
  <costcenter_name></costcenter_name>
</auth>

<auth>
  <customer>STS920315</customer>
  <account>STS920315</account>
  <password>S36338</password>
  <session_id>0a30a980e3540e51eb25423caa79f0cb6512bd43d9caa6e02c990b0a82652dcae0442a7d0949964ee2de23a30ff2c1c3cbd682237d1c378be6413427c69ffba6</session_id>
  <costcenter_name></costcenter_name>
</auth> 
*/
?>