<?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("magic", "mailTo", "mailCc", "mailBcc", "mailSubject", "mailContent"));


$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/mail_service.log";
$csvFile = "MAIL_" . $currentTimeSpecial_01 . ".csv";
$csvPathAndFile = "../temp/download/" . $csvFile;
$hqId = "1";
$title = "TITEL";
$matrix = array();
$opState = "";
$mailResultMsg = "";
$boId = array();
$boObjData = array();
// echo "currentClientIP = " . $currentClientIP . "<br>";
if ($currentClientIP != "") :
// echo "magic = " . $magic . "<br>";
   if ($cr_id != "" && is_numeric($cr_id) && $day != "" && $magic == "adsg_3478") :
// $cT = date("H:i:s"); writeToFile($logFile, $cT . " | 03");
      $sqlquery = "SELECT bo_id, bo_type, bo_obj_data"
                . "  FROM phoenix_log.b2b_objects"
                . "  WHERE bo_type IN (215, 217) AND bo_ext_id0 = '" . $day . "' AND bo_ext_id1 = '" . $cr_id . "' AND  bo_state = '0'"
                . "  ORDER BY bo_type, bo_ext_id2, bo_id";
// echo $sqlquery . "<br><br>";
      $result = $db->query($sqlquery);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
      $count = 0;
      while ($row = $result->fetch_assoc()):
            $boId[$count] = $row["bo_id"];
            $boType[$count] = $row["bo_type"];
            $boObjData[$count] = $row["bo_obj_data"];
            $count++;
      endwhile;
      $result->free();
      $boIdLen = count($boId);

      // if (mysql_errno())
      //   writeToFile("mail_HLS.log", "DB-Error:" . " | " . $currentTime . " | " . date("Y-m-d H:i:s") . " | " . trim($_SERVER['REMOTE_ADDR']) . " | " . $filename . mysql_error());

      if ($boIdLen > 0) :
      
         $crvhSid = getFieldValueFromId("couriervehicle","cr_id",$cr_id,"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 = '" . $day . "' AND bo_ext_id1 = '" . $cr_id . "' AND  bo_state = '0'");
         $barcodeFilename = $absoluteSystemPath . "/temp/download/barcode_" . $cr_id . "_" . $day . "_" . 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("Personalnr.") . "&nbsp;</td>";
         $headline .= "<td class=\"td1\">&nbsp;" . getLngt("Datum") . "&nbsp;</td>";
         $headline .= "<td class=\"td1\">&nbsp;" . getLngt("Automat/VKST") . "&nbsp;</td>";
         $headline .= "<td class=\"td1\">&nbsp;" . getLngt("Objektart") . "&nbsp;</td>";
         $headline .= "<td class=\"td1\">&nbsp;" . getLngt("Objektnr.") . "&nbsp;</td>";
         $headline .= "<td class=\"td1\">&nbsp;" . getLngt("Buchung") . "&nbsp;</td>";
         // $headline .= "<td class=\"td1\">&nbsp;" . getLngt("Standort") . "&nbsp;</td>";
         // $headline .= "<td class=\"td1\">&nbsp;" . getLngt("Wert") . "&nbsp;</td>";
         $headline .= "</tr>";

         $headlineStr = getLngt("Pos.") . ";" . getLngt("Personalnr.") . ";" . getLngt("Datum") . ";" . getLngt("Automat/VKST") . ";"
                      . getLngt("Objektart") . ";" . getLngt("Objektnr.") . ";" . getLngt("Buchung") . ";";
         // $headlineStr .= getLngt("Standort") . ";" . getLngt("Wert") . ";"

         $mailtext .= "<table class=\"table1\">";
         $mailtext .= $headline;

         $atType2Arr = array();         
         $remBoType = "";
         $lfd = 1;
         for ($i = 0; $i < $boIdLen; $i++) :

             if ($boType[$i] == "215") : 
                if ($remBoType != $boType[$i]) :
                   // $lfd = 1;
                endif;
                $remBoType = $boType[$i];

                $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 class=\"td1\" align=\"center\">" . $lfd . "</td>";                // Lfd.
                $mailtext .= "<td class=\"td1\" align=\"center\">" . "" . "</td>";                  // Personalnr.
                $mailtext .= "<td class=\"td1\" align=\"center\">" . $clockDate . "</td>";          // Datum
                $mailtext .= "<td class=\"td1\" align=\"center\">" . $atiSerialno . "</td>";        // Automatennr. / Verkaufsstelle
                $mailtext .= "<td class=\"td1\"align=\"center\">" . $atMatch2 . "</td>";            // Objektart
                $mailtext .= "<td class=\"td1\">&nbsp;" . $atiSerialno2 . "&nbsp;</td>";            // Objektnr.
                $mailtext .= "<td class=\"td1\">" . $bookName . "</td>";                            // Mandant
                // $mailtext .= "<td class=\"td1\" align=\"center\">" . $stkBarcode . "</td>";         // Standort
                // $mailtext .= "<td class=\"td1\" align=\"right\"&nbsp;>" . $amount . "&nbsp;</td>";  // Betrag
                $mailtext .= "</tr>";
                
                $matrix[] = array($lfd, "", $clockDate, $atiSerialno, $atMatch2, $atiSerialno2, $bookName);

             elseif ($boType[$i] == "217") :
                if ($remBoType != $boType[$i]) :
                   // $lfd = 1;
                endif;
                $remBoType = $boType[$i];

                $tmpArr = explode("|",$boObjData[$i]);
                $atihId = $tmpArr[0];
                $atihSerialno = getFieldValueFromId("phoenix_log.articleitemhistory","atih_id",$atihId,"atih_serialno");
                $atihData05 = getFieldValueFromId("phoenix_log.articleitemhistory","atih_id",$atihId,"atih_data_05");
                $cscId = getFieldValueFromId("phoenix_log.articleitemhistory","atih_id",$atihId,"csc_id");
                $usrId = getFieldValueFromId("phoenix_log.articleitemhistory","atih_id",$atihId,"usr_id");
                $atId = getFieldValueFromId("phoenix_log.articleitemhistory","atih_id",$atihId,"at_id");
                $atMatch = getFieldValueFromId("phoenix.article","at_id",$atId,"at_match");
                $cscName = getFieldValueFromId("phoenix.costcenter","csc_id",$cscId,"csc_name");
                $cscBarcode = $cscReverseMatchCodeArr[$cscId];
                $stkId = getFieldValueFromId("phoenix_log.articleitemhistory","atih_id",$atihId,"stk_id");
                $stkName = getFieldValueFromId("phoenix.stock","stk_id",$stkId,"stk_name");
                $stkBarcode = getFieldValueFromId("phoenix.stock","stk_id",$stkId,"stk_barcode");
                $usrPhone2 = getFieldValueFromId("phoenix.user","usr_id",$usrId,"usr_phone2");

                if (!isset($atType2Arr[$atMatch]) || $atType2Arr[$atMatch] == "") :
                   $atType2Arr[$atMatch] = 0;                
                endif;
                $atType2Arr[$atMatch]++;
                $clockTime = substr($tmpArr[2],0,2) . "." . substr($tmpArr[2],-2);
                $clockDate = substr($tmpArr[1],0,2) . "." . substr($tmpArr[1],2,2) . "." . "20" . substr($tmpArr[1],4,2);

                $amount = number_format(round($atihData05,2), 2, ",", ".");

                $bookName = getLngt("HHA");

                $mailtext .= "<tr>";
                $mailtext .= "<td class=\"td1\" align=\"center\">" . $lfd . "</td>";                // Lfd.
                $mailtext .= "<td class=\"td1\" align=\"center\">" . $usrPhone2 . "</td>";          // Personalnr.
                $mailtext .= "<td class=\"td1\" align=\"center\">" . $clockDate . "</td>";          // Datum
                $mailtext .= "<td class=\"td1\" align=\"center\">" . $cscBarcode . "</td>";         // Verkaufsstelle / Automatennr.
                $mailtext .= "<td class=\"td1\"align=\"center\">" . $atMatch . "</td>";             // Objektart
                $mailtext .= "<td class=\"td1\">&nbsp;" . $atihSerialno . "&nbsp;</td>";            // Objektnr.
                $mailtext .= "<td class=\"td1\">" . $bookName . "</td>";                            // Mandant
                // $mailtext .= "<td class=\"td1\" align=\"center\">" . $stkBarcode . "</td>";         // Standort
                // $mailtext .= "<td class=\"td1\" align=\"right\"&nbsp;>" . $amount . "&nbsp;</td>";  // Betrag
                $mailtext .= "</tr>";

                $matrix[] = array($lfd, $usrPhone2, $clockDate, $cscName, $atMatch, $atihSerialno, $bookName);
             endif;

             $lfd++;
         endfor;

         $atType2ArrKeys = array_keys($atType2Arr);
         $atType2ArrKeysLen = count($atType2ArrKeys);

         $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;

            $mailSubject = $title;
            $mailToAddresses = "ASSECUTOR-INFO@hochbahn.de";
            // $mailToAddresses = "admin@assecutor.de";
            $mailAttachedFileType = "";
            $mailCcAddresses = "";
            $mailBccAddresses = "proj.hha@assecutor.de";
            $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";
               for ($i = 0; $i < $boIdLen; $i++) :
                   updateStmt("phoenix_log.b2b_objects","bo_id",$boId[$i],array("bo_state","1"));
               endfor;
            else : 
               $mailResultMsg = "NOK";
            endif;
         endif;
      endif;
   else :
      $opState = "ERR 102 : CR_ID or DAY 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=" . $cr_id . "|day=" . $day . "|bo_id=" . implode(",",$boId) . "|mail_result=" . $mailResultMsg . "|op_state=" . $opState);

echo "OK";
?>
