<?php
/*=======================================================================
 *
 * auto_response_daikin.php
 *
 * CUSTOMER: Daikin
 *
  =======================================================================*/


// 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;

  $isProductive = false;
  
  // $shipmentId = $gdc_01;  // Init
  $shipmentId = $jbId;  // Init

  $callback = trim($gdc_03);  // "shipments", "tours", ....
  if ($callback == "") :
     // Different servers for differenz stateEvents
     if ($stateEvent == "0" || $stateEvent == "1") :
        $callback = "shipments";
        $numOfStations = getCountOfTable("tour", "jb_id = '" . $jbId . "'");
        if ($numOfStations != "" && is_numeric($numOfStations) && $numOfStations >= 3) :
           $callback = "tours";
        endif;
     elseif ($stateEvent == "2") :
        $callback = "shipments";
     endif;
  endif;
  $callback .= "/";  // Add final slash
  if ($isProductive) :
     $server = "http://app.daikintogo.de/api/order-status/" . $shipmentId . "/" . md5($shipmentId . $tr1CommissionNo) . ".json?api_key=zmddssWhjvsgAPac3bRLkgonMsskmCuj";  // Productive
  else :
     $server = "http://previewd2go.ersteheimat.de/api/doc/" . $shipmentId . "/" . md5($shipmentId . $tr1CommissionNo) . ".json?api_key=zmddssWhjvsgAPac3bRLkgonMsskmCuj";  // Test
  endif;

  
  // $crEid = "";
  // if ($crId != "" && $crId != "0") :
  //    $crEid = getFieldValueFromId("courier","cr_id",$crId,"cr_eid");
  // endif;

  // if ($jbId != "" && $trSort != "") :
  /*
  if ($trId != "") :
     // $shipmentId = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_gen_fieldname = 'info_0' AND gdc_obj_id = '" . $jbId . "' AND gdc_context = '" . $trSort . "'");
     $shipmentId = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_gen_fieldname = 'info_0' AND gdc_obj_id = '" . $trId . "'");
     if ($shipmentId == "") :
        $shipmentId = $gdc_01;
        if ($shipmentId == "") :
           $shipmentId = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'info_0' AND gdc_obj_id = '" . $jbId . "'");
        endif;
     endif;
  endif;
  */

  // $courierId = $crEid;
  /*
  $courierId = $crSid;
  if ($courierId == "") :
     $courierId = $gdc_02;
     if ($courierId == "") :
        $courierId = "5329aaec8e06c724ec000002";
     endif;
  endif;
  */

  // Select API-Key from headquarters of the courier
  /*
  $currHq = "";
  if ($crId != "") :
     $currHq = getFieldValueFromId("courier","cr_id",$crId,"hq_id");
  endif;
  $apiKey = "533183292ad6210fd500001700000000OiEV3a6pl3AdL5qDQ79aCl22nBR6roCE";
  if ($currHq == "1") :
     $apiKey = "53319500e26daf03a300001b00000000clbCnJ3K9XjQ6XSbSPZNgmSoiKNO9LNh";
      $courierId = "5335a7f8e26daf03a300008f00000000";
  elseif ($currHq == "2") :
     $apiKey = "53354a542ad6210fd500006000000000VXBWIEM9q5Dh6SJcoYb1PRTfGAB9ehzV";
     // $courierId = "54116e80281ec24aff000143";
     $courierId = "54116e80281ec24aff00014300000000";
  elseif ($currHq == "3") :
     $apiKey = "ynPIWypFHvyQuykyU84SK77iOT_Xkl9u2BS9ExTwsY1F_cBx3OUi-DREjoBSxQpO";
     $courierId = "tHp_T3IsLKbTILsuBamACbmDGRonkwx_";
  elseif ($currHq == "4") :
     $apiKey = "53318d0b2ad6210fd500001900000000-uBBN9P_218rgLiex9lonWn2-NO1YxaC";
         $courierId = "5335a6b4e26daf03a300008e00000000";
  elseif ($currHq == "5") :
     $apiKey = "7SKbzWxaW9lcos49v2T6tASVBGeE7bSLtIfdp8zOfhFxGHNKPvLQYD0cIML3a3ZO";
     $courierId = "mlw2UpV--RkiqIvK1Vf9I1Pjkd2sY-hw";
  elseif ($currHq == "6") :
     $apiKey = "";
     $courierId = "";
  elseif ($currHq == "7") :
     $apiKey = "5331922de26daf03a300001900000000R0jD-YV20LTyFMbz1GaU1LRv1iejXSg2";
     $courierId = "5335a5de2ad6210fd500006b";
  elseif ($currHq == "8") :
     $apiKey = "";
     $courierId = "";
  elseif ($currHq == "9") :
     $apiKey = "XV2xAbdXu9qvEkmy7bt5-O_4fR1rlToUR4OjgyKf7437si404snx5oZyazUtVprB";
     $courierId = "XV2xAbdXu9qvEkmy7bt5-O_4fR1rlToU";
  elseif ($currHq == "10") :
     $apiKey = "";
     $courierId = "";
  elseif ($currHq == "11") :
     if ($isProductive) :
        $apiKey = "533183292ad6210fd500001700000000OiEV3a6pl3AdL5qDQ79aCl22nBR6roCE";
        $courierId = "5335a5152ad6210fd500006a";
     else :
        $apiKey = "I1PDEq_wy1zLKNYblJklO-k-42W02rOI5Ei6YK22mV_CYJm8jDoRAmCBzNw8RSbQ";  // 5335a5152ad6210fd500006a00000000JM6QrjNtF6snXEZEabRrthrOX7pcvkcq   I1PDEq_wy1zLKNYblJklO-k-42W02rOI5Ei6YK22mV_CYJm8jDoRAmCBzNw8RSbQ
        $courierId = "5335a5152ad6210fd500006a00000000";
     endif;
  elseif ($currHq == "90") :
         $apiKey = "";
         $courierId = "";
  endif;
  */  

  // Convert timestamp from localtime to UTC  [2014-03-01 10:00:00   20140301100000]
  $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";

  $requestHeader = "";
  $requestBody = "";

  if ($stateEvent != "2" || $shipmentId != "") :

      // Define header request
      $requestHeader .= "PUT /" . $shipmentId . " HTTP/1.1\r\n";
      $requestHeader .= "Host: " . $server . "\r\n";
      // $requestHeader .= "Host: " . $server . $shipmentId . "\r\n";
      $requestHeader .= "Content-Type: application/json; charset=utf-8\r\n";
      $requestHeader .= "API-Key: " . $apiKey . " \r\n";
      $requestHeader .= "Content-Length: LENGTH\r\n";

      $shipments = array();

          $tmp_array = array();
          if ($stateEvent == "0") {
              $tmp_array['stateEvent'] = "accept";
              // $tmp_array['waybillNr'] = $tr1CommissionNo;
              $tmp_array['courierId'] = $courierId;
              // $tmp_array['timestamps'] = array('acceptedAt' => $timestamp);
              $tmp_array['acceptedAt'] = $timestamp;
          }
          else if ($stateEvent == "1") {
              $tmp_array['stateEvent'] = "pickup";
              // $tmp_array['waybillNr'] = "A-" . $tr1CommissionNo;
              $tmp_array['courierId'] = $courierId;
              // $tmp_array['timestamps'] = array('pickedupAt' => $timestamp);
              $tmp_array['pickedupAt'] = $timestamp;
          }
          else if ($stateEvent == "2") {
          	
          	  // Get event state from GDC
          	  $eventReason = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_gen_fieldname = 'del_code' AND gdc_obj_id = '" . $trId . "'");

          	  if ($eventReason == "" || $eventReason == "0" || ($eventReason >= "100" && $eventReason <= "199")) :
          	      // OK  <=>  dropoff
                 if ($eventReason == "101") :
                    $eventText = "with_contact";
                 elseif ($eventReason == "102") :
                    $eventText = "with_neighbour";
                 elseif ($eventReason == "103") :
                    $eventText = "in_safe_place";
                 else :
                    $eventText = "";
                 endif;
                 $tmp_array['stateEvent'] = "dropoff";
                 $tmp_array['finalConsignee'] = utf8_encode($trSignName);
                 $tmp_array['courierId'] = $courierId;
                 $tmp_array['dropOffSignature'] = $trSign;
                 // $tmp_array['dropOffSignatureUrl'] = "";
                 // $tmp_array['waybillNr'] = "A-" . $tr1CommissionNo;
                 // $tmp_array['waybillNrConfirmation'] = "A-" . $tr1CommissionNo;              
                 // $tmp_array['timestamps'] = array('droppedoffAt' => $timestamp);
                 $tmp_array['droppedoffAt'] = $timestamp;
                 if ($eventText != "") :
                    $tmp_array['dropOffOutcome'] = $eventText;
                 endif;
              elseif ($eventReason >= "1" && $eventReason <= "5") :
                 // Reasons
                 if ($eventReason == "1") :
                    $eventText = "address_not_found";
                 elseif ($eventReason == "2") :
                    $eventText = "recipient_not_found_at_address";
                 elseif ($eventReason == "3") :
                    $eventText = "recipient_not_there";
                 elseif ($eventReason == "4") :
                    $eventText = "acceptance_refused";
                 elseif ($eventReason == "5") :
                    $eventText = "allowed_time_exceeded";
                 else :
                    $eventText = "recipient_not_there";
                 endif;
                 $tmp_array['stateEvent'] = "undeliverable";
                 $tmp_array['undeliverableReason'] = $eventText;
                 // $tmp_array['courierId'] = $courierId;
                 // $tmp_array['dropOffSignature'] = $trSign;
                 // $tmp_array['dropOffSignatureUrl'] = "";
                 // $tmp_array['timestamps'] = array('undeliverableAt' => $timestamp);
                 $tmp_array['undeliverableAt'] = $timestamp;

              elseif ($eventReason == "6") :
                 // Return to sender
                 $tmp_array['stateEvent'] = "returnedToSender";
                 $tmp_array['returnedToSenderContactName'] = "<Vorname Name>";
                 $tmp_array['returnedToSenderSignature'] = "<base 64 encoded image>";
                 $tmp_array['returnedToSenderSignatureUrl'] = "<URL alternativ>";
                 // $tmp_array['timestamps'] = array('returnedToSenderAt' => $timestamp);
                 $tmp_array['returnedToSenderAt'] = $timestamp;
              endif;
          }

          $frameArray = array();
          $frameArray['shipment'] = $tmp_array;

      $shipments[] = $frameArray;
          
      $requestBody .= json_encode($shipments);
      // $requestBody .= array_to_json($shipments);
      $requestBody = substr($requestBody,1,-1);  // Remove "[" and "]"

      // $requestBody = urlencode($requestBody);

      $requestBodyLen = strlen($requestBody);

      $requestHeader = str_replace("LENGTH", $requestBodyLen, $requestHeader);
  endif;

  $sendMode = "GET";

  $requestConfigArray = array();
  if ($requestBody != "") :

     $requestConfigArray["CURLOPT_URL"] = $server . urlencode($requestBody);
     $requestConfigArray["CURLOPT_RETURNTRANSFER"] = true;
  endif;

  return $requestConfigArray;
}

/*
EVENT-RESPONSES [JSON]

// ACCEPT (Annahme des Auftrags durch den Fahrer)
{
  "shipment":
  {
    "stateEvent":"accept",
    "courierId":"<FAHRZEUG_NR>",
    "acceptedAt":"<ZEITSTEMPEL_UTC>"
  }
}

// PICKUP (Abholung)
{
  "shipment":
  {
    "stateEvent":"pickup",
    "courierId":"<FAHRZEUG_NR>",
    "pickedupAt":"<ZEITSTEMPEL_UTC>"
  }
}

// DROP-OFF (Anlieferung)
// [CASE DELIVERED]
{
  "shipment":
  {
    "stateEvent":"dropoff",
    "finalConsignee":"<KUNDENNAME_UNTERSCHRIFT_KLARTEXT>",
    "courierId":"<FAHRZEUG_NR>",
    "dropOffSignature":"<OPTIONAL::UNTERSCHRIFT_BASE_64_ENCODED_>",
    "droppedoffAt":"<ZEITSTEMPEL_UTC>",
    "dropOffOutcome":"<with_contact|with_neighbour|in_safe_place>",
  }
}
// [CASE NOT DELIVERED]
{
  "shipment":
  {
    "stateEvent":"dropoff",
    "courierId":"<FAHRZEUG_NR>",
    "stateEvent":"undeliverable",
    "undeliverableReason'":"<address_not_found|recipient_not_found_at_address|recipient_not_there|acceptance_refused|allowed_time_exceeded|recipient_not_there>"
    "undeliverableAt'":"<ZEITSTEMPEL_UTC>"
  }
}

// ---------------------------------------------------------------

BEISPIEL:

// ACCEPT
{
  "shipment":
  {
    "stateEvent":"accept",  <=  konstant
    "courierId":"E1044",  <=  Stadtbote-Fahrzeugnummer
    "acceptedAt":"2017-01-17T08:31:00Z"  <=  Annahmezeitpunkt
  }
}

// PICKUP
{
  "shipment":
  {
    "stateEvent":"pickup",  <=  konstant
    "courierId":"E1044",  <=  Stadtbote-Fahrzeugnummer
    "pickedupAt":"2017-01-17T08:55:16Z"  <=  Abholzeitpunkt
  }
}

// DROP-OFF
// [CASE DELIVERED]
{
  "shipment":
  {
    "stateEvent":"dropoff",  <=  konstant
    "finalConsignee":"Meier",  <=  Klartext der unterschreibenden Person
    "courierId":"E1044",  <=  Stadtbote-Fahrzeugnummer
    "dropOffSignature":"iVBORw0KGgoAAAANSUhEUgAAAoAAAAEKAQMAAAC4wHZDAAAABlBM........",
    "droppedoffAt":"2017-01-17T15:36:15Z",  <=  Auslieferzeitpunkt
    "dropOffOutcome":"with_contact"  <=  einer der erfolgreichen Übergabearten
  }
}
// [CASE NOT DELIVERED]
{
  "shipment":
  {
    "stateEvent":"dropoff",  <=  konstant
    "courierId":"E444",  <=  Stadtbote-Fahrzeugnummer
    "stateEvent":"undeliverable",  <=  konstant
    "undeliverableReason'":"recipient_not_there",  <=  einer der Gründe für die Nichtzustellunh
    "undeliverableAt'":"2017-01-17T15:36:15Z"  <=  Zeitpunkt
  }
}

---------------------------------------------------------------------------------

PRODUKTIVSYSTEM:

<auth>
  <customer>STExxxxxx</customer>
  <account>STExxxxxx</account>
  <password>Eyyyyy</password>
  <session_id>6759432675943265432564935643295643956439563</session_id>
  <costcenter_name></costcenter_name>
</auth>

----

TESTSYSTEM:

https://mps1.assecutor.de/test_sb/tools/order_request.php

<auth>
  <customer>STS910195</customer>
  <account>STS910195</account>
  <password>S10195_TEST</password>
  <session_id>4e9800998ecf8427d04f1621a119799fd3d7545d3dc81e728d9d41802d63508455ca9038f00b20db4e74220d41d8ea6cd98c2f636f067f89cc14862c8d34e6d8</session_id>
  <costcenter_name></costcenter_name>
</auth>
*/
?>