<?php
/*=======================================================================
 *
 * payments.php
 *
 * Autor: Carsten Annacker
 *
 =======================================================================*/

include_once("../include/auth.inc.php");
include_once("../include/dbglobal.inc.php");

//$dl = $_GET["dl"];
$jbpc_id = isset($_GET["jbpc_id"]) ? $_GET["jbpc_id"] : "";
$f_search_value = isset($_POST["f_search_value"]) ? trim($_POST["f_search_value"]) : "";
if ($f_search_value != "")
  $jbpc_id = trim($f_search_value);

$jb_export_time = isset($_GET["jb_export_time"]) ? $_GET["jb_export_time"] : "";
$csc_ids_related = isset($_GET["csc_ids_related"]) ? $_GET["csc_ids_related"] : "";

$f_payment_select = isset($_POST["f_payment_select"]) ? $_POST["f_payment_select"] : (isset($_GET["f_payment_select"]) ? $_GET["f_payment_select"] : "0");
$f_min_date = isset($_POST["f_min_date"]) ? sqlDate($_POST["f_min_date"]) . " 00:00:00" : "2015-03-10 00:00:00";
$f_max_date = isset($_POST["f_max_date"]) ? sqlDate($_POST["f_max_date"]) . " 23:59:59" : date("Y-m-d") . " 23:59:59";
$f_datetype = isset($_POST["f_datetype"][0]) ? $_POST["f_datetype"][0] : "1";
$f_lubu = isset($_POST["f_lubu"]) ? $_POST["f_lubu"] : "0";
$f_sifi = isset($_POST["f_sifi"]) ? $_POST["f_sifi"] : "0";
$f_schn = isset($_POST["f_schn"]) ? $_POST["f_schn"] : "0";
$f_mofl = isset($_POST["f_mofl"]) ? $_POST["f_mofl"] : "0";
$f_alto = isset($_POST["f_alto"]) ? $_POST["f_alto"] : "0";
//print_r($_POST); die();

if ($f_lubu == "0" && $f_sifi == "0" && $f_schn == "0" && $f_mofl == "0" && $f_alto == "0")
  /*$f_lubu = $f_sifi = */ $f_schn = $f_mofl = $f_alto = "1";

if ($csc_ids_related == "") {
  //$cs_ids_related = "";
//  $csc_ids_related = "";
  if ($f_lubu == "1") {
  //  $cs_ids_related .= ",3534,38252";
    $csc_ids_related .= ",3506";
  }
  if ($f_sifi == "1") {
  //  $cs_ids_related .= ",3540,38253";
    $csc_ids_related .= ",3512";
  }
  if ($f_schn == "1") {
  //  $cs_ids_related .= ",1,72470";
    $csc_ids_related .= ",1";
  }
  if ($f_mofl == "1") {
  //  $cs_ids_related .= ",2,72471";
    $csc_ids_related .= ",2";
  }
  if ($f_alto == "1") {
  //  $cs_ids_related .= ",17093,72185";
    $csc_ids_related .= ",17051";
  }
  $csc_ids_related = substr($csc_ids_related, 1);
}

$mysql_db_default = mysql_connect($dbhost, $dblogin, $dbpassword) or die (mysql_error());
mysql_select_db("phoenix", $mysql_db_default) or die (mysql_error($mysql_db_default));
mysql_query('SET NAMES latin1', $mysql_db_default) or die ('SET NAMES latin1' . ": " . mysql_error($mysql_db_default));

$mysql_db_b2b_history = mysql_connect($dbhost_history, $dblogin_history, $dbpassword_history) or die (mysql_error());
mysql_select_db("phoenix", $mysql_db_b2b_history) or die (mysql_error($mysql_db_b2b_history));
mysql_query('SET NAMES latin1', $mysql_db_b2b_history) or die ('SET NAMES latin1' . ": " . mysql_error($mysql_db_b2b_history));

$csv_txt = get_payments($jbpc_id, $jb_export_time, $f_payment_select, $f_min_date, $f_max_date, /* substr($cs_ids_related, 1), */ $csc_ids_related);
$csv_txt = "<table border=0 cellspacing=0 cellpadding=4 vspace=0 hspace=0>\n<tr><td>" .
  str_replace("<br>\n", "</td></tr>\n<tr><td>", str_replace(";", "</td><td align=right>", $csv_txt)) .
  "\n</table>\n";
$content .= str_replace(">#aa", " bgcolor=\"#DDDDDD\">", str_replace(">#ab", " bgcolor=\"#EEEEEE\">", str_replace(">#ba", " bgcolor=\"#BBBBFF\">", str_replace(">#bb", " bgcolor=\"#CCCCFF\">",
            str_replace(">#cc", " bgcolor=\"#DDBBBB\">", str_replace(">#cd", " bgcolor=\"#DDCCCC\">", str_replace(">#dc", " bgcolor=\"#FF9999\">", str_replace(">#dd", " bgcolor=\"#FFAAAA\">",
            $csv_txt))))))));

$content = str_replace("Zusatz zu", "Zusatz&nbsp;zu", str_replace("LCD happy", "LCD&nbsp;happy", str_replace("LCD sad", "LCD&nbsp;sad", str_replace("OS happy", "OS&nbsp;happy",
           str_replace("OS sad", "OS&nbsp;sad", str_replace("Küchen- und Möbelmon", "Küchen-&nbsp;und&nbsp;Möbelmon", str_replace("Austausch Abholung", "Austausch&nbsp;Abholung",
           str_replace("Austausch Lieferung", "Austausch&nbsp;Lieferung", $content))))))));

function get_payments($jbpc_id, $jb_export_time, $f_payment_select, $f_min_date, $f_max_date, /* $cs_ids_related, */ $csc_ids_related) {
  global $mysql_db_default, $f_datetype;

  $modeArr = array(
    0 => "bar",
    1 => "EC-PIN",
    2 => "EC-Last",
    10 => "Family",
    11 => "Business",
    15 => "Service",
    16 => "LCD happy",
    17 => "LCD sad",
    18 => "OS happy",
    19 => "OS sad",
    20 => "Rechnung an IKEA"
  );
  
  $cs_id_relatedArr = array(
    "3534"  => "LuBu",
    "3540"  => "SiFi",
    "38252" => "LuBu",
    "38253" => "SiFi",
    "1"     => "Schnelsen",
    "2"     => "Moorfleet",
    "17093" => "Altona",
    "72470" => "Schnelsen",
    "72471" => "Moorfleet",
    "72185" => "Altona"
  );
  
  $csc_id_relatedArr = array(
    "3506"  => "LuBu",
    "3512"  => "SiFi",
  //  "38172" => "LuBu/SiFi",
    "1"     => "Schnelsen",
    "2"     => "Moorfleet",
    "17051" => "Altona"
  );

  $cC = "#dc"; $cC2 = "#dd";
//  if ($colCnt % 2 == 0) : $cC = "#cc"; $cC2 = "#cd"; endif;
//  if ($colCnt++ % 2 == 1) : $cC = "#dc"; $cC2 = "#dd"; endif;
  $ret_val = $cC . ($f_payment_select == "1" || $jbpc_id != "" ? "Sammelnr." : "Bemerkung") . ";$cC2" . "Abrechnung" . ";$cC" . "Export" . ";$cC2" . "Zahlart" . ";$cC" . "Markt" . ";$cC2" . "Ordernummer" . ";$cC" . "Auftragsnr." . ";$cC2" . "Zusatz zu" . ";$cC" . "Dispo-Info" . ";$cC2" . "Preis" . ";$cC" . "Lagerk." . ";$cC2" . "Ausführung" . ";$cC" . "Erledigung" . ";$cC2" . "Status" . ";$cC" . "unfertig" . ";$cC2" . "Storno" . ";$cC" . "Fahrer" . ";$cC2" . "Fuhrlohn" . ";$cC" . "Export" . ";$cC2"  . "BSG" . "<br>\n";
  $where_clause2 = "";
  $from_clause = "";
  $field_clause = "";
  
  // Parameter-Auswertung
  if ($jbpc_id != "") {
    // Sammelnummer: Alle unter dieser Sammelnummer abgerechneten Aufträge finden
    $where_clause = "jbpc_id = $jbpc_id";
  } elseif ($jb_export_time != "") {
  	// Exportzeitstempel gesetzt: Alle Aufträge mit diesem Fuhrlohnexport-Zeitstempel finden
    $jbpc_ids = "";
    $sql_query = "SELECT DISTINCT jbpc_id FROM jobpayment, job WHERE jobpayment.jb_id = job.jb_id AND LEFT(jb_export_time, 10) = '" . substr($jb_export_time, 0, 10) . "' AND csc_id_related IN ($csc_ids_related)";
    $res1 = mysql_query($sql_query, $mysql_db_default) or die ($sql_query . ": " . mysql_error($mysql_db_default));
    while ($row1 = mysql_fetch_array($res1, MYSQL_ASSOC)):
      $jbpc_ids .= "," . $row1["jbpc_id"];
    endwhile;
    mysql_free_result($res1);
    if ($jbpc_ids != "") {
      $where_clause = "jbpc_id IN (" . substr($jbpc_ids, 1) . ")";
      $where_clause2 = " AND LEFT(jb_export_time, 10) = '" . substr($jb_export_time, 0, 10) . "'";
    }
  } elseif ($f_payment_select == "2" || $f_payment_select == "3" || $f_payment_select == "4" || $f_payment_select == "5" || $f_payment_select == "6" || $f_payment_select == "7" || $f_payment_select == "8") {
    if ($f_payment_select == "8") {
      $sql_query = "SELECT jb_id FROM phoenix_log.log WHERE logo_id = 10 AND ((hq_id = 1111 AND jb_id >= 307527) OR (hq_id = 1020 AND jb_id >= 343544))";
      $res1 = mysql_query($sql_query, $mysql_db_default) or die ($sql_query . ": " . mysql_error($mysql_db_default));
      while ($row1 = mysql_fetch_array($res1, MYSQL_ASSOC)):
        $jb_ids_storno .= "," . $row1["jb_id"];
      endwhile;
      mysql_free_result($res1);
    }

    $where_clause = "jbpc_id = 0";
    $jbpc_id = "0";
    // Sammelnummer "0": Alle noch abzurechnenden Aufträge finden
    $from_clause = ", genericdatacontainer AS gdc1";
    $addmont_clause = "";
    $where_clause2 =
      ($f_payment_select != "7"
      ? " AND job.jb_id = gdc1.gdc_obj_id AND gdc1.gdc_gen_fieldname = 'acquisitiontime'"
      : " AND ((job.jb_id = gdc1.gdc_obj_id AND gdc1.gdc_gen_fieldname = 'acquisitiontime') OR (job.jb_id = gdc1.gdc_obj_id AND gdc1.gdc_gen_fieldname = 'jb_id_addmont_parent'))") .
      ($f_payment_select != "8"
      ? " AND (jb_storno IS NULL OR jb_storno = 0)" .
        " AND (jobpayment.jbpc_id IS NULL OR jobpayment.jbpc_id = 0)"
      : " AND jb_storno = 2 AND job.jb_id IN (" . substr($jb_ids_storno, 1) . ")" ) .
      " AND (jb_ordertime >= '" . $f_min_date . "' AND jb_ordertime <= '" . $f_max_date . "' AND NOT (job.jb_id IN (315462, 322139, 321777, 319985, 320185, 320946, 316291, 321335, 317036, 323325, 320208, 316406)))" .
      " AND csc_id_related IN ($csc_ids_related)";
    $field_clause = ", jb_service, jbp_tan";
    $serviceMont = pow(2, get_first("SELECT mt_sort FROM metatype WHERE mt_type = 'service' AND mt_mapped_value = 'MO'"));
    $serviceAust = pow(2, get_first("SELECT mt_sort FROM metatype WHERE mt_type = 'service' AND mt_mapped_value = 'AT'"));
    if ($f_datetype == "2")
      $f_datetype = "1";
  } elseif ($f_payment_select == "1") {
  	// Die Sammelnummern aller abgerechneten Aufträge ohne möglichen Fuhrlohnexport finden
    $jbpc_ids = "";
    $sql_query =
      "SELECT DISTINCT jbpc_id FROM genericdatacontainer, jobpayment, job" .
      " WHERE gdc_gen_fieldname = 'acquisitiontime' AND gdc_obj_id = jobpayment.jb_id AND csc_id_related IN ($csc_ids_related)" .
      " AND jobpayment.jb_id = job.jb_id AND jbpc_id != 0 AND (jb_status != 2 OR jb_incomplete = 1) AND jb_cr_price > 0 AND jb_export_time IS NULL";
    if ($f_datetype == "1")
      $sql_query .= 
        " AND (jb_ordertime >= '" . $f_min_date . "' AND jb_ordertime <= '" . $f_max_date . "')";
    $res1 = mysql_query($sql_query, $mysql_db_default) or die ($sql_query . ": " . mysql_error($mysql_db_default));
    while ($row1 = mysql_fetch_array($res1, MYSQL_ASSOC)):
      $jbpc_ids .= "," . $row1["jbpc_id"];
    endwhile;
    mysql_free_result($res1);
    if ($jbpc_ids != "") {
      $where_clause = "jbpc_id IN (" . substr($jbpc_ids, 1) . ")";
      if ($f_datetype == "2")
        $where_clause .= " AND jbpc_bookingdate >= '"  . $f_min_date . "' AND jbpc_bookingdate <= '" . $f_max_date . "'";    
      $where_clause2 = " AND (jb_status != 2 OR jb_incomplete = 1) AND jb_cr_price > 0 AND jb_export_time IS NULL";
    }
  }

  if ($where_clause != "") {
    // Die betreffenden jbpc_ids werden aus der jobpaymentcollection geholt (im Falle von jbpc_id = 0 nur Dummy)
    $sql_query = "SELECT jbpc_id, cs_id, jbpc_mode, jbpc_price, jbpc_bookingdate, jbpc_export_time FROM jobpaymentcollection" .
      " WHERE $where_clause";
    $res = mysql_query($sql_query, $mysql_db_default) or die ($sql_query . ": " . mysql_error($mysql_db_default));  
    
    while (($row = mysql_fetch_array($res, MYSQL_ASSOC)) || $jbpc_id == "0"):
      if ($jbpc_id == "0") {
        $row = array();
        $row["jbpc_id"] = 0;
      }
      $jb_cr_price_sum = 0;
      $bsg_sum = 0;
//      $sql_query = "SELECT SUM(jb_cr_price) FROM jobpayment, job WHERE jbpc_id = '" . $row["jbpc_id"] . "' AND jobpayment.jb_id = job.jb_id AND NOT (jb_export_time IS NULL)";
      $sql_query = "SELECT SUM(jb_cr_price) FROM (SELECT DISTINCT job.jb_id, jb_cr_price FROM jobpayment, job WHERE jbpc_id = '" . $row["jbpc_id"] . "' AND jobpayment.jb_id = job.jb_id AND NOT (jb_export_time IS NULL) AND jb_export_time != '9999-12-31 23:59:59') AS honk";
      $res1 = mysql_query($sql_query, $mysql_db_default) or die ($sql_query . ": " . mysql_error($mysql_db_default));
      if ($row1 = mysql_fetch_row($res1)):
        $jb_cr_price_sum = $row1[0];      
        $bsg_sum = $row["jbpc_price"] - $jb_cr_price_sum;
      endif;    
      mysql_free_result($res1);
    
      $cC = "#dc"; $cC2 = "#dd";
//      if ($colCnt % 2 == 0) : $cC = "#cc"; $cC2 = "#cd"; endif;
//      if ($colCnt++ % 2 == 1) : $cC = "#dc"; $cC2 = "#dd"; endif;
      if ($ret_val != "")
        $ret_val .= "<br>\n";
      if ($jbpc_id != "0")
        $ret_val .= $cC . $row["jbpc_id"] . ";$cC2" . formDate($row["jbpc_bookingdate"]) . ";$cC" . formDate($row["jbpc_export_time"]) . ";$cC2" . $modeArr[$row["jbpc_mode"]] . ";$cC" . $cs_id_relatedArr[$row["cs_id"]] . ";$cC2" . " " . ";$cC" . " " . ";$cC2" . " " . ";$cC" . " " . ";$cC2" . formCur($row["jbpc_price"]) . ";$cC" . "" . ";$cC2" . "" . ";$cC" . " " . ";$cC2" . " " . ";$cC" . " " . ";$cC2" . " " . ";$cC" . "" . ";$cC2" . formCur($jb_cr_price_sum) . ";$cC" . "" . ";$cC2"  . formCur($bsg_sum) . "<br>\n";

      // Lfd. Meter für f_payment_select == "4" merken
      if ($f_payment_select == "4") {
        $sql_query =  
          "SELECT job.jb_id, jbc_amount, ROUND(jbc_price, 2) AS price" .
          " FROM job, jobcalculator, jobpayment" .
          " WHERE jobcalculator.jb_id = job.jb_id AND jb_storno IS NULL AND job.jb_id = jobpayment.jb_id AND srvt_name = '0010:par_01' AND jobpayment.jbpc_id" .
          " IN (" . $row["jbpc_id"] . ")";
        $res1 = mysql_query($sql_query, $mysql_db_default) or die ($sql_query . ": " . mysql_error($mysql_db_default));
        $jbc_lfm = array();
        while ($row1 = mysql_fetch_array($res1, MYSQL_ASSOC)):
          $jbc_lfm[$row1["jb_id"]] = array(formCur($row1["price"] * 1.19), formCur($row1["jbc_amount"]));
        endwhile;
        mysql_free_result($res1);
      }
    
      $sql_query =  
//        "SELECT jobpayment.jb_id, jbpc_id, jobpayment.csc_id, jbp_mode, jbp_price, jbp_bookingtime, jbp_counter, jbp_export_time, jb_cr_price, jb_ordertime, jb_export_time FROM jobpayment LEFT JOIN job ON jobpayment.jb_id = job.jb_id" .
//        " WHERE jobpayment.jb_id IN (SELECT jb_id FROM jobpayment WHERE jbpc_id = '" . $row["jbpc_id"] . "') AND jbp_price != 0 ORDER BY jobpayment.jb_id";
        "SELECT job.jb_id, IFNULL(gdc3.gdc_content, '') AS addmont_parent, jb_totalprice AS totalprice, jbpc_id, job.cr_sid, ROUND(jb_cr_price, 2) AS cr_price," .
        " jb_export_time, (CASE jb_status WHEN 1 THEN 'angenommen' WHEN 2 THEN 'erledigt' WHEN 9 THEN 'Disposition' WHEN 0 THEN 'UN-Dispo' ELSE 'undefiniert' END) AS status," .
        " IF(jb_incomplete=1, 'unfertig', '') AS incomplete, IF(jb_storno=1 OR jb_storno=2, 'storniert', '') AS storno, jb_ordertime, jb_finishtime," .
        " csc_id_related, jbp_mode, jbp_export_time, gdc2.gdc_content AS info_0, tr_commission_no, jb_dispoinfo, jb_freetext_3" .
        $field_clause .
        " FROM tour" .
        $from_clause .
        ", job LEFT JOIN jobpayment ON job.jb_id = jobpayment.jb_id" .
        " LEFT JOIN genericdatacontainer AS gdc2 ON gdc2.gdc_obj_type = 'jb' AND gdc2.gdc_gen_fieldname = 'info_0' AND gdc2.gdc_obj_id = job.jb_id" .
        " LEFT JOIN genericdatacontainer AS gdc3 ON gdc3.gdc_obj_type = 'jb' AND gdc3.gdc_gen_fieldname = 'jb_id_addmont_parent' AND gdc3.gdc_obj_id = job.jb_id" .
        " WHERE job.jb_id = tour.jb_id AND tour.tr_sort = 2 " . 
        ($jbpc_id != "0" ? " AND jobpayment.jbpc_id IN (" . $row["jbpc_id"] . ")" : "") .
        $where_clause2 .
        " ORDER BY " . ($jbpc_id != "0" ? "jbpc_id," : "") . "LEFT(jb_ordertime, 10), tr_commission_no, jb_id";
//echo $sql_query . "<br>\n";
      $res1 = mysql_query($sql_query, $mysql_db_default) or die ($sql_query . ": " . mysql_error($mysql_db_default));
      $prev_row = array();
      $bsg = 0;
      $num_row = 0;
      $colCnt = 0;
      $cC = "#aa"; $cC2 = "#ab";
      while (($row1 = mysql_fetch_array($res1, MYSQL_ASSOC)) || $num_row <= mysql_num_rows($res1)):
        if ($num_row < mysql_num_rows($res1)) {
          if ($row1["addmont_parent"] == "")
            // Die tatsächlich abgerechneten Preise ergeben sich aus jobcalculator (exkl. Lagerkosten),
            // die werden hier vorab schon mal geholt, da das schlecht in die Hauptabfrage passt
            $row1["totalprice"] = get_first("SELECT SUM(ROUND(jbc_totalprice, 2)) FROM jobcalculator WHERE jb_id = " . $row1["jb_id"] . " AND srvt_name != '0003:par_01'");
          // Lagerkosten extra ausweisen
          $row1["jbc_lagerk"] = get_first("SELECT ROUND(jbc_totalprice, 2) FROM jobcalculator WHERE jb_id = " . $row1["jb_id"] . " AND srvt_name = '0003:par_01'");
        }
        if (++$num_row > 1):
//          $bsg += $prev_row["price"];
          $bsg = $prev_row["totalprice"];
          $prev_row_jb_cr_price = "";
          $prev_row_jb_export_time = "";
          $prev_row_bsg = "";
          if (($prev_row["jb_id"] != $row1["jb_id"] || $num_row == (mysql_num_rows($res1)) + 1)):
            $order_no = $prev_row["info_0"];
            if ($order_no == "")
              $order_no = str_replace(";", "", $prev_row["tr_commission_no"]);
            if ($order_no == "")            
              $order_no = get_jb_search($prev_row["jb_id"]);
            
            $prev_row_jb_cr_price = ($prev_row["jb_export_time"] == "9999-12-31 23:59:59" ? formCur("0") : formCur($prev_row["cr_price"]));
//            $prev_row_bsg = formCur($bsg - $prev_row["cr_price"]);
            $prev_row_jb_export_time = ($prev_row["jb_export_time"] == "9999-12-31 23:59:59" ? "Zu L. Sped." : formDate($prev_row["jb_export_time"]));
            $prev_row_bsg = ($prev_row["jb_export_time"] == "9999-12-31 23:59:59" ? formCur($bsg - 0) : formCur($bsg - $prev_row["cr_price"]));
            $bsg = 0;
          endif;
          $billing_error = "";
          $export_error = "";
          if ($jbpc_id == "0") {
            if (($prev_row["jb_service"] & $serviceMont) == $serviceMont && trim($prev_row["cr_sid"]) == "") {
              $export_error = "Fahrer fehlt in OS Auftrag";
            } elseif (in_array($prev_row["jbp_tan"], array("0", "1", "10", "20")) && ($prev_row["incomplete"] != "" || $prev_row["status"] != "erledigt")) {
              $export_error = "Kein Export: Inkasso mit nicht erledigtem/unfertigen Auftrag, Zahlart: " . $modeArr[$prev_row["jbp_tan"]];
            } elseif (
                 get_first("SELECT gdc_gen_fieldname FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $prev_row["jb_id"] . " AND gdc_gen_fieldname = 'jb_addmont'") == "jb_addmont"
              && get_first("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_id = " . $prev_row["jb_id"] . " AND gdc_gen_fieldname = 'jb_addmont'") == "") {
              $export_error = "Montagestunden fehlen";
     	      } elseif ($prev_row["jb_finishtime"] == "0000-00-00 00:00:00" AND ($prev_row["incomplete"] == "" && $prev_row["status"] == "erledigt")) {
              $export_error = "Erledigungszeit des exportierbaren Auftrages ist '0000-00-00 00:00:00'";
            } elseif ($prev_row["cr_price"] > 0 && ($prev_row["incomplete"] != "" || $prev_row["status"] != "erledigt")) {
              $billing_error = "Kein Fuhrlohnexport (Auftrag nicht erledigt/unfertig)";
            }
            $the_error = "";
            if ($f_payment_select == "2" || $f_payment_select == "4" || $f_payment_select == "5" || $f_payment_select == "8")
              $the_error = $export_error;
            if ($f_payment_select == "3")
              $the_error = $billing_error;
            if ($f_payment_select == "4") {
              if ($the_error == "" && $jbc_lfm[$prev_row["jb_id"]] != "") {
                $the_error = $jbc_lfm[$prev_row["jb_id"]][1] . " lfd. Meter zu " . $jbc_lfm[$prev_row["jb_id"]][0] . " (brutto)";
              } else {
              	$the_error = "";
              }
            }
            if ($f_payment_select == "5") {
              if ($the_error == "" && $prev_row["totalprice"] == 0 && ($prev_row["jb_service"] & $serviceAust) != $serviceAust
                && get_first("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $prev_row["jb_id"] . " AND gdc_gen_fieldname = 'jb_service_job'") != '1') {
                $the_error = "Kein Preis verfügbar";
              } else {
              	$the_error = "";
              }
            }
            if ($f_payment_select == "6") {
              if (get_first("SELECT gdc_context FROM genericdatacontainer WHERE gdc_obj_id = " . $prev_row["jb_id"] . " AND gdc_gen_fieldname = 'jb_addmont'") == "0.1"
               && get_first("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_id = " . $prev_row["jb_id"] . " AND gdc_gen_fieldname = 'jb_addmont'") == "") {
                $the_error = "0,1 Montagestunden angefordert";
              } else {
              	$the_error = "";
              }
            }
            if ($f_payment_select == "7") {
              if (in_array($prev_row["jbp_tan"], array("0", "1", "10", "20")) && !($prev_row["incomplete"] != "" || $prev_row["status"] != "erledigt")) {
                $the_error = formCur($prev_row["totalprice"] * 1.19) . " " . $modeArr[$prev_row["jbp_tan"]];
              } else {
              	$the_error = "";
              }
            }
            if ($f_payment_select == "2" || $f_payment_select == "3" || $f_payment_select == "4" || $f_payment_select == "5" || $f_payment_select == "6" || $f_payment_select == "7" || $f_payment_select == "8") {
              if ($f_payment_select == "8")
                $the_error = $prev_row["jb_freetext_3"];
              else
                if (trim($the_error) != "" && trim($prev_row["jb_freetext_3"]) != "") {
                  $the_error .= "<br><b>" . $prev_row["jb_freetext_3"] . "</b>";
              }
            }
          }
//echo $prev_row["jb_id"] . ", " . $jbc_lfm[$prev_row["jb_id"]] . "\n";
          if ($jbpc_id != "0" || $the_error != "") {
            $ret_val .= $cC .
              (($prev_row["jbpc_id"] != "0" && $jbpc_id != "0") ? "<a href=\"../tools/payments.php?jbpc_id=" . $prev_row["jbpc_id"] . "&csc_ids_related=" . $csc_ids_related . "\">" . $prev_row["jbpc_id"] . "</a>" : $the_error) .
              ";$cC2" .            
              ($prev_row["jbpc_id"] != "0" && $jbpc_id == "0" ?
              "<a href=\"../tools/payments.php?jbpc_id=" . $prev_row["jbpc_id"] . "&csc_ids_related=" . $csc_ids_related . "\">" . $prev_row["jbpc_id"] . "</a>" : "") .              
               formDate($row["jbpc_bookingdate"]) . ";$cC" . formDate($prev_row["jbp_export_time"]) . ";$cC2" . $modeArr[$prev_row["jbp_mode"]] .
              ";$cC" . $csc_id_relatedArr[$prev_row["csc_id_related"]] . ";$cC2" . $order_no . ";$cC" .          
              ($prev_row["addmont_parent"] != "" ? $prev_row["jb_id"] :
              "<a href=\"javascript:popupWindow('../admin/jb_detail.php?job_id=" . $prev_row["jb_id"] . "','Auftrag','scrollbars=yes')\">" . $prev_row["jb_id"] . "</a>") .              
              ";$cC2" . $prev_row["addmont_parent"] . ";$cC" . $prev_row["jb_dispoinfo"] . ";$cC2" . formCur($prev_row["totalprice"]) . ";$cC" . str_replace(".", ",", $prev_row["jbc_lagerk"]) . ";$cC2" . formDate($prev_row["jb_ordertime"]) . ";$cC" . formDate($prev_row["jb_finishtime"]) .
              ";$cC2" . $prev_row["status"] . ";$cC" . $prev_row["incomplete"] . ";$cC2" . $prev_row["storno"] . ";$cC" . $prev_row["cr_sid"] . ";$cC2"  . $prev_row_jb_cr_price .
              ";$cC" .
              "<a href=\"../tools/payments.php?jb_export_time=" . substr($prev_row["jb_export_time"], 0, 10) . "&csc_ids_related=" . $csc_ids_related . "\">" . $prev_row_jb_export_time . "</a>" .
              ";$cC2"  . $prev_row_bsg . "<br>\n";
            if ($prev_row_jb_cr_price != ""):
              if ($colCnt % 2 == 0) : $cC = "#ba"; $cC2 = "#bb"; endif;
              if ($colCnt++ % 2 == 1) : $cC = "#aa"; $cC2 = "#ab"; endif;
            endif;
          }
        endif;
        $prev_row = $row1;   
      endwhile;
      mysql_free_result($res1);
      if ($jbpc_id == "0")
        $jbpc_id = "-1";
    endwhile;
    if ($jbpc_id != "-1")
      mysql_free_result($res);
  }
  return $ret_val;
}

function formCur($amount) {
	return str_replace(".", ",", sprintf("%01.2f", round($amount, 2)));
//	return str_replace(".", ",", sprintf("%01.2f", round($amount, 2)));
}

function formDate($sqlDate) {
	if (trim($sqlDate) == "" || trim($sqlDate) == "0000-00-00 00:00:00")
	  return "";
  return substr($sqlDate, 8, 2) . "." . substr($sqlDate, 5, 2) . "." . substr($sqlDate, 0, 4);
}

function sqlDate($germanDate) {
	if (trim($germanDate) == "")
	  return "";
  return substr($germanDate, 6, 4) . "-" . substr($germanDate, 3, 2) . "-" . substr($germanDate, 0, 2);
}

function get_first_row($sqlquery, $mysql_db_id = NULL) {
  global $mysql_db_default;

  if (is_null($mysql_db_id))
    $res = mysql_query($sqlquery, $mysql_db_default) or die ($sqlquery . ": " . mysql_error($mysql_db_default));
  else
    $res = mysql_query($sqlquery, $mysql_db_id) or die ($sqlquery . ": " . mysql_error($mysql_db_id));

  $row = mysql_fetch_array($res);
  mysql_free_result($res);
  return $row;
}

function get_first($sqlquery, $mysql_db_id = NULL) {

  if ($row = get_first_row($sqlquery, $mysql_db_id))
    return $row[0];
  return "";
}

function get_jb_search($jb_id) {
  global $mysql_db_b2b_history, $mysql_db_default;

  $jb_search = get_first("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_search'");  
  if(trim($jb_search) == "") {
  	$sql_query = "SELECT bo_obj_data FROM phoenix_log.b2b_objects WHERE bo_type = 300 AND bo_ext_id0 = " . $jb_id . " AND bo_obj_data LIKE '%|501%'";
    $bo_obj_data = get_first($sql_query);
    if(trim($bo_obj_data) == "")
      $bo_obj_data = get_first(str_replace("b2b_objects", "b2b_objects_2015", $sql_query), $mysql_db_b2b_history);
    if(trim($bo_obj_data) != "")
      list ($jb_search, $dummy) = explode("|", $bo_obj_data);
    if(trim($jb_search) != "") {
      $sql_query = "INSERT INTO genericdatacontainer (gdc_obj_type,gdc_obj_id,gdc_gen_fieldname,gdc_content,gdc_context) VALUES ('jb','" . $jb_id . "','jb_search','" . $jb_search . "','')";
//echo $sql_query . "<br>\n";    
      mysql_query($sql_query, $mysql_db_default) or die ($sql_query . ": " . mysql_error($mysql_db_default));
    }
  }
//  if (trim($jb_search) == "")
//    echo $jb_id . "<br>\n";
  return $jb_search;
}
/**************************************************************************************************************************************************/
// HTML-Output

?>

<html>
<head>
<title>Abrechnungs-&Uuml;bersicht</title>
<link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<style type="text/css">
<!--
.verysmall
{ font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 2pt; font-weight: normal; padding: 0px}
-->
</style>
<script type="text/javascript">
<!--
function popupWindow(url,title,config) {
  popup = window.open(url,title,config);
}

function disable_submit(id_tag) {
  document.getElementById(id_tag).disabled = true;
  document.getElementById(id_tag).style.background = '#CCCCCC';
  document.getElementById(id_tag).style.color = '#808080';
}

function check_submit1() {
  disable_submit('formsubmit');
}

-->
</script>
</head>
<body>
  <table border="0" width="100%" cellspacing="0" cellpadding="0" vspace="10" hspace="0">
    <tr>
      <td>
        &nbsp;
      </td>
      <td align="center">
        <table border="0" cellspacing="0" cellpadding="0" vspace="0" hspace="0">
<?php if (trim($f_search_value) == "" && (($jbpc_id != "" && $jbpc_id != "-1") || $jb_export_time != "")) echo "<!--\n"; ?>
          <tr>
          	<td align="center">
              <form name="statistic" action="payments.php" method="post"><div class="f10bp1_blue">
<?php if (trim($f_search_value) != "") echo "<!--\n"; ?>
                <select name="f_payment_select" class="input">
                <option value="1" <?php if ($f_payment_select == "1") echo "selected"; ?>>Abgerechnete Aufträge mit nicht exportierbaren Fuhrl&ouml;hnen</option>
                <option value="8" <?php if ($f_payment_select == "8") echo "selected"; ?>>Von Mitarbeitern stornierte Auftr&auml;ge</option>
                <option value="2" <?php if ($f_payment_select == "2") echo "selected"; ?>>Nicht abrechnungsfähige Auftr&auml;ge</option>
                <option value="3" <?php if ($f_payment_select == "3") echo "selected"; ?>>Abrechnungsfähige Aufträge mit nicht exportierbaren Fuhrl&ouml;hnen</option>
                <option value="5" <?php if ($f_payment_select == "5") echo "selected"; ?>>Abrechnungsfähige Aufträge ohne Preis</option>
                <option value="6" <?php if ($f_payment_select == "6") echo "selected"; ?>>Abrechnungsfähige Aufträge mit angeforderten 0,1 Montagestunden</option>
                <option value="4" <?php if ($f_payment_select == "4") echo "selected"; ?>>Abrechnungsfähige Küchenaufträge mit lfd. Metern</option>
                <option value="7" <?php if ($f_payment_select == "7") echo "selected"; ?>>Abrechnungsfähige Inkassoaufträge</option>
                </select><br><br>
                <input type="radio" name="f_datetype[]" value="1"<?php if ($f_datetype == "1") echo " checked"; ?>>Ausf&uuml;hrungs-/
                <input type="radio" name="f_datetype[]" value="2"<?php if ($f_datetype == "2") echo " checked"; ?>>Abrechnungsdatum von:&nbsp;
                <input name="f_min_date" type="text" size="9" maxlength="10" class="input"
                  value="<?php echo ($f_min_date != "" ? formDate($f_min_date) : "") ?>">&nbsp;
                bis:&nbsp;
                <input name="f_max_date" type="text" size="9" maxlength="10" class="input"
                  value="<?php echo ($f_max_date != "" ? formDate($f_max_date) : "") ?>"><br><br>
                <input type="checkbox" name="f_lubu" value="1"<?php if ($f_lubu == "1") echo " checked"; ?>>Ludwigsburg&nbsp;
                <input type="checkbox" name="f_sifi" value="1"<?php if ($f_sifi == "1") echo " checked"; ?>>Sindelfingen&nbsp;
                <input type="checkbox" name="f_schn" value="1"<?php if ($f_schn == "1") echo " checked"; ?>>Schnelsen&nbsp;
                <input type="checkbox" name="f_mofl" value="1"<?php if ($f_mofl == "1") echo " checked"; ?>>Moorfleet&nbsp;
                <input type="checkbox" name="f_alto" value="1"<?php if ($f_alto == "1") echo " checked"; ?>>Altona&nbsp;<br><br>
<?php if (trim($f_search_value) != "") echo "-->\n"; ?>
                Suche nach Sammelnummer: <input name="f_search_value" type="text" size="8" maxlength="9" class="input" value="<?php echo $f_search_value ?>">&nbsp;<br><br>
                <input type="submit" id="formsubmit" name="formsubmit" size="2" value="Anzeigen" class="submit" onclick="check_submit1()">
              </form>              
            </td>
          </tr>
<?php if (trim($f_search_value) == "" && (($jbpc_id != "" && $jbpc_id != "-1") || $jb_export_time != "")) echo "-->\n"; ?>
          <tr>
          	<td align="center">
              <?php echo $content;?>
            </td>
          </tr>
        </table>
      </td>
      <td>
        &nbsp;
      </td>
    </tr>
  </table>
</body>
</html>
