<?php
/*=======================================================================
 *
 * inv_aux.inc.php
 *
 * Autor: Carsten Annacker
 *
 =======================================================================*/

include_once("../include/caglobal.inc.php");
include_once("../include/global.inc.php");
include_once("../include/services_func.inc.php");
if (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true))
{
  include_once ("../admin/menu.php");
  include_once ("../include/html.inc.php");
}

function mk_job_list($sqlquery /*, $getCr_sid = true */, $show_invoice_text = "false")
{
  global $PHP_SELF, $db2, $dbh_tr, $hq_id;
  
  $invoice_text_separator = "";  
  while (strlen($invoice_text_separator) < INV_MAXCOLS)
    $invoice_text_separator .= "_";  

//  // get cr_sid of all couriers of current hq
//  if ($getCr_sid)
//    $cr_sid_list = mkCr_sid_list();
  // print $sqlquery . "<br>";
  $res = $db2->query($sqlquery);
  if (DB::isError($res))
    reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
  $i = 0;
  $job_list = array();
  $prev_job_id = 0;
  while ($row = $res->fetch_assoc()):
//print_r($row);
//echo "<br>";
    if (
//         ($row["csc_id_payer"] == 0) ||
//         (
//           (
//             ($row["csc_id_payer"] != 0) ||
//             ($row["jb_fixprice"] != "" && $row["jb_fixprice"] != 0)
//           )
             /*&&*/ $prev_job_id != $row["jb_id"]
//         )
       ):
//      // if csc_id_payer == 0 then costsplit: take every tour of the job
//      // because the payer is the csc_id of each tour
//      // if csc_id_payer != 0 then no costsplit: take only one entry for the job
//      // because payer pays all tours of the job; the same applies if
//      // price is fix_price (no entries in tourservice)
//      // if csc_id_payer == -1 then cash (no invoice):  take only one entry for the job
//      // because paying is not interesting here
      $job_list[$i]["jb_id"] = $row["jb_id"];
      $job_list[$i]["csc_id"] = $row["csc_id"];
      $job_list[$i]["jb_ordertime"] = $row["jb_ordertime"];
      $job_list[$i]["cr_sid"] = $row["cr_sid"];
//      if ($getCr_sid):
//        $job_list[$i]["cr_id"] = $cr_sid_list[$row["cr_id"]];
//      else:
//        $job_list[$i]["cr_id"] = $row["cr_id"];
//      endif;
      $job_list[$i]["jb_finishtime"] = $row["jb_finishtime"];
      $job_list[$i]["jb_booktime"] = $row["jb_booktime"];
      $job_list[$i]["jb_export_time"] = isset($row["jb_export_time"]) ? $row["jb_export_time"] : "";
      $job_list[$i]["emp_id"] = $row["emp_id"];
      if ($row["csc_id_payer"] != 0):
        $job_list[$i]["csc_id_payer"] = $row["csc_id_payer"];
        $job_list[$i]["cnt_costsplit"] = 1;
      else:
        $job_list[$i]["csc_id_payer"] = $row["csc_id_tour"];
        // save tour count for fixprice with costsplit
        $job_list[$i]["cnt_costsplit"] =
          $db2->getOne("SELECT COUNT(jb_id) FROM $dbh_tr WHERE jb_id = " . $row["jb_id"]);
      endif;
      if ($row["jb_storno"] != 3 && $row["jb_storno"] != 4):
        $job_list[$i]["tr_comp"] = $row["tr_comp"] .
          (trim($row["ad_street"]) != "" ? ", " . $row["ad_street"] : "") .
          (trim($row["tr_hsno"]) != "" ? " " . $row["tr_hsno"] : "") .
          (trim($row["ad_zipcode"]) != "" ? ", " . $row["ad_zipcode"] : "") .
          (trim($row["ad_city"]) != "" ? " " . $row["ad_city"] : "") .
          (trim($row["tr_person"]) != "" ? "; " . $row["tr_person"] : "") .
          (trim($row["tr_remark"]) != "" ? "; " . nl2br($row["tr_remark"]) : "");
      else:
        $job_list[$i]["tr_comp"] = "(" . trim($row["jb_invtext"]) . ")";
      endif;
      $job_list[$i]["jb_invoice"] = "";
      if ($show_invoice_text == "true"):
        $job_list[$i]["jb_invoice"] = "<br>\n" . $invoice_text_separator . "<br>\n" .
          nl2br(trim($row["jb_invtext"])) . "<br>\n" . $invoice_text_separator . "<br>\n";
      endif;
      $mandatory_filters = trim(getParameterValue("0", "MASK_MANDATORY_FILTERS", $hq_id));
      if ($mandatory_filters != ''):
        $mandatory_filtersArr = explode(",", $mandatory_filters);
        for ($j = 0; $j < count($mandatory_filtersArr); $j++):
          if ($row["jb_cr_filter"] == $mandatory_filtersArr[$j])
            $row["jb_cr_filter"] = "";
          $row["jb_cr_filter"] = str_replace("," . $mandatory_filtersArr[$j] . ",", ",", $row["jb_cr_filter"]);
          $row["jb_cr_filter"] = str_replace($mandatory_filtersArr[$j] . ",", "", $row["jb_cr_filter"]);
          $row["jb_cr_filter"] = str_replace("," . $mandatory_filtersArr[$j], "", $row["jb_cr_filter"]);
        endfor;
      endif;
      $jb_cr_filter_list_str = "";
      if (trim($row["jb_cr_filter"]) != ""):
        $jb_cr_filter_list = explode(",", $row["jb_cr_filter"]);
//print_r($jb_cr_filter_list);
        for ($j = 0; $j < count($jb_cr_filter_list); $j++):
          if ($jb_cr_filter_list[$j] != ""):
            $jb_cr_filter_list_str .= ", " . $jb_cr_filter_list[$j];
          endif;
        endfor;
      endif;
      if ($jb_cr_filter_list_str != ""):
        $job_list[$i]["jb_invoice"] .= "<br>\nFilter: " . substr($jb_cr_filter_list_str, 2);
      endif;
      $job_list[$i]["jb_cr_remark"] = $row["jb_cr_remark"];
      $job_list[$i]["jb_fixprice"] = $row["jb_fixprice"];
      $job_list[$i++]["jb_incomplete"] = isset($row["jb_incomplete"]) ? $row["jb_incomplete"] : "";
      $prev_jb_invtext = $row["jb_invtext"];
      $prev_job_id = $row["jb_id"];
    else:
      if ($row["jb_storno"] != 3 && $row["jb_storno"] != 4):
        $job_list[$i-1]["tr_comp"] .= "<br>--&gt;&nbsp;" . $row["tr_comp"] .
          (trim($row["ad_street"]) != "" ? ", " . $row["ad_street"] : "") .
          (trim($row["tr_hsno"]) != "" ? " " . $row["tr_hsno"] : "") .
          (trim($row["ad_zipcode"]) != "" ? ", " . $row["ad_zipcode"] : "") .
          (trim($row["ad_city"]) != "" ? " " . $row["ad_city"] : "") .
          (trim($row["tr_person"]) != "" ? "; " . $row["tr_person"] : "") .
          (trim($row["tr_remark"]) != "" ? "; " . nl2br($row["tr_remark"]) : "");
      endif;
    endif;
  endwhile;
//print_r($job_list);
  $res->free();
  return $job_list;
}

//function mkCr_sid_list()
//{
//  global $PHP_SELF, $db2, $hq_id;
//
//  $res = $db2->query("SELECT cr_id, cr_sid FROM courier WHERE hq_id = '$hq_id'");
//  if (DB::isError($res))
//    reportDie ("$PHP_SELF: 'SELECT cr_id, cr_sid ...' :" . $res->getMessage());
//  $cr_sid_list = array();
//  while ($row = $res->fetch_assoc()):
//    $cr_sid_list[$row["cr_id"]] = trim($row["cr_sid"]);
//  endwhile;
//  $res->free();

//  return $cr_sid_list;
//}

//function print_job_list_cust($job_list, &$tpl)
//{
//  global $PHP_SELF, $db2, $hq_id;
//
//  // Print jobs and fetch their costs
//  $i = 0;
//  $all_sum = 0;
//  foreach ($job_list as $job)
//  {
//    if ($i % 2 == 0) : $cellColor = "#DDDDDD"; $cellColor2 = "#EEEEEE"; endif;
//    if ($i++ % 2 == 1) : $cellColor = "#BBBBFF"; $cellColor2 = "#CCCCFF"; endif;
//    $tmp_nr = $job["jb_id"];
//    $tmp_order_name = $db2->getOne("SELECT csc_name FROM costcenter WHERE csc_id = '" . $job["csc_id"] . "'") .
//      ", " .
//      $db2->getOne("SELECT usr_account FROM user WHERE usr_id = '" .
//        $db2->getOne("SELECT usr_id FROM employee WHERE emp_id = '" . $job["emp_id"] . "'") . "'");
//    $tmp_payer_name = $db2->getOne("SELECT csc_name FROM costcenter WHERE csc_id = '" . $job["csc_id_payer"] . "'");
//    $tmp_ordertime = my_datum_zeit_format_datetime($job["jb_ordertime"]);
//    $tmp_cr_id = $job["cr_id"];
//    $tmp_finishtime = my_datum_zeit_format_datetime($job["jb_finishtime"]);
//
//    // fetch costs and print them (if not fixprice)
//    if ($job["jb_fixprice"] == "" || $job["jb_fixprice"] == 0):
//      $sqlquery =
//        "SELECT tr_sort, trs_srv_name, trs_srvt_name, trs_price, trs_discount " .
//        "FROM $dbh_trs WHERE jb_id = '" . $job["jb_id"] . "'";
//      $res = $db2->query($sqlquery);
//      if (DB::isError($res)):
//        reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
//      endif;
//      $is_jb_fixprice = false;
//    else:
//      $is_jb_fixprice = true;
//    endif;
//    $job_sum = 0;
//    while (($row = $res->fetch_assoc()) || $is_jb_fixprice):
//      if (!$is_jb_fixprice):
//        $tmp_srv_name = str_replace("<br>", " ", $row["trs_srv_name"]) . " " . $row["trs_srvt_name"];
//        $tmp_price = $row["trs_price"] - $row["trs_discount"];
//      else:
//        // if costsplit, it must be considerered here!
//        if ($job["cnt_costsplit"] > 1):
//          $tmp_srv_name = "Festpreis (anteilig 1/" . $job["cnt_costsplit"] . ")";
//          $tmp_price = $job["jb_fixprice"] / $job["cnt_costsplit"];
//        else:
//          $tmp_srv_name = "Festpreis";
//          $tmp_price = $job["jb_fixprice"];
//        endif;
//        $is_jb_fixprice = false;
//      endif;
//      $tpl->setCurrentBlock("jobentry");
//      $tpl->setVariable("_jobentry_",
//        "<td bgcolor=\"$cellColor\" align=\"center\">$tmp_nr" .
//        "</td><td bgcolor=\"$cellColor2\" align=\"left\">$tmp_payer_name" .
//        "</td><td bgcolor=\"$cellColor\" align=\"left\">$tmp_order_name" .
//        "</td><td bgcolor=\"$cellColor2\" align=\"center\">$tmp_ordertime" .
//        "</td><td bgcolor=\"$cellColor\" align=\"center\">$tmp_cr_id" .
//        "</td><td bgcolor=\"$cellColor2\" align=\"center\">$tmp_finishtime" .
//        "</td><td bgcolor=\"$cellColor\" align=\"left\">" . $tmp_srv_name .
//        "</td><td bgcolor=\"$cellColor2\" align=\"right\">" . number_format($tmp_price, 2, ',', '.') .
//        "</td>"
//      );
//      $tpl->parseCurrentBlock("jobentry");
//      $tmp_nr = "&nbsp;";
//      $tmp_payer_name = "&nbsp;";
//      $tmp_order_name = "&nbsp;";
//      $tmp_ordertime = "&nbsp;";
//      $tmp_cr_id = "&nbsp;";
//      $tmp_finishtime = "&nbsp;";
//      $job_sum += $tmp_price;
//    endwhile;
//    $tpl->setCurrentBlock("jobentry");
//    $tpl->setVariable("_jobentry_",
//      "<td bgcolor=\"$cellColor\" align=\"center\">&nbsp;" .
//      "</td><td bgcolor=\"$cellColor2\" align=\"left\">&nbsp;" .
//      "</td><td bgcolor=\"$cellColor\" align=\"left\">&nbsp;" .
//      "</td><td bgcolor=\"$cellColor2\" align=\"center\">&nbsp;" .
//      "</td><td bgcolor=\"$cellColor\" align=\"left\">&nbsp;" .
//      "</td><td bgcolor=\"$cellColor2\" align=\"center\">&nbsp;" .
//      "</td><td bgcolor=\"$cellColor\" align=\"left\"><span style=\"color:red\"><i>#</i></span>" .
//      "</td><td bgcolor=\"$cellColor2\" align=\"right\"><span style=\"color:red\"><i>" .
//      number_format($job_sum, 2, ',', '.') .
//      "</i></span></td>"
//    );
//    $tpl->parseCurrentBlock("jobentry");
//    $res->free();
//    $all_sum += $job_sum;
//  }
//
//  if ($i % 2 == 0) : $cellColor = "#DDDDDD"; $cellColor2 = "#EEEEEE"; endif;
//  if ($i % 2 == 1) : $cellColor = "#BBBBFF"; $cellColor2 = "#CCCCFF"; endif;
//  $tpl->setCurrentBlock("jobentry");
//  $tpl->setVariable("_jobentry_",
//    "<td bgcolor=\"$cellColor\" align=\"center\">&nbsp;" .
//    "</td><td bgcolor=\"$cellColor2\" align=\"left\">&nbsp;" .
//    "</td><td bgcolor=\"$cellColor\" align=\"left\">&nbsp;" .
//    "</td><td bgcolor=\"$cellColor2\" align=\"center\">&nbsp;" .
//    "</td><td bgcolor=\"$cellColor\" align=\"left\">&nbsp;" .
//    "</td><td bgcolor=\"$cellColor2\" align=\"center\">&nbsp;" .
//    "</td><td bgcolor=\"$cellColor\" align=\"left\"><span style=\"color:red\"><i><b>Gesamtsumme</b></i></span>" .
//    "</td><td bgcolor=\"$cellColor2\" align=\"right\"><span style=\"color:red\"><i><b>" .
//    number_format($all_sum, 2, ',', '.') .
//    "</b></i></span></td>"
//  );
//  $tpl->parseCurrentBlock("jobentry");
//}

function print_job_list($job_list, &$tpl, $mode = "customer", $target = "html")
{
  global $PHP_SELF, $db2, $hq_id, $ascii_text, $price_title;

//print_r ($job_list);
  if ($mode == "courier"):
    // get Provision
    $hq_cr_prov = getFieldValueFromId("headquarters", "hq_id", "$hq_id", "hq_cr_prov");
    $hq_prov = getFieldValueFromId("headquarters", "hq_id", "$hq_id", "hq_prov");
    if ($target == "html"):
      $tpl .= "<tr>\n" .
        "<td align=\"center\">Lfd. Nr." .
        "</td><td align=\"center\" valign=\"bottom\">Auftr.-Nr.<br>Erfasser<br>Fahrzeug" .
//        "</td><td align=\"center\ valign=\"bottom\"">Erfasser" .
//        "</td><td align=\"center\ valign=\"bottom\"">Besteller (Firma, Person)" .
        "</td><td align=\"center\" valign=\"bottom\">Auftragszeit<br>Annahme<br>Erledigung" .
//        "</td><td align=\"center\" valign=\"bottom\">erledigt" .
//        "</td><td align=\"center\" valign=\"bottom\">gebucht" .
        "</td><td align=\"center\" valign=\"bottom\">Tour" .
        "</td><td align=\"left\" valign=\"bottom\">Leistung" .
        (INV_JB_CR_PRICE == 1
          ? "</td><td align=\"right\" valign=\"bottom\">Auftragswert&nbsp;&euro;" .
          "</td><td align=\"right\" valign=\"bottom\">Provisionsfrei&nbsp;&euro;</td>"
          : "</td><td align=\"right\" valign=\"bottom\">" . $price_title . " &euro;</td>" ) .
        "</tr>\n";
    elseif ($target == "ascii"):
    elseif ($target == "csv"):
    endif;
  elseif ($mode == "customer"):
    if ($target == "html"):
      $tpl .= "<tr>\n" .
        "<td align=\"center\">Lfd. Nr." .
        "</td><td align=\"center\">Auftr.-Nr." .
        "</td><td align=\"center\">Zahler (KST)" .
        "</td><td align=\"center\">Besteller (KST, MA)" .
        "</td><td align=\"center\">bestellt" .
        "</td><td align=\"center\">erledigt" .
        "</td><td align=\"center\">gebucht" .
        "</td><td align=\"center\">Kurier" .
        "</td><td align=\"center\">Leistung" .
        "</td><td align=\"center\">Preis &euro;</td>" .
        "</tr>\n";
    elseif ($target == "ascii"):
    elseif ($target == "csv"):
    endif;
  endif;

  // Print jobs and fetch their costs
  $i = -1;
  $all_sum = 0;
  $all_sum_fuhrlohn = 0;
  $prev_tmp_jb_id = 0;
  $job_cnt = 0;
  foreach ($job_list as $job)
  {
    if ($job["csc_id_payer"] != -1 || ($mode == "courier")): // Cash payments are not to be invoiced!!!
      $tmp_jb_id = $job["jb_id"];
      if ($tmp_jb_id != $prev_tmp_jb_id):
        $prev_tmp_jb_id = $tmp_jb_id;
        $tmp_jb_id_print = $tmp_jb_id;
        $tmp_job_cnt = ++$job_cnt;
        $i++;
        if ($db2->getOne("SELECT emp_id FROM employee WHERE usr_id = '" . $job["emp_id"] . "'") != ""):
          // Erfasser war Employee: Kundenauftrag
          $tmp_csc_name = $db2->getOne("SELECT csc_name FROM costcenter WHERE csc_id = '" . $job["csc_id"] . "'");
          if (trim($tmp_csc_name) != "")
            $tmp_csc_name .= ", ";
          $tmp_order_name = $tmp_csc_name .
            $db2->getOne("SELECT usr_name FROM user WHERE usr_id = '" .
//              $db2->getOne("SELECT usr_id FROM employee WHERE emp_id = '" .
              $job["emp_id"] . "'")
//              . "'")
              ;
        else:
          // Erfasser war kein Employee: Zentralenauftrag
          $tmp_order_name = $job["emp_id"] . $db2->getOne("SELECT cmp_comp FROM company WHERE cmp_id = '" .
            $db2->getOne("SELECT cmp_id FROM headquarters WHERE hq_id = '" .
              $db2->getOne("SELECT hq_id FROM user WHERE usr_id = '" .
                $job["emp_id"] . "'") . "'") . "'") .
            ", " .
            $db2->getOne("SELECT usr_name FROM user WHERE usr_id = '" . $job["emp_id"] . "'");
          $tmp_order_name = "(System)";
        endif;
//        $tmp_ordertime = str_replace("&nbsp;", "<br>", my_datum_zeit_format_datetime($job["jb_ordertime"])) . "&nbsp;Uhr";
        $tmp_ordertime = my_datum_zeit_format_datetime($job["jb_ordertime"], " ") . "&nbsp;Uhr";
        $tmp_cr_id = $job["cr_sid"];
//        $tmp_cr_id = $job["cr_id"];
//        $tmp_finishtime = str_replace("&nbsp;", "<br>", my_datum_zeit_format_datetime($job["jb_finishtime"])) . "&nbsp;Uhr";
        $tmp_finishtime = my_datum_zeit_format_datetime($job["jb_finishtime"], " ") . "&nbsp;Uhr";
//        $tmp_booktime = (trim($job["jb_booktime"]) != ""
//          ? str_replace("&nbsp;", "<br>", my_datum_zeit_format_datetime($job["jb_booktime"])) . "&nbsp;Uhr" : "");
        $tmp_booktime = (trim($job["jb_booktime"]) != ""
          ? my_datum_zeit_format_datetime($job["jb_booktime"], " ") . "&nbsp;Uhr" : "");
        $tmp_is_exported = (trim($job["jb_export_time"]) != "" ? true : false);
        $tmp_comp = $job["tr_comp"];
        $tmp_invoice = $job["jb_invoice"];
        $tmp_remark = $job["jb_cr_remark"];
      endif;
      // wenn Root-Kostenstelle, dann Name aus company nehmen      
      if (trim($db2->getOne("SELECT csc_pre_id FROM costcenter WHERE csc_id = '" . $job["csc_id_payer"] . "'")) == ""):
        $tmp_payer_name = $db2->getOne(
          "SELECT company.cmp_comp FROM company, customer, costcenter" .
          " WHERE customer.cs_id = costcenter.cs_id AND company.cmp_id = customer.cmp_id " .
          " AND costcenter.csc_id = '" . $job["csc_id_payer"] . "'");
      else:
        // wenn Unterkostenstelle, dann Kostenstellennnamen
        $tmp_payer_name = $db2->getOne("SELECT csc_name FROM costcenter WHERE csc_id = '" . $job["csc_id_payer"] . "'");
      endif;
      // Die Kundennummer in Klammern dahinter
      $tmp_payer_name .= " (" . $db2->getOne("SELECT cs.cs_eid from customer AS cs, costcenter AS csc" .
          " WHERE cs.cs_id = csc.cs_id AND csc.csc_id = '" . $job["csc_id_payer"] . "'") . ")";
      $costArr = getJobCosts($job, $mode);
      mk_jobentry($mode, $tpl, $i, $tmp_job_cnt, $tmp_jb_id_print, $tmp_payer_name, $tmp_order_name,
        $tmp_ordertime, $tmp_finishtime, $tmp_booktime, $tmp_comp, $tmp_cr_id, "costArr", "costArr", $target, $costArr, $job["jb_incomplete"], $tmp_invoice, $tmp_remark, $tmp_is_exported);
      $tmp_order_name = "&nbsp;";
      $tmp_job_cnt = "&nbsp;";
      $tmp_ordertime = "&nbsp;";
      $tmp_finishtime = "&nbsp;";
      $tmp_booktime = "&nbsp;";
      $tmp_comp = "&nbsp;";
      $tmp_invoice = "&nbsp;";
      $tmp_remark = "&nbsp;";
      // Auftragssumme
      mk_jobentry($mode, $tpl, $i, "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;",
        "<i class=\"red\">" . $costArr[count($costArr) - 1][0] . "</i>",
        "<i class=\"red\">" . number_format($costArr[count($costArr) - 1][1], 2, ',', '.') . "</i>", $target, "", $job["jb_incomplete"], "", "&nbsp;");
      $tmp_jb_id_print = "&nbsp;";
      // zur Gesamtsumme addieren
      if (INV_JB_CR_PRICE == 1 && !(strpos ($costArr[count($costArr) - 1][0], "Fuhrlohn") === false)):
        $all_sum_fuhrlohn += $costArr[count($costArr) - 1][1];
      else:
        $all_sum += $costArr[count($costArr) - 1][1];
      endif;
    endif;
  }

  $all_sum_fuhrlohn_formatted = "&nbsp;";
  if ($mode == "courier" && INV_JB_CR_PRICE == 1)
    $all_sum_fuhrlohn_formatted = number_format($all_sum_fuhrlohn, 2, ',', '.');

  mk_jobentry($mode, $tpl, ++$i, "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;",
    "<i class=\"red\"><b>" . $all_sum_fuhrlohn_formatted . "</b></i>",
    "<i class=\"red\"><b>Gesamtsumme</b></i>",
    "<i class=\"red\"><b>" . number_format($all_sum, 2, ',', '.') . "</b></i>", $target, "Gesamtsumme", "", "", "&nbsp;");
  if ($mode == "courier" && $target != "csv"):
    if ($hq_cr_prov > 0 || $hq_prov > 0):
      $all_prov = -1 * $job_cnt * ($hq_cr_prov + $hq_prov);
      mk_jobentry($mode, $tpl, $i, "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;",
        "<span style=\"color:red\"><i><b>abzgl. Provision ($job_cnt Auftr. zu " .
        number_format(($hq_cr_prov + $hq_prov), 2, ',', '.') . " &euro;)</b></i></span>",
        "<span style=\"color:red\"><i><b>" . number_format($all_prov, 2, ',', '.') . "</b></i></span>", $target, "", "", "&nbsp;");
      mk_jobentry($mode, $tpl, ++$i, "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;", "&nbsp;",
        "<span style=\"color:red\"><i><b>Abrechnungssumme</b></i></span>",
        "<span style=\"color:red\"><i><b>" . number_format($all_sum + $all_prov, 2, ',', '.') . "</b></i></span>", $target, "", "", "&nbsp;");
    endif;
  endif;
}

function mk_jobentry($mode, &$tpl, $i, $job_cnt, $tmp_jb_id, $tmp_payer_name, $tmp_order_name,
  $tmp_ordertime, $tmp_finishtime, $tmp_booktime, $tmp_comp, $tmp_cr_id, $tmp_srv_name, $tmp_price, $target = "html", $costArr, $jb_incomplete = 0, $tmp_invoice = "", $tmp_remark = "", $tmp_is_exported = false)
{
  global $db2, $ascii_text, $csv_text, $dbhistory,
    $csc_id, $day_from, $month_from, $year_from, $day_to, $month_to, $year_to, $sel_cr_sid, $jb_status, $show_invoice_text, $usr_type;


  if ($tmp_srv_name == "costArr"):
    $tmp_srv_name = "";
    $tmp_price = "";
    for ($j = 0; $j < (count($costArr) - 1); $j++):
      if ($target == "html"):
        $tmp_srv_name .= $costArr[$j][0] . "<br>(" . $db2->getOne("SELECT mt_value FROM metatype WHERE mt_sort = '" . $db2->getOne("SELECT vht_id FROM job WHERE jb_id = " . $tmp_jb_id) . "' AND mt_type = 'vehicletype'") . ")";
        if ($mode == "courier"):
          $jb_cr_serviceprice = (float) $db2->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $tmp_jb_id . " AND mt_sort = 3");
          if ($jb_cr_serviceprice != "" AND $jb_cr_serviceprice != 0)
            $tmp_srv_name .= "<br>inkl. Servicevergütung " . number_format($jb_cr_serviceprice, 2, ',', '.') . " EUR";
//          $jbCrAgio = $db2->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $tmp_jb_id . " AND mt_sort = 7");
          $jbprc_cr_subtotal = (float) $db2->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $tmp_jb_id . " AND mt_sort = 10") - $jb_cr_serviceprice;
//          if ($jbCrAgio != "") {
//            $tmp_srv_name .= "<br>inkl. Kundenaufschlag " . number_format($jbprc_cr_subtotal * ($jbCrAgio / 100), 2, ',', '.') . " EUR (" . number_format($jbCrAgio, 2, ',', '.') . " % auf " . number_format($jbprc_cr_subtotal, 2, ',', '.') . ")";
//		    $jbprc_cr_subtotal = $jbprc_cr_subtotal * (1 + ($jbCrAgio / 100));
//          }
          $jbprc_cr_markup = $db2->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $tmp_jb_id . " AND mt_sort IN (1,9)");
          if ($jbprc_cr_markup != "")
            $tmp_srv_name .= "<br>inkl. Treibstoffzuschlag " . number_format($jbprc_cr_subtotal * ($jbprc_cr_markup / 100), 2, ',', '.') . " EUR (" . number_format($jbprc_cr_markup, 2, ',', '.') . " % auf " . number_format($jbprc_cr_subtotal, 2, ',', '.') . ")";
        endif;
        $tmp_price .= number_format($costArr[$j][1], 2, ',', '.') . "<br>";
      elseif ($target == "ascii"):
        $tmp_srv_name .= "\t" . tabExpand($costArr[$j][0]) . number_format($costArr[$j][1], 2, ',', '.') . "\n";
      elseif ($target == "csv"):
        if ($mode == "customer"):
          $tmp_srv_name .= "\"$tmp_jb_id\"\t\"\"\t\"\"\t\"\"\t\"\"\t\"\"\t\"" .
            $costArr[$j][0] . "\"\t\"" . number_format($costArr[$j][1], 2, ',', '.') . "\"\n";
        elseif ($mode == "courier"):
          $tmp_srv_name .= "\"$tmp_cr_id\"\t\"$tmp_jb_id\"\t\"\"\t\"\"\t\"\"\t\"\"\t\"\"\t\"" .
            $costArr[$j][0] . "\"\t\"" . number_format($costArr[$j][1], 2, ',', '.') . "\"\n";
        endif;
      endif;
    endfor;
  endif;

  if ($target == "html"):
    if ($jb_incomplete == 1):
      if ($i % 2 == 0) : $cellColor = "FFBBBB"; $cellColor2 = "FFCCCC"; endif;
      if ($i % 2 == 1) : $cellColor = "FF9999"; $cellColor2 = "FFAAAA"; endif;
    else:
      if ($i % 2 == 0) : $cellColor = "DDDDDD"; $cellColor2 = "EEEEEE"; endif;
      if ($i % 2 == 1) : $cellColor = "BBBBFF"; $cellColor2 = "CCCCFF"; endif;
    endif;
  endif;
  if ($mode == "customer"):
    if ($target == "html"):
      $tpl .= "<tr>\n" .
        "<td class=\"$cellColor\" align=\"center\" valign=\"top\">$job_cnt" .
        "</td><td class=\"$cellColor2\" align=\"center\" valign=\"top\">" .
        ($usr_type == 1
        ? "<a href=\"../jobs/job_edit.php?jb_id=" . ec($tmp_jb_id) . "&dbhistory=" . ec($dbhistory) . "\" target=_blank>" . $tmp_jb_id . "</a>"
        : "<a href=\"../customer/jb_detail.php?job_id=" . ec($tmp_jb_id) . "&dbhistory=" . ec($dbhistory) . "\" target=_blank>" . $tmp_jb_id . "</a>") .
        "</td><td class=\"$cellColor\" align=\"left\" valign=\"top\">$tmp_payer_name $tmp_invoice" .
        "</td><td class=\"$cellColor2\" align=\"left\" valign=\"top\">$tmp_order_name" .
        "</td><td class=\"$cellColor\" align=\"center\" valign=\"top\">$tmp_ordertime" .
        "</td><td class=\"$cellColor2\" align=\"center\" valign=\"top\">$tmp_finishtime" .
        "</td><td class=\"$cellColor\" align=\"center\" valign=\"top\">$tmp_booktime" .
        "</td><td class=\"$cellColor2\" align=\"center\" valign=\"top\">$tmp_cr_id" .
        "</td><td class=\"$cellColor\" align=\"left\" valign=\"top\">" . $tmp_srv_name .
        "</td><td class=\"$cellColor2\" align=\"right\" valign=\"top\">" . $tmp_price .
        "</td>" .
        "</tr>\n";
    elseif ($target == "ascii"):
      if ($costArr != "" && $costArr != "Gesamtsumme"):
        $ascii_text .= strip_tags(str_replace("&nbsp;", " ", str_replace("<br>", " ",
          "\n\nLfd. Nr.:\t\t\t$job_cnt\n" .
          "Auftr.-Nr.:\t\t\t$tmp_jb_id\n" .
          "Besteller (KST, MA):\t$tmp_order_name\n" .
          "Bestelldatum:\t\t$tmp_ordertime\n" .
          "Kuriernummer:\t\t$tmp_cr_id\n" .
          "Erledigt:\t\t\t$tmp_finishtime\n" .
          "\n$tmp_srv_name")));
      else:
        if ($costArr != "Gesamtsumme"):
          $ascii_text .= strip_tags(str_replace("&nbsp;", " ", str_replace("<br>", " ",
            "\t" . tabExpand(strip_tags($tmp_srv_name)) . "$tmp_price\n")));
        else:
          $ascii_text .= strip_tags(str_replace("&nbsp;", " ", str_replace("<br>", " ",
            "\n\n" . tabExpand(strip_tags($tmp_srv_name)) . "$tmp_price\n")));
        endif;
      endif;
    elseif ($target == "csv"):
      if ($costArr != "" && $costArr != "Gesamtsumme"):
        $csv_text .= strip_tags(str_replace("&nbsp;", " ", str_replace("<br>", " ",
          "\"$tmp_jb_id\"\t\"$tmp_payer_name\"\t\"$tmp_order_name\"\t" .
          "\"$tmp_ordertime\"\t\"$tmp_cr_id\"\t\"$tmp_finishtime\"\n$tmp_srv_name")));
      else:
        if ($costArr != "Gesamtsumme"):
          $csv_text .= strip_tags(str_replace("&nbsp;", " ", str_replace("<br>", " ",
            "\"$tmp_jb_id\"\t\"\"\t\"\"\t\"\"\t\"\"\t\"\"\t\"" .
            strip_tags($tmp_srv_name) . "\"\t\"$tmp_price\"\n")));
        endif;
      endif;
    endif;
  elseif ($mode == "courier"):
    if (INV_SHOW_JB_CR_REMARK == "1" && INV_JB_CR_PRICE == "1" /* letztere Bedingung damit das nur bei Gütertaxi angezeigt wird*/):
      if ($tmp_remark == ""):
        $tmp_remark = "(Bemerkung hinzuf&uuml;gen)";
        $tmp_remark_parm = "";
      else:
        $tmp_remark_parm = $tmp_remark;
      endif;      
      if ($tmp_remark != "&nbsp;"):
        $tmp_remark =
          "<br><br><div id=\"remark_link$tmp_jb_id\">\n" .
          "<i><a href=\"javascript:mkJb_cr_remark('remark_link" . $tmp_jb_id . "','remark_form" . $tmp_jb_id . "');\">$tmp_remark</a></i>" .
          "</div>\n" .
          "<div id=\"remark_form$tmp_jb_id\" style=\"display:none;\">\n" .
          "<form id=\"form$tmp_jb_id\" action=\"../invoice/inv_details_cr.php" .
          "?csc_id=$csc_id&day_from=$day_from&month_from=$month_from&year_from=$year_from&day_to=$day_to&month_to=$month_to&year_to=$year_to&cr_sid=$sel_cr_sid&jb_status=$jb_status&show_invoice_text=$show_invoice_text&dbhistory=$dbhistory\" " .
          "method=\"post\">\n" .
          "<input type=\"hidden\" name=\"jb_id\" value=\"" . $tmp_jb_id . "\">\n" .
          "<textarea id=\"jb_cr_remark$tmp_jb_id\" name=\"jb_cr_remark\" cols=\"60\" rows=\"4\" onKeyUp=\"countDigits('jb_cr_remark$tmp_jb_id')\" onClick=\"countDigits('jb_cr_remark$tmp_jb_id')\">\n" .
          $tmp_remark_parm . "</textarea>\n" .
          "</form>\n" .
          defineButtonType10("Abbrechen", "abbrechen", "mkJb_cr_remark('remark_form$tmp_jb_id','remark_link$tmp_jb_id');", "100", "left", "2", "Abbrechen alt+a", "a") .
          defineButtonType10("Löschen", "loeschen", "doDelete('jb_cr_remark$tmp_jb_id');", "100", "left", "2", "Löschen alt+l", "l") .
          defineButtonType10("Speichern", "speichern", "doSave('form$tmp_jb_id');", "100",  "left", "", "Speichern alt+s", "s") .
          "</div>\n";
      endif;
    else:
        $tmp_remark = "";
    endif;
    if ($target == "html"):
      $tpl .= "<tr>\n" .
        "<td class=\"$cellColor\" align=\"center\" valign=\"top\">$job_cnt" .
        "</td><td class=\"$cellColor2\" align=\"center\" valign=\"top\">$tmp_jb_id" .
          (trim($tmp_order_name) != "&nbsp;" ? "<br>$tmp_order_name": "") . "&nbsp;<br>" .
            (INV_SHOW_CR_ID_PARENT == "1" ? ($costArr == "Gesamtsumme" ? "&nbsp;" : $tmp_cr_id) : "") .   
//        "</td><td class=\"$cellColor\" align=\"left\" valign=\"top\">$tmp_order_name" .
        "</td><td class=\"$cellColor2\" align=\"center\" valign=\"top\">" . str_replace(" ", "&nbsp;", $tmp_ordertime) .
          (trim($tmp_booktime) != "&nbsp;" ? "<br>". str_replace(" ", "&nbsp;", $tmp_booktime) : "") .
          (trim($tmp_finishtime) != "&nbsp;" ? "<br>" . str_replace(" ", "&nbsp;", $tmp_finishtime) : "") .
//        "</td><td class=\"$cellColor\" align=\"center\" valign=\"top\">$tmp_finishtime" .
//        "</td><td class=\"$cellColor2\" align=\"center\" valign=\"top\">$tmp_booktime" .
        "</td><td class=\"$cellColor\" align=\"left\" valign=\"top\">$tmp_comp $tmp_invoice $tmp_remark" .
        "</td><td class=\"$cellColor2\" align=\"left\" valign=\"top\">" . str_replace("Fuhrlohn", "", str_replace("PLZ ", "", $tmp_srv_name)) .
        "</td><td class=\"$cellColor\" align=\"right\" valign=\"top\">" .
        (INV_JB_CR_PRICE == "1" && !(strpos ($tmp_srv_name, "Fuhrlohn") === false) ? "&nbsp;" : $tmp_price) .
        (INV_JB_CR_PRICE == "1"
          ? "</td><td class=\"$cellColor2\" align=\"right\" valign=\"top\">" .
            (!(strpos ($tmp_srv_name, "Fuhrlohn") === false)
              ? $tmp_price
              : ($costArr != "Gesamtsumme" ? "&nbsp;" : $tmp_cr_id))
          : "" ) .
        "</td>" .
        "</tr>\n";
    elseif ($target == "ascii"):
      if ($costArr != "" && $costArr != "Gesamtsumme"):
        $ascii_text .= strip_tags(str_replace("&nbsp;", " ", str_replace("<br>", " ",
          "\n\nLfd. Nr.:\t\t\t$job_cnt\n" .
          "Auftr.-Nr.:\t\t\t$tmp_jb_id\n" .
          "Erfasser:\t$tmp_order_name\n" .
//          "Besteller (Fa., Name):\t$tmp_order_name\n" .
          "Bestelldatum:\t\t$tmp_ordertime\n" .
          "Erledigt:\t\t\t$tmp_finishtime\n" .
          "\n$tmp_srv_name")));
      else:
        if ($costArr != "Gesamtsumme"):
          $ascii_text .= strip_tags(str_replace("&nbsp;", " ", str_replace("<br>", " ",
            "\t" . tabExpand(str_replace("&euro;", "EUR", strip_tags($tmp_srv_name))) . "$tmp_price\n")));
        else:
          $ascii_text .= strip_tags(str_replace("&nbsp;", " ", str_replace("<br>", " ",
            "\n\n" . tabExpand(strip_tags($tmp_srv_name)) . "$tmp_price\n")));
        endif;
      endif;
    elseif ($target == "csv"):
      if ($costArr != "" && $costArr != "Gesamtsumme"):
        $csv_text .= strip_tags(str_replace("&nbsp;", " ", str_replace("<br>", " ",
          "\"$tmp_cr_id\"\t\"$tmp_jb_id\"\t\"$tmp_order_name\"\t" .
          "\"$tmp_ordertime\"\t\"$tmp_finishtime\"\n$tmp_srv_name")));
      else:
        if ($costArr != "Gesamtsumme"):
          $csv_text .= strip_tags(str_replace("&nbsp;", " ", str_replace("<br>", " ",
            "\"$tmp_cr_id\"\t\"$tmp_jb_id\"\t\"\"\t\"\"\t\"\"\t\"\"\t\"\"\t\"" .
            strip_tags($tmp_srv_name) . "\"\t\"$tmp_price\"\n")));
        endif;
      endif;
    endif;
  endif;
}

function tabExpand($aStr)
{
  $tabCnt = ceil((48 - strlen($aStr)) / 6);
  $tabStr = "";
  for ($k = 1; $k <= $tabCnt; $k++) { $tabStr .= "\t"; }
  return ($aStr . $tabStr);
}

?>
