<?php
//die();
define("LOG_NAME", "edi_invoic");
include_once("../tools/edi.inc.php");

//define("VAT", 0);
define("VAT", 0.19); // (ab 01.05.2015)

$hq_settings = array(
  array(
    "hq_id"      => 11,
    "prefix"     => "STHH1",
    "track_id"   => "'ST01','ST02','ST03'",
//    "Linehaul"   => "STHH932446",
    "STBX_SAME"  => "STHH932444",
    "STBX_TIMED" => "STHH932445"),
  array(
    "hq_id"      => 11,
    "prefix"     => "STHH1",
    "track_id"   => "'ST04'",
    "STBX_SAME"  => "STHH933200",
    "STBX_TIMED" => ""),
   array(
    "hq_id"      => 4,
    "prefix"     => "STH1",
    "track_id"   => "'STH01','STH02','STH03'",
//    "Linehaul"   => "STH912002",
    "STBX_SAME"  => "STH912003",
    "STBX_TIMED" => "STH912004"),
  array(
    "hq_id"      => 4,
    "prefix"     => "STH1",
    "track_id"   => "'STH04'",
    "STBX_SAME"  => "STH912132",
    "STBX_TIMED" => ""),
   array(
    "hq_id"      => 8,
    "prefix"     => "STL1",
    "track_id"   => "'STL01','STL02','STL03'",
//    "Linehaul"   => "STL914775",
//    "STBX_SAME"  => "STL914776",
    "STBX_SAME"  => "STL915137", // (ab 01.05.2015)
    "STBX_TIMED" => "STL914777"),
   array(
    "hq_id"      => 7,
    "prefix"     => "STE1",
    "track_id"   => "'STE01','STE02','STE03'",
//    "Linehaul"   => "STE902001",
    "STBX_SAME"  => "STE902002",
    "STBX_TIMED" => "STE902003"),
   array(
    "hq_id"      => 7,
    "prefix"     => "STE1",
    "track_id"   => "'STE04'",
    "STBX_SAME"  => "STE902102",
    "STBX_TIMED" => ""),
   array(
    "hq_id"      => 7,
    "prefix"     => "STE1",
    "track_id"   => "'STE05'",
    "STBX_SAME"  => "STE902103",
    "STBX_TIMED" => ""),
);

$invoicing_parties = array(
  11 => array("Große Bahnstraße 11-25", "HAMBURG", "22525"),
   4 => array("Ikarusallee 15", "HANNOVER", "30179"),
   8 => array("Zschortauer Straße 69-71", "LEIPZIG", "04129"),
   7 => array("Teilungsweg 28", "ESSEN", "45329")
);

$invoicing_tokens = array(
  11 => "S",
   4 => "H",
   8 => "L",
   7 => "E"
);

$inv_date_from_stat_sql = "";
if (date("d") < 15):
  $inv_date = date("Ymd", mktime(0, 0, 0, date("m"), 0, date("Y")));
  $inv_date_from_sql = date("Y-m-d", mktime(0, 0, 0, date("m") - 1, 16, date("Y"))) . " 00:00:00";
  $inv_date_to_sql = date("Y-m-d", mktime(0, 0, 0, date("m"), 0, date("Y"))) . " 23:59:59";
  $inv_date_from_stat_sql = date("Y-m-d", mktime(0, 0, 0, date("m") - 1, 1, date("Y"))) . " 00:00:00";
  $mail_text = 
    "Hallo Herr Karstens,\n" .
    "\n" .
    "im Anhang die Abrechnungsdaten zum Monatsende inkl. der Monatsgesamtübersicht.\n" .
    "\n" .
    "Freundliche Grüße,\n" .
    "Carsten Annacker\n";
  $mail_subject = "Abrechnung Amazon " . date("d.m.Y", mktime(0, 0, 0, date("m"), 0, date("Y")));
else:
  $inv_date = date("Ymd", mktime(0, 0, 0, date("m"), 15, date("Y")));
  $inv_date_from_sql = date("Y-m-d", mktime(0, 0, 0, date("m"), 1, date("Y"))) . " 00:00:00";
  $inv_date_to_sql = date("Y-m-d", mktime(0, 0, 0, date("m"), 15, date("Y"))) . " 23:59:59";
  $mail_text = 
    "Hallo Herr Karstens,\n" .
    "\n" .
    "im Anhang die Abrechnungsdaten zum 15. des Monats.\n" .
    "\n" .
    "Freundliche Grüße,\n" .
    "Carsten Annacker\n";
  $mail_subject = "Abrechnung Amazon " . date("d.m.Y", mktime(0, 0, 0, date("m"), 15, date("Y")));
endif;

//$inv_date = "20150615";
//$inv_date_from_sql = "2015-02-01 00:00:00";
//$inv_date_to_sql = "2015-02-15 23:59:59";
//echo $inv_date . "\n";
//echo $inv_date_from_sql . "\n";
//echo $inv_date_to_sql . "\n";
//die();

$mailObj = new htmlMimeMail();
$mailObj->setFrom("support@assecutor.de");
$mailObj->setSubject($mail_subject);
$mailObj->setText($mail_text);

if ($argv[2] == "prices"):
  foreach (array(11, 4, 8, 7) AS $hq_id)
    get_prices();
endif;

foreach ($hq_settings AS $cs_eidA) {
  $hq_id = $cs_eidA["hq_id"];
  $pre_len = 5;
  if ($hq_id == 11)
    $pre_len = 4;
  $cs_eid["STBX_SAME"] = $cs_eidA["STBX_SAME"];
  $inv_no["STBX_SAME"] = 0;
  $line_items["STBX_SAME"] = "";
  $line_item_no["STBX_SAME"] = 1;
  $sum["STBX_SAME"] = 0;
  $message["STBX_SAME"] = "";
  $track_ids["STBX_SAME"] = "";
  $no_of_segs["STBX_SAME"] = 21;
  $csv_file["STBX_SAME"] = "";
  $csv_stat_file["STBX_SAME"] = "";
  $cs_eid["STBX_TIMED"] =  $cs_eidA["STBX_TIMED"];
  $inv_no["STBX_TIMED"] = 0;
  $line_items["STBX_TIMED"] = "";
  $line_item_no["STBX_TIMED"] = 1;
  $sum["STBX_TIMED"] = 0;
  $message["STBX_TIMES"] = "";
  $track_ids["STBX_TIMED"] = "";
  $no_of_segs["STBX_TIMED"] = 21;
  $csv_file["STBX_TIMED"] = "";
  $csv_stat_file["STBX_TIMED"] = "";
  $sum_stat = array();

  $msg_date = date("Ymd");
  $cur_inv_no = "10000001";
  // Rechnungsnummer 
  $sql_query = "SELECT MAX(RIGHT(ei_inv_no, 8)) FROM edi_invoice WHERE LEFT(ei_inv_no, " . strlen($cs_eidA["prefix"]) . ") = '" . $cs_eidA["prefix"] . "'";
  $res = mysql_query($sql_query) or die ($sql_query . ": " . mysql_error());
  if ($row = mysql_fetch_row($res)):
    if ($row[0] != NULL):
      $cur_inv_no = $row[0] + 1;
      mysql_free_result($res);
    endif;
  endif;
  
  //$sql_query = "SELECT es.ec_track_id, ec.ec_inv_no, ec.em_msg_id, ec.ec_type, ec.ec_amount, LEFT(es.es_date, 10) AS es_es_date, ec.ec_nad, em.em_nad1, em.em_nad2" .
  //  " FROM edi_status AS es, edi_consignee AS ec, edi_message AS em " .
  //  " WHERE es.es_status = 2 AND ec.ec_track_id = es.ec_track_id AND ec.em_msg_id = em.em_msg_id".
  //  " ORDER BY ec.ec_type, es.ec_track_id";
  //$sql_query = "SELECT DISTINCT es1.ec_track_id, ec.ec_inv_no, ec.em_msg_id, ec.ec_type, es1.es_amount, LEFT(es1.es_date, 10) AS es_es_date, ec.ec_nad, em.em_nad1, em.em_nad2" .
  //  " FROM edi_status AS es1, edi_status AS es2, edi_consignee AS ec, edi_message AS em " .
  //  " WHERE es1.es_status <= 1 AND es1.ec_track_id = es2.ec_track_id AND es2.es_status = 303 AND ec.ec_track_id = es1.ec_track_id AND ec.em_msg_id = em.em_msg_id AND es1.es_date > '$inv_date_from_sql' AND es1.es_date < '$inv_date_to_sql'".
  //  " ORDER BY es_es_date, es1.ec_track_id";
  
  // - Nicht stornierte Aufträge mit S1999 checken (äußert sich auch durch fehlerhaftes Auftauchen von S1999 in der DKT-Abrechnung)
  //( - zum testen edi.inc.php in mk_interchange() include_once("../tools/edi_ftp.inc.php"); auskommentieren! Und auch in temp_exec_query()!)
  // - Vor dem Rechnungslauf "Lost by carrier" aussortieren (es_status auf 4 setzen):
  //   SELECT ec_track_id FROM `edi_status` WHERE es_status = 33 and es_date > '2012-03-15'
  //( - Und auch die Pakete, die gescannt aber gar nicht erst ausgeliefert wurden (z. B. Packstationen, auch es_status auf 4 setzen)):
  //   SELECT tourarticle.* FROM tourarticle, job WHERE tourarticle.jb_id = job.jb_id AND job.cr_sid = "S1999" and trat_modify > "2012-03-16" AND tr_sort > 1)
  // - Falsche 411 ('Paket ohne Auftrag' d.h. fehlende Scans) reparieren (in 201 updaten, ebenso IFTSTA 602 in 303 in edi_status und Preise neu berechnen)
  
  // noch nicht abgerechnete erledigte Tracking-IDs finden
  // Doppelte Scannungen (es_status = 303) vermeiden durch DISTINCT
  $sql_query = "SELECT DISTINCT es1.ec_track_id, ec.ec_inv_no, ec.em_msg_id, ec.ec_type, es1.es_amount, LEFT(es1.es_date, 10) AS es_es_date, ec.ec_nad, em.em_nad1, em.em_nad2" .
    " FROM edi_status AS es1 LEFT JOIN phoenix.tourarticle AS trat ON es1.ec_track_id = trat.trat_serialno, phoenix.tour AS tr, phoenix.job AS jb, edi_status AS es2, edi_consignee AS ec, edi_message AS em" .
    " WHERE es1.es_status <= 1 AND LEFT(es1.ec_track_id, $pre_len) IN (" . $cs_eidA["track_id"] . ") AND es1.ec_track_id = es2.ec_track_id AND es2.es_status = 303 AND ec.ec_track_id = es1.ec_track_id AND ec.em_msg_id = em.em_msg_id AND es1.es_date > '$inv_date_from_sql' AND es1.es_date < '$inv_date_to_sql'" .
    " AND trat.jb_id = tr.jb_id AND trat.tr_sort = tr.tr_sort AND jb.jb_id = tr.jb_id AND csc_id_payer IN " . $csc_id_sql[$hq_id] . " AND tr.tr_sort = 1 AND jb.jb_storno IS NULL" .
    " ORDER BY es_es_date, es1.ec_track_id";
//echo $sql_query . "\n";  
  $res = mysql_query($sql_query) or die ($sql_query . ": " . mysql_error());
  while ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
    $ec_type = $row["ec_type"];
    if ($row["ec_type"] == "STBX_NEXT"):
      $ec_type = "STBX_TIMED";
    endif;
    $csv_file[$ec_type] .= $row["es_es_date"] . ";" . $row["ec_track_id"] . ";" . str_replace(".", ",", sprintf("%01.2f", $row["es_amount"])) . ";" .
      str_replace(".", ",", sprintf("%01.4f", round($row["es_amount"] * VAT, 4))) . ";" .
      str_replace(".", ",", sprintf("%01.4f", round($row["es_amount"] * (1 + VAT), 4))) . "\n";
    $line_items[$ec_type] .= mk_line_item($line_item_no[$ec_type]++, $row["es_amount"], $row["ec_nad"], $row["em_msg_id"], $row["ec_track_id"], $row["ec_inv_no"]);
  //  writeLog("invoicing track id: '" . $row["ec_track_id"] . "'");
  //  temp_exec_query("UPDATE edi_status SET es_status = 2 WHERE ec_track_id = '" . $row["ec_track_id"] . "' AND es_status = 1");
    $track_ids[$ec_type] .= ($track_ids[$ec_type] == "" ? "" : "," ) . "'" . $row["ec_track_id"] . "'";
    if (!in_array($row["es_es_date"], array_keys($sum_stat))):
      $sum_stat[$row["es_es_date"]] = array();
    endif;
    if (!in_array($ec_type, array_keys($sum_stat[$row["es_es_date"]]))):
      $sum_stat[$row["es_es_date"]][$ec_type]["cnt"] = 0;
      $sum_stat[$row["es_es_date"]][$ec_type]["price"] = 0;
    endif;
    $sum_stat[$row["es_es_date"]][$ec_type]["cnt"]++;
    $sum_stat[$row["es_es_date"]][$ec_type]["price"] = $row["es_amount"];
    $sum[$ec_type] += $row["es_amount"];
    $no_of_segs[$ec_type] += 9;
    $em_nad1 = $row["em_nad1"];
//    $em_nad2 = $row["em_nad2"];
    $em_nad2 = 128414; // (ab 01.05.2015)
  endwhile;
  mysql_free_result($res);
  
  if ($line_items["STBX_SAME"] != ""):
    mk_interchange_vars();
    $message = "";
    $inv_no["STBX_SAME"] = substr($cs_eidA["prefix"], 0, -1) . $cur_inv_no++;
    $message = mk_message($inv_no["STBX_SAME"], $inv_date, $msg_date, $cs_eid["STBX_SAME"],
      $em_nad1, $em_nad2, $line_items["STBX_SAME"], $line_item_no["STBX_SAME"] -1, $sum["STBX_SAME"], $no_of_segs["STBX_SAME"]);
    writeLog("writing edi_invoice for invoice number '" . $inv_no["STBX_SAME"] . "'");
    temp_exec_query("INSERT INTO edi_invoice (ei_inv_no, ei_msg_no, ei_ic_ref, ei_date, cs_eid) values('" . $inv_no["STBX_SAME"] .
      "', " . $anxe_message_reference_number++ . ", " . $anxe_interchange_control_reference . ", '" . $inv_date . "', '" . $cs_eid["STBX_SAME"] . "')");
    writeLog("writing invoice references in edi_consignee");
    temp_exec_query("UPDATE edi_consignee SET ei_inv_no = '" . $inv_no["STBX_SAME"] . "' WHERE ec_track_id IN (" . $track_ids["STBX_SAME"] . ")");
    $csv_file["STBX_SAME"] .= ";Summe" . ";" . str_replace(".", ",", sprintf("%01.2f", $sum["STBX_SAME"])) . ";" .
      str_replace(".", ",", sprintf("%01.2f", round($sum["STBX_SAME"] * VAT, 2))) . ";" .
      str_replace(".", ",", sprintf("%01.2f", round($sum["STBX_SAME"] * (1 + VAT), 2))) . "\n";
    $fileHandle = @fopen("../temp/edifact/" . $inv_no["STBX_SAME"] . "_" . $cs_eid["STBX_SAME"] . "_" . $inv_date . ".csv", 'w');
    @fwrite($fileHandle, $csv_file["STBX_SAME"]);
    @fclose($fileHandle);
    $mailObj->addAttachment($mailObj->getFile("../temp/edifact/" . $inv_no["STBX_SAME"] . "_" . $cs_eid["STBX_SAME"] . "_" . $inv_date . ".csv"), $inv_no["STBX_SAME"] . "_" . $cs_eid["STBX_SAME"] . "_" . $inv_date . ".csv");
    $total_cnt = 0;
    $total_sum = 0;
    foreach (array_keys($sum_stat) AS $stat_date) {
  //  	if ($sum_stat[$stat_date]["STBX_SAME"]["cnt"] != ""):
        $csv_stat_file["STBX_SAME"] .= $stat_date . ";" . $sum_stat[$stat_date]["STBX_SAME"]["cnt"] . ";" . str_replace(".", ",", sprintf("%01.2f", $sum_stat[$stat_date]["STBX_SAME"]["price"], 2)) .
          ";" . str_replace(".", ",", sprintf("%01.2f", ($sum_stat[$stat_date]["STBX_SAME"]["cnt"] * $sum_stat[$stat_date]["STBX_SAME"]["price"]))) ."\n";
  //    endif;
        $total_cnt += $sum_stat[$stat_date]["STBX_SAME"]["cnt"];
        $total_sum += $sum_stat[$stat_date]["STBX_SAME"]["cnt"] * $sum_stat[$stat_date]["STBX_SAME"]["price"];
    }
    $csv_stat_file["STBX_SAME"] .= "Gesamt:;" . $total_cnt . ";" . str_replace(".", ",", sprintf("%01.2f", round($total_sum / $total_cnt, 2))) . ";" . str_replace(".", ",", sprintf("%01.2f", $total_sum));
    $fileHandle = @fopen("../temp/edifact/" . $inv_no["STBX_SAME"] . "_" . $cs_eid["STBX_SAME"] . "_" . $inv_date . "_stat.csv", 'w');
    @fwrite($fileHandle, $csv_stat_file["STBX_SAME"]);
    @fclose($fileHandle);
    $mailObj->addAttachment($mailObj->getFile("../temp/edifact/" . $inv_no["STBX_SAME"] . "_" . $cs_eid["STBX_SAME"] . "_" . $inv_date . "_stat.csv"), $inv_no["STBX_SAME"] . "_" . $cs_eid["STBX_SAME"] . "_" . $inv_date . "_stat.csv");     
    mk_interchange(1, $message, "INVOIC");
  endif;
  
  if ($line_items["STBX_TIMED"] != ""):
    mk_interchange_vars();
    $message = "";
    $inv_no["STBX_TIMED"] = substr($cs_eidA["prefix"], 0, -1) . $cur_inv_no;
    $message .= mk_message($inv_no["STBX_TIMED"], $inv_date, $msg_date, $cs_eid["STBX_TIMED"],
      $em_nad1, $em_nad2, $line_items["STBX_TIMED"], $line_item_no["STBX_TIMED"] -1, $sum["STBX_TIMED"], $no_of_segs["STBX_TIMED"]);
    writeLog("writing edi_invoice for invoice number '" . $inv_no["STBX_TIMED"] . "'");
    temp_exec_query("INSERT INTO edi_invoice (ei_inv_no, ei_msg_no, ei_ic_ref, ei_date, cs_eid) values('" . $inv_no["STBX_TIMED"] .
      "', " . $anxe_message_reference_number . ", " . $anxe_interchange_control_reference . ", '" . $inv_date . "', '" . $cs_eid["STBX_TIMED"] . "')");
    writeLog("writing invoice references in edi_consignee");
    temp_exec_query("UPDATE edi_consignee SET ei_inv_no = '" . $inv_no["STBX_TIMED"] . "' WHERE ec_track_id IN (" . $track_ids["STBX_TIMED"] . ")");
    $csv_file["STBX_TIMED"] .= ";Summe" . ";" . str_replace(".", ",", sprintf("%01.2f", $sum["STBX_TIMED"])) . ";" .
      str_replace(".", ",", sprintf("%01.2f", round($sum["STBX_TIMED"] * VAT, 2))) . ";" .
      str_replace(".", ",", sprintf("%01.2f", round($sum["STBX_TIMED"] * (1 + VAT), 2))) . "\n";
    $fileHandle = @fopen("../temp/edifact/" . $inv_no["STBX_TIMED"] . "_" . $cs_eid["STBX_TIMED"] . "_" . $inv_date . ".csv", 'w');
    @fwrite($fileHandle, $csv_file["STBX_TIMED"]);
    @fclose($fileHandle);
    $mailObj->addAttachment($mailObj->getFile("../temp/edifact/" . $inv_no["STBX_TIMED"] . "_" . $cs_eid["STBX_TIMED"] . "_" . $inv_date . ".csv"), $inv_no["STBX_TIMED"] . "_" . $cs_eid["STBX_TIMED"] . "_" . $inv_date . ".csv");
    $total_cnt = 0;
    $total_sum = 0;
    foreach (array_keys($sum_stat) AS $stat_date) {
  //    if ($sum_stat[$stat_date]["STBX_TIMED"]["cnt"] != ""):
        $csv_stat_file["STBX_TIMED"] .= $stat_date . ";" . $sum_stat[$stat_date]["STBX_TIMED"]["cnt"] . ";" . str_replace(".", ",", sprintf("%01.2f", $sum_stat[$stat_date]["STBX_TIMED"]["price"], 2)) .
          ";" . str_replace(".", ",", sprintf("%01.2f", ($sum_stat[$stat_date]["STBX_TIMED"]["cnt"] * $sum_stat[$stat_date]["STBX_TIMED"]["price"]))) ."\n";
  //    endif;
        $total_cnt += $sum_stat[$stat_date]["STBX_TIMED"]["cnt"];
        $total_sum += $sum_stat[$stat_date]["STBX_TIMED"]["cnt"] * $sum_stat[$stat_date]["STBX_TIMED"]["price"];
    }
    $csv_stat_file["STBX_TIMED"] .= "Gesamt:;" . $total_cnt . ";" . str_replace(".", ",", sprintf("%01.2f", round($total_sum / $total_cnt, 2))) . ";" . str_replace(".", ",", sprintf("%01.2f", $total_sum));
    $fileHandle = @fopen("../temp/edifact/" . $inv_no["STBX_TIMED"] . "_" . $cs_eid["STBX_TIMED"] . "_" . $inv_date . "_stat.csv", 'w');
    @fwrite($fileHandle, $csv_stat_file["STBX_TIMED"]);
    @fclose($fileHandle);
    $mailObj->addAttachment($mailObj->getFile("../temp/edifact/" . $inv_no["STBX_TIMED"] . "_" . $cs_eid["STBX_TIMED"] . "_" . $inv_date . "_stat.csv"), $inv_no["STBX_TIMED"] . "_" . $cs_eid["STBX_TIMED"] . "_" . $inv_date . "_stat.csv");
    mk_interchange(1, $message, "INVOIC");
  endif;
  if ($inv_date_from_stat_sql != "") {
    $stat_csv = file_get_contents("https://sb.assecutor.de/tools/statistic.php?dl=1&from=" . formDate(substr($inv_date_from_stat_sql, 0, 10)) . "&to=" . formDate(substr($inv_date_to_sql, 0, 10)) . "&hq_id=$hq_id");
    $stat_csv_name = "Abrechnung Amazon " . $invoicing_tokens[$hq_id] . " " . substr($inv_date_from_stat_sql, 0, 10) . " - " . substr($inv_date_to_sql, 0, 10) . ".csv";
    $fileHandle = @fopen("../temp/edifact/" . $stat_csv_name, 'w');
    @fwrite($fileHandle, $stat_csv);
    @fclose($fileHandle);
    $mailObj->addAttachment($mailObj->getFile("../temp/edifact/" . $stat_csv_name), $stat_csv_name);
  }
}
$mailResult = $mailObj->send(array("annacker@gmx.net"), 'smtp');

function get_nad($en_id)
{
  $sqlStmt = "SELECT en_nad FROM edi_nad WHERE en_id = $en_id";
  $res = mysql_query($sqlStmt) or die ($sqlStmt . ": " . mysql_error());

  if ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
    $en_nad = str_replace("&", "&amp;", $row["en_nad"]);
    $en_nad = str_replace("'", "&apos;", $en_nad);
//    $en_nad = str_replace("<", "&lt;", $en_nad);
//    $en_nad = str_replace(">", "&gt;", $en_nad);
//    $en_nad = str_replace('"', "&quot;", $en_nad);
    return $en_nad;
  endif;
  
  return "";
}

function temp_exec_query($sql_query)
{
	global $argv;
	
	if ($argv[1] == "save"):
    exec_query ($sql_query);
  else:
    echo $sql_query . "\n";
  endif;
}

function mk_line_item($line_item_no, $amount, $consignee_id, $em_msg_id, $track_id, $inv_no)
{
	$consignee = get_nad($consignee_id);
  return
  //<!-- SEGMENT LIN+1 -->
    "  <trsd:line.item>" .
    "    <tred:line.item.number>" . $line_item_no . "</tred:line.item.number>" .
    "  </trsd:line.item>" .
    //<!-- SEGMENT IMD+F+8+:::PACKAGE 2KG -->
    "  <trsd:item.description>" .
    "    <tred:item.description.type.coded uncl:code=\"7077:F\">Free-form</tred:item.description.type.coded>" .
    "    <tred:item.characteristic.coded uncl:code=\"7081:8\">Product</tred:item.characteristic.coded>" .
    "    <trcd:item.description>" .
    "      <tred:item.description>" . "PACKAGE" . "</tred:item.description>" .
    "    </trcd:item.description>" .
    "  </trsd:item.description>" .
    //<!-- SEGMENT MOA+203:2.50 -->
    "  <trsd:monetary.amount>" .
    "    <trcd:monetary.amount>" .
    "      <tred:monetary.amount.type.qualifier uncl:code=\"5025:203\">Line item amount</tred:monetary.amount.type.qualifier>" .
    "      <tred:monetary.amount>" . ($amount + 0) . "</tred:monetary.amount>" .
    "    </trcd:monetary.amount>" .
    "  </trsd:monetary.amount>" .
    //<!-- SEGMENT PRI+CAL:2.30 -->
    "  <trsd:price.details>" .
    "    <trcd:price.information>" .
    "      <tred:price.qualifier uncl:code=\"5125:CAL\">Calculation price</tred:price.qualifier>" .
    "      <tred:price>" . ($amount + 0) . "</tred:price>" .
    "    </trcd:price.information>" .
    "  </trsd:price.details>" .
    //<!-- SEGMENT TAX+7+VAT+++:::17.50 -->
    "  <trsd:duty.tax.fee.details>" .
    "    <tred:duty.tax.fee.function.qualifier uncl:code=\"5283:7\">Tax</tred:duty.tax.fee.function.qualifier>" .
    "    <trcd:duty.tax.fee.type>" .
    "      <tred:duty.tax.fee.type.coded uncl:code=\"5153:VAT\">Value added tax</tred:duty.tax.fee.type.coded>" .
    "    </trcd:duty.tax.fee.type>" .
    "    <trcd:duty.tax.fee.detail>" .
//    "      <tred:duty.tax.fee.rate>" . sprintf("%01.2f", VAT * 100) . "</tred:duty.tax.fee.rate>" .
    "      <tred:duty.tax.fee.rate>" . VAT * 100 . "</tred:duty.tax.fee.rate>" .  // (ab 01.05.2015)
    "    </trcd:duty.tax.fee.detail>" .
    "  </trsd:duty.tax.fee.details>" .
    //<!-- SEGMENT NAD+CN++HOMER SIMPSON++5 SPRINGFIELD PLAZA+SPRINGFIELD+STIRLINGS+FK15 0FS+GB -->
    //"  <trsd:name.and.address>" .
      $consignee .
    //"    <tred:party.qualifier uncl:code=\"3035:CN\">Consignee</tred:party.qualifier>" .
    //"    <trcd:name.and.address>" .
    //"      <tred:name.and.address.line>HOMER SIMPSON</tred:name.and.address.line>" .
    //"    </trcd:name.and.address>" .
    //"    <trcd:street>" .
    //"      <tred:street.and.number.p.o.box>5 SPRINGFIELD PLAZA</tred:street.and.number.p.o.box>" .
    //"    </trcd:street>" .
    //"    <tred:city.name>SPRINGFIELD</tred:city.name>" .
    //"    <tred:country.sub.entity.identification>STIRLINGS</tred:country.sub.entity.identification>" .
    //"    <tred:postcode.identification>FK15 0FS</tred:postcode.identification>" .
    //"    <tred:country.coded>GB</tred:country.coded>" .
    //"  </trsd:name.and.address>" .
    //<!-- SEGMENT RFF+AAM:5858272 -->
    "  <trsd:reference>" .
    "    <trcd:reference>" .
    "      <tred:reference.qualifier uncl:code=\"1153:AAM\">Waybill number</tred:reference.qualifier>" .
    "      <tred:reference.number>" . $em_msg_id . "</tred:reference.number>" .
    "    </trcd:reference>" .
    "  </trsd:reference>" .
    //<!-- SEGMENT RFF+CR:PBNA0024090001 -->
    "  <trsd:reference>" .
    "    <trcd:reference>" .
    "      <tred:reference.qualifier uncl:code=\"1153:CR\">Customer reference number</tred:reference.qualifier>" .
    "      <tred:reference.number>" . $track_id . "</tred:reference.number>" .
    "    </trcd:reference>" .
    "  </trsd:reference>" .
    //<!-- SEGMENT RFF+ACC:D0T72XPPR_1 -->
    "  <trsd:reference>" .
    "    <trcd:reference>" .
    "      <tred:reference.qualifier uncl:code=\"1153:ACC\">Shipping unit identification</tred:reference.qualifier>" .
    "      <tred:reference.number>" . $inv_no . "</tred:reference.number>" .
    "    </trcd:reference>" .
    "  </trsd:reference>";
    //<!-- SEGMENT DTM+200:20050809:102 -->
    // optional
    //"  <trsd:date.time.period>" .
    //"    <trcd:date.time.period>" .
    //"      <tred:date.time.period.qualifier uncl:code=\"2005:200\">Pick-up/collection date/time of cargo</tred:date.time.period.qualifier>" .
    //"      <tred:date.time.period>20050809</tred:date.time.period>" .
    //"      <tred:date.time.period.format.qualifier uncl:code=\"2379:102\">CCYYMMDD</tred:date.time.period.format.qualifier>" .
    //"    </trcd:date.time.period>" .
    //"  </trsd:date.time.period>" .
    //<!-- SEGMENT DTM+191:20050811:102 -->
    // optional
    //"  <trsd:date.time.period>" .
    //"    <trcd:date.time.period>" .
    //"      <tred:date.time.period.qualifier uncl:code=\"2005:191\">Delivery date/time, expected</tred:date.time.period.qualifier>" .
    //"      <tred:date.time.period>20050811</tred:date.time.period>" .
    //"      <tred:date.time.period.format.qualifier uncl:code=\"2379:102\">CCYYMMDD</tred:date.time.period.format.qualifier>" .
    //"    </trcd:date.time.period>" .
    //"  </trsd:date.time.period>" .
    //<!-- SEGMENT ALC+C++++LA:::LABELLING -->
    // IMHO not apllicable
    //"  <trsd:allowance.or.charge>" .
    //"    <tred:allowance.or.charge.qualifier uncl:code=\"5463:C\">Charge</tred:allowance.or.charge.qualifier>" .
    //"      <trcd:special.services.identification>" .
    //"      <tred:special.services.coded uncl:code=\"7161:LA\">Labelling</tred:special.services.coded>" .
    //"      <tred:special.service>LABELLING</tred:special.service>" .
    //"    </trcd:special.services.identification>" .
    //"  </trsd:allowance.or.charge>" .
    //<!-- SEGMENT MOA+8:.20 -->
    //"  <trsd:monetary.amount>" .
    //"    <trcd:monetary.amount>" .
    //"      <tred:monetary.amount.type.qualifier uncl:code=\"5025:8\">Allowance or charge amount</tred:monetary.amount.type.qualifier>" .
    //"      <tred:monetary.amount>.20</tred:monetary.amount>" .
    //"    </trcd:monetary.amount>" .
    //"  </trsd:monetary.amount>" .
    //<!-- SEGMENT TAX+7+VAT+++:::17.50 -->
    //"  <trsd:duty.tax.fee.details>" .
    //"    <tred:duty.tax.fee.function.qualifier uncl:code=\"5283:7\">Tax</tred:duty.tax.fee.function.qualifier>" .
    //"    <trcd:duty.tax.fee.type>" .
    //"      <tred:duty.tax.fee.type.coded uncl:code=\"5153:VAT\">Value added tax</tred:duty.tax.fee.type.coded>" .
    //"    </trcd:duty.tax.fee.type>" .
    //"    <trcd:duty.tax.fee.detail>" .
    //"      <tred:duty.tax.fee.rate>17.50</tred:duty.tax.fee.rate>" .
    //"    </trcd:duty.tax.fee.detail>" .
    //"  </trsd:duty.tax.fee.details>";
}

function mk_message($inv_no, $inv_date, $msg_date, $cs_eid, $ship_from_id, $invoicee_id, $line_items, $line_item_no, $amount, $no_segs)
{
  global $anxe_message_reference_number, $invoicing_parties, $hq_id;

	$ship_from = get_nad($ship_from_id);
//NAD+IV+5450534000048::9++AMAZON EU SARL:5 RUE PLAETIS LUXEMBOURG+CO ACCOUNTING SERVICE CENTER:MOOSACHER STRASSE 51+MUENCHEN++80809+DE
//NAD+IV+5450534000048::9++AMAZON EU SARL:5 RUE PLAETIS LUXEMBOURG+CO ACCOUNTING SERVICE CENTER:MARCEL-BREUER-STRASSE 12+MUENCHEN++80807+DE
	$invoicee = str_replace("MOOSACHER STRASSE 51", "MARCEL-BREUER-STRASSE 12", str_replace("80809", "80807", get_nad($invoicee_id)));

  return
    //<!-- SEGMENT UNH+1+INVOIC:D:96A:UN:EAN008 -->
    "  <anxs:message.header>" .
    "    <anxe:message.reference.number>" . $anxe_message_reference_number . "</anxe:message.reference.number>" .
    "    <anxc:message.identifier>" .
    "      <anxe:message.type unsl:code=\"0065:INVOIC\">Invoice message</anxe:message.type>" .
    "      <anxe:message.version.number>D</anxe:message.version.number>" .
    "      <anxe:message.release.number>96A</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>" .
    //<!-- SEGMENT BGM+380+5749303+9 -->
    "  <trsd:beginning.of.message>" .
    "    <trcd:document.message.name>" .
    "    <tred:document.message.name.coded uncl:code=\"1001:380\">Commercial invoice</tred:document.message.name.coded>" .
    "    </trcd:document.message.name>" .
    "    <trcd:document.message.identification>" .
    "      <tred:document.message.number>" . $inv_no . "</tred:document.message.number>" .
    "    </trcd:document.message.identification>" .
    "    <tred:message.function.coded uncl:code=\"1225:9\">Original</tred:message.function.coded>" .
    "  </trsd:beginning.of.message>" .
    //<!-- SEGMENT DTM+3:20050809:102 -->
    "  <trsd:date.time.period>" .
    "    <trcd:date.time.period>" .
    "      <tred:date.time.period.qualifier uncl:code=\"2005:3\">Invoice date/time</tred:date.time.period.qualifier>" .
    "      <tred:date.time.period>" . $inv_date . "</tred:date.time.period>" .
    "      <tred:date.time.period.format.qualifier uncl:code=\"2379:102\">CCYYMMDD</tred:date.time.period.format.qualifier>" .
    "    </trcd:date.time.period>" .
    "  </trsd:date.time.period>" .
    //<!-- SEGMENT DTM+137:20050809:102 -->
    "  <trsd:date.time.period>" .
    "    <trcd:date.time.period>" .
    "      <tred:date.time.period.qualifier uncl:code=\"2005:137\">Document/message date/time</tred:date.time.period.qualifier>" .
    "      <tred:date.time.period>" . $msg_date . "</tred:date.time.period>" .
    "      <tred:date.time.period.format.qualifier uncl:code=\"2379:102\">CCYYMMDD</tred:date.time.period.format.qualifier>" .
    "    </trcd:date.time.period>" .
    "  </trsd:date.time.period>" .
    //<!-- SEGMENT RFF+IT:77100 -->
    "  <trsd:reference>" .
    "    <trcd:reference>" .
    "      <tred:reference.qualifier uncl:code=\"1153:IT\">Internal customer number</tred:reference.qualifier>" .
    "      <tred:reference.number>" . $cs_eid . "</tred:reference.number>" .
    "    </trcd:reference>" .
    "  </trsd:reference>" .
    //<!-- SEGMENT NAD+CA+ABCD++BEST CARRIER+NEW STREET 2+NEWPORT++AB1 3CD+GB -->
    "  <trsd:name.and.address>" .
    "    <tred:party.qualifier uncl:code=\"3035:CA\">Carrier</tred:party.qualifier>" .
    "    <trcd:party.identification.details>" .
    "      <tred:party.id.identification>" . "STBX" . "</tred:party.id.identification>" .
    "    </trcd:party.identification.details>" .
    "    <trcd:party.name>" .
    "      <tred:party.name>" . "Stadtbote GmbH" . "</tred:party.name>" .
    "    </trcd:party.name>" .
    "    <trcd:street>" .
    "      <tred:street.and.number.p.o.box>" . $invoicing_parties[$hq_id][0] . "</tred:street.and.number.p.o.box>" .
    "    </trcd:street>" .
    "    <tred:city.name>" . $invoicing_parties[$hq_id][1] . "</tred:city.name>" .
    "    <tred:postcode.identification>" . $invoicing_parties[$hq_id][2] . "</tred:postcode.identification>" .
    "    <tred:country.coded>" . "DE" . "</tred:country.coded>" .
    "  </trsd:name.and.address>" .
    //<!-- SEGMENT RFF+VA:GB123456789 -->
    "  <trsd:reference>" .
    "    <trcd:reference>" .
    "      <tred:reference.qualifier uncl:code=\"1153:VA\">VAT registration number</tred:reference.qualifier>" .
    "      <tred:reference.number>" . "DE242116880" . "</tred:reference.number>" .
    "    </trcd:reference>" .
    "  </trsd:reference>" .
    //<!-- SEGMENT NAD+SF+5450534000109::9++AMAZON EU SARL+MARSTON GATE FULFILLMENT CENTRE+RIDGEMONT++MK43 0ZA+GB -->
    //"  <trsd:name.and.address>" .
      $ship_from .
    //"    <tred:party.qualifier uncl:code=\"3035:SF\">Ship from</tred:party.qualifier>" .
    //"    <trcd:party.identification.details>" .
    //"      <tred:party.id.identification>5450534000109</tred:party.id.identification>" .
    //"      <tred:code.list.responsible.agency.coded uncl:code=\"3055:9\">EAN (International Article Numbering association)</tred:code.list.responsible.agency.coded>" .
    //"    </trcd:party.identification.details>" .
    //"    <trcd:party.name>" .
    //"      <tred:party.name>AMAZON EU SARL</tred:party.name>" .
    //"    </trcd:party.name>" .
    //"    <trcd:street>" .
    //"      <tred:street.and.number.p.o.box>MARSTON GATE FULFILLMENT CENTRE</tred:street.and.number.p.o.box>" .
    //"    </trcd:street>" .
    //"    <tred:city.name>RIDGEMONT</tred:city.name>" .
    //"    <tred:postcode.identification>MK43 0ZA</tred:postcode.identification>" .
    //"    <tred:country.coded>GB</tred:country.coded>" .
    //"  </trsd:name.and.address>" .
    //<!-- SEGMENT NAD+IV+5450534000055::9++AMAZON EU SARL:5 RUE PLAETIS -->
    //"  <trsd:name.and.address>" .
      $invoicee .
    //"    <tred:party.qualifier uncl:code=\"3035:IV\">Invoicee</tred:party.qualifier>" .
    //"    <trcd:party.identification.details>" .
    //"      <tred:party.id.identification>5450534000055</tred:party.id.identification>" .
    //"      <tred:code.list.responsible.agency.coded uncl:code=\"3055:9\">EAN (International Article Numbering association)</tred:code.list.responsible.agency.coded>" .
    //"    </trcd:party.identification.details>" .
    //"    <trcd:party.name>" .
    //"      <tred:party.name>AMAZON EU SARL</tred:party.name>" .
    //"      <tred:party.name>5 RUE PLAETIS</tred:party.name>" .
    //"    </trcd:party.name>" .
    //"  </trsd:name.and.address>" .
    //<!-- SEGMENT  LUXEMBOURG+CO ACCOUNTING SERVICE CENTER:1-9 THE GROVE+SLOUGH++SL1 1QP+GB -->
    //"  <edifact:raw_segment data=\" LUXEMBOURG+CO ACCOUNTING SERVICE CENTER:1-9 THE GROVE+SLOUGH++SL1 1QP+GB\"/>" .
    //<!-- SEGMENT RFF+VA:GB727255821 -->
    "  <trsd:reference>" .
    "    <trcd:reference>" .
    "      <tred:reference.qualifier uncl:code=\"1153:VA\">VAT registration number</tred:reference.qualifier>" .
//    "      <tred:reference.number>" . "LU20260743" . "</tred:reference.number>" .
    "      <tred:reference.number>" . "DE814584193" . "</tred:reference.number>" . // (ab 01.05.2015)
    "    </trcd:reference>" .
    "  </trsd:reference>" .
    //<!-- SEGMENT CUX+2:GBP:4 -->
    "  <trsd:currencies>" .
    "    <trcd:currency.details>" .
    "      <tred:currency.details.qualifier uncl:code=\"6347:2\">Reference currency</tred:currency.details.qualifier>" .
    "      <tred:currency.coded>" . "EUR" . "</tred:currency.coded>" .
    "      <tred:currency.qualifier uncl:code=\"6343:4\">Invoicing currency</tred:currency.qualifier>" .
    "    </trcd:currency.details>" .
    "  </trsd:currencies>" .
    //<!-- SEGMENT PAT+1++5::D:30 -->
    "  <trsd:payment.terms.basis>" .
    "    <tred:payment.terms.type.qualifier uncl:code=\"4279:1\">Basic</tred:payment.terms.type.qualifier>" .
    "    <trcd:terms.time.information>" .
    "      <tred:payment.time.reference.coded uncl:code=\"2475:5\">Date of invoice</tred:payment.time.reference.coded>" .
    "      <tred:type.of.period.coded uncl:code=\"2151:D\">Day</tred:type.of.period.coded>" .
    "      <tred:number.of.periods>" . "45" . "</tred:number.of.periods>" .
    "    </trcd:terms.time.information>" .
    "  </trsd:payment.terms.basis>" .
    //<!-- SEGMENT PCD+7:2:13 -->
    "  <trsd:percentage.details>" .
    "    <trcd:percentage.details>" .
    "      <tred:percentage.qualifier uncl:code=\"5245:7\">Percentage of invoice</tred:percentage.qualifier>" .
    "      <tred:percentage>" . "0".  "</tred:percentage>" .
    "      <tred:percentage.basis.coded uncl:code=\"5249:13\">Invoice value</tred:percentage.basis.coded>" .
    "    </trcd:percentage.details>" .
    "  </trsd:percentage.details>" .    
    $line_items .    
    //<!-- SEGMENT UNS+S -->
    "  <anxs:section.control>" .
    "    <anxe:section.identification unsl:code=\"0081:S\">Detail/summary section separation</anxe:section.identification>" .
    "  </anxs:section.control>" .
    //<!-- SEGMENT CNT+2:1 -->
    "  <trsd:control.total>" .
    "    <trcd:control>" .
    "      <tred:control.qualifier uncl:code=\"6069:2\">Number of line items in message</tred:control.qualifier>" .
    "      <tred:control.value>" . $line_item_no . "</tred:control.value>" .
    "    </trcd:control>" .
    "  </trsd:control.total>" .
    //<!-- SEGMENT MOA+79:2.50 -->
    "  <trsd:monetary.amount>" .
    "    <trcd:monetary.amount>" .
    "      <tred:monetary.amount.type.qualifier uncl:code=\"5025:79\">Total line items amount</tred:monetary.amount.type.qualifier>" .
    "      <tred:monetary.amount>" . round($amount, 2) . "</tred:monetary.amount>" .
    "    </trcd:monetary.amount>" .
    "  </trsd:monetary.amount>" .
    //<!-- SEGMENT MOA+77:2.94 -->
    "  <trsd:monetary.amount>" .
    "    <trcd:monetary.amount>" .
    "      <tred:monetary.amount.type.qualifier uncl:code=\"5025:77\">Invoice amount</tred:monetary.amount.type.qualifier>" .
    "      <tred:monetary.amount>" . (round($amount, 2) + round($amount * VAT, 2)) . "</tred:monetary.amount>" .
    "    </trcd:monetary.amount>" .
    "  </trsd:monetary.amount>" .
    //<!-- SEGMENT TAX+7+VAT+++:::17.50 -->
    "  <trsd:duty.tax.fee.details>" .
    "    <tred:duty.tax.fee.function.qualifier uncl:code=\"5283:7\">Tax</tred:duty.tax.fee.function.qualifier>" .
    "      <trcd:duty.tax.fee.type>" .
    "      <tred:duty.tax.fee.type.coded uncl:code=\"5153:VAT\">Value added tax</tred:duty.tax.fee.type.coded>" .
    "    </trcd:duty.tax.fee.type>" .
    "    <trcd:duty.tax.fee.detail>" .
//    "      <tred:duty.tax.fee.rate>" . sprintf("%01.2f", VAT * 100) . "</tred:duty.tax.fee.rate>" .
    "      <tred:duty.tax.fee.rate>" . VAT * 100 . "</tred:duty.tax.fee.rate>" .  // (ab 01.05.2015)
    "    </trcd:duty.tax.fee.detail>" .
    "  </trsd:duty.tax.fee.details>" .
    //<!-- SEGMENT MOA+124:0.44 -->
    "  <trsd:monetary.amount>" .
    "    <trcd:monetary.amount>" .
    "      <tred:monetary.amount.type.qualifier uncl:code=\"5025:124\">Tax amount</tred:monetary.amount.type.qualifier>" .
    "      <tred:monetary.amount>" . round($amount * VAT, 2) . "</tred:monetary.amount>" .
    "    </trcd:monetary.amount>" .
    "  </trsd:monetary.amount>" .
    //<!-- SEGMENT MOA+125:2.50 -->
    "  <trsd:monetary.amount>" .
    "    <trcd:monetary.amount>" .
    "      <tred:monetary.amount.type.qualifier uncl:code=\"5025:125\">Taxable amount</tred:monetary.amount.type.qualifier>" .
    "      <tred:monetary.amount>" . round($amount, 2) . "</tred:monetary.amount>" .
    "    </trcd:monetary.amount>" .
    "  </trsd:monetary.amount>" .
    //<!-- SEGMENT UNT+35+1 -->
    "  <anxs:message.trailer>" .
    "    <anxe:number.of.segments.in.the.message>" . $no_segs . "</anxe:number.of.segments.in.the.message>" .
    "    <anxe:message.reference.number>" . $anxe_message_reference_number . "</anxe:message.reference.number>" .
    "  </anxs:message.trailer>";
}

function get_prices() {
  global $price_ranges, $hq_id, $hq_prefixes, $inv_date_from_sql, $inv_date_to_sql;

  $pre_len = strlen($hq_prefixes[$hq_id]) + 2;
//  if (date("d") <= 15)
//    $last_inv_date = date("Y-m-d", mktime(0, 0, 0, date("m"), 1, date("Y")));
//  else
//    $last_inv_date = date("Y-m-d", mktime(0, 0, 0, date("m"), 16, date("Y")));
  $last_inv_date = substr($inv_date_from_sql, 0, 10);
//$last_inv_date = "2013-06-01";
  $i = 0;
  while ($i == 0 || $cur_date != $last_inv_date):
//    $cur_date = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - $i++, date("Y")));
    $cur_date = date("Y-m-d", mktime(0, 0, 0, substr($inv_date_to_sql, 5, 2), substr($inv_date_to_sql, 8, 2) - $i++, substr($inv_date_to_sql, 0, 4)));	
    writeLog($cur_date);
    // Preise ermitteln und eintragen
    foreach(array("('" . $hq_prefixes[$hq_id] . "01','" . $hq_prefixes[$hq_id] . "04','" . $hq_prefixes[$hq_id] . "05')", "('" . $hq_prefixes[$hq_id] . "02','" . $hq_prefixes[$hq_id] . "03')") AS $type_clause) {
      $FROM_CLAUSE = 
        " FROM phoenix.tourarticle AS ta1, phoenix.tourarticleprocess AS tp1, phoenix.tourarticle AS ta2, phoenix.tourarticleprocess AS tp2, phoenix.job AS jb" .
        " WHERE ta1.trat_id = tp1.trat_id AND (tp1.tratp_type = '102' OR tp1.tratp_type = '101') AND ta2.trat_id = tp2.trat_id AND tp2.tratp_type = '201'" .
        " AND ta1.trat_serialno = ta2.trat_serialno AND LEFT(tp1.tratp_createtime, 10) = '" . $cur_date . "' AND LEFT(ta1.trat_serialno, $pre_len) IN "  . $type_clause .
        " AND ta2.jb_id = jb.jb_id AND jb.jb_storno IS NULL";
      $sql_query = "SELECT count(*) AS cnt" . $FROM_CLAUSE;
      $res = mysql_query($sql_query) or die ($sql_query . ": " . mysql_error());
      while ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
        writeLog($row["cnt"]);
        $es_amount = get_price($row["cnt"]);
        $sql_query = "SELECT ta1.trat_serialno" . $FROM_CLAUSE;
        $res1 = mysql_query($sql_query) or die ($sql_query . ": " . mysql_error());
        while ($row1 = mysql_fetch_array($res1, MYSQL_ASSOC)):      
          exec_query("UPDATE phoenix_log.edi_status SET es_amount = $es_amount WHERE es_status IN (0,1) AND ec_track_id = '" . $row1["trat_serialno"] . "'");
        endwhile;
      endwhile;
      mysql_free_result($res);
    }
  endwhile;
}

function formDate($sqlDate) {
  return substr($sqlDate, 8, 2) . "." . substr($sqlDate, 5, 2) . "." . substr($sqlDate, 0, 4);
}

?>