<?php
/*=======================================================================
 *
 * inc_tracking.inc.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/


include_once ('../include/mcglobal.inc.php');
include_once ('../include/email/htmlMimeMail.php');
include_once ('../include/inc_job.inc.php');
include_once ('../include/inc_customer.inc.php');


// Gets all data important for tracking [Called by tracking request, used by broker functionality!]
function getTrackingdataByID ($trackingID) {
	global $db, $db_conn, $PHP_SELF, $debug;
	global $dbInst, $dbname, $dblogin, $dbpassword;
	global $jobData;

  $trackingArray = array();
  if ($trackingID != "") :
  
     // Get connection to meta object instance
     $dbMetaObjConn = getConnectionToMetaDB();
  
     // Check existence of the hash value in table "metatracking"
     $mtrId = getFieldValueFromId("meta_object.metatracking", "mtr_hash", $trackingID, "mtr_id", $dbMetaObjConn);
     if ($debug) :
        echo "trackingID: " . $trackingID . "<br>";
        echo "mtrId: " . $mtrId . "<br>";
     endif;

     if ($mtrId != "" && $mtrId > "0") :

        $moIdRefDB = getFieldValueFromId("meta_object.metatracking", "mtr_id", $mtrId, "mo_id_ref_db", $dbMetaObjConn);
        $objType   = getFieldValueFromId("meta_object.metatracking", "mtr_id", $mtrId, "mtr_obj_type", $dbMetaObjConn);
        $objId     = getFieldValueFromId("meta_object.metatracking", "mtr_id", $mtrId, "mtr_obj_id", $dbMetaObjConn);
        $mtrValue  = getFieldValueFromId("meta_object.metatracking", "mtr_id", $mtrId, "mtr_value", $dbMetaObjConn);

        if ($debug) :
           echo "moIdRefDB: " . $moIdRefDB . "<br>";
           echo "objType: " . $objType . "<br>";
           echo "objId: " . $objId . "<br>";
           echo "mtrValue: " . $mtrValue . "<br>";
        endif;

        if ($moIdRefDB != "" && $moIdRefDB > "0") :

           // Get database instance from table "metaobject"
           $dbInst = getFieldValueFromId("meta_object.metaobject", "mo_id", $moIdRefDB, "mo_value", $dbMetaObjConn);
  
           if ($debug) :
              echo "dbInst: " . $dbInst . "<br>";
           endif;

           if ($dbInst != "") :

              // Get database connection
              $db_conn = getDbConnectionSpecial($dbInst, $dbname, $dblogin, $dbpassword);

              if (substr($objType, 0, 5) == "track") :    // Could be "tracking_trat" [= "tracking" = "track"] (tourarticle/package barcode), "tracking_tr" (station), "tracking_jb" (order), ...

                 // Charset
                 $result = $db_conn->query("SET NAMES LATIN1");
                 if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

                 $fieldClause = "jb.jb_id, jb.hq_id, jb.jb_ordertime, jb.jb_taketime, jb.jb_finishtime, jb.jb_export_time, jb.csc_id_payer,"
                              . "cr.cr_sid, cr.cr_gps_long, cr.cr_gps_lat, cr.cr_gps_time, cr.cr_gps_type,"
                              . "trat.trat_id, trat.trat_name, trat.trat_quantity,"
                              . "trat.trat_packingpieces, trat.trat_serialno, trat.trat_state, trat.trat_remark,"
                              . "tratp.tratp_id, tratp.tratp_no, tratp.tratp_event, tratp.tratp_type, tratp.tratp_state,"
                              . "tratp.tratp_quantity, tratp.tratp_packingpieces, tratp.tratp_remark, tratp.tratp_createtime,"
                              . "mt.mt_value, tr.tr_id, tr.tr_sort, tr.tr_comp, tr.tr_comp2, tr.tr_signname, tr.tr_sign,"
                              . "tr.tr_hsno, tr.tr_person, tr.tr_status, tr.tr_finishtime,"
                              . "ad.ad_street, ad.ad_zipcode, ad.ad_city, ad.ad_country";

                 $fromClause = "FROM phoenix.job AS jb LEFT JOIN phoenix.courier AS cr ON jb.cr_id = cr.cr_id,"
                             . "     phoenix.tour AS tr LEFT JOIN phoenix.address AS ad ON tr.ad_id = ad.ad_id"
                             . "                        LEFT JOIN phoenix.tourarticle AS trat ON tr.tr_id = trat.tr_id"
                             . "                        LEFT JOIN phoenix.tourarticleprocess AS tratp ON trat.trat_id = tratp.trat_id"
                             . "                        LEFT JOIN phoenix.metatype AS mt ON tratp.tratp_event = mt.mt_sort AND mt.mt_type = 'tracking_event'";

                 if ($objType == "tracking_jb" || $objType == "track_jb") :

                    $sqlquery = "SELECT " . $fieldClause . " " . $fromClause
                              . "  WHERE jb.jb_id = '" . $objId . "'          AND"
                              . "        jb.jb_id = tr.jb_id                     "
                              . "  ORDER BY jb.jb_id, tr.tr_sort";


                 elseif ($objType == "tracking_tr" || $objType == "track_tr") :

                    $sqlquery = "SELECT " . $fieldClause . " " . $fromClause
                              . "  WHERE jb.jb_id = tr.jb_id                  AND"
                              . "        tr.tr_id = '" . $objId . "'             "
                              . "  ORDER BY jb.jb_id, tr.tr_sort";

                 elseif ($objType == "tracking_trat" || $objType == "track_trat") :

                    // Check barcode does exists
                    if ($mtrValue != "" && $mtrValue != $objId) :
                                        
                       $sqlquery = "SELECT " . $fieldClause . " " . $fromClause
                                 . "  WHERE jb.jb_id = tr.jb_id                  AND"
                                 . "        tr.tr_id = trat.tr_id                AND"
                                 . "        CONCAT(trat.trat_int_serialno,trat.trat_serialno) = '" . $mtrValue . "' AND"
                                 . "        trat.trat_id = tratp.trat_id         AND"
                                 . "        (NOT ISNULL(tratp.tratp_createtime))    "
                                 . "  ORDER BY tratp.tratp_createtime";

                    else :

                       $sqlquery = "SELECT " . $fieldClause . " " . $fromClause
                                 . "  WHERE jb.jb_id = tr.jb_id                  AND"
                                 . "        tr.tr_id = trat.tr_id                AND"
                                 . "        trat.trat_id = '" . $objId . "'      AND"
                                 . "        trat.trat_id = tratp.trat_id         AND"
                                 . "        (NOT ISNULL(tratp.tratp_createtime))    "
                                 . "  ORDER BY tratp.tratp_createtime";
                    endif;
                 endif;


                 if ($debug) :
                    echo "<br>sqlquery: " . $sqlquery . "<br><br>";
                 endif;

                 $result = $db_conn->query($sqlquery);
                 if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

                 while ($row = $result->fetch_assoc()):
                       $trackingArray[] = $row;
                 endwhile;
                 $result->free();
              else :
                    // Write logdata into log database
                    // writeToLogDB("97",$hqId,"","","","",$objId,"STATUS=OBJTYPE_NOT_FOUND|IP=" . $currentClientIP . "|MO_ID" . $moId);
              endif;
           else :
              // database not specified in metaobject row
              // writeToLogDB("97","","","","","","","STATUS=DB_NOT_SPECIFIED|IP=" . $currentClientIP . "|MO_ID" . $moId);
           endif;
        else :
           // HASH nicht gefunden um Zuordnung herzustellen
        endif;
     endif;
  else :
     // Write logdata into log database
     // writeToLogDB("97","","","","","","","STATUS=EMPTY_OPCODE|IP=" . $currentClientIP . "|MO_ID" . $moId);
  endif;
  return array($objType, $trackingArray);
}


// Inserts ONE tracking item into "metatracking"
function insertMetaTrackingItem ($moIdRefDB, $objType, $objId, $mtrValue = "") {
	global $db, $db_conn, $PHP_SELF, $debug;
	global $dbname, $dblogin, $dbpassword;

	$retArray = array("001","<err_no>001</err_no>\n","<err_desc>" . getLngt("Eintrag in Broker fehlgeschlagen!") . "</err_desc>\n");  // Init only
  if ($moIdRefDB != "" && is_numeric($moIdRefDB)) :

	   if ($objType != "" && substr($objType, 0, 5) == "track") :

	      if ($objId != "" && is_numeric($objId)) :

           // Get database instance connection of "metatracking"
           $db_conn_mtr = getConnectionToMetaDB();
           // $constExtDbInst = getExternalMetaDbInst();
           // $db_conn_mtr = getDbConnectionSpecial($constExtDbInst, $dbname, $dblogin, $dbpassword);

           // Check entry for existence
           // $tmpMtrId = $db_conn_mtr->getOne("SELECT mtr_id FROM meta_object.metatracking WHERE mtr_hash = '" . $mtrHash . "'");
           $tmpMtrId = $db_conn_mtr->getOne("SELECT mtr_id FROM meta_object.metatracking WHERE mo_id_ref_db = '" . $moIdRefDB . "' AND mtr_obj_type = '" . $objType . "' AND mtr_obj_id = '" . $objId . "'");

           if ($tmpMtrId == "") :

             $currentTime = getDateTime("0");
           
             // Generate hash value
     	       $md5Str = $currentTime . $moIdRefDB . $objType . $objId;
     	       if ($mtrValue == "") : $mtrValue = $objId; endif;
              if ($debug) :
                 echo "md5Str: " . $md5Str . "<br>";
                 echo "mtrValue: " . $mtrValue . "<br>";
              endif;

              // Generate unique hash value
              $mtrHash = md5($md5Str);
              if ($debug) :
                 echo "mtrHash: " . $mtrHash . "<br>";
              endif;
       
              $tmpSqlQuery = "INSERT meta_object.metatracking (mo_id_ref_db,mtr_obj_type,mtr_obj_id,mtr_hash,mtr_value) VALUES ('" . $moIdRefDB . "','" . $objType . "','" . $objId . "','" . $mtrHash . "','" . $mtrValue . "') ";
              $result = $db_conn_mtr->query($tmpSqlQuery);
              if (DB::isError($result)) {$err = "ERR";};
              if ($err == "ERR") :
                 $retArray = array("007","<err_no>007</err_no>\n","<err_desc>" . getLngt("Der Tracking-Datensatz konnte nicht angelegt werden!") . "</err_desc>\n");
                 // Send info mail
                 sendInternalMail("INSERT_INTO_METAOBJECT_FAILED: MO_ID_REF_DB=" . $moIdRefDB . "|OBJ_TYPE=" . $objType . "|OBJ_ID=" . $objId);
              else :
                 // Success
                 $mtrIdNew  = $db_conn_mtr->getOne("SELECT LAST_INSERT_ID()");
                 if ($debug) :
                    echo "mtrIdNew: " . $mtrIdNew . "<br>";
                 endif;
                 // $retArray = array("0", $mtrHash, $mtrValue);
                 $retArray = array("0", $objType, $objId, $mtrHash, $mtrValue);
              endif;
           else :
              // $retArray = array("005","<err_no>006</err_no>\n","<err_desc>" . getLngt("Der Eintrag (HASH) existiert schon!") . "</err_desc>\n");
              // NO PROBLEM, because different barcodes or tourarticle IDs have the same job_ID e.g. !!!!
              $mtrHash = getFieldValueFromId("meta_object.metatracking","mtr_id",$tmpMtrId,"mtr_hash",$db_conn_mtr);
              $mtrValue = getFieldValueFromId("meta_object.metatracking","mtr_id",$tmpMtrId,"mtr_value",$db_conn_mtr);                 
              $retArray = array("0", $objType, $objId, $mtrHash, $mtrValue);
           endif;
        else :
           $retArray = array("004","<err_no>004</err_no>\n","<err_desc>" . getLngt("Keine Angabe der Objekt-ID!") . "</err_desc>\n");
        endif;
     else :
        $retArray = array("003","<err_no>003</err_no>\n","<err_desc>" . getLngt("Keine Angabe des Objekttyps!") . "</err_desc>\n");
     endif;
  else :
     $retArray = array("002","<err_no>002</err_no>\n","<err_desc>" . getLngt("Keine Angabe der Referenzdatenbank!") . "</err_desc>\n");
	endif;
	return $retArray;
}


// Inserts ALL possible tracking items into "metatracking" (executed in operational database and used e.g. "order_request", etc.)
// Returns array of arrays with inserted (or existing) entries ($objectType, $objectId, $hash[, $barcode])
function insertTrackingItems ($jbId, $trId = "", $tratId = "", $internalBarcode = "", $barcode = "", $mode = "ALL") {
  // $retArray = array("999","<err_no>001</err_no>\n","<err_desc>" . getLngt("Globale Instanznummer existiert nicht!") . "</err_desc>\n");  // Init only
  $retArray = array();

  // Get mo_id (cust_id) from current operational database
  $moIdRefDB = getParameterValue("0", "GLOBAL_UNIQUE_DB_INSTANCE_NO", "0");
  if ($moIdRefDB != "" && is_numeric($moIdRefDB)) :

     if (($tratId == "" || !is_numeric($tratId) || $tratId <= 0) && ($mode == "SINGLE_TRAT" || $mode == "ALL")) :
        if ($internalBarcode != "" && $barcode != "") :
           $tratId = getFieldValueFromClause("tourarticle","trat_id","trat_int_serialno = '" . $internalBarcode . "' AND trat_serialno = '" . $barcode . "'", $dbConnection);
        endif;
     endif;
     if (($trId == "" || !is_numeric($trId) || $trId <= 0) && ($mode == "SINGLE_TR" || $mode == "ALL")) :
        if ($tratId != "" && is_numeric($tratId) && $tratId > 0) :
           $trId = getFieldValueFromId("tourarticle","trat_id",$tratId,"tr_id");
        endif;
     endif;
     if (($jbId == "" || !is_numeric($jbId) && $jbId <= 0) && ($mode == "SINGLE_JB" || $mode == "ALL")) :
        if ($trId != "" && is_numeric($trId) && $trId > 0) :
           $jbId = getFieldValueFromId("tour","tr_id",$trId,"jb_id");
        endif;
     endif;

     if ($jbId != "" && ($mode == "SINGLE_JB" || $mode == "ALL")) :
	      $tmpArray = insertMetaTrackingItem($moIdRefDB, "tracking_jb", $jbId);
        if ($tmpArray[0] == "0") :
           $retArray[] = array("0", "tracking_jb", $jbId, $tmpArray[3], $tmpArray[4], $barcode);
        else :
           $retArray[] = $tmpArray;
        endif;
     endif;
     if ($trId != ""  && ($mode == "SINGLE_TR" || $mode == "ALL")) :
	      $tmpArray = insertMetaTrackingItem($moIdRefDB, "tracking_tr", $trId);
        if ($tmpArray[0] == "0") :
           $retArray[] = array("0", "tracking_tr", $trId, $tmpArray[3], $tmpArray[4], $barcode);
        else :
           $retArray[] = $tmpArray;
        endif;
     endif;
     if ($tratId != ""  && ($mode == "SINGLE_TRAT" || $mode == "ALL")) :
	      $tmpArray = insertMetaTrackingItem($moIdRefDB, "tracking_trat", $tratId, $internalBarcode . $barcode);
	      if ($tmpArray[0] == "0") :
	         $retArray[] = array("0", "tracking_trat", $tratId, $tmpArray[3], $tmpArray[4], $barcode);
        else :
           $retArray[] = $tmpArray;
	      endif;
	   endif;
	endif;
	return $retArray;
}


// Send tracking mail to (end)customer (executed in operational database)
function sendTrackingHTMLMail ($mailToAddress, $itemDataForMail, $moIdRefDB, $jbId, $trackingLink = "", $hqId = "0", $mdId = "0", $imgLogoArr = array(), $etaOut = "", $mailSubject = "") {
  global $db, $PHP_SELF, $debug;

  if ($mailToAddress != "") :
     if (checkEmailFormat($mailToAddress)) :
        $itemDataForMailLen = count($itemDataForMail);
        if ($itemDataForMailLen > 0) :
           // Generate tracking links
           if ($trackingLink == "") :
              $trackingLink = "http://www.assecutor.de/tracking/tracking/tracking_ADSG.php?trackingID=";
           endif;
           $outputTrackingLinks = "";
           $outputJb = "";
           $outputTr = "";
           $outputTrat = "";

           for ($i = 0; $i < $itemDataForMailLen; $i++) :
               $objType  = $itemDataForMail[$i][1];
               $objId    = $itemDataForMail[$i][2];
               $mtrHash  = $itemDataForMail[$i][3];
               $mtrvalue = $itemDataForMail[$i][4];
               $barcode  = $itemDataForMail[$i][5];

               if ($objType == "tracking_jb") :
                  $outputJb .= "<a href=\"" . $trackingLink . $mtrHash . "\">" . $mtrvalue . "</a><br><br>";
               elseif ($objType == "tracking_tr") :
                  if ($itemDataForMailLen == 1) :
                     // $outputTr .= "<a href=\"" . $trackingLink . $mtrHash . "\">" . $jbId . "</a><br><br>";
                     $outputTr .= "<a href=\"" . $trackingLink . $mtrHash . "\">" . getLngt("Bitte hier klicken!") . "</a><br><br>";
                  else :
                     $outputTr .= "<a href=\"" . $trackingLink . $mtrHash . "\">" . $mtrvalue . "</a><br><br>";
                  endif;
               elseif ($objType == "tracking_trat") :
                  $outputTrat .= "<a href=\"" . $trackingLink . $mtrHash . "\">" . $barcode . "</a><br><br>";
               endif;
           endfor;
           if ($outputJb != "") :
              $outputTrackingLinks .= "<br>" . getLngt("Auftrag") . "<br><br>" . $outputJb . "<br>";
           endif;
           if ($outputTr != "") :
              if ($itemDataForMailLen == 1) :
                 // $outputTrackingLinks .= "<br>" . getLngt("Auftrag") . "<br><br>" . $outputTr . "<br><br>";
                 $outputTrackingLinks .= "<br>" . $outputTr . "<br><br>";
              else :
                 $outputTrackingLinks .= "<br>" . getLngt("Stationen") . "<br><br>" . $outputTr . "<br><br>";
              endif;
           endif;
           if ($outputTrat != "") :
              $outputTrackingLinks .= getLngt("Artikel") . "<br><br>" . $outputTrat . "<br><br><br>";
           endif;

           if ($moIdRefDB != "") :
              $sendMail = true;
              // Set From address
              $mailFromAddress = getParameterValue("0", "MAIL_TRACKING_SENDER_ADDRESS", $hqId, $mdId);
              if ($mailFromAddress == "") :
                 $mailFromAddress = getParameterValue("0", "MAIL_TRACKING_SENDER_ADDRESS", "0", $mdId);
                 if ($mailFromAddress == "") :
                    $mailFromAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $hqId);
                    if ($mailFromAddress == "") :
                       $mailFromAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", "0");
                    endif;
                 endif;
              endif;
              if ($mailFromAddress == "" || !checkEmailFormat($mailFromAddress)) :
                 $sendMail = false;
              endif;

              if ($sendMail) :

                 // Get header image from database
                 $imgFilename = $imgLogoArr[0];
                 $imgHeight = $imgLogoArr[1];
                 $imgWidth = $imgLogoArr[2];                 
                 $cssBackground = $imgLogoArr[3];
                 if ($imgFilename == "") : 
                    $imgFilename = "assecutor.png"; 
                    $imgHeight = "233";
                    $imgWidth = "543";                    
                 endif;
                 if ($cssBackground == "") : 
                    $cssBackground = "#CDD9FD";
                 endif;

                 $mailObj = new htmlMimeMail();

                 $mailtext = "<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=ISO-8859-1\">";
                 $mailtext .= "<title>" . getLngt("Sendungsverfolgung") . "</title>";
                 $mailtext .= "<style type=\"text/css\">";

                 $mailtext .= ".mcTable { border:0px; width:650px; background:" . $cssBackground . "; }";
                 $mailtext .= ".mcTable2 { border:0px; width:610px; background:" . $cssBackground . "; }";

                 $mailtext .= ".spacer05 { height:5px; background:" . $cssBackground . ";}";
                 $mailtext .= ".spacer15 { height:15px; background:" . $cssBackground . ";}";
                 $mailtext .= ".spacer25 { height:25px; background:" . $cssBackground . ";}";
                 $mailtext .= ".spacer50 { height:50px; background:" . $cssBackground . ";}";

                 $mailtext .= ".f10np1       { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt; font-weight: normal; padding: 1px; color: #000000;}";
                 $mailtext .= ".f10bp1       { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt; font-weight: bold; padding: 1px; color: #000000;}";
                 $mailtext .= ".f10np1_green { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt; font-weight: normal; padding: 1px; color: #00BB00;}";
                 $mailtext .= ".f10np1_red   { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt; font-weight: normal; padding: 1px; color: #FF0000;}";
                 $mailtext .= ".f10np1_blue  { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt; font-weight: normal; padding: 1px; color: #1b12b9;}";
                 $mailtext .= ".f12np1       { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: normal; padding: 1px; color: #000000;}";
                 $mailtext .= ".f12bp1       { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: bold; padding: 1px; color: #000000;}";
                 $mailtext .= ".f12np1_blue  { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: normal; padding: 1px; color: #1b12b9;}";
                 $mailtext .= ".f12bp1_blue  { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: bold; padding: 1px; color: #1b12b9;}";
                 $mailtext .= ".f12bp1_darkgreen { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: bold; padding: 1px; color: #008800;}";

                 $mailtext .= "</style>";
                 $mailtext .= "</head>";
                 $mailtext .= "<body>";
                 $mailtext .= "<center>";
                 $mailtext .= "<table class=\"mcTable\">";
                 $mailtext .= "  <tr>";
                 $mailtext .= "  	<td style=\"width:650px;\" align=\"center\">";
                 $mailtext .= "  		<br><img src=\"../images/external/" . $imgFilename . "\" border=\"0\" height=\"" . $imgHeight . "\" width=\"" . $imgWidth . "\">";
                 $mailtext .= "    </td>";
                 $mailtext .= "  </tr>";
                 $mailtext .= "</table>";
                 $mailtext .= "<table class=\"mcTable\"><tr><td class=\"spacer25\"></td></tr></table>";

                 $mailtext .= "<table class=\"mcTable\">";
                 $mailtext .= "	<tr>";
                 $mailtext .= "		<td style=\"width:20px;\">";
                 $mailtext .= "		</td>";
                 $mailtext .= "		<td style=\"width:610px;\" align=\"center\">";
                 if ($etaOut != "") :
                    $mailtext .= "			<span class=\"f10np1_blue\">" . $etaOut . "</span><br><br>";
                 endif;
                 $mailtext .= "			<span class=\"f10np1_blue\">" . getLngt("Zur Verfolgung Ihrer Sendung betätigen Sie bitte nachstehenden Link") . ":</span><br><br>";
                 $mailtext .= $outputTrackingLinks;
                 $mailtext .= "		</td>";
                 $mailtext .= "		<td style=\"width:20px;\">";
                 $mailtext .= "		</td>";
                 $mailtext .= "  </tr>";
                 $mailtext .= "</table>";
                 $mailtext .= "<table class=\"mcTable\"><tr><td class=\"spacer50\"></td></tr></table>";

                 $mailtext .= "<table class=\"mcTable\"><tr><td class=\"spacer50\"></td></tr></table>";
                 $mailtext .= "<table class=\"mcTable\">";
                 $mailtext .= "  <tr>";
                 $mailtext .= "  	<td style=\"width:650px;\" align=\"center\">";
                 $mailtext .= "  		<img src=\"../images/external/adsg_footer_transparent.png\" border=\"0\" height=\"70\" width=\"210\">";
                 $mailtext .= "    </td>";
                 $mailtext .= "  </tr>";
                 $mailtext .= "</table>";
                 $mailtext .= "<table class=\"mcTable\"><tr><td class=\"spacer15\"></td></tr></table>";
                 $mailtext .= "</center>";
                 $mailtext .= "</body>";
                 $mailtext .= "</html>";

                 $mailObj->setHtml($mailtext, null, "./");

                 $mailObj->setFrom($mailFromAddress);

                 // Set Cc address
                 /*
                 $mailCcAddress = getParameterValue("0", "MAIL_CC_ADDRESS", $hqId);
                 if ($mailCcAddress == "" || !checkEmailFormat($mailCcAddress)) :
                    $mailCcAddress = MAIL_CC_ADDRESS;
                 endif;
                 if ($mailCcAddress != "" && checkEmailFormat($mailCcAddress)) :
                    // $mailObj->setCc($mailCcAddress);
                 endif;
                 */

                 // Set Bcc address
                 /*
                 $mailBccAddress = getParameterValue("0", "MAIL_BCC_ADDRESS", $hqId);
                 if ($mailBccAddress == "" || !checkEmailFormat($mailBccAddress)) :
                    $mailBccAddress = MAIL_BCC_ADDRESS;
                 endif;
                 if ($mailBccAddress != "" && checkEmailFormat($mailBccAddress)) :
                    // $mailObj->setBcc($mailBccAddress);
                 endif;
                 */

                 $mailSubject = trim($mailSubject);
                 if ($mailSubject != "") :
                    $mailObj->setSubject($mailSubject);
                 else :
                    $mailObj->setSubject(getLngt("Sendungsverfolgung Ihres Auftrags") . " " . $jbId);
                 endif;

                 // $mailResult = $mailObj->send(array($mailToAddress), 'smtp');
                 $mailResult = $mailObj->send(spliti(",", $mailToAddress), 'smtp');

                 // $mailObj->free();
                 $mailObj = NULL;

                 $retArray = array("0", $mailResult);
              else :
                 $retArray = array("905","<err_no>005</err_no>\n","<err_desc>" . getLngt("Es existiert keine Absenderadresse!") . "</err_desc>\n");
              endif;
           else :
              $retArray = array("904","<err_no>004</err_no>\n","<err_desc>" . getLngt("Der Wert für die Referenzdatenbank fehlt!") . "</err_desc>\n");
           endif;
        else :
           $retArray = array("903","<err_no>003</err_no>\n","<err_desc>" . getLngt("Die ID für die Sendungsverfolgung ist leer!") . "</err_desc>\n");
        endif;
     else :
        $retArray = array("902","<err_no>002</err_no>\n","<err_desc>" . getLngt("Mindestens eine Mailadresse hat kein korrektes Format!") . "</err_desc>\n");
     endif;
  else :
     $retArray = array("901","<err_no>001</err_no>\n","<err_desc>" . getLngt("Keine Mailadresse spezifiziert!") . "</err_desc>\n");
  endif;
  
	return $retArray;
}


// Checks tracking state of the customer (payer or related) if the current job and inserts into "metatracking"
function initTrackingProcessJob($jbId, $dbConnection = "") {
	global $db, $PHP_SELF;
	global $dbname, $dblogin, $dbpassword;
	global $jobData;

  $debug = true;
  $currentTime = getDateTime("0");
  $currentTimestamp = getDateTime("6");

	$retArray = array("101","<err_no>101</err_no>\n","<err_desc>" . getLngt("Keine oder falsche Auftragsnummer!") . "</err_desc>\n");  // Init only
	if ($jbId != "" && is_numeric($jbId)) :
     if (!is_object($dbConnection) || $dbConnection == "") : $dbConnection = $db; endif;

     if (existsEntry("job",array("jb_id",$jbId),$dbConnection)) :
        /*
        if ($jobData == "" || !is_array($jobData) || count($jobData["job"]) == 0) :
           getDBData("job", $jbId);
           getDBData("tour", $jbId);
           getDBData("tourarticle", $jbId);
           // getDBData("genericdatacontainer", $jbId);

        endif;
        */

        // Get current global number of THIS database instance
        $constGlobalDbInstNo = getParameterValue("0", "GLOBAL_UNIQUE_DB_INSTANCE_NO", "0", "0");

        // Get global usage mode
        $globalParUseRelatedCustomer = getParameterValue("0", "GLOBAL_USE_RELATED_CUSTOMER", "0");

        // Generate internal barcode inserted in "tourarticle.trat_int_serialno" if NOT does exist
        $internalSerialno = $currentTimestamp;

        // Get customer (payer or related) from job and check tracking state being activated
        // $jbCscIdPayer = $jobData["job"]["csc_id_payer"];
        // $jbCscIdRelated = $jobData["job"]["csc_id_related"];
        // if ($jbCscIdPayer == "" || $jbCscIdPayer == "0" || $jbCscIdRelated == "" || $jbCscIdRelated == "0" ) :
           $jbFields = getFieldsValueFromId("job", "jb_id", $jbId, array("csc_id_payer","csc_id_related"),$dbConnection);
           $jbCscIdPayer = $jbFields[0];
           $jbCscIdRelated = $jbFields[1];
        // endif;
        $csIdPayer = getFieldValueFromId("costcenter","csc_id",$jbCscIdPayer,"cs_id",$dbConnection);
        $csIdRelated = getFieldValueFromId("costcenter","csc_id",$jbCscIdRelated,"cs_id",$dbConnection);
        $csTrackingPayer = getFieldValueFromId("customer","cs_id",$csIdPayer,"cs_tracking",$dbConnection);
        $csTrackingRelated = getFieldValueFromId("customer","cs_id",$csIdRelated,"cs_tracking",$dbConnection);

        $cscRelevant = "csc_id_payer";
        $cscIdRelevant = $jbCscIdPayer;
        $csIdRelevant = $csIdPayer;
        $csTrackingRelevant = $csTrackingPayer;
        if ($globalParUseRelatedCustomer == "1") :
           $cscRelevant = "csc_id_related";
           $cscIdRelevant = $jbCscIdRelated;
           $csIdRelevant = $csIdRelated;
           $csTrackingRelevant = $csTrackingRelated;
        endif;

        if ($debug) :
           echo "jbId : " . $jbId . "<br>";
           echo "globalParUseRelatedCustomer : " . $globalParUseRelatedCustomer . "<br>";
           echo "jbCscIdPayer : " . $jbCscIdPayer . "<br>";
           echo "jbCscIdRelated : " . $jbCscIdRelated . "<br>";
           echo "csIdPayer : " . $csIdPayer . "<br>";
           echo "csIdRelated : " . $csIdRelated . "<br>";
           echo "csTrackingPayer : " . $csTrackingPayer . "<br>";
           echo "csTrackingRelated : " . $csTrackingRelated . "<br>";
           echo "cscRelevant : " . $cscRelevant . "<br>";
           echo "cscIdRelevant : " . $cscIdRelevant . "<br>";
           echo "csIdRelevant : " . $csIdRelevant . "<br>";
           echo "<br><br>";
        endif;

        // **** Insert tracking data and send mails to payer or related customer ****
        if ($csTrackingRelevant == "1" || $csTrackingRelevant == "3") :

           $itemDataForMail = array();

           // Insert tracking data into "metatracking"
           $tratArray = getTratArticles($jbId);
           $tratArrayLen = count($tratArray);
           if ($tratArrayLen > 0) :
              // There are tour articles with or without barcodes
              for ($i = 0; $i < $tratArrayLen; $i++) :
                  $trId = trim($tratArray[$i][12]);
                  $tratId = trim($tratArray[$i][11]);
                  $tratSerialno = trim($tratArray[$i][4]);
                  $tratIntSerialno = trim($tratArray[$i][13]);
                  if ($tratIntSerialno == "" && $tratId != "") :
                     // Set generated default internal serial number if does not exist and update it into the database
                     $tratIntSerialno = $internalSerialno;
                     updateStmt("tourarticle","trat_id",$tratId,array("trat_int_serialno",$tratIntSerialno));
                  endif;
                  // if ($tratSerialno != "") : 
                     $tmpArray = insertTrackingItems($jbId, $trId, $tratId, $tratIntSerialno, $tratSerialno);
                     $tmpArrayLen = count($tmpArray);
                     for ($j = 0; $j < $tmpArrayLen; $j++) :
                         $tmpExist = false;
                         $itemDataForMailLen = count($itemDataForMail);
                         for ($k = 0; $k < $itemDataForMailLen; $k++) :
                             // Check for hash existence
                             if ($tmpArray[$j][2] == $itemDataForMail[$k][2]) :
                                $tmpExist = true;
                                break 1;
                             endif;
                         endfor;
                         if (!$tmpExist) :
                            $itemDataForMail[] = $tmpArray[$j];
                         endif;
                     endfor;
                  // endif;
              endfor;
           else :
              $trArray = getColVectorFromDB2ArrayByClause("tour", "tr_id", "jb_id = '" . $jbId . "'", "", "", "DISTINCT", $dbConnection);
              $trArrayLen = count($trArray);
              if ($trArrayLen > 0) :
                 for ($i = 0; $i < $trArrayLen; $i++) :
                     $tmpArray = insertTrackingItems($jbId, $trArray[$i]);
                     $tmpArrayLen = count($tmpArray);
                     for ($j = 0; $j < $tmpArrayLen; $j++) :
                         if (!in_array($tmpArray[$j], $itemDataForMail)) :
                            $itemDataForMail[] = $tmpArray[$j];
                         endif;
                     endfor;
                 endfor;
              endif;
              // $itemDataForMail[] = insertTrackingItems($jbId); // Inserted implicitly by inserting stations
           endif;
           $itemDataForMailLen = count($itemDataForMail);

           if ($debug) :
              echo "tratArray: <br>"; print_r($tratArray); echo "<br><br>";
              echo "itemDataForMail: <br>"; print_r($itemDataForMail); echo "<br><br>";
           endif;

           // Items does exist for sending mail
           if ($itemDataForMailLen > 0) :
              // Get mail address of (paying or related) customer by itself
              $csJbstatusmail2csc = getFieldValueFromId("customer","cs_id",$csIdRelevant,"cs_jbstatusmail2csc",$dbConnection);
              if ($csJbstatusmail2csc == "1") :
                 // Use email address of the costcenter
                 $mailToAddress = getFieldValueFromClause("costcenteraddress","cscad_email","csc_id = '" . $cscIdRelevant . "' AND adt_id = '2'",$dbConnection);
              else :
                 // Use email address in master data sheet
                 $csAdmin     = getFieldValueFromId("customer","cs_id",$csIdRelevant,"cs_admin",$dbConnection);
                 $usrId       = getFieldValueFromId("employee","emp_id",$csAdmin,"usr_id",$dbConnection);
                 $mailToAddress = getFieldValueFromId("user","usr_id",$usrId,"usr_email",$dbConnection);
              endif;

              // Send email to customer
              $retArray = sendTrackingHTMLMail($mailToAddress, $itemDataForMail, $constGlobalDbInstNo, $jbId);
              if ($retArray[0]) :
                 // $mailsendStatus = getLngt("Die Nachricht wurde versandt!");
                 // Write logdata into log database
                 // writeToLogDB("22",$currentHqId,$job_id,$currentSessionUsrId,"","","",$f_email);
              else :
                 // $mailsendStatus = getLngt("Die Nachricht konnte nicht gesendet werden!");
                 // Write logdata into log database
                 // writeToLogDB("23",$currentHqId,$job_id,$currentSessionUsrId,"","","",$f_email);
                 $retArray = array("106","<err_no>106</err_no>\n","<err_desc>" . getLngt("Die Email konnte nicht mehr versendet werden!") . "</err_desc>\n");
              endif;
           else :
              $retArray = array("104","<err_no>104</err_no>\n","<err_desc>" . getLngt("Es wurden keine Trackingdaten zurückgeliefert!") . "</err_desc>\n");
           endif;
        endif;


        // **** Insert tracking data end customer or station mail addresses ****
        if ($csTrackingRelevant == "2" || $csTrackingRelevant == "3") :

           $itemDataForMail = array();

           // Get mail address of each station
           $trArray = getColVectorFromDB2ArrayByClause("tour", "tr_id", "jb_id = '" . $jbId . "' AND tr_sort >= '2' AND ", "", "", "", $dbConnection);
           $trArrayLen = count($trArray);
           if ($trArrayLen > 0) :
              for ($i = 0; $i < $trArrayLen; $i++) :
                  $itemDataForMail[] = insertTrackingItems($jbId, $trArray[$i]);
              endfor;
           endif;
           


                
        endif;
	   else :
        $retArray = array("103","<err_no>103</err_no>\n","<err_desc>" . getLngt("Der Auftrag existiert nicht!") . "</err_desc>\n");
	   endif;
  else :
     $retArray = array("102","<err_no>102</err_no>\n","<err_desc>" . getLngt("Keine Auftragsnummer!") . "</err_desc>\n");
  endif;

  return $retVal;
}


// **** TEST ****

// $res = initTrackingProcessJob("1872318");   // HTG Test
// $res = initTrackingProcessJob("16020472");  // STB Hennig
// $res = initTrackingProcessJob("21096155");  // STB925112 tevitel AG

// print_r($res);
?>
