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


include_once ("../include/mcglobal.inc.php");
include_once ("../include/auth.inc.php");
include_once ("../include/image.inc.php");
include_once ("../include/caglobal.inc.php");


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "customerId", "cscIdRoot", "cscIdActual",
                  "day_from", "month_from", "year_from", "day_to", "month_to", "year_to",
                  "g_cs_id", "g_csc_id", "g_csc_name", "initCsSearch", "f_filter", "f_vht_filter",
                  "f_inv_no", "f_inv_datetime_day", "f_inv_datetime_month", "f_inv_datetime_year",
                  "f_jobs", "invId4PDF", "statusMessage", "deactivateMenu"));

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

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

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

$utf8euro = mb_convert_encoding("?", 'UTF-8');
$utf8sz = mb_convert_encoding("ß", 'UTF-8');

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


function callJbDetail() {
  global $db, $outputFormatField, $automailer, $f_act, $job_id, $currentHqId;
  global $dbh_jb, $dbh_tr, $dbh_trs, $dbh_log;
  include ("../admin/jb_detail_.php");
  return array($sqlqueryJob, $sqlqueryTour, $sqlqueryCourier, $sqlqueryCosts);
}


// Check range of date. All fields have to be set
if ($day_from == "" || $month_from == "" || $year_from == "" || 
    $day_to == "" || $month_to == "" || $year_to == "") :
 
    // Initialize date-ranges to the current date
    $fromDateRange = getDateTime("1") . "000000";
    $toDateRange = getDateTime("1") . "235959";
 
    $day_from = getDateTime("day");
    $month_from = getDateTime("month");
    $year_from = getDateTime("year");
    $day_to = getDateTime("day");
    $month_to = getDateTime("month");
    $year_to = getDateTime("year");
else :
    $fromDateRange = $year_from . pad($month_from,2) . pad($day_from,2) . "000000";
    $toDateRange = $year_to . pad($month_to,2) . pad($day_to,2) . "235959";
endif;

// Select user-type for mode of security check 
$userType = getFieldValueFromId("user","usr_id",$usr_id,"usr_type");

// Check authentication verifying emmployee an his/her costcenter- and customer-association
if ( !( ($userType == "1") || authCheck($hq_id,$usr_id,$emp_id,$cscIdRoot,$customerId,$cscIdActual) ) ) : gotoReferer("1"); endif;

// Get the rights of the employee logged in and check the accessibility
authCheckEmployeeRights($emp_id, "7", "1");

getDBNames("0");    // Only use current tables (no history tables)

// Get company data
$g_cmp_id = getFieldValueFromId("customer", "cs_id", $g_cs_id, "cmp_id");
$g_cs_eid = getFieldValueFromId("customer", "cs_id", $g_cs_id, "cs_eid");
$g_cmp_comp = getFieldValueFromId("company", "cmp_id", $g_cmp_id, "cmp_comp");
$g_cmp_comp2 = getFieldValueFromId("company", "cmp_id", $g_cmp_id, "cmp_comp2");

mcTrim($f_inv_no);
$f_inv_datetime = "";
if ($f_inv_datetime_month >= "1" && $f_inv_datetime_month <= "12" && $f_inv_datetime_day >= "1" && $f_inv_datetime_day <= "31") :
   $f_inv_datetime = $f_inv_datetime_year . "-" . $f_inv_datetime_month . "-" . $f_inv_datetime_day . " 12:00:00";
endif;
$f_jobs_len = is_countable($f_jobs) ? count($f_jobs) : 0;
$sumOfJobPrices = 0;
$numOfRows = 0;

if ($f_filter == "") : $f_filter = "0"; endif;     // Filter (order clause by PDF generation)
if ($f_vht_filter == "") : $f_vht_filter = array(); endif;      // filter for vehicle of the courier for exporting ALL or ONLY the specified vehicle types


// Store invoice data to jobs
if ($f_act == "storeJobs") :
   if ($g_cs_id != "") :
      if ($f_jobs_len > 0) :
         if ($f_inv_no != "" && $f_inv_datetime != "") :
   
            // Transaction control starts here
            // TA("B");
           
            // Iterate all jobs
            for ($i = 0; $i < $f_jobs_len; $i++) :
      
                $jbId = $f_jobs[$i];

                // Insert job into table "invoice" if does not exist else update
                if (!(existsEntry("invoice",array("jb_id",$jbId)))) :
                   insertStmt("invoice", array("jb_id", $jbId, "inv_no", $f_inv_no, "inv_datetime", $f_inv_datetime));
                else :
                   updateStmt("invoice", "jb_id", $jbId, array("inv_no", $f_inv_no, "inv_datetime", $f_inv_datetime));
                endif;
            endfor;
      
            // TA("C");
            // TA("E");
      
            $f_act = "loadJobsOfCustomer";
         else :
            $statusMessage = "Sie müssen eine Rechnungsnummer und ein Rechnungsdatum vergeben!";
         endif;
      else :
         $statusMessage = "Es wurden noch keine Aufträge identifiziert!";
      endif;
   else :
      $statusMessage = "Sie haben noch keinen Kunden ausgewählt!";
   endif;   
endif;

// Generate PDF document
if ($f_act == "generatePDF") :
   if ($invId4PDF != "") :

      // Decision to use the job archive or normal tables
      $dbhistory = checkHistoryLevel($dbhistory, "jb", $jbId);
      $dbhistory = getDBNames($dbhistory);
   
      // Set filters
      $orderByClause = "jb.csc_id_payer, jb.jb_id";                                 // Internal ID of the costcenter of the payer
      if ($f_filter == "0") : $orderByClause = "csc.csc_name, jb.jb_id"; endif;     // Name of the costcenter of the payer 
      if ($f_filter == "1") : $orderByClause = "jb.jb_id"; endif;                   // Job number
   
      $jobArray = array();
      $sqlquery = "SELECT jb.jb_id, usr.usr_email, jb.cr_sid, jb.hq_id"
                . " FROM invoice AS inv, job AS jb, costcenter AS csc, customer AS cs, employee AS emp, user AS usr"
                . " WHERE inv.inv_no = '" . $invId4PDF . "'     AND"
                . "       inv.jb_id = jb.jb_id                  AND"
                . "       jb.csc_id_payer = csc.csc_id          AND"
                . "       csc.cs_id = cs.cs_id                  AND"
                . "       cs.cs_admin = emp.emp_id              AND"
                . "       emp.usr_id = usr.usr_id               "
                . " ORDER BY " . $orderByClause;
      $result = $db->query($sqlquery);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
      while ($row = $result->fetch_assoc()):
            $jobArray[] = array($row["jb_id"], $row["hq_id"]);
      endwhile;
      $result->free();

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

      $lenJobArray = count($jobArray);
      if ($lenJobArray > 0) :

         // 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", "");
         // $font = $pdf->load_font("Courier New", "winansi", "");
         
         // Iterate all jobs of the selected invoice
         for ($i = 0; $i < $lenJobArray; $i++) :
         
             // pdfNewPage();
         
             // Current job and mail address
             $job_id = $jobArray[$i][0];
             $currentHqId = $jobArray[$i][1];
             
             // Get number of entries in tour to scale the width of the PDF-page
             $pdfPageWidth = 1000;
             $pdfPageHeight = 500;
             $numOfTourEntries = getCountOfTable("tour", "jb_id = '" . $job_id . "'");
             $numOfTourEntries -= 5;
             if ($numOfTourEntries > 0) :
                $pdfPageWidth += ($numOfTourEntries * 200);
             endif;

             $pdf->begin_page_ext(0,0, "width=" . $pdfPageWidth . " height=" . $pdfPageHeight);
             $pdf->setfont($font, 12);
             $pdf->show_xy("Rechnung: " . $invId4PDF, 15, 480);
             $pdf->show_xy("Auftrag: " . $job_id, 15, 465);
             $pdf->setfont($font, 8);
             
             // PDF_begin_page_ext($pdf, $pdfPageWidth, 500, "");
             // PDF_setfont($pdf, $font, 12);
             // PDF_show_xy($pdf, "Rechnung: " . $invId4PDF, 15, 480);
             // PDF_show_xy($pdf, "Auftrag : " . $job_id, 15, 465);
             // PDF_setfont($pdf, $font, 8);
             
             if ($job_id != "" && $currentHqId != "") :
                ob_start();
                $sqlStatementArray = callJbDetail();
                ob_end_clean();    // Erases output buffer
             endif;

             // Job data
             $result = $db->query($sqlStatementArray[0]);
             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";
             $titlesArray = spliti(",",$titles);
             $fieldsArray = spliti(",",$fields); 
             $fieldsLength = count($fieldsArray);
             $pdfTextOffsetRow = 0;    // Offset for rows
             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]);

                       $pdf->show_xy($titlesArray[$j] . ": ", 15, (430 - $pdfTextOffsetRow));
                       $pdf->show_xy(formatOutput($row[$tmpVarName],$outputFormatField[$tmpVarName]), 100, (430 - $pdfTextOffsetRow));
                       // PDF_show_xy($pdf, $titlesArray[$j] . ": ", 15, (430 - $pdfTextOffsetRow));
                       // PDF_show_xy($pdf, formatOutput($row[$tmpVarName],$outputFormatField[$tmpVarName]), 100, (430 - $pdfTextOffsetRow));
                       
                       
                       $job_cr_sid = $row["cr_sid"];
                       
                       $pdfTextOffsetRow = $pdfTextOffsetRow + 10;
                   endfor;                         
             endwhile;
             $result->free();          

             // Tour data
             $result = $db->query($sqlStatementArray[1]);
             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);
             $tourentry = "";
             $rowCounter = 0;             
             $pdfTextOffsetCol = 0;    // Offset for cols
             while ($row = $result->fetch_assoc()):
                   $rowCounter++;                   
                   $pdfTextOffsetRow = 0;    // Offset for rows
                                      
                   for ($j = 0; $j < $fieldsLength; $j++) :
                       
                       if (trim($titlesArray[$j]) == "") : $titlesArray[$j] = " "; endif;

                       if ($rowCounter == 1) :
                          if (!mb_check_encoding($titlesArray[$j], 'UTF-8')) {
                             $titlesArray[$j] = mb_convert_encoding($titlesArray[$j], 'UTF-8');
                          }
                          $pdf->show_xy($titlesArray[$j] . ": ", (15 + $pdfTextOffsetCol), (270 - $pdfTextOffsetRow));
                          // PDF_show_xy($pdf, $titlesArray[$j] . ": ", (15 + $pdfTextOffsetCol), (270 - $pdfTextOffsetRow));
                       elseif ($j == 0) :
                          $tourentry .= "<img arr>";
                       else :
                          $tourentry .= "";
                       endif;
                       $tmpVarName = $fieldsArray[$j];
                       ${$tmpVarName} = $row[$tmpVarName];
                       $outField = formatOutput(${$tmpVarName},$outputFormatField[$tmpVarName]);

                       // 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";
                             $im = createSignImage($rawCoord);
                             $boolImg = true;
                             if (!file_exists($imgFilename)) :
                                $boolImg = imagepng($im, $imgFilename);
                             endif;

                             // $image1 = PDF_load_image($pdf, "png", $path . substr($imgFilename, 2), "");
                             if ($boolImg) :
                                // $image1 = PDF_load_image($pdf, "png", $path . substr($imgFilename, 2), "");
                                $image1 = $pdf->load_image("png", $imgFilename, "");
                                if ($image1 != -1) :
                                   // PDF_fit_image($pdf, $image1, (100 + $pdfTextOffsetCol), 70, "boxsize {100 50} fitmethod meet" );
                                   $pdf->fit_image($image1, (100 + $pdfTextOffsetCol), 70, "boxsize {100 50} fitmethod meet" );
                                endif;
                             endif;
                          endif;
                       endif;

                       // Finishtime of the stop
                       if ($tmpVarName == "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;
                          if (!mb_check_encoding($outField, 'UTF-8')) {
                             $outField = mb_convert_encoding($outField, 'UTF-8');
                          }
                          $pdf->show_xy($outField, (100 + $pdfTextOffsetCol), (270 - $pdfTextOffsetRow));
                          // PDF_show_xy($pdf, $outField, (100 + $pdfTextOffsetCol), (270 - $pdfTextOffsetRow));
                          $pdfTextOffsetRow = $pdfTextOffsetRow + 10;
                       endif;
                   endfor;         
                   $pdfTextOffsetCol = $pdfTextOffsetCol + 120;
             endwhile;
             $result->free();             
             
             // Courier data
             $result = $db->query($sqlStatementArray[2]);
             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);
             $pdfTextOffsetRow = 0;    // Offset for rows
             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]);                       

                       $tmpOut = $titlesArray[$j] . ": ";
                       if (!mb_check_encoding($tmpOut, 'UTF-8')) {
                         $tmpOut = mb_convert_encoding($tmpOut, 'UTF-8');
                       }
                       $pdf->show_xy($tmpOut, 250, (430 - $pdfTextOffsetRow));
                       
                       $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, (430 - $pdfTextOffsetRow));
                       
                       // PDF_show_xy($pdf, $titlesArray[$j] . ": ", 250, (430 - $pdfTextOffsetRow));
                       // PDF_show_xy($pdf, formatOutput($row[$tmpVarName],$outputFormatField[$tmpVarName]), 300, (430 - $pdfTextOffsetRow));
                       
                       $pdfTextOffsetRow = $pdfTextOffsetRow + 10;
                   endfor;                         
             endwhile;
             $result->free();
         
             // Job costs
             $result = $db->query($sqlStatementArray[3]);
             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;
             $pdfTextOffsetRow = 0;    // Offset for rows
             while ($row = $result->fetch_assoc()):
                   $rowCounter++;
                   $pdfTextOffsetCol = 0;    // Offset for cols
                   
                   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;

                       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), 370);
                          // PDF_show_xy($pdf, $titlesArray[$j] . ": ", (15 + $pdfTextOffsetCol), 370);
                       endif;
                       
                       $outField = formatOutput($row[$tmpVarName],$outputFormatField[$tmpVarName]);
                       
                       // 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), (360 - $pdfTextOffsetRow));
                       // PDF_show_xy($pdf, $outField, (15 + $pdfTextOffsetCol), (360 - $pdfTextOffsetRow));

                       $pdfTextOffsetCol = $pdfTextOffsetCol + 150;
                   endfor;
                   
                   $pdfTextOffsetRow = $pdfTextOffsetRow + 10;
             endwhile;
             $result->free();
             if ($rowCounter > 0) :
                $pdfTextOffsetCol = $pdfTextOffsetCol - 150;
                $sumOfBusinessVolume = number_format(round($sumOfBusinessVolume,2), 2, ",", ".");
                $sumOfBusinessVolume = pad($sumOfBusinessVolume,8," ");
                $pdf->show_xy($sumOfBusinessVolume . " GESAMT", (15 + $pdfTextOffsetCol), (360 - $pdfTextOffsetRow));
                // PDF_show_xy($pdf, $sumOfBusinessVolume . " GESAMT", (15 + $pdfTextOffsetCol), (360 - $pdfTextOffsetRow));
             endif;
         
             $pdf->end_page_ext("");
             // PDF_end_page_ext($pdf, "");
         endfor;

         $pdf->end_document("");
         // PDF_end_document($pdf, "");
         $output = $pdf->get_buffer();
         // $output = PDF_get_buffer($pdf);
         header("Content-type: application/pdf"); //set filetype to pdf.
         header("Content-Length: ".strlen($output)); //content length
         header("Content-Disposition: attachment; filename=" . $invId4PDF . ".pdf"); // you can use inline or attachment.
         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
         header('Pragma: public');
         echo $output; // actual print area!
         // PDF_delete($pdf);
         die();
      else :
         $statusMessage = "Es wurde keine PDF-Datei generiert!";
      endif;
   else :
      $statusMessage = "Es liegt eine Inkonsistenz bzgl. der Rechnungsnummer vor!";
   endif;
endif;


// Show all specified jobs of the customer
$invoiceNumberArray = array();    // Distinct array of all invoice numbers of the selelected date interval
if ($f_act == "loadJobsOfCustomer") :
   if ($g_cs_id != "") :   

       // Filter export according specified vehicle types (if NO type is specified then this filter is not be used)
       $whereClauseFilterVehicleType = "";
       $f_vht_filter_len = count($f_vht_filter);
       if ($f_vht_filter_len > 0) :          
          for ($i = 0; $i < $f_vht_filter_len; $i++) :
              if ($whereClauseFilterVehicleType != "") :
                 $whereClauseFilterVehicleType .= " OR ";
              endif;
              $whereClauseFilterVehicleType .= " jb.vht_id = '" . $f_vht_filter[$i] . "'";
          endfor;
          if ($whereClauseFilterVehicleType != "") :
             $whereClauseFilterVehicleType = " AND (" . $whereClauseFilterVehicleType . ") ";
          endif;
       endif;

       $sqlquery = "SELECT jb.jb_id, jb.jb_totalprice AS price, jb.jb_export_time, jb.jb_ordertime, jb.jb_finishtime, jb.jb_freetext_1,"
                    . "    jb.cr_sid, tr.tr_commission_no, csc.csc_name, inv.inv_no, inv.inv_datetime "
                    . " FROM job AS jb LEFT JOIN invoice AS inv ON inv.jb_id = jb.jb_id, tour AS tr, costcenter AS csc"
                    . " WHERE jb.jb_status = '2'                  AND"
                    . "       (NOT isnull(jb.jb_export_time))     AND"
                    . "       jb.jb_ordertime >= '$fromDateRange' AND"
                    . "       jb.jb_ordertime <= '$toDateRange'   AND"
                    . "       jb.jb_id = tr.jb_id                 AND"
                    . "       tr.tr_sort = '1'                    AND"
                    . "       jb.csc_id_payer = csc.csc_id        AND"
                    . "       csc.cs_id = '" . $g_cs_id . "' "
                    .         $whereClauseFilterVehicleType
                    . " ORDER BY jb.jb_id";

       $result = $db->query($sqlquery);
// echo $sqlquery . "<br>";
       if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     
       $out = "";
       while ($row = $result->fetch_assoc()):
             $numOfRows++;
             
             $sumOfJobPrices += $row["price"];
 
             $out .= "<tr class=\"f10np1\">";
             
             $invNo = $row["inv_no"];
             if ($invNo == "") : 
                $invNo = "&nbsp;";
             else :
               $j = array_search($invNo, $invoiceNumberArray);
               if ($j === FALSE) : $invoiceNumberArray[] = $invNo; endif;
             endif;
             $out .= "<td align=\"center\"> ". $invNo . "</td> ";

             $tmpDateTime = formatOutput($row["inv_datetime"],"datetime","3");                                        
             $out .= "<td align=\"center\"> ". substr($tmpDateTime,0,8) . " - " . substr($tmpDateTime,11,5) . "</td>";             
             
             $out .= "<td align=\"center\"><input type=\"checkbox\" name=\"f_jobs[]\" value=\"". $row["jb_id"] . "\" > </td> ";
             $out .= "<td align=\"center\"> ". $row["jb_id"] . "</td> ";
             
             $tmpDateTime = formatOutput($row["jb_ordertime"],"datetime","3");
             $out .= "<td align=\"center\"> ". substr($tmpDateTime,0,8) . " - " . substr($tmpDateTime,11,5) . "</td>";
             
             $tmpDateTime = formatOutput($row["jb_finishtime"],"datetime","3");
             $out .= "<td align=\"center\"> ". substr($tmpDateTime,0,8) . " - " . substr($tmpDateTime,11,5) . "</td>";
             $out .= "<td align=\"right\"> ". formatOutput($row["price"],"float_rounded_2") . "&nbsp;</td> ";
             $out .= "<td align=\"center\"> ". $row["cr_sid"] . "</td> ";
             // $out .= "<td> ". $row["jb_freetext_1"] . "<br>[Kst.: " . $row["csc_name"] . "]</td> ";
             $out .= "<td align=\"center\">";
             /*
             if ($row["jb_export_time"] == "" || $row["jb_export_time"] == "0000-00-00 00:00:00") :
                 $out .= "<a href=\"../jobs/job_edit.php?jb_id=" . ec($row["jb_id"]) . "\" target=\"_blank\">" . $row["jb_id"] . "</a>";
             else :
                 $out .= "Exportiert";
             endif;
             */
             $out .= "</td>";
             $out .= "</tr>\n";
       endwhile;
       $result->free();
   else :
      $statusMessage = "Sie haben noch keinen Kunden ausgewählt!";
   endif;
endif;


// *** Output ***

// Preparation of the generation of the PDF-documents
$outInvoiceNumbersForPDF = "";
$invoiceNumberArrayLen = count($invoiceNumberArray);
for ($i = 0; $i < $invoiceNumberArrayLen; $i++) {
	  $outInvoiceNumbersForPDF .= "<a href=\"javascript:generateInvoicePDF('" . ec($invoiceNumberArray[$i]) . "');\" target\"_blank\">" . $invoiceNumberArray[$i] . "</a>";
	  if ((($i + 1) % 5) == 0) :
	     $outInvoiceNumbersForPDF .= "<br><br>";
	  else :
	     $outInvoiceNumbersForPDF .= "&nbsp;&nbsp;";
	  endif;
}

$currentFrameName = "";  // Empty string for "main frame"

// Date-ranges 
$filter_dateranges .= "<td><span class=\"f12bp1_blue\">Auftragsdatum:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>";
$filter_dateranges .= "Von:\n";
$filter_dateranges .= "<select name=\"day_from\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'jb_inv_assoc', 'day_from', 'day_from', 'month_from', 'year_from', '', '', '')\"></select>\n";
$filter_dateranges .= "<select name=\"month_from\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'jb_inv_assoc', 'month_from', 'day_from', 'month_from', 'year_from', '', '', '')\"></select>\n";
$filter_dateranges .= "<select name=\"year_from\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'jb_inv_assoc', 'year_from', 'day_from', 'month_from', 'year_from', '', '', '')\"></select>\n";
$filter_dateranges .= "</td><td>&nbsp;&nbsp;bis:\n";
$filter_dateranges .= "<select name=\"day_to\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'jb_inv_assoc', 'day_to', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
$filter_dateranges .= "<select name=\"month_to\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'jb_inv_assoc', 'month_to', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
$filter_dateranges .= "<select name=\"year_to\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'jb_inv_assoc', 'year_to', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
$filter_dateranges .= "</td>";   

// Javascript-function as template only for
$js_date = "<script type=\"text/javascript\">\n";
$js_date .= "<!--\n";
$js_date .= "function initForm() {\n";
$js_date .= "  fillDateFields(1,\"" . $currentFrameName . "\",\"jb_inv_assoc\",\"\",\"day_from\",\"month_from\",\"year_from\",\"\",\"\",\"\");\n";
$js_date .= "  setDateTimeFields(\"" . $currentFrameName . "\",\"jb_inv_assoc\",".$day_from.",".$month_from.",".$year_from.", \"\", \"\", \"day_from\", \"month_from\", \"year_from\", \"\", \"\", \"\");\n";
$js_date .= "  fillDateFields(1,\"" . $currentFrameName . "\",\"jb_inv_assoc\", \"\", \"day_to\", \"month_to\", \"year_to\", \"\", \"\", \"\");\n";
$js_date .= "  setDateTimeFields(\"" . $currentFrameName . "\",\"jb_inv_assoc\",".$day_to.",".$month_to.",".$year_to.", \"\", \"\", \"day_to\", \"month_to\", \"year_to\", \"\", \"\", \"\");\n";
$js_date .= "}\n";
$js_date .= "-->\n";
$js_date .= "</script>\n";   
?>

<html>

<head>
<title>PDF-AUSGABE</title>

<link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<style type="text/css">
  <?php include_once ("../css/navigation.css.php"); ?>
</style>

<?php include_once ("../include/js_framework.inc.php"); ?>

<script src="../include/searchLists.js" type="text/javascript"></script>
<script src="../include/checkFormTags.js" type="text/javascript"></script>
<script src="../include/lib_global.js" type="text/javascript"></script>

<?php echo $js_date ?>

<script type="text/javascript">
<!--
// NAVIGATION
<?php echo $jsMenuOut; ?>

function searchCs() {
  searchCsCscGeneric('111000000000111');
};

function finishPage(mode) {
  if (mode == 'storeJobs') {
     if (document.forms[0].g_cs_id.value != '') {
     	  if (document.forms[0].f_inv_no.value != '' && document.forms[0].f_inv_datetime_day.value != '' && 
     	      document.forms[0].f_inv_datetime_month.value != '' && document.forms[0].f_inv_datetime_year.value != '') {
           if (confirm('Möchten Sie die Rechnungsnummer und das Rechnungsdatum den markierten Aufträgen zuordnen?')) {        	
  	           document.forms[0].f_act.value = mode;
   	           document.forms[0].action.disabled = true;
               document.forms[0].submit();
           }
        } else {
        	alert('Tragen Sie bitte eine Rechnungsnummer und ein Rechnungsdatum ein!');
        }
     } else {
       alert('Sie müssen zuvor bitte einen Kunden wählen!');
     }
  }
  if (mode == 'clearPage') {
     if (confirm('Möchten Sie die komplette Seite zurücksetzen?')) {     	
        document.location.href = "jb_inv_assoc.php?currentNavigationItem=pdf_ausgabe";
     }
  }
  if (mode == 'clearPageAndCustomerSearch') {
     if (document.forms[0].g_cs_id.value != '') {
        if (confirm('Möchten Sie einen neuen Kunden wählen? Die Seiteninformationen gehen verloren!')) {
           document.location.href = "jb_inv_assoc.php?initCsSearch=1";
        }
     } else {
     	searchCs();
     };
  }
  if (mode == 'loadJobsOfCustomer') {
     // if (confirm('Aufträge für den gewählten Kunden anzeigen?')) {
        document.forms[0].f_act.value = mode;
        document.forms[0].submit();
     // }
  }
};

function checkDate(checkObj,mode) {
  var resetValue = checkDateFields(checkObj,mode);
  if (resetValue) {
  	 checkObj.value = '';
     checkObj.focus();
  }
}

function generateInvoicePDF(invNo) {
  document.forms[0].invId4PDF.value = invNo;
  document.forms[0].f_act.value = 'generatePDF';
  document.forms[0].submit();
}

function showPageStatus() {
  alert('g_cs_id: ' + document.forms[0].g_cs_id.value);
  alert('g_csc_id: ' + document.forms[0].g_csc_id.value);
  alert('g_csc_name: ' + document.forms[0].g_csc_name.value);
}

function jbCheckAll(numOfRows) {
  for (i = 0; i < numOfRows; i++) {
	  document.getElementsByName('f_jobs[]')[i].checked = true;
	}
}

function jbUncheckAll(numOfRows) {
  for (i = 0; i < numOfRows; i++) {
	  document.getElementsByName('f_jobs[]')[i].checked = false;
  }
}
-->
</script>

</head>

<body onLoad="<?php echo $phpCurrentNavigationOnLoad ?>initForm();displayStatusMessage(); <?php if ($initCsSearch == "1") : echo "searchCs();" ; endif; ?>">

<?php echo $phpMenuOut ?>
<?php echo $phpReducedMenuOut ?>
<?php echo $phpPageTitelOut ?>

<div class="maincontent" name="maincontent" id="maincontent">

  <form name="jb_inv_assoc" action="jb_inv_assoc.php" method="post">
  
  <input type="hidden" name="f_act" value="">
  <input type="hidden" name="g_cs_id" value="<?php echo $g_cs_id ?>">
  <input type="hidden" name="g_csc_id" value="<?php echo $g_csc_id ?>">
  <input type="hidden" name="invId4PDF" value="">
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">

  <?php echo htmlDivLineSpacer("5px"); ?>

  <!- Date-ranges -->
  <div class="f12bp1_blue">
    <table cellspacing="0" cellpadding="0" vspace="0" hspace="0">
      <tr>
         <?php echo $filter_dateranges ?>
      </tr>
    </table>
  </div>
  <?php echo htmlDivLineSpacer("40px", "", "left"); ?>

  <div class="f12bp1_blue">
    <div style="float:left">
      Aufträge der Firma:&nbsp;&nbsp;
      <input type="text" name="g_cmp_comp" value="<?php echo $g_cmp_comp ?>" size="30" readonly >
      <input type="text" name="g_cmp_comp2" value="<?php echo $g_cmp_comp2 ?>" size="30" readonly >
      <input type="text" name="g_cs_eid" value="<?php echo $g_cs_eid ?>" size="10" readonly >
      <input type="text" name="g_csc_name" value="<?php echo $g_csc_name ?>" size="25" readonly >
      &nbsp;&nbsp;
      <!-- <input type="button" value="!!!" onClick="showPageStatus();"> -->
    </div>
    <?php echo defineButtonType10("Kunde&nbsp;suchen", "action_search", "finishPage('clearPageAndCustomerSearch');", "120", "left", "5"); ?>
  </div>
  <?php echo htmlDivLineSpacer("30px", "", "left"); ?>

  <!- Vehicle filters -->
  <div>
    Fahrzeug-Filter: &nbsp;&nbsp;&nbsp;
    <?php echo addCheckboxesFromTable("f_vht_filter","metatype","mt_sort","mt_value","mt_sort","mt_type = 'vehicletype' AND mt_sort > '0' AND mt_sort < '8'","", "&nbsp;&nbsp;&nbsp;&nbsp;"); ?>
  </div>
  <?php echo htmlDivLineSpacer("30px", "", "left"); ?>

  <!-- Search, reset and store -->
  <div>
    <?php echo defineButtonType10("Seite&nbsp;komplett&nbsp;zurücksetzen", "action_reset", "finishPage('clearPage');", "220", "left", "10"); ?>
    <?php echo defineButtonType10("Rechnungsangaben&nbsp;zuordnen", "action_reset", "finishPage('storeJobs');", "220", "left", "10"); ?>
    <?php echo defineButtonType10("Aufträge&nbsp;anzeigen", "action_load", "finishPage('loadJobsOfCustomer');", "200", "left", "10"); ?>
  </div>
  <?php echo htmlDivLineSpacer("30px", "", "left"); ?>

  <div>
    Rechnungsnummer: <input type="text" name="f_inv_no" value="">
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    Rechnungsdatum: <input type="text" name="f_inv_datetime_day" value="" size="2" maxlength="2" onBlur="checkDate(this,'day')">
                    <input type="text" name="f_inv_datetime_month" value="" size="2" maxlength="2" onBlur="checkDate(this,'month')">
                    <input type="text" name="f_inv_datetime_year" value="" size="4" maxlength="4" onBlur="checkDate(this,'year')">
                    (TT-MM-JJJJ)
  </div>
  <?php echo htmlDivLineSpacer("30px", "", "left"); ?>
  
  <div>
    <div style="float:left">
      Aufträge markieren: &nbsp;&nbsp;&nbsp;
    </div>
    <?php echo defineButtonType10("Alle", "action_check", "jbCheckAll(" . $numOfRows . ");", "60", "left", "3"); ?>
    <?php echo defineButtonType10("Keine", "action_uncheck", "jbUncheckAll(" . $numOfRows . ");", "60", "left", "3"); ?>
  </div>
  <?php echo htmlDivLineSpacer("30px", "", "left"); ?>
  
  <!-- Input fields for new jobs-->
  <div>
    <table class="f8np1" border="1" cellpadding="0">
      <tr>
        <td>&nbsp;Re.-Nr.&nbsp;</td> <td>&nbsp;Re.-Dat.&nbsp;</td> <td>&nbsp;Zuordnen&nbsp;</td> <td>&nbsp;Auftrag&nbsp;</td> 
        <td>&nbsp;Auftragszeit&nbsp;</td> <td>&nbsp;Erledigungszeit&nbsp;</td> 
        <td>&nbsp;Betrag&nbsp;</td> <td>&nbsp;Fahrzeug&nbsp;</td>
      </tr>
    
      <!-- Stored jobs -->
      <?php echo $out ?>
      
      <?php if ($sumOfJobPrices != 0) : ?>
      <tr>
        <td>&nbsp;&nbsp;</td> <td>&nbsp;&nbsp;</td> <td>&nbsp;&nbsp;</td> <td>&nbsp;&nbsp;</td> 
        <td>&nbsp;&nbsp;</td> <td>&nbsp;&nbsp;</td> 
        <td class="f8np1_red">&nbsp;<?php echo number_format(round($sumOfJobPrices,2), 2, ",", ".") ?>&nbsp;</td> <td>&nbsp;&nbsp;</td>
      </tr>
      <?php endif; ?>
    </table>
  </div>
  <?php echo htmlDivLineSpacer("30px", "", "left"); ?>

  <!-- Invoice numbers of the selected interval to generate PDF documents -->
  <div>
    PDF-Dokument generieren für Rechnungsnummer:<br><br>
    <table class="f8np1" border="0" cellpadding="0">
      <tr>
        <td>
          Sortierung der Aufträge nach Kostenstelle
          <input type="radio" name="f_filter" value="0" <?php if ($f_filter == "0") : echo "checked"; endif; ?>>
          &nbsp;&nbsp;&nbsp;&nbsp;oder nach Auftragsnummer
          <input type="radio" name="f_filter" value="1" <?php if ($f_filter == "1") : echo "checked"; endif; ?>>
          <br><br>
        </td>
      </tr>
      <tr>
        <td>
          <?php echo $outInvoiceNumbersForPDF ?>
        </td>
      </tr>
    </table>
  </div>
  <?php echo htmlDivLineSpacer("30px", "", "left"); ?>

  </form>
</div>

</body>

</html>
