<?php

include_once ("../include/mcglobal.inc.php");
include_once ("../include/html.inc.php");
include_once ("../include/inc_html2pdf.inc.php");
// include_once ("htmlMimeMail.php");
// include_once ("../include/barcode_BCGcode39_saveImage.php");
include_once ("../include/barcode_BCGcode128_saveImage.php");


getSecHttpVars("0", array("bo_id", "magic"));


$currentClientIP = trim($_SERVER['REMOTE_ADDR']);

$currentTime = date("Y-m-d H:i:s");
$currentDate = date("d.m.Y");
$currentTimeSpecial_01 = date("Ymd_His");

$absoluteSystemPath = getAbsoluteSystemPath();
$outputFormatField = defineOutputFormats();

$logFile = "../log/HLS_acc.log";
$csvFile = "HLS_acc_" . $currentTimeSpecial_01 . ".csv";
$csvPathAndFile = "../temp/download/" . $csvFile;
$hqId = "1";
$title = "HHA :: Transfer Geldkassetten und Safebags";
$matrix = "";
$opState = "";
$mailResultMsg = "";

// Init
$boId = $bo_id;  // Mapping
$boType = ""; 
$boState = "";
$boExtId0 = "";
$boExtId1 = "";
$boExtId2 = "";
$boObjData = "";
// echo "currentClientIP = " . $currentClientIP . "<br>";
// echo "boId = " . $boId . "<br>";
// echo "magic = " . $magic . "<br>";
if ($currentClientIP != "") :

   if ($bo_id != "" && is_numeric($bo_id) && $magic == "adsg_3478") :

      $sqlquery = "SELECT bo_id, bo_type, bo_state, bo_ext_id0, bo_ext_id1, bo_ext_id2, bo_obj_data"
                . "  FROM phoenix_log.b2b_objects"
                . "  WHERE bo_id = '" . $boId . "' AND bo_type = '221' AND bo_state = '1'";
// echo $sqlquery . "<br><br>"; die();
      $result = $db->query($sqlquery);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

      while ($row = $result->fetch_assoc()):
            $boType = $row["bo_type"]; 
            $boState = $row["bo_state"];
            $boExtId0 = $row["bo_ext_id0"];  // day
            $boExtId1 = $row["bo_ext_id1"];  // cr_id
            $boExtId2 = $row["bo_ext_id2"];  // trans_id
            $boObjData = $row["bo_obj_data"];
      endwhile;
      $result->free();

      // if (mysql_errno())
      //   writeToFile("mail_HLS_acc.log", "DB-Error:" . " | " . $currentTime . " | " . date("Y-m-d H:i:s") . " | " . trim($_SERVER['REMOTE_ADDR']) . " | " . $filename . mysql_error());
// echo "boState = " . $boState . "<br>";
// echo "boExtId1 = " . $boExtId1 . "<br>";
// echo "boObjData = " . $boObjData . "<br>";
      if ($boState == "1" && $boExtId1 != "" && $boObjData != "") :

         $crvhSid = getFieldValueFromId("couriervehicle","cr_id",$boExtId1,"crvh_sid");
         $tourNo = substr($crvhSid, -1);

         $cmpId = getFieldValueFromId("headquarters","hq_id",$hqId,"cmp_id");
         $cmpLogo = getFieldValueFromId("company","cmp_id",$cmpId,"cmp_logo");
         $cmpLogoWidth = getFieldValueFromId("company","cmp_id",$cmpId,"cmp_logo_width");
         $cmpLogoHeight = getFieldValueFromId("company","cmp_id",$cmpId,"cmp_logo_height");

         // Get mapping "csc_id" => "Barcode"
         $cscReverseMatchCodeArr = array();  // Use reverse array because CSC_INTERNAL_MATCH_CODE contains value like "VSBA=843894|VSBT=843890|VSBI=843888|...." but "843894=VSBA|843890=VSBT|...." is needed(!!!!)
         $cscInternalMatchCodes = getParameterValue("0", "CSC_INTERNAL_MATCH_CODE", $hqId);
         if ($cscInternalMatchCodes == "") : $cscInternalMatchCodes = getParameterValue("0", "CSC_INTERNAL_MATCH_CODE", "0"); endif;
         $arrCscVirtNoMapping = getKeyValueArrayFromString($cscInternalMatchCodes);
         $arrKeysOfArrCscVirtNoMapping = array_keys($arrCscVirtNoMapping);
         $arrKeysOfArrCscVirtNoMappingLen = count($arrKeysOfArrCscVirtNoMapping);         
         for ($i = 0; $i < $arrKeysOfArrCscVirtNoMappingLen; $i++) :
             $cscReverseMatchCodeArr[$arrCscVirtNoMapping[$arrKeysOfArrCscVirtNoMapping[$i]]] = $arrKeysOfArrCscVirtNoMapping[$i];
         endfor;

         // Get barcode image
         /*
         $barcode = getFieldValueFromClause("phoenix_log.b2b_objects", "bo_obj_data", "bo_type = '218' AND bo_ext_id0 = '" . $boExtId0 . "' AND bo_ext_id1 = '" . $boExtId1 . "' AND  bo_state = '0'");
         $barcodeFilename = $absoluteSystemPath . "/temp/download/barcode_" . $cr_id . "_" . $boExtId0 . "_" . getDateTime("6") . ".png";
         $tmpImgWidth = "300";
         $tmpImgHeight = "50";
         // $barcodeImg = barcode_BCGcode39_saveImage($barcodeFilename , "..", $barcode, $tmpScaleFactor, $tmpThickness, $tmpImgWidth, $tmpImgHeight);
         $barcodeImg = barcode_BCGcode128_saveImage($barcodeFilename , "..", $barcode, $tmpScaleFactor, $tmpThickness, $tmpImgWidth, $tmpImgHeight);
         */

         $mailtext  = "<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=ISO-8859-1\">"
                    . "<style>"
                    . " .table1 {border-collapse: collapse; border: 1px solid black;}"
                    . " .td1 {border: 1px solid black;}"
                    . "</style>"
                    . "</head><body>";
         // $mailtext .= "<img src=\"" . $absoluteSystemPath . "/images/external/" . $cmpLogo . "\" border=\"0\" height=\"" . ($cmpLogoHeight / 1.5) . "\" width=\"" . ($cmpLogoWidth / 1.5) . "\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
         // $mailtext .= $barcodeImg . "<br><br>";
         $mailtext .= "<b>Datum: " . $currentDate . "</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
         $mailtext .= "<b>Übergabe aus der Tour " . $tourNo . "</b><br><br>";
         // $mailtext .= "<img src=\"" . $absoluteSystemPath . "/images/spacer_lightgray.jpg\" border=\"0\" height=\"3\" width=\"650\"><br><br>";

         $headline = "";
         $headline .= "<tr>";
         // $headline .= "<td class=\"td1\">&nbsp;" . getLngt("Pos.") . "&nbsp;</td>";
         $headline .= "<td class=\"td1\">&nbsp;" . getLngt("Automat/VKST") . "&nbsp;</td>";
         $headline .= "<td class=\"td1\">&nbsp;" . getLngt("Objektart/-nr") . "&nbsp;</td>";
         $headline .= "<td class=\"td1\">&nbsp;" . getLngt("Buchung") . "&nbsp;</td>";
         $headline .= "<td class=\"td1\">&nbsp;" . getLngt("Datum") . "&nbsp;</td>";
         $headline .= "<td class=\"td1\">&nbsp;" . getLngt("Zeit") . "&nbsp;</td>";
         $headline .= "</tr>";

         $headlineStr = getLngt("Automatennummer") . ";" . getLngt("Kassettencode") . ";" . getLngt("Betrag") . ";" . getLngt("Belegzeit") . ";" . getLngt("Annahmezeit") . ";";

         $mailtext .= "<table border=\"0\">";
         // $mailtext .= $headline;

         // $atType2Arr = array();

         // if ($boState == "1" && $boObjData != "") : 

            /*
            $tmpArr = explode(" ",$boObjData[$i]);
            $atiSerialno = $tmpArr[0];
            $atId = getFieldValueFromId("articleitem","ati_serialno",$atiSerialno,"at_id");
            $atMatch = getFieldValueFromId("article","at_id",$atId,"at_match");
            $stkId = getFieldValueFromId("articleitem","ati_serialno",$atiSerialno,"stk_id");
            $stkName = getFieldValueFromId("stock","stk_id",$stkId,"stk_name");
            $stkBarcode = getFieldValueFromId("stock","stk_id",$stkId,"stk_barcode");
            
            $atiSerialno2 = $tmpArr[1];
            $atId2 = getFieldValueFromId("articleitem","ati_serialno",$atiSerialno2,"at_id");
            $atMatch2 = getFieldValueFromId("article","at_id",$atId2,"at_match");
            if (!isset($atType2Arr[$atMatch2]) || $atType2Arr[$atMatch2] == "") :
               $atType2Arr[$atMatch2] = 0;                
            endif;
            $atType2Arr[$atMatch2]++;
            
            $amount = substr($tmpArr[2],0,-2) . "." . substr($tmpArr[2],-2);
            $amount = number_format(round($amount,2), 2, ",", ".");
            
            $clockTime = substr($tmpArr[4],0,2) . "." . substr($tmpArr[4],-2);
            $clockDate = substr($tmpArr[3],0,2) . "." . substr($tmpArr[3],2,2) . "." . "20" . substr($tmpArr[3],4,2);

            $bookName = getLngt("HHA");
            if ($atiSerialno >= "100" && $atiSerialno <= "999") :
               $bookName = getLngt("HADAG");
            endif;
            */

            $mailtext .= "<tr>";
            $mailtext .= "<td>" . $headlineStr . "</td>";
            $mailtext .= "</tr>";
            $mailtext .= "<tr>";
            $mailtext .= "<td>" . str_replace("\n","<br>",$boObjData) . "</td>";
            $mailtext .= "</tr>";
         // endif;

         /*
         $mailtext .= "</table>";
         $mailtext .= "</br></br>";
         $mailtext .= "<b>" . getLngt("Summen:") . "</b>";
         $mailtext .= "<table border=\"0\">";
         for ($i = 0; $i < $atType2ArrKeysLen; $i++) :
             if ($atType2ArrKeys[$i] != "") :
                $mailtext .= "<tr>";
                $mailtext .= "<td>" . $atType2ArrKeys[$i] . "</td>";
                $mailtext .= "<td align=\"right\">" . $atType2Arr[$atType2ArrKeys[$i]] . "</td>";
                $mailtext .= "</tr>";
             endif;
         endfor;
         $mailtext .= "</table>";
         */
         /*
         $mailtext .= "</br></br></br></br>";
         $mailtext .= "<table border=\"0\">";
         $mailtext .= "<tr>";
         $mailtext .= "<td>_________________________</td><td width=\"200px\"></td><td>_________________________</td>";
         $mailtext .= "</tr>";
         $mailtext .= "<tr>";
         $mailtext .= "<td>" . getLngt("HOCHBAHN") . "</td><td width=\"200px\"></td><td>" . getLngt("HLS") . "</td>";
         $mailtext .= "</tr>";
         $mailtext .= "</table>";
         */
         $mailtext .= "</body>";

         // Generate PDF document
         // $fileNameTarget = generatePDF($mailtext, $title, "0", "0", "", "", "");

         // Send mail with attached (generated) PDF document
         if (true) :
            // Get CSV array
            /*
            $csvMatrix = convertMatrixToCsv($matrix, $headlineStr);
            $csvMatrixLen = count($csvMatrix);
            for ($f = 0; $f < $csvMatrixLen; $f++) :
                writeToFile($csvPathAndFile, $csvMatrix[$f]);
            endfor;
            */
            writeToFile($csvPathAndFile, $boObjData);

            $mailSubject = $title;
            $mailToAddresses = "ASSECUTOR-INFO@hochbahn.de";
// $mailToAddresses = "admin@assecutor.de";
            $mailAttachedFileType = "";
            $mailCcAddresses = "";
            $mailBccAddresses = "proj.hha@assecutor.de";
// $mailBccAddresses = "";
            $mailSenderAddress = "sys-op@assecutor.de";
            // Generate mail (object)
            $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($mailtext, null, "./");
            // $mailObj->setText($mailtext);

            if (file_exists($csvPathAndFile)) :
               $attachment = $mailObj->getFile($csvPathAndFile);
               $mailObj->addAttachment($attachment, $csvFile, 'text/csv');
            endif;

            $mailResult = $mailObj->send(array($mailToAddresses), 'smtp');
            // $mailResult = sendPDFMail($hqId, $mailtext, $title, $mailToAddresses, $fileNameTarget, $mailSubject, $mailText, $mailAttachedFileType, $mailCcAddresses, $mailBccAddresses, $mailSenderAddress, $parKeyForLogFile, $objId, $cascadingObjType);

            if ($mailResult) :
               $mailResultMsg = "OK";
               updateStmt("phoenix_log.b2b_objects","bo_id",$boId,array("bo_state","2"));
            else : 
               $mailResultMsg = "NOK";
            endif;
            $opState = $mailResultMsg;
         endif;
      endif;
   else :
      $opState = "ERR 102 : BO_ID missing or you do not have the force!";
   endif;
else :
   $opState = "ERR 101 : Unknown client IP!";
endif;


// Append to log file
writeToFile($logFile, "datetime=" . $currentTime . "|IP=" . $currentClientIP . "|cr_id=" . $boExtId1 . "|day=" . $boExtId0 . "|bo_id=" . $boId . "|mail_result=" . $mailResultMsg . "|op_state=" . $opState);

echo "OK";
// echo $opState;
?>
