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


// Error reporting
// error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING & ~E_DEPRECATED);


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;


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

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

// Get the array for formatting the database-values for the output according to the defined type
// $outputFormatField = defineOutputFormats();

$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_PDF", "0");
if ($logFile == "") :
   $logFile = getParameterValue("0", "AUTO_EXPORT_LOGFILE", "0");
   if ($logFile == "") : $logFile = "../log/auto_export.log"; endif;
endif;

// Send mode
// $sendMode = "SFTP";  
$sendMode = "MAIL";

$parMdGlobalShortname = getParameterValue("0", "MD_GLOBAL_SHORTNAME", "0");  // Like "STB", "HTG", "HTM", etc.
if ($parMdGlobalShortname == "") : $parMdGlobalShortname = "ADSG"; endif;

// Special (S)FTP upload location
$ftp_server = getParameterValue("0", "FTP_SERVER_CS_" . $csId, "0");
if ($ftp_server == "") : $ftp_server = getParameterValue("0", "FTP_SERVER_PDF", "0"); endif;
$ftp_user_name = getParameterValue("0", "FTP_USER_CS_" . $csId, "0");
if ($ftp_user_name == "") : $ftp_user_name = getParameterValue("0", "FTP_USER_PDF", "0"); endif;
$ftp_user_pass = getParameterValue("0", "FTP_PASSWORD_CS_" . $csId, "0");
if ($ftp_user_pass == "") : $ftp_user_pass = getParameterValue("0", "FTP_PASSWORD_PDF", "0"); endif;

$localPath = getParameterValue("0", "FTP_LOCALPATH_CS_" . $csId, "0");
if ($localPath == "") : $localPath = getParameterValue("0", "FTP_LOCALPATH_PDF", "0"); endif;
if ($localPath == "") :
   $localPath = "../import/upload/" . $parMdGlobalShortname . "/MISC/PDF/";
endif;
$remotePath = getParameterValue("0", "FTP_REMOTEPATH_CS_" . $csId, "0");
if ($remotePath == "") : $remotePath = getParameterValue("0", "FTP_REMOTEPATH_PDF", "0"); endif;
if ($remotePath == "") : $remotePath = "/"; endif;
// Get subpath especially defined each customer
$remoteSubPath = getParameterValue("0", "FTP_REMOTESUBPATH_PDF_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;
// *********************************************************************


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

  // Exclude jobs with special vehicles (E.g.: Do not generate a mail if internal job is generated with vehicle SID=1888)
  $excludedVehicles = getParameterValue("0", "EMAIL_CRVHSID_NO_MAIL", "0");
  $whereClauseExcludedVehicles = "";
  if ($excludedVehicles != "") :
     $tmp = spliti(",",$excludedVehicles);
     $lenTmp = count($tmp);
     for ($i = 0; $i < $lenTmp; $i++) {  
        $whereClauseExcludedVehicles .= " jb.cr_sid != '" . $tmp[$i] . "' AND ";
     };
  endif;

  $jbExporttimeStart = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'cs' AND gdc_gen_fieldname = 'auto_export_pdf_last_exportdate' AND gdc_obj_id = '" . $csId . "'");
  if ($jbExporttimeStart == "") :
     $jbExporttimeStart = getDateTime("date_firstday_currentmonth_currentyear");
  endif;
// $jbExporttimeStart = "2017-01-18 00:00:00";

  // 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_taketime, jb.jb_finishtime, jb.jb_export_time, "
            . "       usr_cr.usr_name AS cr_usr_name, usr_cr.usr_firstname AS cr_usr_firstname,"
            . "       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, csc_tr.csc_name AS tr_csc_name, cs_tr.cs_eid AS tr_cs_eid, mt.mt_value AS vht_name," 
            . "       trat.trat_packingpieces, trat.trat_remark, trat.trat_weight,"
            . "       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 LEFT JOIN metatype AS mt ON jb.vht_id_real = mt.mt_sort AND mt.mt_type = 'vehicletype'"
            . "                LEFT JOIN courier AS cr ON jb.cr_id = cr.cr_id"
            . "                LEFT JOIN user AS usr_cr ON cr.usr_id = usr_cr.usr_id,"
            . "      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 costcenter AS csc_tr ON tr.csc_id = csc_tr.csc_id"
            . "                 LEFT JOIN customer AS cs_tr ON cs_tr.cs_id = csc_tr.cs_id"
            . "                 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'"
            . "                 LEFT JOIN genericdatacontainer AS gdc_tr_finished ON 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',"
            . "      costcenter AS csc, customer AS cs, employee AS emp, user AS usr"
            . " WHERE (ISNULL(jb.jb_storno) OR jb.jb_storno = '0')      AND"
            . "       jb.jb_status = '2'                                AND"
            . "       jb.jb_export_time > '" . $jbExporttimeStart . "'  AND"
            .         $whereClauseExcludedVehicles
            . "       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                                  "
            . " ORDER BY tr.jb_id, tr.tr_sort";

// ????     . " jb.jb_automailsent != '997' AND jb.jb_automailsent != '998' AND jb.jb_automailsent != '999' AND"
// ????     . " tr.tr_sort = '1' AND tr.tr_status = '1' AND"
// $sqlquery .= " LIMIT 0,6";
// echo $sqlquery . "\n"; die();

  $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") :
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["jb_id"]                   = $row["jb_id"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["jb_status"]               = $row["jb_status"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["jb_ordertime"]            = $row["jb_ordertime"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["jb_taketime"]             = $row["jb_taketime"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["jb_finishtime"]           = $row["jb_finishtime"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["jb_export_time"]          = $row["jb_export_time"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["cr_id"]                   = $row["cr_id"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["cr_sid"]                  = $row["cr_sid"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["vht_name"]                = $row["vht_name"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["cr_usr_name"]             = $row["cr_usr_name"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["cr_usr_firstname"]        = $row["cr_usr_firstname"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["hq_id"]                   = $row["hq_id"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["gdc_content"]             = $row["gdc_content"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["gdc_context"]             = $row["gdc_context"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["gdc_tr_finished_content"] = $row["gdc_tr_finished_content"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["gdc_info_0_content"]      = $row["gdc_info_0_content"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["gdc_info_1_content"]      = $row["gdc_info_1_content"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["gdc_info_2_content"]      = $row["gdc_info_2_content"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["gdc_info_3_content"]      = $row["gdc_info_3_content"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["gdc_info_4_content"]      = $row["gdc_info_4_content"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["tr_id"]                   = $row["tr_id"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["tr_sort"]                 = $row["tr_sort"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["tr_status"]               = $row["tr_status"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["tr_finishtime"]           = $row["tr_finishtime"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["tr_commission_no"]        = $row["tr_commission_no"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["tr_comp"]                 = $row["tr_comp"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["tr_comp2"]                = $row["tr_comp2"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["tr_person"]               = $row["tr_person"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["tr_phone"]                = $row["tr_phone"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["tr_hsno"]                 = $row["tr_hsno"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["tr_signname"]             = $row["tr_signname"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["tr_sign"]                 = $row["tr_sign"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["tr_cs_freetext"]          = $row["tr_cs_freetext"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["tr_csc_name"]             = $row["tr_csc_name"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["tr_cs_eid"]               = $row["tr_cs_eid"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["ad_street"]               = $row["ad_street"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["ad_zipcode"]              = $row["ad_zipcode"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["ad_city"]                 = $row["ad_city"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["trat_packingpieces"]      = $row["trat_packingpieces"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["trat_remark"]             = $row["trat_remark"];
           $data[$row["jb_id"] . "_" . $row["tr_sort"]]["trat_weight"]             = $row["trat_weight"];
        // endif;
  endwhile;
  $result->free();
  // return $data;  // is global
} 


function getJobHTML4PDF ($jbId, $maxTrSort) {
	global $absoluteSystemPath, $data;

	$retOutput = "";

	if (is_array($data) && is_numeric($maxTrSort) && $maxTrSort >= 1) :

     $tdStyle = " style=\"vertical-align:top\"";
     $numOfJobCols = 4;
     $numOfChars = 24;

     // Define index for associative job array
     $aKey = $jbId . "_1";

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

     // Job         
     $retOutput .= "<tr>";
     $retOutput .= "  <td colspan=\"4\"><h3>" . getLngt("Auftrag") . " : " . $jbId . "</h3></td>";
     $retOutput .= "</tr>";

     // Courier
     $retOutput .= "<tr>";
     $retOutput .= "  <td style=\"width:90px\">" . getLngt("Fahrzeug") . ":"  . "</td>";
     $retOutput .= "  <td style=\"width:200px\">" . $data[$aKey]["vht_name"] . "</td>";
     $retOutput .= "  <td style=\"width:70px\">" . getLngt("Name") . ":"  . "</td>";
     $retOutput .= "  <td style=\"width:200px\">" . $data[$aKey]["cr_usr_name"] . "</td>";
     $retOutput .= "</tr>";
     $retOutput .= "<tr>";
     $retOutput .= "  <td>" . getLngt("Auftragszeit") . ":"  . "</td>";
     $retOutput .= "  <td>" . formatOutput($data[$aKey]["jb_ordertime"], "datetime", 1) . "</td>";
     $retOutput .= "  <td>" . getLngt("Vorname") . ":"  . "</td>";
     $retOutput .= "  <td>" . $data[$aKey]["cr_usr_firstname"] . "</td>";
     $retOutput .= "</tr>";
     $retOutput .= "<tr>";
     $retOutput .= "  <td>" . getLngt("Annahme") . "</td>";
     $retOutput .= "  <td>" . formatOutput($data[$aKey]["jb_taketime"], "datetime", 1) . "</td>";
     $retOutput .= "  <td>" . getLngt("SID") . "</td>";
     $retOutput .= "  <td>" . $data[$aKey]["cr_sid"] . ":"  . "</td>";
     $retOutput .= "</tr>";
     $retOutput .= "<tr>";
     $retOutput .= "  <td>" . getLngt("Erledigung") . ":"  . "</td>";
     $retOutput .= "  <td>" . formatOutput($data[$aKey]["jb_finishtime"], "datetime", 1) . "</td>";
     $retOutput .= "  <td>" . "</td>";
     $retOutput .= "  <td>" . "</td>";
     $retOutput .= "</tr>";
     
     $retOutput .= "</table>";
     $retOutput .= "</br>";


     // Tour
     $fieldNames = array(getLngt("Empfänger"), getLngt("Zusatz"), getLngt("Person"), getLngt("Straße, Hausnr."), getLngt("PLZ, Ort"), getLngt("EID"), getLngt("Kostenstelle"), getLngt("Tel."), getLngt("Kommissionsnr."), getLngt("Erledigungszeit"), getLngt("Klartext"), getLngt("Unterschrift"));
     $fieldValues = array("tr_comp", "tr_comp2", "tr_person", "ad_street_hsno", "ad_zipcode_city", "tr_cs_eid", "tr_csc_name", "tr_phone", "tr_commission_no", "tr_finishtime", "tr_signname", "tr_sign");
     $fieldsLen = count($fieldValues);
     
     $retOutput .= "<table border=\"0\" style=\"font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: normal; padding: 1px;\">";
     
     for ($i = 1; $i <= $maxTrSort; $i+=$numOfJobCols) :

         for ($f = 0; $f < $fieldsLen; $f++) :

             $retOutput .= "<tr>";
             $retOutput .= "<td>" . $fieldNames[$f] . ":" . "</td>";
             for ($j = $i; $j < ($i + $numOfJobCols); $j++) :

                 if ($j <= $maxTrSort) :

                    // Define index for associative job array
                    $aKey = $jbId . "_" . $j;

                    // Clean up fields
                    if ($data[$aKey]["tr_comp"] == ".") : 
                       $data[$aKey]["tr_comp"] = "";
                    endif;
                    if ($data[$aKey]["tr_phone"] == "0") : 
                       $data[$aKey]["tr_phone"] = "";
                    endif;
                    if (strtolower($data[$aKey]["tr_csc_name"]) == "extern") : 
                       $data[$aKey]["tr_csc_name"] = "";
                       $data[$aKey]["tr_cs_eid"] = "";
                    endif;
                    

                    // Generate sign image
                    if ($fieldValues[$f] == "tr_sign") :
                       if ($data[$aKey]["tr_sign"] != "") :
                          $rawCoord = splitRawCoordinates($data[$aKey]["tr_sign"]);
                          $maxCoord = checkMaxCoordinates($rawCoord);
                          $tmpSignPath = "/temp/signs/";
                          $imgFilename = $aKey .  ".png";
                          $im = createSignImage($rawCoord);
                          if (!file_exists(".." . $tmpSignPath . $imgFilename)) :
                             imagepng($im, ".." . $tmpSignPath . $imgFilename);
                          endif;
                          $retOutput .= "<td>" . "<img src=\"" . $absoluteSystemPath . $tmpSignPath . $imgFilename . "\" border=\"0\" height=\"75\" width=\"90\">" . "</td>";
                       else :
                          $retOutput .= "<td>&nbsp;</td>";
                       endif;
                    elseif ($fieldValues[$f] == "tr_finishtime") :
                       $retOutput .= "<td>" . formatOutput($data[$aKey]["tr_finishtime"], "datetime", 1) . "</td>";
                    elseif ($fieldValues[$f] == "ad_street_hsno") :
                       $retOutput .= "<td>" . substr($data[$aKey]["ad_street"],0,($numOfChars - 10)) . "&nbsp;" . $data[$aKey]["tr_hsno"] . "</td>";
                    elseif ($fieldValues[$f] == "ad_zipcode_city") :
                       $retOutput .= "<td>" . $data[$aKey]["ad_zipcode"] . "&nbsp;" . substr($data[$aKey]["ad_city"],0,($numOfChars - 6)) . "</td>";
                    else :
                       $retOutput .= "<td>" . substr($data[$aKey][$fieldValues[$f]],0,$numOfChars) . "</td>";
                    endif;
                 endif;
             endfor;
             $retOutput .= "</tr>";
         endfor;
     endfor;

     $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");
   $currentDate = getDateTime("1");

   $csEid = getFieldValueFromId("customer","cs_id",$csId,"cs_eid");

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

   // Check global state of export being active
   $constAutoExportEnabled = getParameterValue("0", "AUTO_EXPORT_ENABLED_PDF", "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 == "FTP" || $sendMode == "SFTP") :
      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;
   endif;


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

      $idxDatFile = "idx_" . $csEid . "_" . $currentDate . ".dat";
      $exportFile = $localPath . $idxDatFile;
      $exportFileLog = $localPath . "idx_" . $currentDate . ".log";

      getDoneJobsOfCustomer($csId);
      $jbkArr = array_keys($data);  // Index: "jobId_trSort"
      $jbkArrLen = count($jbkArr);

      $pdfFileName = $csEid . "_" . $currentDate;

      // Remove local files
      $filesToBeRemoved = glob($localPath . $csEid . "*.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
      $outputHTML = "";
      $remJbId = "";
      $maxExportTime = "";
      for ($i = 0; $i < $jbkArrLen; $i++) :

          $aKey = $jbkArr[$i];  // $aKey <=> "jobId_trSort"
          $jbId = $data[$aKey]["jb_id"];
          $trSort = $data[$aKey]["tr_sort"];
          $trId = $data[$aKey]["tr_id"];
          $maxTrSort = getMaxOfField("tour", "tr_sort", "jb_id = '" . $jbId . "'");
          if ($maxExportTime == "" || $data[$aKey]["jb_export_time"] > $maxExportTime) :
             $maxExportTime = $data[$aKey]["jb_export_time"];
          endif;

          $dataArrayToBeExported = array();  // Init row (job data set)
          $dataArrayToBeExported[0] = $csEid;
          $dataArrayToBeExported[1] = $jbId;
          $dataArrayToBeExported[2] = $trSort;
          $dataArrayToBeExported[3] = $data[$aKey]["tr_comp"];
          $dataArrayToBeExported[4] = $data[$aKey]["tr_comp2"];
          $dataArrayToBeExported[5] = substr($data[$aKey]["tr_finishtime"],8,2) . "." . substr($data[$aKey]["tr_finishtime"],5,2) . "." . substr($data[$aKey]["tr_finishtime"],0,4);  // Stationserledigung
          $dataArrayToBeExported[6] = $data[$aKey]["tr_commission_no"];

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

          // Generate HTML for single Job
          if ($remJbId != $jbId) :
             $remJbId = $jbId;
             $outputHTML .= getJobHTML4PDF($jbId, $maxTrSort);
          endif;

          writeToFile($exportFile, $dataToBeExported . "\r");      // "idx_<cs_eid>_<export_day>.dat"
          writeToFile($exportFileLog, $dataToBeExported . "\r");  // Log: "idx_<export_day>.log"
      endfor;  // Loop all jobs


      // Write PDF by conversion of HTML
      if ($outputHTML != "") : 

         // Customer
         $tmpOutput = "<table border=\"0\" style=\"font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: normal; padding: 1px;\">";
         $tmpOutput .= "<tr>";
         $tmpOutput .= "  <td><h2>" . getLngt("Kunde") . " : " . $csEid . "</h2></br></td>";
         $tmpOutput .= "</tr>";           
         $tmpOutput .= "</table>";
         
         $outputHTML = $tmpOutput . $outputHTML;
      
         $fileNameTarget = generatePDF($outputHTML, $jbId, "0", "0", "", "", $localPath, $pdfFileName);
      endif;


      // [2.] Send process
      $errorOccurred = false;

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

            if ($pdfFileName != "" && $fileNameTarget != "") :

               // 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") :
                  if (existsEntry("genericdatacontainer",array("gdc_obj_type","cs","gdc_obj_id",$csId,"gdc_gen_fieldname","auto_export_pdf_last_exportdate"))) :
                     updateStmt("genericdatacontainer","gdc_obj_type","cs",array("gdc_content", $maxExportTime, "gdc_context", ""),"gdc_obj_id = '" . $csId . "' AND gdc_gen_fieldname = 'auto_export_pdf_last_exportdate'");
                  else :
                     insertStmt("genericdatacontainer", array("gdc_obj_type", "cs", "gdc_obj_id", $csId, "gdc_gen_fieldname", "auto_export_pdf_last_exportdate", "gdc_content", $maxExportTime, "gdc_context", ""));
                  endif;
                  writeToFile($logFile, $currentTime . " (S)FTP PROCESS OK!" . " " . $csId);
                  writeToFile($logFile, "-------------------------------------------------------------------------------------------------------------------");
                  if ($debug) : echo " - OK! " . $br . " \n\r"; endif;
               else :
                  $errorOccurred = true;
                  writeToFile($logFile, $currentTime . " - ERR: (S)FTP PROCESS FAILED!" . " " . $csId);
                  writeToFile($logFile, "-------------------------------------------------------------------------------------------------------------------");
                  if ($debug) : echo " - ERR: " . $opArray[0] . " : " . $opArray[1] . $br . " \n\r"; endif;
               endif;                

               // writeToFile($logFile, "JB=" . $jbId . "|TR=" . $trId . "|STATE=" . $gdcContext . "|DATETIME=" . $currentTime);
               if ($debug) : echo $br . "\n\r"; endif;

               // Take index file containing the list of pdf files
               if (!$errorOccurred) :
                  $opArray = ftpUpload($idxDatFile, $idxDatFile, $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 PDF 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") :
         
         if ($pdfFileName != "" && $fileNameTarget != "") :
         
            // Get mail receiver adress(es)
            $csHqId = getFieldValueFromId("customer","cs_id",$csId,"hq_id");
            $csJbStatusMail2Csc = getFieldValueFromId("customer","cs_id",$csId,"cs_jbstatusmail2csc");
            if ($csJbStatusMail2Csc == "1") :
               $cscIdRoot = getFieldValueFromId("customer","cs_id",$csId,"csc_id");
               $mailToAddresses = getFieldValueFromClause("costcenteraddress", "cscad_email", "csc_id = '" . $cscIdRoot . "' AND adt_id  = '2'");
               if ($mailToAddresses == "" || !checkEmailFormat($mailToAddresses)) :
                  $csJbStatusMail2Csc = "0";
               endif;
            endif;
            if ($csJbStatusMail2Csc != "1") :
               $csAdmin = getFieldValueFromId("customer","cs_id",$csId,"cs_admin");
               $csUsrId = getFieldValueFromId("employee","emp_id",$csAdmin,"usr_id");
               $mailToAddresses = getFieldValueFromId("user","usr_id",$csUsrId,"usr_email");
            endif;

            // Take email address stored to costcenter (invoice address) if activated
            if ($f_email_csc != "" && $takeCscMailAdress == "1") :
               $f_email = $f_email_csc;
            endif;         

            if ($mailSenderAddress == "") :
               $mailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $csHqId);
               if ($mailSenderAddress == "") : $mailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", "0"); endif;
            endif;

            if ($mailAttachedFileType == "") : $mailAttachedFileType = "pdf"; endif;
            if ($pageTitel == "") : $pageTitel = $currentTime; endif;

            $mailSubject = getLngt("Transportaufträge für die Kundenr.") . " " . $csEid;
            $mailText = getLngt("Transportaufträge für die Kundenr.") . " " . $csEid;

            $mailObj = new htmlMimeMail();
            $mailObj->setFrom($mailSenderAddress);
            if ($mailCcAddresses != "") :
               $mailObj->setCc($mailCcAddresses);
            endif;
            if ($mailBccAddresses != "") :
               $mailObj->setBcc($mailBccAddresses);
            endif;
            $mailObj->setSubject($mailSubject);

            // Mail content
            // $mailObj->setHtml($htmlOut, null, "./");
            $mailObj->setText($mailText);

            // Attachment
            if (file_exists($fileNameTarget)) :
               $attachment = $mailObj->getFile($fileNameTarget);
               if ($mailAttachedFileType == "pdf") :
                  $mailObj->addAttachment($attachment, $pageTitel . "." . $mailAttachedFileType, 'application/pdf');
            // elseif ($mailAttachedFileType == "ps") :
            //    $mailObj->addAttachment($attachment, $pageTitel, 'application/????');
               else :
                  $mailObj->addAttachment($attachment, $pageTitel . "." . $mailAttachedFileType, 'application/pdf');
               endif;
            endif;
// echo $mailToAddresses . "\n";
// $mailToAddresses = "mv@assecutor.de";
// $mailToAddresses = "peter.karstens@stadtbote.de,admin@assecutor.de";
            // $writeToLogfile = true;
            $mailResult = false;
            if ($mailToAddresses != "" && checkEmailFormat($mailToAddresses)) :
               $mailResult = $mailObj->send(array($mailToAddresses), 'smtp');
            endif;

            if ($mailResult) :
               if (existsEntry("genericdatacontainer",array("gdc_obj_type","cs","gdc_obj_id",$csId,"gdc_gen_fieldname","auto_export_pdf_last_exportdate"))) :
                  updateStmt("genericdatacontainer","gdc_obj_type","cs",array("gdc_content", $maxExportTime, "gdc_context", $mailToAddresses),"gdc_obj_id = '" . $csId . "' AND gdc_gen_fieldname = 'auto_export_pdf_last_exportdate'");
               else :
                  insertStmt("genericdatacontainer", array("gdc_obj_type", "cs", "gdc_obj_id", $csId, "gdc_gen_fieldname", "auto_export_pdf_last_exportdate", "gdc_content", $maxExportTime, "gdc_context", $mailToAddresses));
               endif;
               if ($debug) : echo " - MAIL PROCESS OK! \n\r"; endif;
            else :
               writeToFile($logFile, $currentTime . " - ERR: MAIL PROCESS FAILED!" . " " . $csId);
               writeToFile($logFile, "-------------------------------------------------------------------------------------------------------------------");
               // sendInternalMail("AUTOEXPORT PDF_MAIL FAILED! [" . $csId . "][" . $csEid . "][" . $currentTime . "][" . $mailToAddresses . "]");
               if ($debug) : echo "MAIL PROCESS FAILED! \n\r"; endif;
            endif;
            $mailObj = NULL;
         endif;
      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

*/
?>
