<?php
//echo getTimezone("20130101010000") . "\n";
//echo getTimezone("20130330010000") . "\n";
//echo getTimezone("20130330020000") . "\n";
//echo getTimezone("20130330030000") . "\n";
//echo getTimezone("20130330040000") . "\n";
//echo getTimezone("20130331010000") . "\n";
//echo getTimezone("20130331020000") . "\n";
//echo getTimezone("20130331030000") . "\n";
//echo getTimezone("20130331040000") . "\n";
//echo getTimezone("20130601010000") . "\n";
//die();

define("LOG_NAME", "edi_iftsta");
include_once("../tools/edi.inc.php");
$location_ids = array(
  "ST0" => array("STR", "STUTTGART"),
  "STS" => array("STR", "STUTTGART"),
  "STH" => array("HAJ", "HANNOVER"),
  "STL" => array("LEJ", "LEIPZIG"),
  "STE" => array("DUS", "DUESSELDORF")
);
mk_interchange_vars();

// Allgemein:
// - mapping PLZ zu hq_id
// Fahrer-Pool
// Mapping PLZ zu IATA-code
//
// Sonstiges: 
// jb_locktime '9999-12-31 12:59:59' (auch in den Auftragsdetails beachten wg. Ausbuchen)

// Currently used in shiptrack:
//101 - IFTMIN
//102 - Shipment received by carrier (check_jb_permanent)
//201 - Arrival Scan (Scanning in Niederlassung)
//202 - departure scan (Abholung Niederlassung, check_jb_permanent)
//301 - delivered (VPA)
//304 - delivery attempted (VPA)
//411 - Manifest, no shipment
//412 - Shipment, no manifest

$status_codes = array(
//"101" => NOT TO BE SENT VIA EDI
"102" => "302", // Origin scan from the carrier. First scan after it has entered the carrier’s network
"201" => "303", // Entered the carrier’s hub. Everytime it enters a carrier’s hub/depot
"202" => "304", // Departed carrier’s hub. Everytime it departs a carrier’s hub/depot
"301" => "214", // "Delivered to customer",
"302" => "209", // "Out for Delivery"
"304" => "6", // "Attempt unsuccessful. An unsuccessful attempt has been made to deliver the goods/consignments/equipment.",
"308" => "712", // "Available for pickup";   // Package is available for pickup from pickup location
"320" => "713", // "Customer pickup";
"328" => "7", // Shipment addressed to a company that is closed on weekends. Shipment will be deliverd on the next working day" / Business closed. The goods/consignements/equipment could not be delivered/collected as the business was closed"
"401" => "30", // Incorrect address
"403" => "21", // "Customer moved",
"407" => "49", // Customer rejected
"409" => "33", // "Lost by carrier",
"411" => "602", // "Shipment manifested for collection",
"412" => "37", // "Missing and/or incorrect documents. The goods/consignments/equipment require complete and correct documentation.",
"416" => "640", // "Undeliverable, return to sender (Amazon)",
"451" => "211" // "Customer did not pick up, back to seller",
);

$message = "";
$anxe_interchange_control_count = 0;

//if (date("d") == "15" || date("d", mktime(0, 0, 0, date("m"), date("d") + 1, date("Y"))) == "01"):
  $es_date_from = date("Y-m-d 00:00:00", mktime(0, 0, 0, date("m"), date("d") + 1, date("Y")));
//else:
//  $es_date_from = date("Y-m-d 00:00:00", mktime(0, 0, 0, date("m"), date("d") - 1, date("Y")));
//endif;
//echo "$es_date_from" . "\n"; die();

// Special entries in table edi_status:
// 0 not finished (per track_id)
// 1 finished  (per track_id)
// 0 and 1 alternatively only
// Noch nicht fertige Tracking IDs finden
//$sql_query = "SELECT es.ec_track_id, ec_weight FROM edi_status AS es LEFT JOIN edi_consignee AS ec ON es.ec_track_id = ec.ec_track_id WHERE es_status = 0" . " AND es_date < '$es_date_from'";
$sql_query = "SELECT es.ec_track_id, ec_weight FROM edi_status AS es, edi_consignee AS ec WHERE es.ec_track_id = ec.ec_track_id AND es_status = 0" . " AND es_date < '$es_date_from'";
//$sql_query = "SELECT es.ec_track_id, ec_weight FROM edi_status AS es, edi_consignee AS ec WHERE es.ec_track_id = ec.ec_track_id AND es_status = 1 AND es_date > '2013-03-30 00:00:00' AND es_date < '2013-03-30 23:59:59' AND es_status = 1";
//echo $sql_query; die();
$res = mysql_query($sql_query) or die ($sql_query . ": " . mysql_error());
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
//            $sqlquery = "SELECT MAX(es_date) FROM edi_status WHERE ec_track_id = '" . $row["ec_track_id"] . "' AND es_status != 0";
//            $res2 = mysql_query($sqlquery) or die ($sqlquery . ": " . mysql_error());
//            $row2 = mysql_fetch_row($res2);

            // Get tracking ID from "tourarticle"            
            $sqlquery = "SELECT trat.trat_id, trat.jb_id, trat.tr_sort, trat.trat_state, trat.trat_remark,"
                      . "       tratp.tratp_type, tratp.tratp_state, tratp.tratp_remark, tratp.tratp_createtime,"
                      . "       tr.tr_signname, tr.tr_hsno,"
                      . "       ad.ad_street, ad.ad_zipcode, ad.ad_city, ad.ad_country"
                      . "  FROM phoenix.tourarticle AS trat, phoenix.tourarticleprocess AS tratp, phoenix.tour AS tr, phoenix.address AS ad"
                      . "  WHERE trat.trat_serialno = '" . $row["ec_track_id"] . "' AND trat.trat_name != 'freescan' AND"
                      . "        trat.trat_id = tratp.trat_id AND"
//                      . "        tratp.tratp_createtime > '" . $row2[0] . "' AND"
                      . "        trat.jb_id = tr.jb_id AND"
                      . "        trat.tr_sort = tr.tr_sort AND"
                      . "        tr.ad_id = ad.ad_id"
                      . "  ORDER BY tratp.tratp_createtime";
//            mysql_free_result($res2);
            $res1 = mysql_query($sqlquery) or die ($sqlquery . ": " . mysql_error());

  while ($row1 = mysql_fetch_array($res1, MYSQL_ASSOC)):
//echo $row1["tratp_type"];
    if ($row1["tratp_type"] != 101):
      $es_status = $status_codes[$row1["tratp_type"]];
      $es_date = $row1["tratp_createtime"];    
      if (check_event($row["ec_track_id"], $es_status, $es_date) == 0):
        // tracking ID finished?
        if ($row1["tratp_type"] == '301' || $row1["tratp_type"] == '411' || $row1["tratp_type"] == '412' || $row1["tratp_type"] == '416' || $row1["tratp_type"] == '407' || $row1["tratp_type"] == '409' || $row1["tratp_type"] == '401' || $row1["tratp_type"] == '403' || $row1["tratp_type"] == '451' || $row1["tratp_type"] == '320'):
          writeLog("finalizing track id: '" . $row["ec_track_id"] . "', because of event: '" . $row1["tratp_type"] . "', date: '" . $row1["tratp_createtime"] . "'");
          exec_query("UPDATE edi_status SET es_status = 1 WHERE ec_track_id = '" . $row["ec_track_id"] . "' AND es_status = 0");
        endif;
        writeLog("sending event for track id: '" . $row["ec_track_id"] . "', IFTSTA-event: '" . $es_status . "', date: '" . $es_date . "'");
        $message .= mk_message($row["ec_track_id"], $location_ids[substr($row["ec_track_id"], 0, 3)][0], $location_ids[substr($row["ec_track_id"], 0, 3)][1], "DE", $es_status,
          substr($es_date, 0, 4) . substr($es_date, 5, 2) . substr($es_date, 8, 2) . substr($es_date, 11, 2) . substr($es_date, 14, 2) . substr($es_date, 17, 2), $row["ec_weight"]);
        exec_query("INSERT INTO edi_status (ec_track_id,es_msg_no,es_ic_ref,es_date,es_status) VALUES ('" .
          $row["ec_track_id"] . "','" . $anxe_message_reference_number++ . "','" . $anxe_interchange_control_reference . "','" . $es_date . "','" . $es_status . "')");
        exec_query("UPDATE phoenix.tourarticleprocess SET tratp_state = 2 WHERE trat_id = " . $row1["trat_id"] . " AND tratp_type = '".  $row1["tratp_type"] ."' AND tratp_createtime = '" . $row1["tratp_createtime"] . "'");
        $anxe_interchange_control_count++;
      endif;
    endif;
  endwhile;
  mysql_free_result($res1);
endwhile;
mysql_free_result($res);

if ($anxe_interchange_control_count > 0):
  mk_interchange($anxe_interchange_control_count, $message, "IFTSTA");
  writeLog("finished, IFTSTA was created");
else:
  writeLog("finished, nothing to be done");
endif;

function check_event($ec_track_id, $es_status, $es_date)
{
  $sql_query = "SELECT COUNT(*) FROM edi_status WHERE ec_track_id = '$ec_track_id' AND es_status = $es_status AND es_date = '$es_date'";
  $res = mysql_query($sql_query) or die ($sql_query . ": " . mysql_error());
  
  $event_exists = 0;
  if ($row = mysql_fetch_row($res)):
    if ($row[0] == 1)
      return 1;
  endif;
  
  return 0;
}

function mk_message($track_id, $tred_place_location_identification, $tred_place_location, $tred_related_place_location_one_identification,
  $tred_status_reason_coded,$tred_date_time_period, $tred_measurement_value, $tred_number_of_packages = 1)
{
	global $anxe_message_reference_number;
	
  return
    "  <anxs:message.header>" .
    "    <anxe:message.reference.number>" . $anxe_message_reference_number . "</anxe:message.reference.number>" .
    "    <anxc:message.identifier>" .
    "      <anxe:message.type unsl:code=\"0065:IFTSTA\">International multimodal status report message</anxe:message.type>" .
    "      <anxe:message.version.number>D</anxe:message.version.number>" .
    "      <anxe:message.release.number>01A</anxe:message.release.number>" .
    "      <anxe:controlling.agency unsl:code=\"0051:UN\">UN/ECE/TRADE/WP.4</anxe:controlling.agency>" .
    "      <anxe:association.assigned.code unknown:code=\"0057:EAN008\">EAN008</anxe:association.assigned.code>" .
    "    </anxc:message.identifier>" .
    "  </anxs:message.header>" .
    "  <trsd:beginning.of.message>" .
    "    <trcd:document.message.name>" .
    "      <tred:document.message.name.coded uncl:code=\"1001:23\">Status information</tred:document.message.name.coded>" .
    "    </trcd:document.message.name>" .
    "    <trcd:document.message.identification>" .
    "      <tred:document.message.number>" . $track_id . "</tred:document.message.number>" .
    "    </trcd:document.message.identification>" .
    "  </trsd:beginning.of.message>" .
    "  <trsd:name.and.address>" .
    "    <tred:party.qualifier uncl:code=\"3035:SF\">Ship from</tred:party.qualifier>" .
    "  </trsd:name.and.address>" .
    "  <trsd:name.and.address>" .
    "    <tred:party.qualifier uncl:code=\"3035:ST\">Ship to</tred:party.qualifier>" .
    "  </trsd:name.and.address>" .
    "  <trsd:place.location.identification>" .
    "    <tred:place.location.qualifier unknown:code=\"3227:175\">175</tred:place.location.qualifier>" .
    "    <trcd:location.identification>" .
    "      <tred:place.location.identification>" . $tred_place_location_identification . "</tred:place.location.identification>" .
    "      <tred:code.list.responsible.agency.coded uncl:code=\"3055:3\">IATA (International Air Transport Association)</tred:code.list.responsible.agency.coded>" .
    "      <tred:place.location>" . $tred_place_location . "</tred:place.location>" .
    "    </trcd:location.identification>" .
    "    <trcd:related.location.one.identification>" .
    "      <tred:related.place.location.one.identification>" . $tred_related_place_location_one_identification . "</tred:related.place.location.one.identification>" .
    "    </trcd:related.location.one.identification>" .
    "  </trsd:place.location.identification>" .

    "  <trsd:consignment.information>" .
    "    <tred:consolidation.item.number>1</tred:consolidation.item.number>" .
    "  </trsd:consignment.information>" .
    "  <trsd:status>" .
    "    <trcd:status.type>" .
    "      <tred:status.type.coded uncl:code=\"9015:1\">Transport</tred:status.type.coded>" .
    "    </trcd:status.type>" .
    "    <trcd:status.reason>" .
    "      <tred:status.reason.coded unknown:code=\"9013:" . $tred_status_reason_coded . "\">" . $tred_status_reason_coded . "</tred:status.reason.coded>" .
    "    </trcd:status.reason>" .
    "  </trsd:status>" .
    "  <trsd:reference>" .
    "    <trcd:reference>" .
    "      <tred:reference.qualifier uncl:code=\"1153:POR\">Purchase order response number</tred:reference.qualifier>" .
    "    </trcd:reference>" .
    "  </trsd:reference>" .
    "  <trsd:details.of.transport>" .
    "    <tred:transport.stage.qualifier uncl:code=\"8051:30\">On-carriage transport</tred:transport.stage.qualifier>" .
    "    <tred:conveyance.reference.number>1</tred:conveyance.reference.number>" .
    "    <trcd:carrier>" .
    "      <tred:carrier.identification>" . "STBX" . "</tred:carrier.identification>" .
    "    </trcd:carrier>" .
    "  </trsd:details.of.transport>" .
    "  <trsd:date.time.period>" .
    "    <trcd:date.time.period>" .
    "      <tred:date.time.period.qualifier uncl:code=\"2005:ZZZ\">Mutually defined</tred:date.time.period.qualifier>" .
    "      <tred:date.time.period>" . $tred_date_time_period . "</tred:date.time.period>" .
    "      <tred:date.time.period.format.qualifier uncl:code=\"2379:204\">CCYYMMDDHHMMSS</tred:date.time.period.format.qualifier>" .
//    "      <tred:date.time.period>" . $tred_date_time_period . getTimezone($tred_date_time_period) . "</tred:date.time.period>" .
//    "      <tred:date.time.period.format.qualifier uncl:code=\"2379:304\">CCYYMMDDHHMMSSZZZ</tred:date.time.period.format.qualifier>" .
////    "      <tred:date.time.period>" . convert2CET($tred_date_time_period) . "CET</tred:date.time.period>" .
////    "      <tred:date.time.period.format.qualifier uncl:code=\"2379:304\">CCYYMMDDHHMMSSZZZ</tred:date.time.period.format.qualifier>" .
    "    </trcd:date.time.period>" .
    "  </trsd:date.time.period>" .
    "  <trsd:equipment.details>" .
    "    <tred:equipment.qualifier unknown:code=\"8053:AA\">AA</tred:equipment.qualifier>" .
    "  </trsd:equipment.details>" .
    "  <trsd:measurements>" .
    "    <tred:measurement.application.qualifier unknown:code=\"6311:ABR\">ABR</tred:measurement.application.qualifier>" .
    "    <trcd:measurement.details>" .
    "       <tred:measurement.dimension.coded uncl:code=\"6313:AAD\">Total gross weight</tred:measurement.dimension.coded>" .
    "    </trcd:measurement.details>" .
    "    <trcd:value.range>" .
    "      <tred:measure.unit.qualifier>KG</tred:measure.unit.qualifier>" .
    "      <tred:measurement.value>" . $tred_measurement_value . "</tred:measurement.value>" .
    "    </trcd:value.range>" .
    "  </trsd:measurements>" .
    "  <trsd:goods.item.details>" .
    "    <tred:goods.item.number>" . "1" . "</tred:goods.item.number>" .
    "    <trcd:number.and.type.of.packages>" .
    "      <tred:number.of.packages>" . $tred_number_of_packages . "</tred:number.of.packages>" .
    "      <tred:type.of.packages.identification>CTN</tred:type.of.packages.identification>" .
    "    </trcd:number.and.type.of.packages>" .
    "  </trsd:goods.item.details>" .
    
    "  <anxs:message.trailer>" .
    "    <anxe:number.of.segments.in.the.message>14</anxe:number.of.segments.in.the.message>" .
    "    <anxe:message.reference.number>" . $anxe_message_reference_number . "</anxe:message.reference.number>" .
    "  </anxs:message.trailer>";
}

//$IFTSTA = array(
//  array("anxs:interchange.header",             "edi_message", "em_unb",  "", "INTERCHANGE HEADER"),
//    // Header
//    array("anxs:message.header",                 "edi_message", "em_unh",  "", "MESSAGE HEADER"),
//    array("trsd:beginning.of.message",           "edi_message", "em_bgm",  "", "BEGINNING OF MESSAGE"),
//    array("trsd:name.and.address",               "edi_message", "em_nad1", "", "Shipper Name and Address"),
//    array("trsd:name.and.address",               "edi_message", "em_nad2", "", "NAME AND ADDRESS"),
//    array("trsd:place.location.identification",  "edi_message", "em_loc",  "", "Real Location of Freight"),
//    // Detail
//    array("trsd:consignment.information",        "edi_message", "em_cni",  "", "CONSIGNENT INFROMATION"),
//    array("trsd:status",                         "edi_message", "em_sts",  "", "Shipment Status"),
//    array("trsd:reference",                      "edi_message", "em_sts",  "", "Shipment ID"),
//    array("trsd:details.of.transport",           "edi_message", "em_tdt",  "", "DETAILS OF TRANSPORT"),
//    array("trsd:date.time.period",               "edi_message", "em_dtm",  "", "DATE/TIME/PERIOD"),
//    array("trsd:equipment.details",              "edi_message", "em_eqd",  "", "EQUIPMENT DETAILS"),
//    array("trsd:measurements",                   "edi_message", "ec_mea",  "", "MEASUREMENTS"),
//    array("trsd:goods.item.details",             "edi_message", "ec_gid",  "", "GOODS ITEM DETAILS"),
//    // Summary
//    array("anxs:message.trailer",                "edi_message", "em_unt",  "", "MESSAGE TRAILER"),
//  array("anxs:interchange.trailer",            "edi_message", "em_unz",  "", "INTERCHANGE")
//);

//// When run in Finland (GMT +0200), the first line below prints "Jan 01 1998 00:00:00", while the second prints "Dec 31 1997 22:00:00".
////echo date("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
////echo gmdate("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
////$broken_time=explode(':','10:56:45');
////$time=date('H:i:s',mktime(1+$broken_time[0],0+$broken_time[1],0+$broken_time[2],0,0,0));
////echo $time;
//function convert2CET($localdate)
//{
//// convert local time to CET (Problem: daylight saving time)
//// CET is GMT+1
//
//// add one hour to local date/time and convert the result to GMT (without DST); the result is CET
//  return gmdate("YmdHis", mktime(substr($localdate, 8, 2) + 1, substr($localdate, 10, 2), substr($localdate, 12, 2), substr($localdate, 4, 2), substr($localdate, 6, 2), substr($localdate, 0, 4)));
//}

function getTimezone($localdate)
{
//echo substr($localdate, 0, 4) . "-" . substr($localdate, 4, 2) . "-" . substr($localdate, 6, 2) . " " .
//    substr($localdate, 8, 2) . ":" . substr($localdate, 10, 2) . ":" . substr($localdate, 12, 2) . " ";
  return date('I', strtotime(substr($localdate, 0, 4) . "-" . substr($localdate, 4, 2) . "-" . substr($localdate, 6, 2) . " " .
    substr($localdate, 8, 2) . ":" . substr($localdate, 10, 2) . ":" . substr($localdate, 12, 2))) == 1 ? "CES" : "CET";
}
?>