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


include_once ("../include/mcglobal.inc.php");
if (!isset($automailer) || $automailer != "1") :
   include_once ("../include/auth.inc.php");
endif;
include_once ("../include/image.inc.php");
include_once ("../include/jb_detail_history.inc.php");



// Check this file 
if (mcIsSet($includePDFGeneric) != "1") :
   // Check HTTP-Parameters
   getSecHttpVars("1",array("f_act", "customerId", "cscIdRoot", "cscIdActual", "statusMessage", "deactivateMenu",
                            "jbId", "csId", "crId", "storeAsFile", "dbhistory"));
endif;

$phpVer56Plus = false;
if (substr(phpversion(), 0, 3) >= "5.6") :
   $phpVer56Plus = true;
endif;

$pageTitel = "PDF-Generator";
// include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");


// Check for authentication access and granted rights
if (!isset($automailer) || $automailer != "1") :
   $usrAccessArray["hq"] = "1"; $usrAccessArray["cs"] = "1";
   authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
endif;

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

$outputFormatField = defineOutputFormats();

// Init
mcIsSet($jbId);
mcIsSet($storeAsFile);
$utf8euro = mb_convert_encoding("€", 'UTF-8');
$utf8sz = mb_convert_encoding("ß", 'UTF-8');

// Include functions
include_once ("../include/inc_pdf.inc.php");


// *********************************************
// TESTABSCHNITTE
// [0.] Ausgabeeinstellungen
/*
error_reporting(E_ALL);
ini_set('display_errors', 1);
*/
// [I.] Auflistung verfügbarer Methoden
/*
try {
    // Erstelle eine neue PDFlib-Instanz
    $pdf = new PDFlib();

    // Überprüfe, welche Methoden verfügbar sind
    echo "Verfügbare Methoden in PDFlib:<br>";
    $methods = get_class_methods($pdf);
    foreach ($methods as $method) {
        echo $method . "<br>";
    }
} catch (PDFlibException $e) {
    echo "PDFlib-Fehler: " . $e->get_errmsg();
} catch (Exception $e) {
    echo "Allgemeiner Fehler: " . $e->getMessage();
}
*/
// [II.] Voreinstellungen abfragen
/*
$pdf = new PDFlib();
$pdf->set_option("errorpolicy=exception");
echo "Fehlernummer: " . $pdf->get_errnum() . "<br>";
*/
// die();
// *********************************************


// ***********************************
// * Generate PDF document for a JOB *
// ***********************************
if ($f_act == "generatePDFJob") :
   if ($jbId != "") :

      // Decision to use the job archive or normal tables
      $dbhistory = checkHistoryLevel($dbhistory, "jb", $jbId);
      $dbhistory = getDBNames($dbhistory);

      $automailer = "1";      // Takes care for NO web output in jb_details
      $f_act = "";            // Takes care for NO operation in jb_details

      // Declare PDF File
      getPDFObject(getLicenceKey());

      // PDF_open_file($pdf);
      //  open new PDF file; insert a file name to create the PDF on disk
      if ($pdf->begin_document("", "") == 0)  {
          die("Error: " .  $pdf->get_errmsg());
      }

      setPDFInfo("Auftragsdetails");
      setPDFParameter();
      $font = $pdf->load_font("Arial", "winansi", "");
         
      // Current job and mail address
      $job_id = $jbId;    // Prepare for "jb_details.php" ...
      $currentHqId = getFieldValueFromId($dbh_jb,"jb_id",$job_id,"hq_id");

      // Get number of entries in tour to scale the width of the PDF-page
      $pdfPageWidth = getParameterValue("0", "PDF_PAGE_WIDTH", $hq_id);
      if ($pdfPageWidth == "" || !is_numeric($pdfPageWidth)) : $pdfPageWidth = 595; endif;
      $pdfPageHeight = getParameterValue("0", "PDF_PAGE_HEIGHT", $hq_id);
      if ($pdfPageHeight == "" || !is_numeric($pdfPageHeight)) : $pdfPageHeight = 842; endif;

      // Get number of stations of the current job
      $numOfTourEntries = getCountOfTable($dbh_tr, "jb_id = '" . $job_id . "'");
      
      // Number of displayed stations per line
      $constPDFNumOfStationsPerLine = getParameterValue("0", "PDF_JB_STATIONS_PER_LINE", $hq_id);
      if ($constPDFNumOfStationsPerLine == "" || !is_numeric($constPDFNumOfStationsPerLine)) : $constPDFNumOfStationsPerLine = 4; endif;

      // Offset for rows
      $pdfTextOffsetRow = getParameterValue("0", "PDF_TEXT_OFFSET_LINE", $hq_id);
      if ($pdfTextOffsetRow == "" || !is_numeric($pdfTextOffsetRow)) : $pdfTextOffsetRow = "10"; endif;

      $pdfLineFeed = getParameterValue("0", "PDF_JB_STATIONS_LINE_FEED", $hq_id);
      if ($pdfLineFeed == "" || !is_numeric($pdfLineFeed)) : $pdfLineFeed = "0"; endif;
      if ($pdfLineFeed == "1" && $numOfTourEntries > 5) :
         $pdfPageWidth += (($numOfTourEntries - 5) * 200);
      endif;

      pdfNewPage();

      // Check for getting real or historic job data
      $takeRealJobData = checkForTakingRealOrHistoricJobData("0");

      if ($takeRealJobData) :
      
         // ****************************
         // *** Use current job data ***
         // ****************************

         if ($job_id != "" && $currentHqId != "") :
            ob_start();
            if ($takeRealJobData) :
               $tmpJobDataArray = getJobSnapshot($job_id, "1", "0");
            endif;
            ob_end_clean();    // Erases output buffer
         endif;

         // Job data
         $result = $db->query($sqlqueryJob);
         if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage() . ": " . $sqlStatementArray[0]);
         $titles = "Fahrzeug,Auftragszeit,Annahme,Erledigung";
         $fields = "vht_value,jb_ordertime,jb_taketime,jb_finishtime";
         $displayFormats = "1,1,1,14";  // Look for mcglobal.php
         $titlesArray = spliti(",",$titles);
         $fieldsArray = spliti(",",$fields);
         $displayFormatsArray = spliti(",",$displayFormats);
         $fieldsLength = count($fieldsArray);
         $pdfCurrentPositionYJobData = $pdfCurrentPositionY - 15;
         while ($row = $result->fetch_assoc()):
               for ($j = 0; $j < $fieldsLength; $j++) :
                   if (trim($titlesArray[$j]) == "") : $titlesArray[$j] = " "; endif;
                   $tmpVarName = $fieldsArray[$j];
                   $row[$tmpVarName] = str_replace("<br>", " ", $row[$tmpVarName]);
                   $row[$tmpVarName] = str_replace("&nbsp;", " ", $row[$tmpVarName]);
         
                   if ($displayFormatsArray[$j] == "") : $displayFormatsArray[$j] = "1"; endif;
         
                   $pdfCurrentPositionYJobData = $pdfCurrentPositionYJobData - $pdfTextOffsetRow;
                   
                   $tmpOut = $titlesArray[$j] . ": ";
                   if (!mb_check_encoding($tmpOut, 'UTF-8')) {
                     $tmpOut = mb_convert_encoding($tmpOut, 'UTF-8');
                   }
                   $pdf->show_xy($tmpOut, 15, $pdfCurrentPositionYJobData);

                   $tmpOut = formatOutput($row[$tmpVarName],$outputFormatField[$tmpVarName],$displayFormatsArray[$j]);
                   if (!mb_check_encoding($tmpOut, 'UTF-8')) {
                     $tmpOut = mb_convert_encoding($tmpOut, 'UTF-8');
                   }
                   $pdf->show_xy($tmpOut, 100, $pdfCurrentPositionYJobData);

                   $job_cr_sid = $row["cr_sid"];
               endfor;                         
         endwhile;
         $result->free();


         // Courier data
         if ($sqlqueryCourier != "") :
            $result = $db->query($sqlqueryCourier);
            if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage() . ": " . $sqlStatementArray[2]);
            $titles = "Name,Vorname,SID";
            $fields = "usr_name,usr_firstname,cr_sid";
            $titlesArray = spliti(",",$titles);
            $fieldsArray = spliti(",",$fields); 
            $fieldsLength = count($fieldsArray);
            $pdfCurrentPositionYCourierData = $pdfCurrentPositionY - 15;
            while ($row = $result->fetch_assoc()):
                  for ($j = 0; $j < $fieldsLength; $j++) :
                      if (trim($titlesArray[$j]) == "") : $titlesArray[$j] = " "; endif;
                      $tmpVarName = $fieldsArray[$j];
            
                      // Take cr_sid from job because (1:n)-relation "courier:vehicle"
                      if ($tmpVarName == "cr_sid") :
                         $row[$tmpVarName] = $job_cr_sid;
                      endif;
            
                      $row[$tmpVarName] = str_replace("<br>", " ", $row[$tmpVarName]);
                      $row[$tmpVarName] = str_replace("&nbsp;", " ", $row[$tmpVarName]);                       
            
                      $pdfCurrentPositionYCourierData = $pdfCurrentPositionYCourierData - $pdfTextOffsetRow;
                      
                      $tmpOut = $titlesArray[$j] . ": ";
                      if (!mb_check_encoding($tmpOut, 'UTF-8')) {
                        $tmpOut = mb_convert_encoding($tmpOut, 'UTF-8');
                      }
                      $pdf->show_xy($tmpOut, 250, $pdfCurrentPositionYCourierData);
                      
                      $tmpOut = formatOutput($row[$tmpVarName],$outputFormatField[$tmpVarName]);
                      if (!mb_check_encoding($tmpOut, 'UTF-8')) {
                        $tmpOut = mb_convert_encoding($tmpOut, 'UTF-8');
                      }
                      $pdf->show_xy($tmpOut, 300, $pdfCurrentPositionYCourierData);
                  endfor;                         
            endwhile;
            $result->free();
         endif;


         // Job costs
         if ($sqlqueryCosts != "") :
            $result = $db->query($sqlqueryCosts);
            if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage() . ": " . $sqlStatementArray[3]);
            $titles = "Kostenstelle,EID,Kunde,Leistung,Betrag";
            $fields = "csc_name,cs_eid,cmp_comp,trs_srv_name,business_volume";
            $titlesArray = spliti(",",$titles);
            $fieldsArray = spliti(",",$fields); 
            $fieldsLength = count($fieldsArray);
            $sumOfBusinessVolume = 0;
            $rowCounter = 0;
            $pdfCurrentPositionYCostsData = min($pdfCurrentPositionYJobData, $pdfCurrentPositionYCourierData) - 25;
            while ($row = $result->fetch_assoc()):
                  if ($row["business_volume"] != 0) :
                     $rowCounter++;
                     $pdfTextOffsetCol = 0;    // Offset for cols
                     if ($rowCounter == 1) :
                        $tmpOut = $titlesArray[$j] . ": ";
                        if (!mb_check_encoding($tmpOut, 'UTF-8')) {
                          $tmpOut = mb_convert_encoding($tmpOut, 'UTF-8');
                        }
                        $pdf->show_xy($tmpOut . ": ", (15 + $pdfTextOffsetCol), $pdfCurrentPositionYCostsData);
                     endif;
                     $pdfCurrentPositionYCostsData = $pdfCurrentPositionYCostsData - $pdfTextOffsetRow;

                     for ($j = 0; $j < $fieldsLength; $j++) :
                         if (trim($titlesArray[$j]) == "") : $titlesArray[$j] = " "; endif;
                         $tmpVarName = $fieldsArray[$j];
                         $row[$tmpVarName] = str_replace("<br>", " ", $row[$tmpVarName]);
                         $row[$tmpVarName] = str_replace("&nbsp;", " ", $row[$tmpVarName]);
                         $row[$tmpVarName] = substr($row[$tmpVarName],0,30);

                         // Summation field
                         if ($tmpVarName == "business_volume") :
                            $sumOfBusinessVolume += $row[$tmpVarName];
                         endif;

                         mcArrIsSet($outputFormatField, $tmpVarName);
                         $outField = formatOutput($row[$tmpVarName],$outputFormatField[$tmpVarName]);
                         $outField = substr($outField,0,25);
                         
                         // Format business volume
                         if ($tmpVarName == "business_volume") :
                            $outField = pad($outField,8," ");
                         endif;

                         if (!mb_check_encoding($outField, 'UTF-8')) {
                             $outField = mb_convert_encoding($outField, 'UTF-8');
                         }
                         $pdf->show_xy($outField, (15 + $pdfTextOffsetCol), $pdfCurrentPositionYCostsData);
                     
                         $pdfTextOffsetCol = $pdfTextOffsetCol + 125;
                     endfor;                  
                  endif;
            endwhile;

            $result->free();
            if ($rowCounter > 0) :
               $pdfTextOffsetCol = $pdfTextOffsetCol - 125;
               $sumOfBusinessVolume = number_format(round($sumOfBusinessVolume,2), 2, ",", ".");
               $sumOfBusinessVolume = pad($sumOfBusinessVolume,8," ");
               $pdfCurrentPositionYCostsData = $pdfCurrentPositionYCostsData - $pdfTextOffsetRow;
               $pdf->show_xy("GESAMT", (15 + $pdfTextOffsetCol - 50), $pdfCurrentPositionYCostsData);
               $pdf->show_xy($sumOfBusinessVolume, (15 + $pdfTextOffsetCol), $pdfCurrentPositionYCostsData);
            endif;
         endif;


         // Tour data
         $result = $db->query($sqlqueryTour);
         if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage() . ": " . $sqlStatementArray[1]);
         $titles = "Firma,Zusatz,Person,Straße + Hausnr.,PLZ + Ort,EID,Kostenstelle,Tel.,Kommissionsnr.,Erledigungszeit,Klartext,Unterschrift";
         $fields = "tr_comp,tr_comp2,tr_person,ad_street_hsno,ad_zipcode_city,cs_eid,csc_name,tr_phone,tr_commission_no,tr_finishtime,tr_signname,tr_sign";
         $titlesArray = spliti(",",$titles);
         $fieldsArray = spliti(",",$fields);
         $fieldsLength = count($fieldsArray);
         $rowCounter = 0;
         $numOfPrintedTourLine = 1;
         $pdfCurrentPositionYTourDataOffset = 0;
         $pdfTextOffsetCol = 0;    // Offset for cols
         $imgFilenames = array();
         while ($row = $result->fetch_assoc()):
               $rowCounter++;
               if ($rowCounter > 1 && (($rowCounter - 1) % $constPDFNumOfStationsPerLine) == 0) :
                  $pdfCurrentPositionYTourDataOffset = $pdfCurrentPositionYTourDataOffset + 180;
                  $pdfTextOffsetCol = 0;
                  $numOfPrintedTourLine++;
               endif;
               if ($numOfPrintedTourLine == 4) :
                  $pdf->end_page_ext("");
                  $pdfCurrentPositionYTourDataOffset = 0;
                  pdfNewPage(430);
                  $numOfPrintedTourLine = 0;
               endif;
               $pdfCurrentPositionYTourData = $pdfCurrentPositionYCostsData - 25 - $pdfCurrentPositionYTourDataOffset;

               for ($j = 0; $j < $fieldsLength; $j++) :

                   if (trim($titlesArray[$j]) == "") : $titlesArray[$j] = " "; endif;
         
                   if (($rowCounter - 1) % $constPDFNumOfStationsPerLine == 0) :
                      $tmpOut = $titlesArray[$j] . ": ";
                      if (!mb_check_encoding($tmpOut, 'UTF-8')) {
                        $tmpOut = mb_convert_encoding($tmpOut, 'UTF-8');
                      }
                      $pdf->show_xy($tmpOut . ": ", (15 + $pdfTextOffsetCol), $pdfCurrentPositionYTourData);
                   endif;
                   $tmpVarName = $fieldsArray[$j];
                   ${$tmpVarName} = mcArrIsSet($row, $tmpVarName);

                   $outField = "";
                   // if (${$tmpVarName} == "null") : ${$tmpVarName} = ""; endif;
                   if (${$tmpVarName} != "") :
                      // ${$tmpVarName} = mb_convert_encoding(${$tmpVarName}, 'UTF-8');
                      mcArrIsSet($outputFormatField, $tmpVarName);
                      $outField = formatOutput(${$tmpVarName},$outputFormatField[$tmpVarName]);
                   endif;

                   // Customer-sign
                   if ($tmpVarName == "tr_sign") :
                      if ($row["tr_sign"] != "") :
                         $rawCoord = splitRawCoordinates($row["tr_sign"]);
                         $maxCoord = checkMaxCoordinates($rawCoord);
         
                         $tmpSignPath = "../temp/signs/";
                         if (SIGNS_PATH != "") : $tmpSignPath = SIGNS_PATH; endif;                   
                         $imgFilename = $tmpSignPath . $job_id . "_" . $row["tr_sort"] . ".png";
                         $imgFilenames[] = $imgFilename;
                         $im = createSignImage($rawCoord);
                         $boolImg = true;
                         if (!file_exists($imgFilename)) :
                            $boolImg = imagepng($im, $imgFilename);
                         endif;

                         if ($boolImg) :
                            $image1 = $pdf->load_image("png", $imgFilename, "");
                            if ($image1 != -1) :
                               // pdf_place_image($pdf, $image1, (100 + $pdfTextOffsetCol), ($pdfCurrentPositionYTourData - $maxCoord[1]), 0.5);
                               // $pdf->fit_image($image1, (100 + $pdfTextOffsetCol), ($pdfCurrentPositionYTourData - $maxCoord[1]), "scale 0.5" );
                               // $pdf->fit_image($image1, (100 + $pdfTextOffsetCol), $pdfCurrentPositionYTourData - 50, "scale 0.4" );
                               $pdf->fit_image($image1, (100 + $pdfTextOffsetCol), $pdfCurrentPositionYTourData - 50, "boxsize {100 50} fitmethod meet" );
                            endif;
                         endif;
                      endif;
                   endif;

                   // Finishtime of the stop
                   if ($tmpVarName == "tr_finishtime") :
                      mcIsSet($tr_finishtime);
                      if (substr($tr_finishtime,0,4) == "1970") :
                         $outField = "";
                      endif;
                   endif;
         
                   // Do not show customer data if external costcenter
                   if ($tmpVarName == "usr_phone" || $tmpVarName == "usr_email" || $tmpVarName == "cs_eid") :
                      $tmpCscPath = mcArrIsSet($row, "csc_path");
                      if ($tmpCscPath != "" &&!(strpos(strtoupper($tmpCscPath), "//EXTERN//") === FALSE)) :
                         $outField = "";
                      endif;
                   endif;
         
                   if ($tmpVarName != "tr_sign") :   // all but the sign !!!
                      if ($outField == "&nbsp;") : $outField = ""; endif;
                      $outField = substr($outField, 0, 24);
                      if (!mb_check_encoding($outField, 'UTF-8')) {
                          $outField = mb_convert_encoding($outField, 'UTF-8');
                      }
                      $pdf->show_xy($outField, (100 + $pdfTextOffsetCol), $pdfCurrentPositionYTourData);
                   endif;

                   $pdfCurrentPositionYTourData = $pdfCurrentPositionYTourData - $pdfTextOffsetRow;
               endfor;         
               $pdfTextOffsetCol = $pdfTextOffsetCol + 120;               
         endwhile;
         $result->free();

         // Remove stored temporary images (signs) on the filesystem
         $tmpSignPath = "../temp/signs/";
         $imgFilenamesLen = count($imgFilenames);
         if (SIGNS_PATH != "") : $tmpSignPath = SIGNS_PATH; endif;
         for ($im = 0; $im < $imgFilenamesLen; $im++) :
             if (file_exists($tmpSignPath . $imgFilenames[$im])) :
                unlink($tmpSignPath . $imgFilenames[$im]);
             endif;
         endfor;

      else :

         // ***********************************
         // *** Use historic job (raw) data ***
         // ***********************************

         // Job data
         $titles = "Fahrzeug,Auftragszeit,Annahme,Erledigung";
         $fields = "vht_value,jb_ordertime,jb_taketime,jb_finishtime";
         $titlesArray = spliti(",",$titles);
         $fieldsArray = spliti(",",$fields); 
         $fieldsLength = count($fieldsArray);
         $pdfCurrentPositionYJobData = $pdfCurrentPositionY - 15;
         for ($j = 0; $j < $fieldsLength; $j++) :
             if (trim($titlesArray[$j]) == "") : $titlesArray[$j] = " "; endif;
             $tmpVarName = $fieldsArray[$j];
             $fieldValue = ${"jb_" . $tmpVarName};
             $fieldValue = str_replace("<br>", " ", $fieldValue);
             $fieldValue = str_replace("&nbsp;", " ", $fieldValue);

             $pdfCurrentPositionYJobData = $pdfCurrentPositionYJobData - $pdfTextOffsetRow;
             
             $tmpOut = $titlesArray[$j] . ": ";
             if (!mb_check_encoding($tmpOut, 'UTF-8')) {
               $tmpOut = mb_convert_encoding($tmpOut, 'UTF-8');
             }
             $pdf->show_xy($tmpOut, 15, $pdfCurrentPositionYJobData);

             if (!mb_check_encoding($fieldValue, 'UTF-8')) {
               $fieldValue = mb_convert_encoding($fieldValue, 'UTF-8');
             }
             $pdf->show_xy($fieldValue, 100, $pdfCurrentPositionYJobData);

             $job_cr_sid = $jb_cr_sid;
         endfor;


         // Courier data
         $titles = "Name,Vorname,SID";
         $fields = "usr_name,usr_firstname,cr_sid";
         $titlesArray = spliti(",",$titles);
         $fieldsArray = spliti(",",$fields); 
         $fieldsLength = count($fieldsArray);
         $pdfCurrentPositionYCourierData = $pdfCurrentPositionY - 15;
         for ($j = 0; $j < $fieldsLength; $j++) :
             if (trim($titlesArray[$j]) == "") : $titlesArray[$j] = " "; endif;
             $tmpVarName = $fieldsArray[$j];
             $fieldValue = ${"cr_" . $tmpVarName};

             // Take cr_sid from job because (1:n)-relation "courier:vehicle"
             if ($tmpVarName == "cr_sid") :
                $fieldValue = $job_cr_sid;
             endif;
             
             $fieldValue = str_replace("<br>", " ", $fieldValue);
             $fieldValue = str_replace("&nbsp;", " ", $fieldValue);                       

             $pdfCurrentPositionYCourierData = $pdfCurrentPositionYCourierData - $pdfTextOffsetRow;
             
             $tmpOut = $titlesArray[$j] . ": ";
             if (!mb_check_encoding($tmpOut, 'UTF-8')) {
               $tmpOut = mb_convert_encoding($tmpOut, 'UTF-8');
             }
             $pdf->show_xy($tmpOut . ": ", 250, $pdfCurrentPositionYCourierData);
             
             $tmpOut = formatOutput($fieldValue,$outputFormatField[$tmpVarName]);
             if (!mb_check_encoding($tmpOut, 'UTF-8')) {
               $tmpOut = mb_convert_encoding($tmpOut, 'UTF-8');
             }
             $pdf->show_xy($tmpOut, 300, $pdfCurrentPositionYCourierData);
         endfor;


         // Job costs
         // $titles = "Kostenstelle,EID,Kunde,Leistung,Betrag";
         $titles = "GESAMTBETRAG";
         // $fields = "csc_name,cs_eid,cmp_comp,trs_srv_name,business_volume";
         $fields = "business_volume";
         $titlesArray = spliti(",",$titles);
         $fieldsArray = spliti(",",$fields); 
         $fieldsLength = count($fieldsArray);
         $sumOfBusinessVolume = 0;
         $pdfTextOffsetCol = 0;    // Offset for cols
         $pdfCurrentPositionYCostsData = min($pdfCurrentPositionYJobData, $pdfCurrentPositionYCourierData) - 25;
         for ($j = 0; $j < $fieldsLength; $j++) :
             if (trim($titlesArray[$j]) == "") : $titlesArray[$j] = " "; endif;
         
             $tmpVarName = $fieldsArray[$j];
             $fieldValue = "";
         
             // Summation field
             if ($tmpVarName == "business_volume") :
                if (mcIsSet($costs_sum_withoutmarkup) != "") :
                   $fieldValue = $costs_sum_withoutmarkup;
                endif;
                if (mcIsSet($costs_sum) != "") :
                   $fieldValue = $costs_sum;
                endif;
             endif;

             $tmpOut = $titlesArray[$j] . ": ";
             if (!mb_check_encoding($tmpOut, 'UTF-8')) {
               $tmpOut = mb_convert_encoding($tmpOut, 'UTF-8');
             }
             $pdf->show_xy($tmpOut . ": " . $fieldValue, (15 + $pdfTextOffsetCol), $pdfCurrentPositionYCostsData);

             // $pdf->show_xy($titlesArray[$j] . ": ", (450 + $pdfTextOffsetCol), $pdfCurrentPositionYCostsData);
             // $pdf->show_xy($fieldValue, (520 + $pdfTextOffsetCol), $pdfCurrentPositionYCostsData);

             $pdfTextOffsetCol = $pdfTextOffsetCol + 125;
         endfor;
         /*
         if ($rowCounter > 0) :
            $pdfTextOffsetCol = $pdfTextOffsetCol - 150;
            $sumOfBusinessVolume = number_format(round($sumOfBusinessVolume,2), 2, ",", ".");
            $sumOfBusinessVolume = pad($sumOfBusinessVolume,8," ");
            $pdfCurrentPositionYCostsData = $pdfCurrentPositionYCostsData - $pdfTextOffsetRow;
            $pdf->show_xy($fieldValue . " GESAMT", (15 + $pdfTextOffsetCol), $pdfCurrentPositionYCostsData);
         endif;
         */

         // Tour data
         $titles = "Firma,Zusatz,Person,Straße + Hausnr.,PLZ + Ort,EID,Kostenstelle,Tel.,Kommissionsnr.,Erledigungszeit,Klartext,Unterschrift";
         $fields = "tr_comp,tr_comp2,tr_person,ad_street_hsno,ad_zipcode_city,cs_eid,csc_name,tr_phone,tr_commission_no,tr_finishtime,tr_signname,tr_sign";
         $titlesArray = spliti(",",$titles);
         $fieldsArray = spliti(",",$fields);
         $fieldsLength = count($fieldsArray);
         $rowCounter = 0;
         $pdfCurrentPositionYTourDataOffset = 0;
         $pdfTextOffsetCol = 0;    // Offset for cols
         $numOfPrintedTourLine = 1;
         $imgFilenames = array();
         mcIsSet($tr_numberofstations, 0);
         for ($i = 0; $i < $tr_numberofstations; $i++) :
               $rowCounter++;
               if ($rowCounter > 1 && (($rowCounter - 1) % $constPDFNumOfStationsPerLine) == 0) :
                  $pdfCurrentPositionYTourDataOffset = $pdfCurrentPositionYTourDataOffset + 180;
                  $pdfTextOffsetCol = 0;
                  $numOfPrintedTourLine++;
               endif;
               if ($numOfPrintedTourLine == 4) :
                  $pdf->end_page_ext("");
                  $pdfCurrentPositionYTourDataOffset = 0;
                  pdfNewPage(430);
                  $numOfPrintedTourLine = 0;
               endif;
               $pdfCurrentPositionYTourData = $pdfCurrentPositionYCostsData - 25 - $pdfCurrentPositionYTourDataOffset;

               for ($j = 0; $j < $fieldsLength; $j++) :

                   if (trim($titlesArray[$j]) == "") : $titlesArray[$j] = " "; endif;

                   if (($rowCounter - 1) % $constPDFNumOfStationsPerLine == 0) :
                      $tmpOut = $titlesArray[$j] . ": ";
                      if (!mb_check_encoding($tmpOut, 'UTF-8')) {
                        $tmpOut = mb_convert_encoding($tmpOut, 'UTF-8');
                      }
                      $pdf->show_xy($tmpOut, (15 + $pdfTextOffsetCol), $pdfCurrentPositionYTourData);
                   endif;
                   $tmpVarName = $fieldsArray[$j];
                   $fieldValue = ${"tr_" . $rowCounter. "_" . $tmpVarName};
                   // $outField = formatOutput($fieldValue,$outputFormatField[$tmpVarName]);
                   $outField = $fieldValue;
         
                   // Customer-sign
                   if ($tmpVarName == "tr_sign") :
                      if ($fieldValue != "") :
                         $rawCoord = splitRawCoordinates($fieldValue);
                         $maxCoord = checkMaxCoordinates($rawCoord);
                         
                         $tmpSignPath = "../temp/signs/";
                         if (SIGNS_PATH != "") : $tmpSignPath = SIGNS_PATH; endif;                   
                         $imgFilename = $tmpSignPath . $job_id . "_" . ($i + 1) . ".png";
                         $imgFilenames[] = $imgFilename;
                         $im = createSignImage($rawCoord);
                         $boolImg = true;
                         if (!file_exists($imgFilename)) :
                            $boolImg = imagepng($im, $imgFilename);
                         endif;

                         if ($boolImg) :
                            $image1 = $pdf->load_image("png", $imgFilename, "");
                            if ($image1 != -1) :
                               // $pdf->fit_image($image1, (100 + $pdfTextOffsetCol), ($pdfCurrentPositionYTourData - $maxCoord[1]), "scale 0.5" );
                               // $pdf->fit_image($image1, (100 + $pdfTextOffsetCol), $pdfCurrentPositionYTourData - 50, "scale 0.4" );
                               $pdf->fit_image($image1, (100 + $pdfTextOffsetCol), $pdfCurrentPositionYTourData - 50, "boxsize {100 50} fitmethod meet" );                               
                            endif;
                         endif;
                      endif;
                   endif;
         
                   // Finishtime of the stop
                   if ($tmpVarName == "tr_finishtime") :
                      mcIsSet($tr_finishtime);
                      if (substr($tr_finishtime,0,4) == "1970") :
                         $outField = "";
                      endif;
                   endif;
         
                   // Do not show customer data if external costcenter
                   /*
                   if ($tmpVarName == "usr_phone" || $tmpVarName == "usr_email" || $tmpVarName == "cs_eid") :
                      if (!(strpos(strtoupper($row["csc_path"]), "//EXTERN//") === FALSE)) :
                         $outField = "";
                      endif;
                   endif;
                   */
         
                   if ($tmpVarName != "tr_sign") :   // all but the sign !!!
                      if ($outField == "&nbsp;") : $outField = ""; endif;
                      $outField = substr($outField, 0, 24);

                      if (!mb_check_encoding($outField, 'UTF-8')) {
                          $outField = mb_convert_encoding($outField, 'UTF-8');
                      }
                      $pdf->show_xy($outField, (100 + $pdfTextOffsetCol), $pdfCurrentPositionYTourData);
                   endif;
                   
                   $pdfCurrentPositionYTourData = $pdfCurrentPositionYTourData - $pdfTextOffsetRow;
               endfor;         
               $pdfTextOffsetCol = $pdfTextOffsetCol + 120;
         endfor;
         
         // Remove stored temporary images (signs) on the filesystem
         $tmpSignPath = "../temp/signs/";
         $imgFilenamesLen = count($imgFilenames);
         if (SIGNS_PATH != "") : $tmpSignPath = SIGNS_PATH; endif;
         for ($im = 0; $im < $imgFilenamesLen; $im++) :
             if (file_exists($tmpSignPath . $imgFilenames[$im])) :
                unlink($tmpSignPath . $imgFilenames[$im]);
             endif;
         endfor;
      endif;
      
      $pdf->end_page_ext("");

      if ($storeAsFile == "1") :
         if ($pdfFile == "") : $pdfFile = "Auftrag_" . $jbId . ".pdf"; endif;
         closePDFObjectAsFile($pdfFile);
      else :
         closePDFObject("Auftrag_" . $jbId);
         die();
      endif;
   else :
      $statusMessage = "Es wurde kein Auftrag selektiert!";
   endif;
endif;


// ****************************************
// * Generate PDF document for a CUSTOMER *
// ****************************************
if ($f_act == "generatePDFCustomer") :
   if ($csId != "") :
   
      $f_act = "";            // Takes care for NO operation in jb_details

      // Declare PDF File
      getPDFObject(getLicenceKey());

      // PDF_open_file($pdf);
      //  open new PDF file; insert a file name to create the PDF on disk
      if ($pdf->begin_document("", "") == 0)  {
          die("Error: " .  $pdf->get_errmsg());
      }
      
      setPDFInfo("Kunde");
      setPDFParameter();
      $font = $pdf->load_font("Arial", "winansi", "");
      // $pdf->setfont($font, 16);
// echo "font = " . $font . "<br>"; die();
      ob_start();
      ob_end_clean();    // Erases output buffer
      
      // Get number of entries in tour to scale the width of the PDF-page
      $pdfPageWidth = 500;
      $pdfPageHeight = 700;
      $tabulator_00 = 15;
      $tabulator_01 = 110;

      $pdf->begin_page_ext(0,0, "width=" . $pdfPageWidth . " height=" . $pdfPageHeight);
      $pdf->setfont($font, 12);

      if (!mb_check_encoding($f_cmp_comp, 'UTF-8')) {$f_cmp_comp = mb_convert_encoding($f_cmp_comp, 'UTF-8');};
      if (!mb_check_encoding($f_cmp_comp2, 'UTF-8')) {$f_cmp_comp2 = mb_convert_encoding($f_cmp_comp2, 'UTF-8');};
      $offset = 0;
      $pdf->show_xy("Kunde: ", $tabulator_00, $pdfPageHeight - ($offset + 30));      
      $pdf->show_xy($f_cmp_comp, $tabulator_01, $pdfPageHeight - ($offset + 30));
      $pdf->show_xy($f_cmp_comp2, $tabulator_01, $pdfPageHeight - ($offset + 45));
      $pdf->show_xy("[". $f_cs_eid . "]", $tabulator_01, $pdfPageHeight - ($offset + 60));


      $pdf->setfont($font, 10);
      
      if (!mb_check_encoding($f_cmp_tax_idno, 'UTF-8')) {$f_cmp_tax_idno = mb_convert_encoding($f_cmp_tax_idno, 'UTF-8');};
      $offset = 80;
      $pdf->show_xy("Steuernr.: ", $tabulator_00, $pdfPageHeight - $offset);
      $pdf->show_xy($f_cmp_tax_idno, $tabulator_01, $pdfPageHeight - $offset);
      
      if (!mb_check_encoding($f_cmp_stax_idno, 'UTF-8')) {$f_cmp_stax_idno = mb_convert_encoding($f_cmp_stax_idno, 'UTF-8');};
      $offset = 90;
      $pdf->show_xy("USt.-Nr.: ", $tabulator_00, $pdfPageHeight - $offset);
      $pdf->show_xy($f_cmp_stax_idno, $tabulator_01, $pdfPageHeight - $offset);
      
      if (!mb_check_encoding($f_cmp_bank, 'UTF-8')) {$f_cmp_bank = mb_convert_encoding($f_cmp_bank, 'UTF-8');};
      $offset = 110;
      $pdf->show_xy("Bankverbindung: ", $tabulator_00, $pdfPageHeight - $offset);
      $pdf->show_xy($f_cmp_bank, $tabulator_01, $pdfPageHeight - $offset);
      $pdf->show_xy("Konto: " . $f_cmp_bankacc . "   BLZ: " . $f_cmp_bankno, $tabulator_01, $pdfPageHeight - ($offset + 10));

      if (!mb_check_encoding($f_ad_street, 'UTF-8')) {$f_ad_street = mb_convert_encoding($f_ad_street, 'UTF-8');};
      if (!mb_check_encoding($f_ad_city, 'UTF-8')) {$f_ad_city = mb_convert_encoding($f_ad_city, 'UTF-8');};
      $offset = 140;
      $pdf->show_xy("Stra" . $utf8sz . "e, Nr.: ", $tabulator_00, $pdfPageHeight - $offset);
      $pdf->show_xy($f_ad_street . " " . $f_cmp_hsno, $tabulator_01, $pdfPageHeight - $offset);
      $pdf->show_xy("PLZ, Ort: ", $tabulator_00, $pdfPageHeight - ($offset + 10));
      $pdf->show_xy($f_ad_zipcode . " " . $f_ad_city, $tabulator_01, $pdfPageHeight - ($offset + 10));
      
      $offset = 170;
      $pdf->show_xy("Email: ", $tabulator_00, $pdfPageHeight - $offset);
      $pdf->show_xy($f_usr_email, $tabulator_01, $pdfPageHeight - $offset);
      $pdf->show_xy("Mail bei:", $tabulator_00, $pdfPageHeight - ($offset + 10));
      $pdf->show_xy("Erledigung: " . ($f_cs_jbstatusmail == "1" ? "Ja" : "Nein") . "   Abholung: " . ($f_cs_jbstatusmail2 == "1" ? "Ja" : "Nein") . "   Erfassung: " . ($f_cs_jbstatusmail3 == "1" ? "Ja" : "Nein") , $tabulator_01, $pdfPageHeight - ($offset + 10));
     
      $offset = 200;
      $pdf->show_xy("Telekommunik.: ", $tabulator_00, $pdfPageHeight - $offset);
      $pdf->show_xy("Tel.: " . $f_usr_phone . "   Mobil: " . $f_usr_phone2, $tabulator_01, $pdfPageHeight - $offset);
      $pdf->show_xy("Fax: " . $f_usr_fax, $tabulator_01, $pdfPageHeight - ($offset + 10));

      if (!mb_check_encoding($f_usr_name, 'UTF-8')) {$f_usr_name = mb_convert_encoding($f_usr_name, 'UTF-8');};
      if (!mb_check_encoding($f_usr_firstname, 'UTF-8')) {$f_usr_name = mb_convert_encoding($f_usr_firstname, 'UTF-8');};
      $offset = 230;
      $pdf->show_xy("Benutzer: ", $tabulator_00, $pdfPageHeight - $offset);
      $pdf->show_xy("Name: " . $f_usr_name . "   Vorname: " . $f_usr_firstname, $tabulator_01, $pdfPageHeight - $offset);
      $pdf->show_xy("Zugangskonto: " . $f_usr_account, $tabulator_01, $pdfPageHeight - ($offset + 10));

      $offset = 260;
      $pdf->show_xy("Status: ", $tabulator_00, $pdfPageHeight - $offset);
      $pdf->show_xy(($f_cmp_authenticated == "1" ? "Nicht gesperrt" : "Gesperrt") . " und " . ($f_cmp_visible == "1" ? "sichtbar" : "nicht sichtbar"), $tabulator_01, $pdfPageHeight - $offset);

      $offset = 280;
      $pdf->show_xy("Rabatt: ", $tabulator_00, $pdfPageHeight - $offset);
      $pdf->show_xy($f_cs_discount . " %   (auf Fixpreis: " . ($f_cs_fixprice_discount == "1" ? "Aktiv" : "Nicht aktiv") . ")", $tabulator_01, $pdfPageHeight - $offset);
      $pdf->show_xy("Porto: ", $tabulator_00, $pdfPageHeight - ($offset + 10));
      $pdf->show_xy($f_cmp_postage . " " . $utf8euro, $tabulator_01, $pdfPageHeight - ($offset + 10));
      $pdf->show_xy("Provision: ", $tabulator_00, $pdfPageHeight - ($offset + 20));
      $pdf->show_xy($f_cs_prov . " %", $tabulator_01, $pdfPageHeight - ($offset + 20));
      $pdf->show_xy("Zuschlag: ", $tabulator_00, $pdfPageHeight - ($offset + 30));
      $pdf->show_xy($f_cs_markup_prov . " %   (" . ($f_cs_markup == "1" ? "aktiv" : "nicht aktiv") . ")", $tabulator_01, $pdfPageHeight - ($offset + 30));
      $pdf->show_xy("MwSt.: ", $tabulator_00, $pdfPageHeight - ($offset + 40));
      $pdf->show_xy($g_tx_value . " %  (" . $g_tx_sign . ")", $tabulator_01, $pdfPageHeight - ($offset + 40));
      $pdf->show_xy("Versand: ", $tabulator_00, $pdfPageHeight - ($offset + 50));
      $pdf->show_xy("Rechnung an Zentrale: " . ($f_cmp_inv2hq_0 == "checked" ? "JA" : "NEIN") . "   " . "Einzelrechnung: " . ($f_cmp_inv2hq_1 == "checked" ? "JA" : "NEIN"), $tabulator_01, $pdfPageHeight - ($offset + 50));
      $pdf->show_xy("Kommiss.-Nr.: ", $tabulator_00, $pdfPageHeight - ($offset + 60));
      $pdf->show_xy("Erforderlich im Auftrag: " . ($f_cs_commission_no_1 == "checked" ? "JA" : "NEIN"), $tabulator_01, $pdfPageHeight - ($offset + 60));
      $pdf->show_xy("Vermittlung: ", $tabulator_00, $pdfPageHeight - ($offset + 70));
      $pdf->show_xy("Listenkunde: " . ($f_cs_jobbatch_0 == "checked" ? "JA" : "NEIN") . "   " . "Anforderung: " . ($f_cs_cr_fav_only_0 == "checked" ? "JA" : "NEIN") . "   " . "Rechnungstext: " . ($f_cs_invtext_mode_0 == "checked" ? "JA" : "NEIN"), $tabulator_01, $pdfPageHeight - ($offset + 70));

      $offset = 370;
      $pdf->show_xy("Branche: ", $tabulator_00, $pdfPageHeight - $offset);
      $pdf->show_xy($g_br_name . " (" . $g_br_key . ")", $tabulator_01, $pdfPageHeight - $offset);

      mcIsSet($adInvoiceFields, array());
      mcArrIsSet($adInvoiceFields, 0); mcArrIsSet($adInvoiceFields, 1); mcArrIsSet($adInvoiceFields, 2);
      if (!mb_check_encoding($adInvoiceFields[0], 'UTF-8')) {$adInvoiceFields[0] = mb_convert_encoding($adInvoiceFields[0], 'UTF-8');};
      if (!mb_check_encoding($adInvoiceFields[1], 'UTF-8')) {$adInvoiceFields[1] = mb_convert_encoding($adInvoiceFields[1], 'UTF-8');};
      if (!mb_check_encoding($adInvoiceFields[2], 'UTF-8')) {$adInvoiceFields[2] = mb_convert_encoding($adInvoiceFields[2], 'UTF-8');};
      $offset = 390;
      $pdf->show_xy("Abw. Rechn.: ", $tabulator_00, $pdfPageHeight - $offset);
      if ($adIdRootInvoice != "" && ($adIdRootInvoice != $f_ad_id || $adHsnoRootInvoice != $f_cmp_hsno)) :
         $pdf->show_xy($adInvoiceFields[0] . " " . $adHsnoRootInvoice, $tabulator_01, $pdfPageHeight - $offset);
         $pdf->show_xy($adInvoiceFields[1] . " " . $adInvoiceFields[2], $tabulator_01, $pdfPageHeight - ($offset + 10));
      else :
         $pdf->show_xy("Keine", $tabulator_01, $pdfPageHeight - $offset);
      endif;

      if (!mb_check_encoding($cmpCompRootInvoice, 'UTF-8')) {$cmpCompRootInvoice = mb_convert_encoding($cmpCompRootInvoice, 'UTF-8');};
      if (!mb_check_encoding($cmpComp2RootInvoice, 'UTF-8')) {$cmpComp2RootInvoice = mb_convert_encoding($cmpComp2RootInvoice, 'UTF-8');};
      $offset = 420;
      $pdf->show_xy("Abw. Firma: ", $tabulator_00, $pdfPageHeight - $offset);
      if (($cmpCompRootInvoice != $f_cmp_comp || $cmpComp2RootInvoice != $f_cmp_comp2)) :
         $pdf->show_xy($cmpCompRootInvoice, $tabulator_01, $pdfPageHeight - $offset);
         $pdf->show_xy($cmpComp2RootInvoice, $tabulator_01, $pdfPageHeight - ($offset + 10));
      else :
         $pdf->show_xy("Keine", $tabulator_01, $pdfPageHeight - $offset);
      endif;

      if (!mb_check_encoding($g_cscad_comp, 'UTF-8')) {$g_cscad_comp = mb_convert_encoding($g_cscad_comp, 'UTF-8');};
      $offset = 450;
      $pdf->show_xy("Bezahler: ", $tabulator_00, $pdfPageHeight - $offset);
      if ($g_csc_id != "" && $g_cscad_comp != "") :
         $pdf->show_xy($g_cscad_comp, $tabulator_01, $pdfPageHeight - $offset);
         // $pdf->show_xy($g_cscad_comp2, $tabulator_01, $pdfPageHeight - ($offset + 10));
      else :
         $pdf->show_xy("Selbst", $tabulator_01, $pdfPageHeight - $offset);
      endif;

      if (!mb_check_encoding($g2_cmp_comp, 'UTF-8')) {$g2_cmp_comp = mb_convert_encoding($g2_cmp_comp, 'UTF-8');};
      $offset = 470;
      $pdf->show_xy("Metakunde: ", $tabulator_00, $pdfPageHeight - $offset);
      if ($g2_csc_id != "" && $g2_cmp_comp != "") :
         $pdf->show_xy($g2_cmp_comp, $tabulator_01, $pdfPageHeight - $offset);
         // $pdf->show_xy($g_cscad_comp, $tabulator_01, $pdfPageHeight - ($offset + 10));
      else :
         $pdf->show_xy("Keiner", $tabulator_01, $pdfPageHeight - $offset);
      endif;

      if (!mb_check_encoding($f_cmp_remark, 'UTF-8')) {$f_cmp_remark = mb_convert_encoding($f_cmp_remark, 'UTF-8');};
      if (!mb_check_encoding($f_cmp_remark2, 'UTF-8')) {$f_cmp_remark2 = mb_convert_encoding($f_cmp_remark2, 'UTF-8');};
      $offset = 490;
      $pdf->show_xy("Bemerkung: ", $tabulator_00, $pdfPageHeight - $offset);
      // $pdf->show_boxed($f_cmp_remark, $tabulator_01, $pdfPageHeight - $offset - 100, 350, 100, "left", "");
      $textflow = $pdf->create_textflow($f_cmp_remark, "font={$font} fontsize=8");
      
      // Output text for "$f_cmp_remark"
      $offset -= 10;
      $boxOffset = 10;
      do {
      	  $textflow = $pdf->create_textflow($f_cmp_remark, "font={$font} fontsize=8");
          $result = $pdf->fit_textflow($textflow, $tabulator_01, $pdfPageHeight - $offset - $boxOffset, 350, $pdfPageHeight - $offset, "blind=true");
      // $pdf->show_xy("X-" . $boxOffset, $tabulator_01, $pdfPageHeight - $offset - $boxOffset);
      // $pdf->show_xy("X", 350, $pdfPageHeight - $offset);
          if ($result == "_boxfull") {
              $boxOffset += 10;
          }
      } while ($result == "_boxfull");
      $textflow = $pdf->create_textflow($f_cmp_remark, "font={$font} fontsize=8");
      $pdf->fit_textflow($textflow, $tabulator_01, $pdfPageHeight - $offset - $boxOffset, 350, $pdfPageHeight - $offset, "");

      $offset += $boxOffset + 20;

      $pdf->show_xy("Interne", $tabulator_00, $pdfPageHeight - $offset);
      $pdf->show_xy("Bemerkung", $tabulator_00, $pdfPageHeight - $offset - 10);
      // $pdf->show_boxed($f_cmp_remark2, $tabulator_01, $pdfPageHeight - $offset - 210, 350, 100, "left", "");
      $textflow = $pdf->create_textflow($f_cmp_remark2, "font={$font} fontsize=8");

      // Output text for "$f_cmp_remark2"
      $offset -= 10;
      $boxOffset = 10;
      do {
      	  $textflow = $pdf->create_textflow($f_cmp_remark2, "font={$font} fontsize=8");
          $result = $pdf->fit_textflow($textflow, $tabulator_01, $pdfPageHeight - $offset - $boxOffset, 350, $pdfPageHeight - $offset, "blind=true");
      // $pdf->show_xy("X-" . $boxOffset, $tabulator_01, $pdfPageHeight - $offset - $boxOffset);
      // $pdf->show_xy("X", 350, $pdfPageHeight - $offset);
          if ($result == "_boxfull") {
              $boxOffset += 10;
          }
      } while ($result == "_boxfull");
      $textflow = $pdf->create_textflow($f_cmp_remark2, "font={$font} fontsize=8");
      $pdf->fit_textflow($textflow, $tabulator_01, $pdfPageHeight - $offset - $boxOffset, 350, $pdfPageHeight - $offset, "");
      $offset += $boxOffset + 20;

      $pdf->setfont($font, 8);
  
      $pdf->end_page_ext("");

      if ($storeAsFile == "1") :
         if ($pdfFile == "") : $pdfFile = "Kunde_" . $csId . ".pdf"; endif;
         closePDFObjectAsFile($pdfFile);
      else :
         closePDFObject("Kunde_" . $csId);
         die();
      endif;
   else :
      $statusMessage = "Es wurde kein Kunde selektiert!";
   endif;
endif;

?>