<?php

// Alte PLZ-Zuordnung für Stuttgart
//S1011;S1091;S1055;S1093
//70563,70565,70567,70569,70597,70599,70619,70629,70771,73760;70372,70374,70376,70378,70435,70437,70439,70469,70499,70825,70839;70173,70174,70176,70178,70180,70182,70184,70186,70188,70190,70191,70192,70193,70195,70197,70199,70327,70329;71032,71034,71063,71065,71067,71069,71106,71229,71254,71272,71277,71282,71287,71701,71706,71735
// Alte PLZ-Zuordnung für Essen
//E1120;E1121;E1122;E1123
//40472,40489,40878,40880,40882,40883,40885;40210,40211,40212,40213,40215,40217,40219,40468,40474,40476,40477,40479,40545,40547,40549;40227,40231,40233,40235,40237,40239,40470,40625,40629,40627;40221,40223,40225,40229,40589,40591,40593,40595,40597,40599

include_once("../include/email/htmlMimeMail.php");
include_once("../locating/xServer.inc.php");
include_once("../include/glob_defs.inc.php");

if (!isset($usr_id))
  $usr_id = 0;
if (!isset($hq_id))
  $hq_id = 0;

// Testumgebung Leipzig
if ($usr_id == 800001 || $usr_id == 834522): // admin_l oder l_zanger
  $hq_id = 99;
endif;

// Testumgebung Essen
if ($usr_id == 700001 || $usr_id == 842586): // admin_e oder staboe_test
  $hq_id = 98;
endif;

$mysql_db = mysql_connect($dbhost, $dblogin, $dbpassword) or die (mysql_error($mysql_db));
mysql_select_db("phoenix_log", $mysql_db) or die (mysql_error($mysql_db));
mysql_query('SET NAMES latin1', $mysql_db) or die ('SET NAMES latin1' . ": " . mysql_error($mysql_db));

$usr_string = "";
if (isset($usr_id) && $usr_id != 0):
  $sql_query = "SELECT usr_account, usr_name, usr_firstname, usr_phone FROM phoenix.user WHERE usr_id = $usr_id";
  $res = mysql_query($sql_query, $mysql_db) or die ($sql_query . ": " . mysql_error($mysql_db));
  $row = mysql_fetch_row($res);
  $usr_string = ", usr_id = $usr_id ('" . $row[0] . "', '" . $row[1] . "', '" . $row[2] . "', '" . $row[3] . "')";
  mysql_free_result($res);
endif;

writeLog("dbhost = '$dbhost', hq_id = '$hq_id'" . $usr_string);

$anxe_interchange_control_reference = 0;
$anxe_message_reference_number = 0;

$jb_id_tempA = array();
$csc_id_externA = array();
$ad_id_hqA = array();
$csc_id_payerA = array ();
$csc_id_sql = array();
$jb_idA = array();
$jb_id_sql = array();
$mailaddr = array();
$tr_sort_maxA = array();
$zipcodes = array("STBX_SAME" => "");

$sql_query = "SELECT hq_id, par_key, par_value, par_text FROM phoenix.parameter WHERE hq_id != '' AND par_key IN " .
  "('CARTAGE_JB_ID_TEMP', 'CSC_ID_PAYER_EXTERN', 'CARTAGE_AD_HQ_ID', 'CARTAGE_CSC_ID_PAYER', 'CARTAGE_JB_ID', 'CARTAGE_MAIL_ADDR', 'CARTAGE_ZIPCODE_RELATION')";
$res = mysql_query($sql_query, $mysql_db) or die ($sql_query . ": " . mysql_error($mysql_db));
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
  $tmpA[$row["hq_id"]][$row["par_key"]] = $row["par_value"];
  $tmpAtext[$row["hq_id"]][$row["par_key"]] = $row["par_text"];
endwhile;
mysql_free_result($res);
foreach ($tmpA AS $hq_id_tmp => $key_vals) {
	if ($key_vals["CARTAGE_JB_ID_TEMP"] != ""):
    $tr_sort_maxA[$hq_id_tmp] = 499;
    $jb_id_tempA[$hq_id_tmp] = $key_vals["CARTAGE_JB_ID_TEMP"];
    $csc_id_externA[$hq_id_tmp] = $key_vals["CSC_ID_PAYER_EXTERN"];
    $ad_id_hqA[$hq_id_tmp] = $key_vals["CARTAGE_AD_HQ_ID"];
    $par_valueA = explode(",", $key_vals["CARTAGE_CSC_ID_PAYER"]);
    $csc_id_payerA[$par_valueA[0]] = 'STBX_SAME';
    $csc_id_payerA[$par_valueA[1]] = 'STBX_TIMED';
    $csc_id_payerA[$par_valueA[2]] = 'STBX_NEXT';
    $csc_id_sql[$hq_id_tmp] = "(" . $par_valueA[0] . "," . $par_valueA[1] . "," . $par_valueA[2] . ")";
    $par_valueA = explode(",", $key_vals["CARTAGE_JB_ID"]);
    $jb_idA[$hq_id_tmp]["STBX_SAME"] = $par_valueA[0];
    $jb_idA[$hq_id_tmp]["STBX_TIMED"] = $par_valueA[1];
    $jb_idA[$hq_id_tmp]["STBX_NEXT"] = $par_valueA[2];
    $jb_id_sql[$hq_id_tmp] = "(" . $par_valueA[0] . "," . $par_valueA[1] . "," . $par_valueA[2] . ")";
    $par_valueA = explode(",", $key_vals["CARTAGE_MAIL_ADDR"]);
    $mailaddr[$hq_id_tmp]["from"] = $par_valueA[0];
    $mailaddr[$hq_id_tmp]["bcc"] = $par_valueA[1];
    $mailaddr[$hq_id_tmp]["sendto"] = array($par_valueA[2]);
    $par_valueA = explode(";", $key_vals["CARTAGE_ZIPCODE_RELATION"]);
    $par_textA = explode(";", $tmpAtext[$hq_id_tmp]["CARTAGE_ZIPCODE_RELATION"]);
    for ($i = 0; $i < count($par_textA); $i++):
      $par_textAA = explode(",", $par_textA[$i]);
      foreach ($par_textAA as $val) {
      	if (trim($val) != "")
          $zipcodes[$val . ""] = $par_valueA[$i];
      }
    endfor;
  endif;
}

//echo "jb_id_tempA:\n";
//print_r($jb_id_tempA);
//echo "csc_id_externA:\n";
//print_r($csc_id_externA);
//echo "ad_id_hqA:\n";
//print_r($ad_id_hqA);
//echo "csc_id_payerA:\n";
//print_r($csc_id_payerA);
//echo "csc_id_sql:\n";
//print_r($csc_id_sql);
//echo "jb_idA:\n";
//print_r($jb_idA);
//echo "jb_id_sql:\n";
//print_r($jb_id_sql);
//echo "mailaddr:\n";
//print_r($mailaddr);
//echo "tr_sort_maxA:\n";
//print_r($tr_sort_maxA);
//echo "zipcodes:\n";
//print_r($zipcodes);

//$csc_id_lineA = array(
//  11 => 845034,
//   4 => 848216,
//   8 => 845034,
//   7 => 845034
//);

$hq_prefixes = array(
  11 => "ST",
//  11 => "STS",
   4 => "STH",
   8 => "STL",
   7 => "STE",
  98 => "STE",
  99 => "STL"
);

$hq_prefixes_add = array(
  11 => array("ST04", "dummy2"),
   4 => array("STH04", "dummy2"),
   8 => array("dummy1", "dummy2"),
   7 => array("STE04", "STE05"),
  98 => array("dummy1", "dummy2"),
  99 => array("dummy1", "dummy2")
);

$end_start_zipcodes = array(
  "S1090" => array(array()                            , array()),
  "S1091" => array(array(9.19216705663, 48.8405277748), array()), // 70437
//  "S1092" => array(array(9.21061506123, 48.7854294095), array()), // 70188
  "S1092" => array(array(9.15915706133, 48.8306528117), array()), // 70435
//  "S1093" => array(array(9.19216705663, 48.8405277748), array()), // 70437
  "S1093" => array(array(9.1852, 48.8598), array()), // Kornwestheim 
  "S1094" => array(array(9.10877331509, 48.8078819236), array()), // 70499
  "S1011" => array(array(9.006580     , 48.786411)    , array(9.216667, 48.483333)), // Hertichstr. 10 / Mittelpunkt Reutlingen
  "S1767" => array(array()                            , array()),
  "E1120" => array(array(7.000545     , 51.495869)    , array()), // Teilungsweg 28
  "E1121" => array(array(7.000545     , 51.495869)    , array()),
  "E1122" => array(array(7.000545     , 51.495869)    , array()),
  "E1123" => array(array(7.000545     , 51.495869)    , array())
);

function xml2edi($xmlfilename)
{	
  $path_parts = pathinfo($xmlfilename);
  $edifilename = $path_parts["dirname"] . "/" . str_replace("." . $path_parts["extension"], "", $path_parts["basename"]) . ".edi";
	
  $system_result = "";
  $cmd = "xml2edi $xmlfilename > $edifilename 2>&1";
  $ausgabe = system($cmd, $system_result);
  writeLog("creating edi from xml: '$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 xml2edi");
    $mailObj->setText(
      "'" . $cmd . "' returned a value different from '0': \$system_result = '$system_result'");
    $mailResult = $mailObj->send("admin@assecutor.de", 'smtp');
  }
  return $system_result;
}

function my_str_check_mysql($aStr)
{
  $aStr = str_replace('\'', '\\\'', $aStr);
  return $aStr;
}

function my_str_check_edi($aStr)
{
  $aStr = str_replace('\'', '\\\'', $aStr);
  $aStr = str_replace("\"", '\\"', $aStr);
  $aStr = str_replace("\n", '\\n', $aStr);
  $aStr = str_replace("\r", '\\r', $aStr);
  return $aStr;
}

function exec_query($sqlquery, $do_log = 0) {
  global $mysql_db;

  if ($do_log == 1)
    writeLog($sqlquery);
  mysql_query($sqlquery, $mysql_db) or die ($sqlquery . ": " . mysql_error($mysql_db));	
}

function get_first_row($sqlquery, $do_log = 0) {
  global $mysql_db;

  if ($do_log == 1)
    writeLog($sqlquery);
  $res = mysql_query($sqlquery, $mysql_db) or die ($sqlquery . ": " . mysql_error($mysql_db));
  $row = mysql_fetch_row($res);
  mysql_free_result($res);

  return $row;
}

function writeLog($log_text)
{
  global $hq_id;
  
  if ($hq_id == "" || $hq_id == 0):
    $hq_id_str = "";
  else:
    $hq_id_str = $hq_id . "_";
  endif;
  $today = getdate();
  $fileHandle = @fopen("../log/amazon_" . $hq_id_str . $today['year'] . sprintf("%02d", $today['mon']) . ".log", 'a');
  @fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] [" . LOG_NAME . "] " . $log_text .  "\n");
  @fclose($fileHandle);
  return;
}

function sort_zipcode($jb_id_sort, $hq_id)
{
  global $jb_id_tempA, $mysql_db;

  $trat_idA2 = array();
  $csv_contents = array();

  if ($jb_id_sort == 0)
    return;

  writeLog("sorting by zipcode: jb_id = '$jb_id_sort'"); 
  // trat_ids (für Abholung und Anlieferung) des zu sortierenden Jobs finden
  $sql_query = "SELECT DISTINCT tr.jb_id, tr.tr_sort, ta.trat_id, ta.trat_serialno, ad.ad_country, ad.ad_zipcode, tr.tr_comp, tr.tr_person, ad.ad_city, ad.ad_street, tr.tr_hsno, tr.tr_comp2" .
    "  FROM phoenix.tourarticle AS ta, phoenix.tour AS tr, phoenix.address AS ad" .
    "  WHERE tr.jb_id = $jb_id_sort AND tr.jb_id = ta.jb_id AND tr.tr_sort = ta.tr_sort AND tr.ad_id = ad.ad_id AND tr.tr_sort > 1" .
    "  ORDER BY tr.tr_cs_freetext, ad.ad_zipcode, ad.ad_street, tr.tr_hsno";
// echo $sql_query . "\n";

  $res = mysql_query($sql_query, $mysql_db) or die ($sql_query . ": " . mysql_error($mysql_db));
  while ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
    $trat_idA2[$row["trat_serialno"]] = array($row["trat_id"], $row["jb_id"], $row["tr_sort"], $row["ad_zipcode"]);
    $tr_ware_from_to = XScheckAddress(my_str_check_mysql($row["ad_country"]), my_str_check_mysql($row["ad_zipcode"]), my_str_check_mysql($row["ad_city"]), my_str_check_mysql($row["ad_street"]), my_str_check_mysql($row["tr_hsno"])) ? 1 : 0;  
    if ($tr_ware_from_to != 1)
	    writeLog("address not found: " . $row["ad_country"] . ", " . $row["ad_zipcode"] . ", " . $row["ad_city"] . ", " . $row["ad_street"] . ", " . $row["tr_hsno"]);
    $tr_cs_freetext_clause = "";
//	  if ($row["tr_comp2"] == "STBX_TIMED")
//	    $tr_cs_freetext_clause = ", tr_cs_freetext = ''";
//writeLog("UPDATE tour SET tr_ware_from_to = $tr_ware_from_to" . " WHERE jb_id = " . $row["jb_id"] . " AND tr_sort = " . $row["tr_sort"]);
    exec_query("UPDATE phoenix.tour SET tr_ware_from_to = $tr_ware_from_to" . $tr_cs_freetext_clause . " WHERE jb_id = " . $row["jb_id"] . " AND tr_sort = " . $row["tr_sort"]);
  endwhile;
  mysql_free_result($res);

  $tr_sort = 1;
  foreach ($trat_idA2 AS $trat_serialno => $vals) {
//    writeLog("sorting by zipcode: " . $trat_serialno . ", " . $vals[3] . ", jb_id/tr_sort old: " . $vals[1] . ", " . $vals[2] . " -> new: " . $jb_id_tempA[$hq_id] . ", " . $tr_sort);
    exec_query("UPDATE phoenix.tour SET jb_id = " . $jb_id_tempA[$hq_id] . ", tr_sort = " . $tr_sort++ . " WHERE jb_id = " . $vals[1] . " AND tr_sort = " . $vals[2]);
  }

  $i = 1;
  $tr_sort = 2;
  foreach ($trat_idA2 AS $trat_serialno => $vals) {
//    writeLog("sorting by zipcode: " . $trat_serialno . ", " . $vals[3] . ", jb_id/tr_sort old: " . $jb_id_tempA[$hq_id] . ", " . $i . " -> new: " . $jb_id_sort . ", " . $tr_sort);
    exec_query("UPDATE phoenix.tour SET jb_id = " . $jb_id_sort . ", tr_sort = " . $tr_sort . " WHERE jb_id = " . $jb_id_tempA[$hq_id] . " AND tr_sort = " . $i++);
    exec_query("UPDATE phoenix.tourarticle SET jb_id = " . $jb_id_sort . ", tr_sort = " . $tr_sort++ . " WHERE trat_id = " . $vals[0]);
  }
}

function send_csv_mail($jb_id_send) {
	global $csc_id_payerA, $jb_id_sql, $mailaddr, $jb_idA, $mysql_db;

	$csv_contents1 = "";
	$csv_contents2 = "";
  $row = get_first_row("SELECT csc_id_payer, jb_ordertime, cr_sid, hq_id FROM phoenix.job WHERE jb_id = $jb_id_send");
  $ec_type = $csc_id_payerA[$row[0]];
  $jb_ordertime = $row[1];
  $cr_sid = $row[2];
  $hq_id = $row[3];

  $jb_id_send_list = "('$jb_id_send')";
  $jb_id_mail = " - $jb_id_send";
  $no_scnd_sql = "";
  if ($jb_id_send == $jb_idA[$hq_id]['STBX_NEXT']):
    $jb_id_send_list = $jb_id_sql[$hq_id];
    $cr_sid = "Amazon";
    $ec_type = "alle Pakete";
    $jb_ordertime = date("Y-m-d H:i:s", time());
    $jb_id_mail = "";
    $no_scnd_sql = " AND LEFT (tr_comp, 1) != '*'";
	endif;
	
  $sql_query = "SELECT tr.jb_id, tr.tr_sort, tr_comp, tr_person, tr_comp2, tr_hsno, tr_cs_freetext, trat_serialno, ad_zipcode, ad_city, ad_street, ec_weight, ec_dim" .
    "  FROM phoenix.tour AS tr, phoenix.tourarticle AS ta, phoenix.address AS ad, phoenix_log.edi_consignee AS ec" .
    "  WHERE tr.jb_id IN $jb_id_send_list AND tr.jb_id = ta.jb_id AND tr.tr_sort = ta.tr_sort AND tr.tr_sort > 1 AND tr.ad_id = ad.ad_id AND trat_serialno = ec_track_id" . $no_scnd_sql .
    "  ORDER BY jb_id, tr_sort";
  $res = mysql_query($sql_query, $mysql_db) or die ($sql_query . ": " . mysql_error($mysql_db));
  while ($row = mysql_fetch_array($res, MYSQL_ASSOC)):  
    if (substr($row["ec_weight"], 0, 1) == "."):
      $row["ec_weight"] = "0" . $row["ec_weight"];
    endif;
    $ec_weight = str_replace(".", ",", $row["ec_weight"]);
    $p = xml_parser_create();
    xml_parse_into_struct($p, $row["ec_dim"], $vals, $index);
    xml_parser_free($p);
    $ec_dim = str_replace(".", ",", str_replace(" ", "", str_replace("\n", "", $vals[8]["value"] . "x" . $vals[11]["value"] . "x" . $vals[14]["value"])));
    $ec_dim1 = str_replace(".", ",", sprintf("%01.2f", round(($vals[8]["value"] * $vals[11]["value"] * $vals[14]["value"]) / 1000, 2)));
    $csv_contents1 .= $row["tr_sort"] . "," . $row["trat_serialno"] . "," . str_replace(",", ";", $row["tr_comp"]) . "," . str_replace(",", ";", $row["tr_person"]) . "," . $row["ad_zipcode"] . "," . $row["ad_city"] . "," . str_replace(",", ";", $row["ad_street"]) . " " . str_replace(",", ";", $row["tr_hsno"]) . "," . str_replace(",", ".", $ec_weight) . "," . str_replace(",", ".", $ec_dim1) . "," . str_replace(",", ".", $ec_dim) . "\n";
    $csv_contents2 .= $row["tr_sort"] . ";" . $row["trat_serialno"] . ";" . str_replace(";", ",", $row["tr_comp"]) . ";" . str_replace(";", ",", $row["tr_person"]) . ";" . $row["ad_zipcode"] . ";" . $row["ad_city"] . ";" . str_replace(";", ",", $row["ad_street"]) . " " . str_replace(";", ",", $row["tr_hsno"]) . ";" . $ec_weight . ";" . $ec_dim1 . ";" . $ec_dim . "\n";
    if ($jb_id_send != $jb_idA[$hq_id]['STBX_NEXT'])
      $cr_sid = trim($row["tr_cs_freetext"]);
  endwhile;

  $csv_file_name = $cr_sid . "_" . $ec_type . "_" . substr($jb_ordertime, 0, 10) . "_" . $jb_id_send . ".csv";
  $fileHandle = @fopen("../temp/edifact/" . "(1)_" . $csv_file_name, 'w');
  @fwrite($fileHandle, $csv_contents1);
  @fclose($fileHandle);
  $fileHandle = @fopen("../temp/edifact/" . "(2)_" . $csv_file_name, 'w');
  @fwrite($fileHandle, $csv_contents2);
  @fclose($fileHandle);
  $mailObj = new htmlMimeMail();
  $mailObj->setFrom($mailaddr[$hq_id]["from"]);
  if ($jb_id_send == $jb_idA[$hq_id]['STBX_NEXT']):
//    $mailObj->setCc("leier@stadtbote.de");
  endif;
  $mailObj->setBcc($mailaddr[$hq_id]["bcc"]);
  $mailObj->setSubject("$cr_sid - $ec_type - " . substr($jb_ordertime, 0, 10) . $jb_id_mail);
  $mailObj->setText(
    "Fahrer:  " . $cr_sid . "\n" .
    "Typ:     " . $ec_type . "\n" .
    "Eingang: " . substr($jb_ordertime, 0, 10) . "\n" .
    "Auftrag: " . $jb_id_send . "\n");
  $mailObj->addAttachment($mailObj->getFile("../temp/edifact/" . "(1)_" . $csv_file_name), "(1)_" . $csv_file_name);   
  $mailObj->addAttachment($mailObj->getFile("../temp/edifact/" . "(2)_" . $csv_file_name), "(2)_" . $csv_file_name);   
  $mailResult = $mailObj->send($mailaddr[$hq_id]["sendto"], 'smtp');
  writeLog("result of sending mail for jb_id = '$jb_id_send': '" . $mailResult . "'");

  mysql_free_result($res);
}

function get_price($sum) {
	
  $price_ranges = array(
       0 =>  0.00,
       3 => 15.00,
       9 =>  8.50,
      49 =>  6.75,
      99 =>  5.90,
     149 =>  4.50,
     199 =>  3.90,
     399 =>  3.25,
   99999 =>  2.85
  );
	
  foreach ($price_ranges AS $cnt => $price) {
  	if ($sum <= $cnt):
  	  return $price;
  	endif;
  }  
}

function mk_interchange_vars()
{
	global $anxe_interchange_control_reference, $anxe_message_reference_number;

	// IDs für Interchange-header und Message-Header generieren
	$row = get_first_row("SELECT MAX(es_msg_no), MAX(es_ic_ref) FROM edi_status");
  $anxe_interchange_control_reference = $row[1] + 1;
  $anxe_message_reference_number = $row[0] + 1;

  $row = get_first_row("SELECT MAX(ei_msg_no), MAX(ei_ic_ref) FROM edi_invoice");
  if ($row[1] > $anxe_interchange_control_reference - 1)
    $anxe_interchange_control_reference = $row[1] + 1;
  if ($row[0] > $anxe_message_reference_number - 1)
    $anxe_message_reference_number = $row[0] + 1;
}

function mk_interchange_header($anxe_date, $anxe_time)
{
	global $anxe_interchange_control_reference;

  return
    "<?xml version=\"1.0\"?>" .
    "<edifact:message" .
    "  xmlns:edifact='http://www.xml-edifact.org/LIB/xml-edifact-03/edifact.rdf'" .
    "  xmlns:trsd='http://www.xml-edifact.org/LIB/xml-edifact-03/trsd.rdf'" .
    "  xmlns:trcd='http://www.xml-edifact.org/LIB/xml-edifact-03/trcd.rdf'" .
    "  xmlns:tred='http://www.xml-edifact.org/LIB/xml-edifact-03/tred.rdf'" .
    "  xmlns:uncl='http://www.xml-edifact.org/LIB/xml-edifact-03/uncl.rdf'" .
    "  xmlns:anxs='http://www.xml-edifact.org/LIB/xml-edifact-03/anxs.rdf'" .
    "  xmlns:anxc='http://www.xml-edifact.org/LIB/xml-edifact-03/anxc.rdf'" .
    "  xmlns:anxe='http://www.xml-edifact.org/LIB/xml-edifact-03/anxe.rdf'" .
    "  xmlns:unsl='http://www.xml-edifact.org/LIB/xml-edifact-03/unsl.rdf'" .
    "  xmlns:unknown='http://www.xml-edifact.org/LIB/xml-edifact-03/unknown.rdf'>" .
    "  <anxs:interchange.header>" .
    "    <anxc:syntax.identifier>" .
    "      <anxe:syntax.identifier unsl:code=\"0001:UNOA\">UN/ECE level A</anxe:syntax.identifier>" .
    "      <anxe:syntax.version.number>1</anxe:syntax.version.number>" .
    "    </anxc:syntax.identifier>" .
    "    <anxc:interchange.sender>" .
    "      <anxe:sender.identification>" . "STBX" . "</anxe:sender.identification>" .
    "      <anxe:recipients.identification.qualifer unknown:code=\"0007:ZZ\">" . "ZZ" . "</anxe:recipients.identification.qualifer>" .
    "   </anxc:interchange.sender>" .
    "    <anxc:interchange.recipient>" .
    "      <anxe:recipient.identification>" . "5450534000000" . "</anxe:recipient.identification>" .
    "      <anxe:recipients.identification.qualifer unsl:code=\"0007:14\">" . "EAN (European Article Numbering Association)" . "</anxe:recipients.identification.qualifer>" .
    "    </anxc:interchange.recipient>" .
    "    <anxc:date.time.of.preparation>" .
    "      <anxe:date>" . $anxe_date . "</anxe:date>" .
    "      <anxe:time>" . $anxe_time . "</anxe:time>" .
    "    </anxc:date.time.of.preparation>" .
    "    <anxe:interchange.control.reference>" . $anxe_interchange_control_reference . "</anxe:interchange.control.reference>" .
    "  </anxs:interchange.header>";
}

function mk_interchange_trailer($anxe_interchange_control_count)
{
  global $anxe_interchange_control_reference;

  return
    "  <anxs:interchange.trailer>" .
    "    <anxe:interchange.control.count>" . $anxe_interchange_control_count . "</anxe:interchange.control.count>" .
    "    <anxe:interchange.control.reference>" . $anxe_interchange_control_reference . "</anxe:interchange.control.reference>" .
    "  </anxs:interchange.trailer>" .
    "</edifact:message>";
}

function mk_interchange($anxe_interchange_control_count, $message, $prefix)
{
	global $anxe_interchange_control_reference, $argv;
	
//  $edi_file = "IFTSTA_" . $anxe_interchange_control_reference;
  $edi_file = "STBX_" . $anxe_interchange_control_reference . "_" . $prefix;
  $fileHandle = @fopen("../temp/edifact/" . $edi_file . ".xml", 'w');
  fwrite($fileHandle, utf8_encode(mk_interchange_header(date("dmy"), date("Hi")) . $message . mk_interchange_trailer($anxe_interchange_control_count)));
  fclose($fileHandle);

  if (xml2edi("../temp/edifact/" . $edi_file . ".xml") != 0) {
    writeLog("an eror occured in creating ../temp/edifact/" . $edi_file . ".xml, upload to ftp-server is stopped");
	  return;
  };

	if ($prefix == "INVOIC")
	  return;

//	echo $sql_query . "\n";
 
  $edi_files = array($edi_file . ".edi");
  $action = "up";
  include_once("../tools/edi_ftp.inc.php");

}

?>