<?php
/*=======================================================================
 *
 * auto_export_lyreco.php
 *
 * Autor: Marc Vollmann
 *
  =======================================================================*/

include_once ("../include/mcglobal.inc.php");
include_once ("../include/html.inc.php");
include_once ("../include/inc_html2pdf.inc.php");
include_once ("../include/inc_file.inc.php");
include_once ("../include/image.inc.php");
include_once ("../include/inc_job.inc.php");
include_once ("../include/ftp.inc.php");
include_once ('../include/email/htmlMimeMail.php');


$autoMode = false;
if (!isset($argv[1]) || $argv[1] == "") :
   $isCron = false;
//   include_once ("../include/auth.inc.php");
   getSecHttpVars("1",array("f_act", "csId"));
   $autoMode = true;
//   $usrAccessArray["hq"] = "1"; $usrAccessArray["cs"] = "1";
//   authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
//   authCheckEmployeeRights($emp_id, "1", "1");
else :
   // Init parameters
   $f_act = ""; $title = ""; 

   $isCron = true;
   if ($argv[1] == "acapella7890") : $autoMode = true; endif;
   if ($autoMode) :
      if (isset($argv[2]) && $argv[2] != "") : $csId = $argv[2]; endif;
   endif;
endif;

// Error reporting
error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);

// Set timezone
// date_default_timezone_set('Europe/Berlin');

// Execution-Time for script
set_time_limit(1200);


$absoluteSystemPath = getAbsoluteSystemPath();  // Definition of absolute path, filename and extension. Has to be called here BEFORE calling function "outputMetaFieldSpecial()" !!!!

// Log file
$logFile = getParameterValue("0", "AUTO_EXPORT_LOGFILE_LYRECO", "0");
if ($logFile == "") :
   $logFile = getParameterValue("0", "AUTO_EXPORT_LOGFILE", "0");
   if ($logFile == "") : $logFile = "../log/auto_export.log"; endif;
endif;

// Send mode
$sendMode = "SFTP";

// Pick up data from the first station of each job
$pickUpArray = array();

// Special (S)FTP upload location
$ftp_server = getParameterValue("0", "FTP_SERVER_LYRECO", "0");
$ftp_user_name = getParameterValue("0", "FTP_USER_LYRECO", "0");
$ftp_user_pass = getParameterValue("0", "FTP_PASSWORD_LYRECO", "0");

$localPath = getParameterValue("0", "FTP_LOCALPATH_LYRECO", "0");
if ($localPath == "") :
   $localPath = "../import/upload/HTG/MISC/LYRECO/";
endif;
$remotePath = getParameterValue("0", "FTP_REMOTEPATH_LYRECO", "0");
if ($remotePath == "") :
   $remotePath = "/secure.tifdocs.com/hansetrans/";
endif;
// Get subpath especially defined each customer
$remoteSubPath = getParameterValue("0", "FTP_REMOTEPATH_LYRECO_CS_" . $csId, "0");
if ($remoteSubPath != "") :
   $remotePath .= $remoteSubPath;
endif;

// *********************************************************************
$debug = false;
if ($debug) :
   $ftp_server = getParameterValue("0", "FTP_SERVER_MPS1", "0");
   $ftp_user_name = getParameterValue("0", "FTP_USER_MPS1", "0");
   $ftp_user_pass = getParameterValue("0", "FTP_PASSWORD_MPS1", "0");
   $localPath = getParameterValue("0", "FTP_LOCALPATH_MPS1", "0");
   $remotePath = getParameterValue("0", "FTP_REMOTEPATH_MPS1", "0");
endif;
// *********************************************************************


// Scan event description mapping
$scanMsgArray = array();
$scanMsgArray["0"] = "OK";
$scanMsgArray["3"] = "Ware_nicht_benötigt";
$scanMsgArray["6"] = "Bestelldaten_falsch";
$scanMsgArray["7"] = "Auftrag_doppelt";
$scanMsgArray["9"] = "LE-Nr._vorhanden";
$scanMsgArray["10"] = "Falsche_Kartonware";
$scanMsgArray["11"] = "Im_Lager_beschädigt";
$scanMsgArray["13"] = "Falsch_sortiert";
$scanMsgArray["15"] = "Nachtsprung_beschädigt";
$scanMsgArray["18"] = "RDC_beschädigt";


// Get jobs for auto_export
function getDoneJobsOfCustomer($csId) {
  global $db, $logFile, $pickUpArray;
  $retArray = array();

  // $constAmStarttimeInDays = getParameterValue("0", "AUTO_EXPORT_STARTTIME_IN_DAYS", "0");  // "Meta-Global" <=> hq_id = 0
  $constAmStarttimeInDays = 5;

  $startTime = getDateTime("datetime_plus_offset", array(0,0,0,0,-($constAmStarttimeInDays),0), "Y-m-d") . " 00:00:00";
  $endTime =   getDateTime("datetime_plus_offset", array(0,0,0,0,0,0), "Y-m-d") . " 23:59:59";
  // $currentTime = getDateTime("0");

  $jbOrdertimeStart = "2015-04-27 00:00:00";

// TEST
// $startTime = "2014-11-13 00:00:00";
// $endTime = "2014-11-13 23:59:59";

  // Get jobs of the specified customer
  $sqlquery = "SELECT jb.jb_id, jb.jb_status, jb.cr_id, jb.cr_sid, jb.hq_id, jb.jb_ordertime, jb.jb_finishtime,"
            . "       tr.tr_id, tr.tr_sort, tr.tr_status, tr.tr_commission_no, tr.tr_finishtime, tr.tr_comp, tr.tr_comp2, tr.tr_person, tr.tr_phone, tr.tr_hsno, tr.tr_signname, tr.tr_sign, tr.tr_cs_freetext,"
            . "       ad.ad_street, ad.ad_zipcode, ad.ad_city," 
            . "       trat.trat_packingpieces, trat.trat_remark, trat.trat_weight,"
            . "       gdc.gdc_content, gdc.gdc_context, gdc_tr_finished.gdc_content AS gdc_tr_finished_content,"
            . "       gdc_info_0.gdc_content AS gdc_info_0_content, gdc_info_1.gdc_content AS gdc_info_1_content, gdc_info_2.gdc_content AS gdc_info_2_content,"
            . "       gdc_info_3.gdc_content AS gdc_info_3_content, gdc_info_4.gdc_content AS gdc_info_4_content"
            . " FROM job AS jb,"
            . "      tour AS tr LEFT JOIN address AS ad ON tr.ad_id = ad.ad_id" 
            . "                 LEFT JOIN tourarticle AS trat ON trat.tr_id = tr.tr_id"
            . "                 LEFT JOIN genericdatacontainer AS gdc ON gdc.gdc_obj_id = tr.tr_id AND gdc.gdc_obj_type = 'tr' AND gdc.gdc_gen_fieldname = 'auto_export'"
            . "                 LEFT JOIN genericdatacontainer AS gdc_info_0 ON gdc_info_0.gdc_obj_id = tr.tr_id AND gdc_info_0.gdc_obj_type = 'tr' AND gdc_info_0.gdc_gen_fieldname = 'info_0'"
            . "                 LEFT JOIN genericdatacontainer AS gdc_info_1 ON gdc_info_1.gdc_obj_id = tr.tr_id AND gdc_info_1.gdc_obj_type = 'tr' AND gdc_info_1.gdc_gen_fieldname = 'info_1'"
            . "                 LEFT JOIN genericdatacontainer AS gdc_info_2 ON gdc_info_2.gdc_obj_id = tr.tr_id AND gdc_info_2.gdc_obj_type = 'tr' AND gdc_info_2.gdc_gen_fieldname = 'info_2'"
            . "                 LEFT JOIN genericdatacontainer AS gdc_info_3 ON gdc_info_3.gdc_obj_id = tr.tr_id AND gdc_info_3.gdc_obj_type = 'tr' AND gdc_info_3.gdc_gen_fieldname = 'info_3'"
            . "                 LEFT JOIN genericdatacontainer AS gdc_info_4 ON gdc_info_4.gdc_obj_id = tr.tr_id AND gdc_info_4.gdc_obj_type = 'tr' AND gdc_info_4.gdc_gen_fieldname = 'info_4',"
            . "      costcenter AS csc, customer AS cs, employee AS emp, user AS usr, genericdatacontainer AS gdc_tr_finished"
            . " WHERE (isnull(jb.jb_storno) OR jb.jb_storno = '0' OR jb.jb_storno = '1') AND"
            . "       jb.jb_status IN ('1', '2')                     AND"
            . "       jb.jb_offer = '0'                              AND"
            . "       jb.jb_ordertime >= '" . $jbOrdertimeStart . "' AND"
            . "       jb.csc_id_payer = csc.csc_id                   AND"
            . "       csc.cs_id = cs.cs_id                           AND"
            . "       cs.cs_id = '" . $csId . "'                     AND"
            . "       cs.cs_admin = emp.emp_id                       AND"
            . "       emp.usr_id = usr.usr_id                        AND"
            . "       jb.jb_id = tr.jb_id                            AND"
            . "       tr.tr_finishtime >= '" . $startTime . "'       AND"
            . "       tr.tr_finishtime <= '" . $endTime . "'         AND"
            . "       tr.tr_status = '1'                             AND"
            . "       gdc_tr_finished.gdc_obj_id = tr.tr_id          AND"
            . "       gdc_tr_finished.gdc_obj_type = 'tr'            AND"
            . "       gdc_tr_finished.gdc_gen_fieldname = 'del_code' AND"
            . "       gdc_tr_finished.gdc_content IN ('0','3','6','7','9','10','11','13','15','18')"
            . " ORDER BY tr.jb_id, tr.tr_sort";
// echo $sqlquery . "\n"; die();
// TEST
// . "       jb.jb_ordertime >= '2014-11-23 00:00:00'     AND"
// . "       jb.jb_ordertime <= '2014-11-23 23:59:59'     AND"

  $result = $db->query($sqlquery);
  // $result = $db->query($sqlquery . " UNION " . $sqlquery2);
  if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
  while ($row = $result->fetch_assoc()):
        if ($row["tr_sort"] >= "2" && $row["gdc_context"] != "JOB_EXPORTED") :
           $retArray[$row["tr_id"]]["jb_id"]                   = $row["jb_id"];
           $retArray[$row["tr_id"]]["jb_status"]               = $row["jb_status"];
           $retArray[$row["tr_id"]]["jb_ordertime"]            = $row["jb_ordertime"];
           $retArray[$row["tr_id"]]["jb_finishtime"]           = $row["jb_finishtime"];
           $retArray[$row["tr_id"]]["cr_id"]                   = $row["cr_id"];
           $retArray[$row["tr_id"]]["cr_sid"]                  = $row["cr_sid"];
           $retArray[$row["tr_id"]]["hq_id"]                   = $row["hq_id"];
           $retArray[$row["tr_id"]]["gdc_content"]             = $row["gdc_content"];
           $retArray[$row["tr_id"]]["gdc_context"]             = $row["gdc_context"];
           $retArray[$row["tr_id"]]["gdc_tr_finished_content"] = $row["gdc_tr_finished_content"];
           $retArray[$row["tr_id"]]["gdc_info_0_content"]      = $row["gdc_info_0_content"];
           $retArray[$row["tr_id"]]["gdc_info_1_content"]      = $row["gdc_info_1_content"];
           $retArray[$row["tr_id"]]["gdc_info_2_content"]      = $row["gdc_info_2_content"];
           $retArray[$row["tr_id"]]["gdc_info_3_content"]      = $row["gdc_info_3_content"];
           $retArray[$row["tr_id"]]["gdc_info_4_content"]      = $row["gdc_info_4_content"];
           $retArray[$row["tr_id"]]["tr_id"]                   = $row["tr_id"];
           $retArray[$row["tr_id"]]["tr_sort"]                 = $row["tr_sort"];
           $retArray[$row["tr_id"]]["tr_status"]               = $row["tr_status"];
           $retArray[$row["tr_id"]]["tr_finishtime"]           = $row["tr_finishtime"];
           $retArray[$row["tr_id"]]["tr_commission_no"]        = $row["tr_commission_no"];
           $retArray[$row["tr_id"]]["tr_comp"]                 = $row["tr_comp"];
           $retArray[$row["tr_id"]]["tr_comp2"]                = $row["tr_comp2"];
           $retArray[$row["tr_id"]]["tr_person"]               = $row["tr_person"];
           $retArray[$row["tr_id"]]["tr_phone"]                = $row["tr_phone"];
           $retArray[$row["tr_id"]]["tr_hsno"]                 = $row["tr_hsno"];
           $retArray[$row["tr_id"]]["tr_signname"]             = $row["tr_signname"];
           $retArray[$row["tr_id"]]["tr_sign"]                 = $row["tr_sign"];
           $retArray[$row["tr_id"]]["tr_cs_freetext"]          = $row["tr_cs_freetext"];
           $retArray[$row["tr_id"]]["ad_street"]               = $row["ad_street"];
           $retArray[$row["tr_id"]]["ad_zipcode"]              = $row["ad_zipcode"];
           $retArray[$row["tr_id"]]["ad_city"]                 = $row["ad_city"];
           $retArray[$row["tr_id"]]["trat_packingpieces"]      = $row["trat_packingpieces"];
           $retArray[$row["tr_id"]]["trat_remark"]             = $row["trat_remark"];
           $retArray[$row["tr_id"]]["trat_weight"]             = $row["trat_weight"];
        endif;

        // Define pick up data (address, etc.)
        if ($row["tr_sort"] == "1") :
           $pickUpArray[$row["jb_id"]]["jb_id"]              = $row["jb_id"];
           $pickUpArray[$row["jb_id"]]["jb_status"]          = $row["jb_status"];
           $pickUpArray[$row["jb_id"]]["jb_ordertime"]       = $row["jb_ordertime"];
           $pickUpArray[$row["jb_id"]]["jb_finishtime"]      = $row["jb_finishtime"];
           $pickUpArray[$row["jb_id"]]["cr_id"]              = $row["cr_id"];
           $pickUpArray[$row["jb_id"]]["cr_sid"]             = $row["cr_sid"];
           $pickUpArray[$row["jb_id"]]["hq_id"]              = $row["hq_id"];
           $pickUpArray[$row["jb_id"]]["gdc_content"]        = $row["gdc_content"];
           $pickUpArray[$row["jb_id"]]["gdc_context"]        = $row["gdc_context"];
           $pickUpArray[$row["jb_id"]]["gdc_info_0_content"] = $row["gdc_info_0_content"];
           $pickUpArray[$row["jb_id"]]["gdc_info_1_content"] = $row["gdc_info_1_content"];
           $pickUpArray[$row["jb_id"]]["gdc_info_2_content"] = $row["gdc_info_2_content"];
           $pickUpArray[$row["jb_id"]]["gdc_info_3_content"] = $row["gdc_info_3_content"];
           $pickUpArray[$row["jb_id"]]["gdc_info_4_content"] = $row["gdc_info_4_content"];
           $pickUpArray[$row["jb_id"]]["tr_sort"]            = $row["tr_sort"];
           $pickUpArray[$row["jb_id"]]["tr_status"]          = $row["tr_status"];
           $pickUpArray[$row["jb_id"]]["tr_finishtime"]      = $row["tr_finishtime"];
           $pickUpArray[$row["jb_id"]]["tr_commission_no"]   = $row["tr_commission_no"];
           $pickUpArray[$row["jb_id"]]["tr_comp"]            = $row["tr_comp"];
           $pickUpArray[$row["jb_id"]]["tr_comp2"]           = $row["tr_comp2"];
           $pickUpArray[$row["jb_id"]]["tr_person"]          = $row["tr_person"];
           $pickUpArray[$row["jb_id"]]["tr_phone"]           = $row["tr_phone"];
           $pickUpArray[$row["jb_id"]]["tr_hsno"]            = $row["tr_hsno"];
           $pickUpArray[$row["jb_id"]]["tr_signname"]        = $row["tr_signname"];
           $pickUpArray[$row["jb_id"]]["tr_sign"]            = $row["tr_sign"];
           $pickUpArray[$row["jb_id"]]["tr_cs_freetext"]     = $row["tr_cs_freetext"];
           $pickUpArray[$row["jb_id"]]["ad_street"]          = $row["ad_street"];
           $pickUpArray[$row["jb_id"]]["ad_zipcode"]         = $row["ad_zipcode"];
           $pickUpArray[$row["jb_id"]]["ad_city"]            = $row["ad_city"];
        endif;
  endwhile;
  $result->free();
  return $retArray;
} 


function getStationHTML4PDF ($rowArray, $aKey, $jbId, $csInvAddress) {
	global $absoluteSystemPath, $pickUpArray, $scanMsgArray;

	$retOutput = "";

	if (is_array($rowArray)) :

     // Scan event messages
     $scanMessage = $scanMsgArray[$rowArray["gdc_tr_finished_content"]];
     if ($scanMessage != "") :
        $scanMessage = $rowArray["gdc_tr_finished_content"] . " : " . $scanMessage;
     endif;

     // Generate sign image
     if ($rowArray["tr_sign"] != "") :
        $rawCoord = splitRawCoordinates($rowArray["tr_sign"]);
        $maxCoord = checkMaxCoordinates($rawCoord);
        $tmpSignPath = "/temp/signs/";
        $imgFilename = $aKey .  ".png";
        $im = createSignImage($rawCoord);
        if (!file_exists(".." . $tmpSignPath . $imgFilename)) :
           imagepng($im, ".." . $tmpSignPath . $imgFilename);
        endif;
     endif;

     $tdStyle = " style=\"vertical-align:top\"";
     $retOutput .= "<table border=\"0\" style=\"font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: normal; padding: 1px;\">";

     // TOP
     $retOutput .= "<tr>";
     $retOutput .= "  <td><br><br><br><br><h2>" . getLngt("Abliefernachweis") . "</h2></td>";
     $retOutput .= "  <td align=\"right\" vertical-align=\"middle\"><img src=\"" . $absoluteSystemPath . "/images/external/logo_hansetrans.jpg" . "\" border=\"0\" height=\"49\" width=\"200\"></td>";
     $retOutput .= "</tr>";
     $retOutput .= "<tr>";
     $retOutput .= "  <td colspan=\"2\">____________________________________________________________________________________________________<br><br></td>";
     $retOutput .= "</tr>";
     $retOutput .= "<tr>";
     $retOutput .= "  <td colspan=\"2\"><h3>" . getLngt("Auftrag") . "</h3><br></td>";
     $retOutput .= "</tr>";
     
     $retOutput .= "<tr>";

     // LINKE SEITE
     $retOutput .= "  <td width=\"70%\">";
     $retOutput .= "    <table border=\"0\">";
     // Empfänger
     $retOutput .= "      <tr>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            getLngt("Empfänger") . ":";
     $retOutput .= "        </td>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            $rowArray["tr_comp"] . "<br>" . ($rowArray["tr_cs_freetext"] != "" ? $rowArray["tr_cs_freetext"] : "") . "<br>" . ($rowArray["tr_comp2"] != "" ? $rowArray["tr_comp2"] : "") . "<br>" . ($rowArray["tr_phone"] != "" ? $rowArray["tr_phone"] : "") . "<br>";
     $retOutput .=            $rowArray["ad_street"] . "&nbsp;" . $rowArray["tr_hsno"] . "<br>" . $rowArray["ad_zipcode"] . "&nbsp;" . $rowArray["ad_city"] . "<br><br>";
     $retOutput .= "        </td>";
     $retOutput .= "      </tr>";
     // Anspechpartner
     $retOutput .= "      <tr>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            getLngt("Anspechpartner") . ":&nbsp;&nbsp;";
     $retOutput .= "        </td>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            $rowArray["tr_person"] . "<br><br>";
     $retOutput .= "        </td>";
     $retOutput .= "      </tr>";
     // Absender
     $retOutput .= "      <tr>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            getLngt("Absender") . ":";
     $retOutput .= "        </td>";
     $retOutput .= "        <td" . $tdStyle . ">";
     if (count($csInvAddress) > 0) :
        // Rechnungsadresse
        $retOutput .=         $csInvAddress["comp"] . "<br>" . $csInvAddress["street"] . "&nbsp;" . $csInvAddress["hsno"] . "<br>" . $csInvAddress["zipcode"] . "&nbsp;" . $csInvAddress["city"] . "<br><br>";
     else :
        // Abhol-/Lieferadresse
        $retOutput .=         $pickUpArray[$jbId]["tr_comp"] . "<br>" . $pickUpArray[$jbId]["ad_street"] . "&nbsp;" . $pickUpArray[$jbId]["tr_hsno"] . "<br>" . $pickUpArray[$jbId]["ad_zipcode"] . "&nbsp;" . $pickUpArray[$jbId]["ad_city"] . "<br><br>";
     endif;
     $retOutput .= "        </td>";
     $retOutput .= "      </tr>";
     $retOutput .= "    </table>";
     $retOutput .= "  </td>";

     // RECHTE SEITE
     $retOutput .= "  <td width=\"30%\">";
     $retOutput .= "    <table border=\"0\">";
     // Ladedatum
     $retOutput .= "      <tr>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            getLngt("Datum") . ":";
     $retOutput .= "        </td>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            substr($rowArray["jb_ordertime"],8,2) . "." . substr($rowArray["jb_ordertime"],5,2) . "." . substr($rowArray["jb_ordertime"],0,4) . "<br><br>";
     $retOutput .= "        </td>";
     $retOutput .= "      </tr>";
     // Lieferscheinnr.
     $retOutput .= "      <tr>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            getLngt("Lieferscheinnr.") . ":&nbsp;&nbsp;";
     $retOutput .= "        </td>";
     $retOutput .= "        <td" . $tdStyle . ">";
     // $retOutput .=            $rowArray["tr_commission_no"] . "<br><br>";
     $retOutput .=            $rowArray["gdc_info_2_content"] . "<br><br>";
     $retOutput .= "        </td>";
     $retOutput .= "      </tr>";
     // Auftragsnr.
     $retOutput .= "      <tr>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            getLngt("Auftragsnr.") . ":";
     $retOutput .= "        </td>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            $rowArray["gdc_info_0_content"] . "<br>";
     $retOutput .= "        </td>";
     $retOutput .= "      </tr>";
     // Kundennrnr.
     $retOutput .= "      <tr>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            getLngt("Kundennr.") . ":";
     $retOutput .= "        </td>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            $rowArray["gdc_info_1_content"] . "<br><br><br>";
     $retOutput .= "        </td>";
     $retOutput .= "      </tr>";

     // Pakete
     $retOutput .= "      <tr>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            getLngt("Pakete") . ":";
     $retOutput .= "        </td>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            $rowArray["trat_packingpieces"] . "<br>";
     $retOutput .= "        </td>";
     $retOutput .= "      </tr>";
     // Paletten
     $retOutput .= "      <tr>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            getLngt("Paletten") . ":";
     $retOutput .= "        </td>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            $rowArray["trat_remark"] . "<br>";
     $retOutput .= "        </td>";
     $retOutput .= "      </tr>";
     // Gewicht
     $retOutput .= "      <tr>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            getLngt("Gewicht") . ":";
     $retOutput .= "        </td>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            number_format(round($rowArray["trat_weight"],2), 2, ",", ".") . " kg<br>";
     $retOutput .= "        </td>";
     $retOutput .= "      </tr>";
     // Scan-Event
     $retOutput .= "      <tr>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            getLngt("Scan-Event") . ":";
     $retOutput .= "        </td>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            $scanMessage . "<br><br>";
     $retOutput .= "        </td>";
     $retOutput .= "      </tr>";
     $retOutput .= "    </table>";
     $retOutput .= "  </td>";
     $retOutput .= "</tr>";
     
     // BOTTOM
     $retOutput .= "<tr>";
     $retOutput .= "  <td colspan=\"2\"><h2>" . getLngt("Auslieferung") . "</h2><br><br></td>";
     $retOutput .= "</tr>";
     $retOutput .= "<tr>";
     $retOutput .= "  <td>";
     $retOutput .= "    <table border=\"0\">";
     // Sendungsstatus
     $retOutput .= "      <tr>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            getLngt("Sendungsstatus") . ":&nbsp;&nbsp;";
     $retOutput .= "        </td>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            getLngt("Komplette Auslieferung") . "<br><br>";
     $retOutput .= "        </td>";
     $retOutput .= "      </tr>";
     // Auslieferdatum
     $retOutput .= "      <tr>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            getLngt("Erfolgte am") . ":";
     $retOutput .= "        </td>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            substr($rowArray["tr_finishtime"],8,2) . "." . substr($rowArray["tr_finishtime"],5,2) . "." . substr($rowArray["tr_finishtime"],0,4) . "&nbsp;" . substr($rowArray["tr_finishtime"],11,2) . ":" . substr($rowArray["tr_finishtime"],14,2) . "<br><br>";
     $retOutput .= "        </td>";
     $retOutput .= "      </tr>";
     // Empfänger
     $retOutput .= "      <tr>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            getLngt("Empfänger") . ":";
     $retOutput .= "        </td>";
     $retOutput .= "        <td" . $tdStyle . ">";
     $retOutput .=            ($rowArray["tr_signname"] != "" ? $rowArray["tr_signname"] : getLngt("Keine Klartextangabe")) . "<br><br>";
     $retOutput .= "        </td>";
     $retOutput .= "      </tr>";
     $retOutput .= "    </table>";
     $retOutput .= "  </td>";
     $retOutput .= "</tr>";
     $retOutput .= "<tr>";
     
     // BOTTOM
     // $retOutput .= "<tr>";
     // $retOutput .= "  <td colspan=\"2\"><br><br></td>";
     // $retOutput .= "</tr>";
     // Sign
     $retOutput .= "<tr>";
     $retOutput .= "  <td" . $tdStyle . " height=\"290\" width=\"320\" colspan=\"2\" align=\"right\">";
     $retOutput .= "    <h3>Unterschriftsfeld&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</h3>";
     $retOutput .= "    <table style=\"height: 270px; width: 320px; border:1px solid #000000; padding:10px;\">";
     $retOutput .= "      <tr>";
     $retOutput .= "        <td>";
     $retOutput .= "          <img src=\"" . $absoluteSystemPath . $tmpSignPath . $imgFilename . "\" border=\"0\" height=\"250\" width=\"300\">";
     $retOutput .= "        </td>";
     $retOutput .= "      </tr>";
     $retOutput .= "    </table>";
     $retOutput .= "  </td>";
     $retOutput .= "</tr>";
     
     $retOutput .= "</table>";
	endif;

	return $retOutput;
}


// **** MAIN ****

// Get script name of the requested customer
if ($csId != "" && is_numeric($csId) && $csId > "0") :
   
   // Set execution time for keepalive
   $currentTime = getDateTime("0");
   // updateStmt("keepalive", "ka_process", "autoexport", array("ka_lastexecutiontime", $currentTime),"");

   // Get invoice address of the current customer
   $csInvAddress = getAddress($csId, "costcenteraddress", "2");


   // **************************
   // *** Send automatically ***
   // **************************

   // Check global state of export being active
   $constAutoExportEnabled = getParameterValue("0", "AUTO_EXPORT_ENABLED_LYRECO", "0");
   if ($constAutoExportEnabled == "") :
      $constAutoExportEnabled = "1";
   endif;
 
   // Check remote existence of file "idx.dat". If does exist then do NOT execute export and upload !!!!
   $f_ftp_ssl = "0";
   if ($sendMode == "SFTP") : $f_ftp_ssl = "2"; endif;
   $tmpArray = ftpDir($ftp_server, $ftp_user_name, $ftp_user_pass, $remotePath, "", $f_ftp_ssl);
   $fileNamesRemote = $tmpArray[0];
   $tmpErrNo = $tmpArray[1];
   $tmpErrDesc = $tmpArray[2];
   $fileNamesRemoteLen = count($fileNamesRemote);
   for ($j = 0; $j < $fileNamesRemoteLen; $j++) :
       if ($fileNamesRemote[$j] == "idx.dat") :
          $constAutoExportEnabled = "0";  // Avoid execution because remote data not have been completed !!!!
          writeToFile($logFile, $currentTime . " - ERR: EXPORT ABORTED! REMOTE DATA STILL EXIST!" . " " . $csId);
          writeToFile($logFile, "-------------------------------------------------------------------------------------------------------------------");
          if ($debug) : echo "EXPORT ABORTED! REMOTE DATA STILL EXIST! \n\r"; endif;
       endif;
   endfor;


   // Start export      
   if ($constAutoExportEnabled == '1') :

      $dayExport = getDateTime("1");  // "Ymd"

      $exportFile = $localPath . "idx.dat";
      $exportFileCopy = $localPath . "idx_" . $dayExport . ".bak";

      $jbArr = getDoneJobsOfCustomer($csId);
      $jbkArr = array_keys($jbArr);
      $jbkArrLen = count($jbkArr);

      $pdfFileArray = array();      // Path and PDF filename
      $pdfFileNameArray = array();  // PDF Filename only

      // Remove local files
      $filesToBeRemoved = glob($localPath . "*.pdf");
      foreach($filesToBeRemoved as $fileRemoved) {
        if (is_file($fileRemoved)) :
           unlink($fileRemoved);
        endif;
      }
      // Remove last "idx.dat"
      if (file_exists($exportFile)) :
         unlink($exportFile);
      endif;


      // [1.] Iterate jobs for generating export file
      for ($i = 0; $i < $jbkArrLen; $i++) :

          $aKey = $jbkArr[$i];  // $aKey =!= $trId !!!!
          $trId = $jbArr[$aKey]["tr_id"];
          $jbId = $jbArr[$aKey]["jb_id"];
          $trSort = $jbArr[$aKey]["tr_sort"];

          // The remote order no has to have no "0" at the beginning
          if ($jbArr[$aKey]["gdc_info_0_content"] != "") :
             while (substr($jbArr[$aKey]["gdc_info_0_content"],0,1) == "0"):
                   $jbArr[$aKey]["gdc_info_0_content"] = substr($jbArr[$aKey]["gdc_info_0_content"],1);
             endwhile;
          endif;

          $pdfFileName = "H" . $jbId . pad($trSort, 3);

          $dataArrayToBeExported = array();  // Init row (job data set)
          $dataArrayToBeExported[0] = "l01q";
          $dataArrayToBeExported[1] = "01";
          $dataArrayToBeExported[2] = $pdfFileName . ".pdf";  // Eindeutiger, fortlaufender Name des PDFs durch die Auftragsnummer
          $dataArrayToBeExported[3] = "";
          $dataArrayToBeExported[4] = $jbArr[$aKey]["gdc_info_2_content"];  // Lieferungsnr. Lyreco
          $dataArrayToBeExported[5] = $jbArr[$aKey]["gdc_info_0_content"];  // Auftragsnummer Lyreco
          $dataArrayToBeExported[6] = substr($jbArr[$aKey]["jb_ordertime"],8,2) . "." . substr($jbArr[$aKey]["jb_ordertime"],5,2) . "." . substr($jbArr[$aKey]["jb_ordertime"],0,4);  // Ladedatum
          // $dataArrayToBeExported[7] = $jbArr[$aKey]["gdc_info_1_content"];  // Tour-Nr.
          if ($jbArr[$aKey]["hq_id"] == "106") :
             $dataArrayToBeExported[7] = "000000";
          elseif ($jbArr[$aKey]["hq_id"] == "107") :
             $dataArrayToBeExported[7] = "004500"; 
          elseif ($jbArr[$aKey]["hq_id"] == "110") :
             $dataArrayToBeExported[7] = "009000"; 
          endif;
          // $dataArrayToBeExported[8] = $jbArr[$aKey]["cr_sid"];  // Fahrernummer
          $dataArrayToBeExported[8] = "000000";  // Fahrernummer "Ersatzfahrer"
          $dataArrayToBeExported[9] = "001";  // "000" oder Anzahl der Seiten im PDF
          $dataArrayToBeExported[10] = ($jbArr[$aKey]["tr_sign"] == "" ? "01" : "02");

          $dataToBeExported = "\"" . implode("\";\"", $dataArrayToBeExported) . "\"";

          writeToFile($exportFile, $dataToBeExported . "\r");      // "idx.dat"
          writeToFile($exportFileCopy, $dataToBeExported . "\r");  // Copy "idx_<export_day>.dat"

          // Generate HTML for single Job
          $outputHTML = getStationHTML4PDF($jbArr[$aKey], $aKey, $jbId, $csInvAddress);

          // Write PDF by conversion of HTML
          if ($outputHTML != "") : 
             $fileNameTarget = generatePDF($outputHTML, $jbId, "0", "0", "", "", $localPath, $pdfFileName);
          endif;
          
          $pdfFileNameArray[$i] = $pdfFileName;
          $pdfFileArray[$i] = $fileNameTarget;
      endfor;  // Loop all jobs


      // [2.] Send process
      $pdfFileNameArrayLen = count($pdfFileNameArray);
      $errorOccurred = false;

      if ($sendMode == "FTP" || $sendMode == "SFTP") :
      
         if ($ftp_server != "" && $ftp_user_name != "" && $ftp_user_pass != "") :

            if ($pdfFileNameArrayLen > 0) :

               for ($i = 0; $i < $jbkArrLen; $i++) :

                   $aKey = $jbkArr[$i];  // $aKey =!= $trId !!!!
                   $trId = $jbArr[$aKey]["tr_id"];
                   $jbId = $jbArr[$aKey]["jb_id"];
                   $trSort = $jbArr[$aKey]["tr_sort"];

                   $pdfFileName = "H" . $jbId . pad($trSort, 3);

                   // Take PDF and put to the remote FTP environment
                   $f_ftp_ssl = "0";
                   if ($sendMode == "SFTP") : $f_ftp_ssl = "2"; endif;

                   if ($debug) : 
                      $br = ""; 
                      if (!$isCron) : $br = "<br>"; endif;
                      echo "pdfFileName" . " " . $pdfFileName . ".pdf" . $br . " \n\r";
                   endif;

                   $opArray = ftpUpload($pdfFileName . ".pdf", $pdfFileName . ".pdf", $ftp_server, $ftp_user_name, $ftp_user_pass, $localPath, $remotePath, $f_ftp_ssl);

                   if ($opArray[0] == "0") :
                      $gdcContext = "JOB_EXPORTED";

                      if ($debug) : echo "OK! " . $br . " \n\r"; endif;
                   else :
                      $errorOccurred = true;  // At least one job 
                      $gdcContext = "JOB_NOT_EXPORTED";

                      if ($debug) : echo "ERROR! " . $opArray[0] . " : " . $opArray[1] . $br . " \n\r"; endif;
                   endif;                

                   $gdcEntryExists = false;
                   if ($jbArr[$aKey]["gdc_context"] != "") :
                       $gdcEntryExists = true;
                   endif;

                   if ($gdcEntryExists) :
                      updateStmt("genericdatacontainer","gdc_obj_type","tr",array("gdc_content", $dayExport, "gdc_context", $gdcContext),"gdc_obj_id = '" . $trId . "' AND gdc_gen_fieldname = 'auto_export'");
                   else :
                      insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trId, "gdc_gen_fieldname", "auto_export", "gdc_content", $dayExport, "gdc_context", $gdcContext));
                   endif;

                   writeToFile($logFile, "JB=" . $jbId . "|TR=" . $trId . "|STATE=" . $gdcContext . "|DATETIME=" . $currentTime);

                   if ($debug) : echo $br . "\n\r"; endif;
               endfor;  // Loop all filenames

               // Take index file containing the list of pdf files
               if (!$errorOccurred) :
                  $opArray = ftpUpload("idx.dat", "idx.dat", $ftp_server, $ftp_user_name, $ftp_user_pass, $localPath, $remotePath, $f_ftp_ssl);
                  writeToFile($logFile, "FILE=INDEX|STATE=SENT|DATETIME=" . $currentTime);

                  if ($debug) : echo "idx.dat UPLOADED!" . $br . "\n\r"; endif;
               else :
                  writeToFile($logFile, "FILE=INDEX|STATE=NOT_SENT|DATETIME=" . $currentTime);
                  sendInternalMail("AUTOEXPORT LYRECO FAILED! NO INDEX FILE SENT! [" . $currentTime . "]");

                  if ($debug) : echo "idx.dat NOT UPLOADED!" . $br . "\n\r"; endif;
               endif;
               writeToFile($logFile, "-------------------------------------------------------------------------------------------------------------------");

               if ($f_ftp_ssl == "2") :
                  sftpQuitConnection($connId);
               else :
                  ftpQuitConnection($connId);
               endif;
            endif;
         endif;
         
      elseif ($sendMode == "MAIL") :

         // ...

      endif;

   else :
      writeToFile($logFile, $currentTime . " - ERR: EXPORT DISABLED BY DATABASE PARAMETER!" . " " . $csId);
      writeToFile($logFile, "-------------------------------------------------------------------------------------------------------------------");
      if ($debug) : echo "EXPORT DISABLED BY DATABASE PARAMETER! \n\r"; endif;
   endif;  // AUTO_EXPORT_ENABLED
else :
     writeToFile($logFile, $currentTime . " - ERR: UNKNOWN CUSTOMER!" . " " . $csId);
     writeToFile($logFile, "-------------------------------------------------------------------------------------------------------------------");
endif;


/*

**** PROCEDURE INSERTION OF NEW CUSTOMER ****

[1.] Call special script "../sysadmin/mcInsertObjIntoMetaobjectInstance.php" to insert a new customer in meta objects 

[2.] Insert parameter for customer individual script file name suffix in table "parameter"
     $getIncludeFileNameSuffix = getParameterValue("0", "AUTO_EXPORT_INCLUDE_FILENAME_SUFFIX_CS_" . $csId, "0");

[3.] Add customer call in CRON list

*/
?>
