<?php
/*=======================================================================
 *
 * auto_response_ics_group.php
 *
 * CUSTOMER: ICS Group
 *
  =======================================================================*/


include ("../include/inc_job.inc.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;

  $isProductive = true;
  
  // Init
  $shipmentId = $jbId;
  $courierId = $crSid;
  if ($tr1CommissionNo == "") :
     $tr1CommissionNo = getFieldValueFromClause("tour", "tr_commission_no", "jb_id = '" . $jbId . "' AND tr_sort = '1'");
  endif;
  // Commission no. of the current station
  $trXCommissionNo = "";
  if ($trSort != "" && is_numeric($trSort)) :
     $trXCommissionNo = getFieldValueFromClause("tour", "tr_commission_no", "jb_id = '" . $jbId . "' AND tr_sort = '" . $trSort . "'");
  endif;

  $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 = "https://icsintprod.service-now.com/api/icsia/v1/ics_votian_api/shipment";  // ICS Productive
  else :
     $server = "https://icsinttest.service-now.com/api/icsia/v1/ics_votian_api/shipment";  // ICS Test
     // $server = "https://ext01.sb-test.assecutor.de/tools/autoresponder_out.php";  // ADSG Test
  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";

  // tr.gdc.info_0 (current station)
  $trGdc0 = "";
  $tratArr = array();
  $scanSerialNo = "";
  if ($trId != "" && is_numeric($trId) && $trId > 0) :
     $trGdc0 = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_gen_fieldname = 'info_0' AND gdc_obj_id = '" . $trId . "'");
     
     // $retArray[] = array($row["at_id"], $row["trat_quantity"], $row["trat_sort"], $row["trat_packingpieces"], $row["trat_serialno"], $row["trat_state"], $row["trat_remark"], $row["trat_price"], $row["trat_name"], $row["trat_description"], $row["trat_weight"], $row["trat_id"], $row["tr_id"], $row["trat_int_serialno"]);
     $tratArr = getTratArticles($jbId, $trSort, "trat.trat_name = 'freescan'");
     $tratArrLen = count($tratArr);
     for ($i = 0; $i < $tratArrLen; $i++) :
         if (substr($tratArr[$i][4], 0, 2) == "GY") :
            $scanSerialNo = $tratArr[$i][4];
            break 1;
         endif;
     endfor;
  endif;

  $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['shipmentId'] = $shipmentId;
              $tmp_array['commissionNo'] = $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['shipmentId'] = $shipmentId;
              $tmp_array['commissionNo'] = $tr1CommissionNo;
              // $tmp_array['partNo'] = $trGdc0;
              if ($scanSerialNo != "") :
                 $tmp_array['partNo'] = $scanSerialNo;
              else :
                 $tmp_array['partNo'] = utf8_encode($trSignName);
              endif;
              $tmp_array['courierId'] = $courierId;
              // $tmp_array['finalConsignee'] = utf8_encode($trSignName);
              $tmp_array['finalConsignee'] = "";
              // $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 == "1" || ($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['shipmentId'] = $shipmentId;
                 $tmp_array['commissionNo'] = $tr1CommissionNo;
                 // $tmp_array['commissionNo'] = $trXCommissionNo;
                 // $tmp_array['partNo'] = $trGdc0;
                 if ($trSort == "2") :
                    $tmp_array['partNo'] = "";
                    $tmp_array['courierId'] = $courierId;
                    $tmp_array['finalConsignee'] = utf8_encode($trSignName);
                 else :
                    if ($scanSerialNo != "") :
                       $tmp_array['partNo'] = $scanSerialNo;
                    else :
                       $tmp_array['partNo'] = utf8_encode($trSignName);
                    endif;
                    // $tmp_array['partNo'] = utf8_encode($trSignName);
                    $tmp_array['courierId'] = $courierId;
                    $tmp_array['finalConsignee'] = "";
                 endif;
                 // $tmp_array['dropOffSignature'] = $trSign;
                 // $tmp_array['dropOffSignatureUrl'] = "";
                 // $tmp_array['waybillNrConfirmation'] = "A-" . $tr1CommissionNo;              
                 // $tmp_array['timestamps'] = array('droppedoffAt' => $timestamp);
                 $tmp_array['droppedoffAt'] = $timestamp;
                 if ($eventText != "") :
                    $tmp_array['dropOffOutcome'] = $eventText;
                 endif;
              elseif ($eventReason >= "2" && $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;

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

     if ($isProductive) :
        $authUser = "ics-votian-app";
        $authPassword = "uD6I3ZNLPKX6#rztOljxKNwjHSG1kAgu";  // Enpoint ICS Live
     else :
        $authUser = "ics-votian-app";
        $authPassword = "uD6I3ZNLPKX6#rztOljxKNwjHSG1kAgu";  // Enpoint ICS Test
     endif;
     // $response = sendCurlRequestPOST($server, $requestBody, $authUser, $authPassword);
     // $response = curl_post();

     $sendMode = "POST";  // !!!!

     $requestConfigArray["CURLOPT_URL"] = $server;
     // $requestConfigArray["CURLOPT_HTTPHEADER"] = array('Content-Type: application/json', 'API-Key: ' . $apiKey);
     $requestConfigArray["CURLOPT_RETURNTRANSFER"] = true;
     $requestConfigArray["CURLOPT_CUSTOMREQUEST"] = "PUT";
     $requestConfigArray["CURLOPT_USERPWD"] = $authUser.":".$authPassword;
     $requestConfigArray["CURLOPT_POSTFIELDS"] = $requestBody;  // JSON
  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 ۢergabearten
  }
}
// [CASE NOT DELIVERED]
{
  "shipment":
  {
    "stateEvent":"dropoff",  <=  konstant
    "courierId":"E444",  <=  Stadtbote-Fahrzeugnummer
    "stateEvent":"undeliverable",  <=  konstant
    "undeliverableReason'":"recipient_not_there",  <=  einer der Gr�� Nichtzustellunh
    "undeliverableAt'":"2017-01-17T15:36:15Z"  <=  Zeitpunkt
  }
}

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

TESTSYSTEM:

https://ext01.sb-test.assecutor.de/service/order_request.php

<auth>
  <customer>STB931501</customer>
  <account>STB931501</account>
  <password>B16291</password>
  <session_id>7899ee4f9d0e8d75201a265cdd6593bfeccbc87e4b5ce2fe28308fd9f2a7baf30f55b9a535c8eb63aa462655c7d7b8e26903e32e3c99ff2101c163d17c08c13a</session_id>
  <costcenter_name></costcenter_name>
</auth>


PRODUKTIVSYSTEM:

https://sb.assecutor.de/service/order_request.php

<auth>
  <customer>STB981400</customer>
  <account>STB981400</account>
  <password>B53553</password>
  <session_id>d31d9686d30416819a2961aac8f68a2beccbc87e4b5ce2fe28308fd9f2a7baf347ac07f954dfbb415f5736ce883c9d63f8eb58cde3405e8f1fdf830611a70c99</session_id>
  <costcenter_name></costcenter_name>
</auth>

<auth>
  <customer>STDD911817</customer>
  <account>STDD911817</account>
  <password>DD33400</password>
  <session_id>19eca5979ccbb752778e6c5f090dc9b61679091c5a880faf6fb5e6087eb1b2dc72ac8188292c9dedd2143ec5fbde4051c8659bb8b6740345bfc5bc9580c7f773</session_id>
  <costcenter_name></costcenter_name>
</auth>

<auth>
  <customer>STE902864</customer>
  <account>STE902864</account>
  <password>E46315</password>
  <session_id>09982e07c27a59881a8bd3d7dddc85fa8f14e45fceea167a5a36dedd4bea2543abf029473ce0bfa0e49e41068615cb5fb2bd34bd4feaaae2573602646aee5030</session_id>
  <costcenter_name></costcenter_name>
</auth>

<auth>
  <customer>STF911135</customer>
  <account>STF911135</account>
  <password>F11235</password>
  <session_id>83d8be72f731a9977c2ac9e41807ac0de4da3b7fbbce2345d7772b0674a318d5a025610400df0004baf120b6911630e451a911bd53b0701671e3c300ae1b888a</session_id>
  <costcenter_name></costcenter_name>
</auth>

<auth>
  <customer>STH913950</customer>
  <account>STH913950</account>
  <password>H43684</password>
  <session_id>5f7733de9c8bddeb31b24d3434640003a87ff679a2f3e71d9181a67b7542122c387ec2bdd6e52b74a7a1bf842c5659dd71363f369cc70fdda448f2294cb63a1c</session_id>
  <costcenter_name></costcenter_name>
</auth>


<auth>
  <customer>STHB924577</customer>
  <account>STHB924577</account>
  <password>HB70591</password>
  <session_id>9f727bc55d5aa9dc9349ea9da97b1ff8c4ca4238a0b923820dcc509a6f75849bc9b01db029304245bf06db3883d29a7006a7d8922fe0a28a93a27dc34655ab5f</session_id>
  <costcenter_name></costcenter_name>
</auth>

<auth>
  <customer>STHH947392</customer>
  <account>STHH947392</account>
  <password>HH88263</password>
  <session_id>3f998e713a6e02287c374fd26835d87ec81e728d9d4c2f636f067f89cc14862c8adfcd4d91e409b5a9d980ee9cd162b3cb1dce19a1ecfac6ab645a445dbf2991</session_id>
  <costcenter_name></costcenter_name>
</auth>

<auth>
  <customer>STL916402</customer>
  <account>STL916402</account>
  <password>L75964</password>
  <session_id>716e1b8c6cd17b771da77391355749f3c9f0f895fb98ab9159f51fd0297e236d05b73db0b6c1597e1fbc6437823c75961f7644ae52ccfec4186932a06590ab16</session_id>
  <costcenter_name></costcenter_name>
</auth>

<auth>
  <customer>STM900635</customer>
  <account>STM900635</account>
  <password>M62526</password>
  <session_id>c338d814c14c9d479eb5ec0b99d887f645c48cce2e2d7fbdea1afc51c7c6ad26e0f7fe1ac61e9f35f6d9b0d1cce6a0248608130fb721b6bc6db5d68f50fe3b49</session_id>
  <costcenter_name></costcenter_name>
</auth>

<auth>
  <customer>STS920450</customer>
  <account>STS920450</account>
  <password>S27602</password>
  <session_id>a6d8ecc0b8747fb7c28e0d64c7dfcbe86512bd43d9caa6e02c990b0a82652dca0db382fb1b1d9c87d3153dec7411e6486b93418d329319225be2985457c86cde</session_id>
  <costcenter_name></costcenter_name>
</auth>
*/
?>