<?php
//die();
// NEXT und TIMED zusammenfassen
$cur_date = date("Y-m-d H:i:s");
//$cur_date = "2012-12-03 15:02:27";
define("LOG_NAME", "edi_iftmin");
//include_once("../include/email/htmlMimeMail.php");
$hq_id = 0;
include_once("../tools/edi.inc.php");
$action = "down";
include_once("../tools/edi_ftp.inc.php");

//$edi_files = array(
//  "1363784696860_1025836987287.tmp"
//);

writeLog("edi_files = " . var_export($edi_files, true));
//die();

$IFTMIN = array(
  array("anxs:interchange.header",             "edi_message", "em_unb",  "", "INTERCHANGE 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:date.time.period",               "edi_message", "em_dtm1", "", "Manifest Processing Date/Time"),
  array("trsd:date.time.period",               "edi_message", "em_dtm2", "", "Shipment Date"),
  array("trsd:transport.service.requirements", "edi_message", "em_tsr",  "", "TRANSPORT SERVICE REQUIREMENTS"),
  array("trsd:currencies",                     "edi_message", "em_cux",  "", "CURRENCIES"),
  array("trsd:free.text",                      "edi_message", "em_ftx",  "", "Manifest Instructions"),
  array("trsd:control.total",                  "edi_message", "em_cnt1", "", "Total Line Items"),
  array("trsd:control.total",                  "edi_message", "em_cnt2", "", "Total Gross Weight"),
  array("trsd:control.total",                  "edi_message", "em_cnt3", "", "Total Quantity"),
  array("trsd:control.total",                  "edi_message", "em_cnt4", "", "Total Amount"),
  array("trsd:terms.of.delivery.or.transport", "edi_message", "em_tod",  "", "TERMS OF DELIVERY OR TRANSPORT"),
  array("trsd:place.location.identification",  "edi_message", "em_loc",  "", "Origin"),
  array("trsd:reference",                      "edi_message", "em_rff1", "", "Carrier SCAC Code"),
  array("trsd:reference",                      "edi_message", "em_rff2", "", "REFERENCE"),
  array("trsd:reference",                      "edi_message", "em_rff3", "", "Commercial Invoice Number"),
  array("trsd:reference",                      "edi_message", "em_rff4", "", "Reference1"),
  array("trsd:reference",                      "edi_message", "em_rff5", "", "Reference2"),
  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:contact.information",            "edi_message", "em_cta",  "", "CONTACT INFORMATION"),
  array("trsd:communication.contact",          "edi_message", "em_com",  "", "COMMUNICATION CONTACT"),
  array("trsd:reference",                      "edi_message", "em_rff6", "", "Amazon Tax ID"),
  array("trsd:goods.item.details",             "edi_consignee", "ec_gid",  "", "GOODS ITEM DETAILS"),
  array("trsd:transport.movement.details",     "edi_consignee", "ec_tmd",  "", "TRANSPORT MOVEMENT DETAILS"),
  array("trsd:place.location.identification",  "edi_consignee", "ec_loc1", "", "PLACE/LOCATION IDENTIFICATION"),
  array("trsd:place.location.identification",  "edi_consignee", "ec_loc2", "", "PLACE/LOCATION IDENTIFICATION"),
  array("trsd:place.location.identification",  "edi_consignee", "ec_loc3", "", "PLACE/LOCATION IDENTIFICATION"),
  array("trsd:monetary.amount",                "edi_consignee", "ec_moa1", "", "Amazon Freight Cost"),
  array("trsd:monetary.amount",                "edi_consignee", "ec_moa2", "", "CIF Value"),
  array("trsd:monetary.amount",                "edi_consignee", "ec_moa3", "", "Value of Goods"),
  array("trsd:monetary.amount",                "edi_consignee", "ec_moa4", "", "Consignee Freight Charge"),
  array("trsd:monetary.amount",                "edi_consignee", "ec_moa5", "", "Consignee Gift Wrap Charge"),
  array("trsd:monetary.amount",                "edi_consignee", "ec_moa6", "", "Insurance"),
  array("trsd:monetary.amount",                "edi_consignee", "ec_moa7", "", "COD Charge"),
  array("trsd:monetary.amount",                "edi_consignee", "ec_moa8", "", "Other Invoice Amounts"),
  array("trsd:free.text",                      "edi_consignee", "ec_ftx1", "", "Freight Terms"),
  array("trsd:free.text",                      "edi_consignee", "ec_ftx2", "", "Reason For Export"),
  array("trsd:name.and.address",               "edi_consignee", "ec_nad", "", "Consignee Name and Address"),
  array("trsd:measurements",                   "edi_consignee", "ec_mea1", "", "Gross Weight"),
  array("trsd:measurements",                   "edi_consignee", "ec_mea2", "", "Chargeable Weight"),
  array("trsd:dimensions",                     "edi_consignee", "ec_dim",  "", "DIMENSIONS"),
  array("trsd:reference",                      "edi_consignee", "ec_rff1", "", "Bill of Lading"),
  array("trsd:date.time.period",               "edi_consignee", "ec_dtm",  "", "DATE/TIME/PERIOD"),
  array("trsd:reference",                      "edi_consignee", "ec_rff2", "", "Bill of Lading"),
  array("trsd:reference",                      "edi_consignee", "ec_rff3", "", "Master Bill of Lading"),
  array("trsd:reference",                      "edi_consignee", "ec_rff4", "", "Bill of Lading"),
  array("trsd:package.identification",         "edi_package", "ep_pci", "", "PACKAGE IDENTIFICATION"),
  array("trsd:reference",                      "edi_package", "ep_rff", "", "REFERENCE"),
  array("anxs:message.trailer",                "edi_message", "em_unt", "", "MESSAGE TRAILER"),
  array("anxs:interchange.trailer",            "edi_message", "em_unz", "", "INTERCHANGE")
);

define("CONSIGNEE_START", 24);
define("CONSIGNEE_TYPE", 25);
define("CONSIGNEE_AMOUNT", 29);
define("CONSIGNEE_ADDRESS", 39);
define("CONSIGNEE_WEIGHT", 40);
define("CONSIGNEE_INVNO", 43);
define("CONSIGNEE_TRACK_ID", 45);
define("CONSIGNEE_PHONE", 46);
define("CONSIGNEE_END", 47);
define("PACKAGE_START", 48);
define("PACKAGE_VEN_NO", 49);
define("PACKAGE_END", 49);

define("MAX_TR_SORT", 99999);

$jb_id_lineA = array(
  "ST010" => 12806260,
//  "ST020" => 12806260,
//  "ST030" => 12806260,
  "ST040" => 12805634,
  "STH01" => 12806264,
  "STH04" => 12805632,
  "STL01" => 12806268,
  "STE01" => 12806267,
  "STE04" => 12806262,
  "STE05" => 12806265
);

$tr_sortA = array(
  'STBX_SAME' => 2,
  'STBX_TIMED' => 2,
  'STBX_NEXT' => 2
);

$hq_prefixes = array(
  "ST0" => 11,
  "STS" => 11,
  "STH" =>  4,
  "STL" =>  8,
  "STE" =>  7
);

$track_idA = array();
$jb_id_line = 0;
$prefix = "";

//if (!isset($argv[1]) || $argv[1] == ""):
//   die("missing parameter\n");
//else:

//  foreach ($edi_files AS $edi_file) {
writeLog("processing " . $edi_file);

  	$level = 0;
    $cnt = -1;
    $curelem = "";
    $cdatabuf = "";
    $curtext = "";

    $em_msg_id = "";
    $ec_inv_no = "";
    $ec_weight = "";
    $ec_amount = "";
    $ec_type = "";
    $ec_type_real = "";
    $track_id = "";

    $ad_street = "";
    $ad_zipcode = "";
    $ad_city = "";
    $ad_country = "";
    $tr_hsno  = "";
    $tr_comp = "";
    $tr_person1 = "";
    $tr_person = "";
    $tr_phone = "";
    
    $ep_ven_no = "";

    $xml_contents = edi2xml("../temp/edifact/" . $edi_file);
    if ($xml_contents != "error") {
      $parser = xml_parser_create('UTF-8');
      xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'iso-8859-1');
      xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
      xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
      xml_set_element_handler($parser, "startElement", "endElement");
      xml_set_character_data_handler($parser, "cdata");
      xml_set_default_handler ($parser, "defHandler");
      xml_parse($parser, $xml_contents);
      xml_parser_free($parser);
      writeToDB("edi_message", $fields = "em_msg_id", $values = "'" . $em_msg_id . "'");
    }
//  print_r($IFTMIN);
//  }
  
  // Aufträge in Scanliste wieder sichtbar machen
  foreach($jb_idA[$hq_id] AS $type => $jb_id_tmp) {
  	if ($tr_sortA[$type] > 2):
      $dummy = file ("http://www.assecutor.de/stadtbote/tools/check_address.php?jb_id=$jb_id_tmp&hq_id=$hq_id&remote_addr=212.79.60.67");
      sort_zipcode($jb_id_tmp, $hq_id);
      exec_query("UPDATE phoenix.job SET jb_status = 999 WHERE jb_id = " . $jb_id_tmp, 0);
    else:
      exec_query("UPDATE phoenix.job SET jb_status = 998 WHERE jb_id = " . $jb_id_tmp, 0);
    endif;
	}
  exec_query("UPDATE phoenix.job SET jb_ordertime = '" . date("Y") . "-01-01 01:01:01' WHERE jb_id IN " . $jb_id_sql[$hq_id], 0);

  // Gewichte- und Volumenmail senden
  exec_query("UPDATE phoenix.job SET jb_version = jb_version - 1 WHERE jb_id = " . $jb_idA[$hq_id]['STBX_NEXT'], 1);
  $row = get_first_row("SELECT jb_version FROM phoenix.job WHERE jb_id = " . $jb_idA[$hq_id]['STBX_NEXT']);
writeLog("jb_version = " . $row[0]);
  if ($row[0] == 0)
    send_csv_mail($jb_idA[$hq_id]['STBX_NEXT']);

  // Alte Tracking-IDs in Sendungsverfolgung löschen
  $prefix_add = "";
  if ($prefix == "ST0"):
    $prefix = "ST";
    $prefix_add = "0";
  endif;
  $prefixes = array(
    $prefix . "01" . $prefix_add => "",
    $prefix . "02" . $prefix_add => "",
    $prefix . "03" . $prefix_add => ""
  );
  foreach ($prefixes AS $prefix => $val) {
  	$row = get_first_row("SELECT MIN(trat_serialno) FROM phoenix.tourarticle where left(trat_serialno, 5) = '$prefix' AND trat_modify > '" . date("Y-m-d H:i:s", mktime(0, 0, 0, date("m") - 3, date("d") + 1, date("Y"))) . "' AND CHAR_LENGTH(trat_serialno) = 13 AND tr_sort = 1 AND jb_id NOT IN " . $jb_id_sql[$hq_id], 1);
    $prefixes[$prefix] = $row[0];
  }
  $dbhost = "172.16.0.111:3711";
  mysql_connect($dbhost, $dblogin, $dbpassword) or die (mysql_error());
  mysql_select_db("meta_object") or die (mysql_error());
  mysql_query('SET NAMES latin1') or die ('SET NAMES latin1' . ": " . mysql_error());

  foreach ($prefixes AS $prefix => $val) {
    $sqlquery = "DELETE FROM metaobject WHERE mo_obj_type = 'track' AND LEFT(mo_value, 5) = '$prefix' AND mo_value < '$val'";
writeLog($sqlquery);
    mysql_query($sqlquery) or die ($sqlquery . ": " . mysql_error());
  }

  // Neue Tracking-IDs in Hash-Tabelle eintragen
  if (count ($track_idA) > 0):
    writeLog("writing tracking ids to '$dbhost'");
    foreach ($track_idA AS $track_id) {
//      writeLog("writing tracking id '$track_id' to '$dbhost'");
	    $sql_query = "INSERT INTO metaobject (mo_id_ref_db, mo_name, mo_obj_type, mo_obj_id, mo_hash, mo_value) VALUES (1, '', 'track', 0, '$track_id', '$track_id')";
      mysql_query($sql_query) or die ($sql_query . ": " . mysql_error());
    }
  endif;

  mysql_close();
  writeLog("import for hq_id = '$hq_id' successful");
  
//endif;

function initImport($track_id) {
	global $hq_id, $hq_prefixes, $prefix, $jb_id_sql, $jb_idA, $tr_sortA, $jb_id_line, $jb_id_lineA, $zipcodes, $mysql_db;

  $prefix = substr($track_id, 0, 3);
  if (array_key_exists($prefix, $hq_prefixes)):
    $hq_id = $hq_prefixes[$prefix];    
    writeLog("hq_id = '$hq_id' derived from track_id = '$track_id'");
  else:
    writeLog("irregular value in first three digits in beginning of tracking-id: '" . $prefix . "'");
    die();
  endif;

  exec_query("UPDATE phoenix.job SET jb_version = jb_version + 1 WHERE jb_id = " . $jb_idA[$hq_id]['STBX_NEXT'], 1);
  // Warten, falls ein anderer Import gerade läuft (Amazon liefert manchmal in mehreren Schüben schnell hintereinander)
  do {
  	$row1 = get_first_row ("SELECT jb_status FROM phoenix.job WHERE jb_id = " . $jb_idA[$hq_id]['STBX_NEXT']);
    if ($row1[0] == 997):
      writeLog("waiting for running 'edi_iftmin.php' to terminate...");
      sleep(10); // wait 10 seconds...
    endif;
  } while ($row1[0] == 997);
  exec_query("UPDATE phoenix.job SET jb_status = 997 WHERE jb_id IN " . $jb_id_sql[$hq_id] . " AND jb_status != 997", 0);

//  // Linienauftrag des heutigen Tages finden (ist als Dauerauftrag bereits vorhanden)
//  $sql_query = "SELECT jb_id FROM phoenix.job WHERE csc_id_payer = " . $csc_id_lineA[$hq_id] . " AND LEFT(jb_ordertime, 10) = '" . date("Y-m-d") . "' AND jb_storno IS NULL AND jb_permanent = 2 AND hq_id = $hq_id";
//  $res = mysql_query($sql_query, $mysql_db) or die ($sql_query . ": " . mysql_error($mysql_db));
////writeLog("[$sql_query]");
  $jb_id_line = $jb_id_lineA[substr($track_id, 0, 5)];
//  if ($row = mysql_fetch_row($res)):
//    $jb_id_line = $row[0];
//    writeLog("found line haul order: jb_id_line = '$jb_id_line'");
//  else:
//    writeLog("line haul order not found: [$sql_query]");
//  endif;
//  mysql_free_result($res);

  // Bereits bestehende Aufträge finden (Amazon liefert manchmal in mehreren Schüben)
  $sql_query = "SELECT job.jb_id, MAX(tr_sort) FROM phoenix.job, phoenix.tour WHERE job.jb_id IN " . $jb_id_sql[$hq_id] . " AND job.jb_id = tour.jb_id GROUP BY job.jb_id";
  $res = mysql_query($sql_query, $mysql_db) or die ($sql_query . ": " . mysql_error($mysql_db));
  while ($row = mysql_fetch_row($res)):
    foreach ($jb_idA[$hq_id] AS $type => $jb_id_tmp){
      if ($jb_id_tmp == $row[0]):
        $tr_sortA[$type] = $row[1] + 1;
      endif;
    }
  endwhile;
  mysql_free_result($res);
}

/**
 * Quelle: http://reeg.junetz.de/DSP/node31.html
 *
 * @param    parser    Object    Parserobjekt
 * @param    name      string    Name des öffnenden Elements
 * @param    atts      array     Array mit Attributen
 */
function startElement($parser, $name, $atts) {	
  global $cnt, $level, $curelem, $IFTMIN;

  $att_str = "";
  foreach($atts AS $key => $att) {
    $att_str .= " " . $key . "=" . "\"" . $att . "\"";
  }

  $curelem = $name;
  if ($level++ == 1):  
    if ($name != $IFTMIN[++$cnt][0]):
      if ($name == $IFTMIN[CONSIGNEE_START][0]):
        $cnt = CONSIGNEE_START;
      elseif ($name == $IFTMIN[PACKAGE_START][0]):
        $cnt = PACKAGE_START;
      else:
        writeLog("illegal tagname found: <$name>, expected: <" . $IFTMIN[$cnt][0] . ">");
      endif;
    endif;
    $IFTMIN[$cnt][3] .= "<$name" . "$att_str>\n";
  elseif ($level > 2):
    for ($i = 2; $i < $level; $i++)
      $IFTMIN[$cnt][3] .= "  ";
    $IFTMIN[$cnt][3] .= "<$name" . "$att_str>\n";
  endif;
}

/**
 * Quelle: http://reeg.junetz.de/DSP/node31.html
 *
 * @param  parser    Object    Parserobjekt
 * @param  name      string    Name des schließenden Elements
 */
function endElement($parser, $name) {
  global $level, $curtext, $curelem, $cdatabuf, $IFTMIN, $cnt, $em_msg_id, $ec_inv_no, $ep_ven_no, $track_id, $cnt, $ad_street, $ad_zipcode,  $ad_city, $ad_country,
    $tr_sortA, $tr_hsno, $tr_comp, $tr_person1, $tr_person, $tr_phone, $ec_weight, $ec_amount, $ec_type, $ec_type_real, $jb_id_line, $track_idA, $jb_idA, $hq_id, $cur_date, $mysql_db;
  
  if ($cdatabuf != ""):
    for ($i = 2; $i < $level; $i++)
      $IFTMIN[$cnt][3] .= "  ";
    $IFTMIN[$cnt][3] .= "  " . $cdatabuf . "\n";
    $cdatabuf = "";
  endif;
  if ($level > 1):
    for ($i = 2; $i < $level; $i++)
      $IFTMIN[$cnt][3] .= "  ";
    $IFTMIN[$cnt][3] .= "</$name>\n";
  endif;

  if ($curelem == "tred:document.message.number")
    $em_msg_id = $curtext;
  if ($curelem == "tred:movement.type" && $cnt == CONSIGNEE_TYPE):
    $ec_type = $curtext;
    if ($ec_type == "STBX_TIMED")
      $ec_type = "STBX_NEXT";
    $ec_type_real = $curtext;
  endif;
  if ($curelem == "tred:reference.number" && $cnt == CONSIGNEE_INVNO)
    $ec_inv_no = $curtext;
  if ($curelem == "tred:reference.number" && $cnt == CONSIGNEE_TRACK_ID)
    $track_id = $curtext;
  if ($curelem == "tred:reference.number" && $cnt == CONSIGNEE_PHONE)
    $tr_phone = $curtext;
  if ($curelem == "tred:reference.number" && $cnt == PACKAGE_VEN_NO)
    $ep_ven_no = $curtext;
  if ($curelem == "tred:name.and.address.line" && $cnt == CONSIGNEE_ADDRESS)
    $tr_comp = $curtext;
  if ($curelem == "tred:street.and.number.p.o.box" && $cnt == CONSIGNEE_ADDRESS):
    if ($tr_person1 == ""):
      $tr_person1 = $curtext;
    else:
      $tr_person = $tr_person1;
    endif;
    $ad_street_parts = explode(" ", str_replace(" /", "/", str_replace("/ ", "/", $curtext)));
// echo $curtext . "\n";
// echo $tr_person . "\n";
// print_r($ad_street_parts);
    // Besonderheit Amazon: Wiederholung der kompletten Straßenangabe in der Hausnummer
    if (count($ad_street_parts) > 1):
      if ($ad_street_parts[count($ad_street_parts) - 1] == $ad_street_parts[count($ad_street_parts) - 2]):
        $ad_street_parts[count($ad_street_parts) - 1] = "";
      endif;
    endif;
    $ad_street_parts = explode(" ", str_replace("  ", " ", str_replace(".", ". ", trim(implode(" ", $ad_street_parts)))));
// print_r($ad_street_parts);
    $ad_street = $ad_street_parts[0];
    $tr_hsno = "";
    if (count($ad_street_parts) > 1):            
      $tr_hsno = $ad_street_parts[1];
      if (count($ad_street_parts) > 2):
        if (strlen($ad_street_parts[count($ad_street_parts) - 1]) == 1):
          if (ord(strtoupper($ad_street_parts[count($ad_street_parts) - 1])) >= ord("A")
            && ord(strtoupper($ad_street_parts[count($ad_street_parts) - 1])) <= ord("Z")):
            $tr_hsno = $ad_street_parts[count($ad_street_parts) - 2] . " " . $ad_street_parts[count($ad_street_parts) - 1];
            for ($k = 1; $k < count($ad_street_parts) - 2; $k++)
              $ad_street .= " " . $ad_street_parts[$k];
          else:
            for ($k = 1; $k < count($ad_street_parts) - 1; $k++)
              $ad_street .= " " . $ad_street_parts[$k];
            $tr_hsno = $ad_street_parts[count($ad_street_parts) - 1];
          endif;
        else:
          for ($k = 1; $k < count($ad_street_parts) - 1; $k++)
            $ad_street .= " " . $ad_street_parts[$k];
          $tr_hsno = $ad_street_parts[count($ad_street_parts) - 1];
        endif;
      endif;
    endif;
  endif;
  if ($curelem == "tred:city.name" && $cnt == CONSIGNEE_ADDRESS)
    $ad_city = $curtext;
  if ($curelem == "tred:postcode.identification" && $cnt == CONSIGNEE_ADDRESS)
    $ad_zipcode = $curtext;
  if ($curelem == "tred:country.coded" && $cnt == CONSIGNEE_ADDRESS)
    $ad_country = $curtext;
  if ($curelem == "tred:measurement.value" && $cnt == CONSIGNEE_WEIGHT)
    $ec_weight = $curtext;
  if ($curelem == "tred:monetary.amount" && $cnt == CONSIGNEE_AMOUNT)
    $ec_amount = str_replace(",", ".", $curtext);

  if ($name == "trsd:reference" && $cnt == CONSIGNEE_END):
    if ($hq_id == 0)
      initImport($track_id);
    writeLog("importing track_id: trat_serialno = '$track_id'");
    writeToDB("edi_consignee", $fields = "ec_inv_no,em_msg_id,ec_track_id,ec_type,ec_weight,ec_amount",
      $values = "'" . $ec_inv_no . "','" . $em_msg_id . "','" . $track_id . "','" . $ec_type_real . "','" . $ec_weight . "','" . $ec_amount . "'");
    writeToDB("edi_status", $fields = "ec_track_id,es_msg_no,es_ic_ref,es_date,es_status",
      $values = "'" . $track_id . "','0','0','" . $cur_date . "','0'");
    // Tracking-ID für Websiten-tracking merken
    $track_idA[] = $track_id;
    // Station für end customer Auftrag, mit track_id in tr_remark
    $jb_id_tmp = $jb_idA[$hq_id][$ec_type];
    write_tour($ad_street, $ad_zipcode, $ad_city, $ad_country, $jb_id_tmp, $tr_sortA[$ec_type], $tr_hsno, $tr_comp, $tr_person, $tr_phone, $ec_type_real,
     '#CHECK:' . $track_id . '#\n#CHECKSCND:' . substr($track_id, -6, 4) . '#', "1");
    $tr_id = mysql_insert_id($mysql_db);
    // tourarticle für Abholung in Niederlassung
//    writeLog("writing article: jb_id = '$jb_id_tmp', tr_sort = '1', trat_serialno = '$track_id'");    
    exec_query("INSERT INTO phoenix.tourarticle (tr_id, jb_id, tr_sort, trat_serialno) VALUES (0, $jb_id_tmp, 1, '$track_id')");
    // tourarticle für end customer station
//    writeLog("writing article: jb_id = '$jb_id_tmp', tr_sort = '" . $tr_sortA[$ec_type] . "', trat_serialno = '$track_id'");    
    exec_query("INSERT INTO phoenix.tourarticle (tr_id, jb_id, tr_sort, trat_serialno) VALUES ($tr_id, $jb_id_tmp, " . $tr_sortA[$ec_type]++ . ", '$track_id')");
    // tourarticle für Linienauftrag Abholung
//    writeLog("writing article: jb_id = '" . $jb_id_line . "', tr_sort = '1', trat_serialno = '$track_id'");    
    exec_query("INSERT INTO phoenix.tourarticle (tr_id, jb_id, tr_sort, trat_serialno) VALUES (0, $jb_id_line, 1, '$track_id')");
    $trat_id = mysql_insert_id($mysql_db);
    // tourarticleprocess für Linienauftrag Abholung: event 101 (paperwork received)
    exec_query("INSERT INTO phoenix.tourarticleprocess (trat_id, tratp_type, tratp_state, tratp_remark, tratp_createtime) VALUES ($trat_id, '101', 1, '', '" . $cur_date . "')");
//    writeLog("writing event: trat_id = '$trat_id', tratp_type = '101', tratp_createtime = '" . $cur_date . "', tratp_remark = ''");    
    //  tourarticle für Linienauftrag Anlieferung
//    writeLog("writing article: jb_id = '" . $jb_id_line . "', tr_sort = '2', trat_serialno = '$track_id'");    
//    exec_query("INSERT INTO phoenix.tourarticle (jb_id, tr_sort, trat_serialno) VALUES ($jb_id_line, 2, '$track_id')");
//  writeToLogDB("55",$hq_id,$jbIdNew,$usr_id,$tour["f_jb_cr_id"],$tour["f_jb_cr_sid"],$csId, "Import Tourenplanung");
//    $ec_inv_no = "";
    $ec_weight = "";
    $ec_amount = "";
    $ec_type = "";
    $ec_type_real = "";
    $track_id = "";
    $ad_street = "";
    $ad_zipcode = "";
    $ad_city = "";
    $ad_country = "";
    $tr_hsno  = "";
    $tr_comp = "";
    $tr_person1 = "";
    $tr_person = "";
    $tr_phone = "";
  endif;

  if ($name == "trsd:reference" && $cnt == PACKAGE_END)
    writeToDB("edi_package", $fields = "ep_ven_no,ec_inv_no", $values = "'" . $ep_ven_no . "','" . $ec_inv_no . "'");

  $curtext = "";
  $level--;
  $curelem = "";
}

/**
 * Quelle: http://reeg.junetz.de/DSP/node31.html
 *
 * @param    parser    Object    Parserobjekt
 * @param    text      string    Der Text
 */
function cdata($parser, $text) {
  global $cdatabuf, $curtext, $curelem;

  $curtext .= $text;
//  if ($cdatabuf == ""):
//    $cdatabuf = "[$curelem]\n$text";
//  else:
    $cdatabuf .= "$text";
//  endif;
}

function defHandler($parser, $data)
{
//  echo "defHandler: '$data'\n";
}

function edi2xml($edifilename)
{	
  $path_parts = pathinfo($edifilename);
  $xmlfilename = $path_parts["dirname"] . "/" . str_replace("." . $path_parts["extension"], "", $path_parts["basename"]) . ".xml";
	
  $system_result = "";
  $cmd = "edi2xml $edifilename > $xmlfilename 2>&1";
  $ausgabe = system($cmd, $system_result);
  writeLog("creating xml from edi: '$cmd', result = '$ausgabe', system_result = '$system_result'");
  if ($system_result != 0) {
    writeLog("an error occured: \$system_result is different from '0', a mail will be sent to <admin@assecutor.de>");
    $mailObj = new htmlMimeMail();
    $mailObj->setFrom("support@assecutor.de");
    $mailObj->setSubject("error in calling edi2xml");
    $mailObj->setText(
      "'" . $cmd . "' returned a value different from '0': \$system_result = '$system_result'");
    $mailResult = $mailObj->send("admin@assecutor.de", 'smtp');
    return "error";
  }

  $srcFile = fopen($xmlfilename, "r");
  $contents = str_replace(chr(2), "??", fread($srcFile, filesize($xmlfilename)));
  fclose($srcFile);

//echo $contents; die();
  return $contents;
//  return xml2array($contents);
}

function write_tour($ad_street, $ad_zipcode, $ad_city, $ad_country, $jb_id, $tr_sort, $tr_hsno, $tr_comp, $tr_person, $tr_phone, $tr_comp2, $tr_remark, $tr_ware_from_to)
{
	global $zipcodes, $hq_id, $csc_id_externA;

	$tr_cs_freetext = "";
	$ad_zipcode = substr(trim($ad_zipcode), -5, 5);
	if (in_array($ad_zipcode, array_keys($zipcodes)) && $tr_sort > 1)
	  $tr_cs_freetext = $zipcodes[$ad_zipcode];
	if ($tr_comp2 == "STBX_SAME" && $tr_sort > 1 && !($hq_id == 8))
	  $tr_cs_freetext = $zipcodes["STBX_SAME"];

  $ad_id = insertAddress($ad_street, $ad_zipcode, $ad_city, $ad_country);
  exec_query("INSERT INTO phoenix.tour (jb_id, tr_sort, ad_id, tr_hsno, csc_id, tr_status, tr_comp, tr_comp2, tr_person, tr_phone, tr_remark, tr_ware_from_to, tr_mediationarea_id, tr_cs_freetext) VALUES (" .
    "$jb_id, $tr_sort, $ad_id, '$tr_hsno', " . $csc_id_externA[$hq_id] . ", 0, '" . my_str_check_edi($tr_comp) . "', '$tr_comp2', '" . my_str_check_edi($tr_person) . "', '" .
    my_str_check_edi($tr_phone) . "', '" . my_str_check_edi($tr_remark) . "', 0, 0, '$tr_cs_freetext')");
  writeLog("creating tourstop: jb_id = '$jb_id', tr_sort = '$tr_sort'");
}

function writeToDB($table, $fields, $values)
{
	global $IFTMIN;
	
  for ($i = 0; $i < count($IFTMIN); $i++):
    if ($IFTMIN[$i][1] == $table):
      $IFTMIN[$i][3] = $IFTMIN[$i][3];
      if ($fields != "") $fields .= ",";
      if ($values != "") $values .= ",";
      $fields .= $IFTMIN[$i][2];
      if ($IFTMIN[$i][0] == "trsd:name.and.address"):
        $values .= "'" . insertNAD(my_str_check_edi($IFTMIN[$i][3])) . "'";
      else:
        $values .= "'" . my_str_check_edi($IFTMIN[$i][3]) . "'";
      endif;
      $IFTMIN[$i][3] = "";
    endif;
  endfor;
  exec_query("INSERT INTO $table ($fields) VALUES ($values)");
}

function insertNAD($nad)
{
	global $mysql_db;

  $sqlStmt = "SELECT en_id FROM edi_nad WHERE en_nad = '$nad'";
  $res = mysql_query($sqlStmt, $mysql_db) or die ($sqlStmt . ": " . mysql_error($mysql_db));

  if ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
    $en_id = $row["en_id"];
  else:
    exec_query("INSERT INTO edi_nad (en_nad) VALUES ('$nad')");
    $en_id = mysql_insert_id($mysql_db);
  endif;
  mysql_free_result($res);
  
  return $en_id;
}

function insertAddress($ad_street, $ad_zipcode, $ad_city, $ad_country)
{
	global $mysql_db;

	$ad_street = my_str_check_edi($ad_street);
	$ad_zipcode = my_str_check_edi($ad_zipcode);
	$ad_city = my_str_check_edi($ad_city);
	$ad_country = my_str_check_edi($ad_country);
	
  $sqlStmt = "SELECT ad_id FROM phoenix.address WHERE ad_street = '$ad_street' " .
    "AND ad_zipcode = '$ad_zipcode' AND ad_city = '$ad_city' AND ad_country = '$ad_country'";
  $res = mysql_query($sqlStmt, $mysql_db) or die ($sqlStmt . ": " . mysql_error($mysql_db));

  if ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
    $ad_id = $row["ad_id"];
  else:
    exec_query("INSERT INTO phoenix.address (ad_street, ad_zipcode, ad_city, ad_country) VALUES ('$ad_street', '$ad_zipcode', '$ad_city', '$ad_country')");
//    $ad_id = mysql_query("SELECT LAST_INSERT_ID()");
    $ad_id = mysql_insert_id($mysql_db);
  endif;
  mysql_free_result($res);
  
  return $ad_id;
}

?>