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

$check_jb_permanent_flag = true;
include_once("../include/dbglobal.inc.php");
include_once("../include/inc_check_publicholiday.inc.php");
include_once("../include/caglobal.inc.php");
include_once("../include/global.inc.php");
include_once("../include/services_func.inc.php");
trace_execution_time_start();

// $hq_id muss bereits definiert sein!!!
// $db2 auch!
  
$sqlquery = "SELECT tax.tx_id, tax.tx_value FROM tax";
$res = $db2->query($sqlquery);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery': " . $res->getMessage());
$sales_tax_rate_sign_list = "var sales_tax_rate_sign_list = [";
$i = 0;
while ($row = $res->fetch_assoc()):
  if ($i++ > 0)
    $sales_tax_rate_sign_list .= ",";
  $sales_tax_rate_sign_list .= "[\"" . $row["tx_id"] . "\", \"" . $row["tx_value"] . "\"]";
endwhile;
$res->free();
$sales_tax_rate_sign_list .= "];\n";

$sqlquery = "SELECT crf_short, crf_text, crf_status FROM courierfilter ORDER BY crf_short";
$res = $db2->query($sqlquery);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery': " . $res->getMessage());
// die Kurier-Filter sollen alphabetisch von oben nach unten statt von links nach rechts sortiert sein...
// deshalb erst einmal die Daten aus der Abfrage übernehmen...
$crf_rows = array();
while ($row = $res->fetch_assoc()):
  $crf_rows[] = $row;
endwhile;
$res->free();
// ... und dann umsortieren ...
// die Filter werden von rechts nach links aufgebaut, also müssen sie hier
// erst in die richtige Reihenfolge gebracht werden, so dass am Schluss
// die sichtbare Reihenfolge von oben nach unten ist
$courierfilter_list = "var cfl=[";
$crf_rows_rows = 4; // 4 Spalten
$crf_rows_lines = ceil(count($crf_rows) / $crf_rows_rows); // ergibt x Zeilen
for ($j = 0; $j < $crf_rows_lines; $j++):
  for ($k = 0; $k < $crf_rows_rows; $k++):
    $i = ($k * $crf_rows_lines + $j);
    if ($courierfilter_list != "var cfl=[")
      $courierfilter_list .= ",\n";
    if ($i < count($crf_rows)):
      $courierfilter_list .= 
        "[\"" . $crf_rows[$i]["crf_short"] . "\", \"" . $crf_rows[$i]["crf_text"] . "\", \"" . $crf_rows[$i]["crf_status"] . "\", 0]";
    else:
      $courierfilter_list .= 
        "[\"" . "&nbsp;" . "\", \"" . "&nbsp;" . "\", \"0\", 0]";
    endif;
  endfor;
endfor;
$courierfilter_list .= "];\n";

// getPublicHolidays benutzt globale hq_id
$ph_list = getPublicHolidays(getDateTime("year"), "1", "0");
$js_ph_list = "var ph=[";
$js_ph_list_prev = "";
$j = 0;
for ($i = 0; $i < count($ph_list); $i++):
  $js_ph_list_cur = $ph_list[$i][0] . sprintf("%02d", $ph_list[$i][1]) . sprintf("%02d", $ph_list[$i][2]);
  if ($js_ph_list_prev != $js_ph_list_cur):
    if ($i > 0)
      $js_ph_list .= ",\n";
    $js_ph_list .= "\"" . $js_ph_list_cur . "\"";
    $js_ph_list_prev = $js_ph_list_cur;
  endif;
endfor;
$js_ph_list .= "];\n";

// get fake-zipcodes from DB
$sqlquery = "SELECT distinct srvp1.srvp_plz AS srvp_plz_source, srvp2.srvp_plz AS srvp_plz_target, srva_id, srva2_id, srvsam_name" .
  " FROM serviceplz AS srvp1, serviceplz AS srvp2, servicesubareamapping AS srvsam" .
  " WHERE srvp1.srvp_id = srvsam.srva_id AND srvp2.srvp_id = srvsam.srva2_id ORDER BY srvp1.srvp_plz, srvsam_sort";
$res = $db2->query($sqlquery);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery': " . $res->getMessage());
$i = 0;
$js_fz_list = "var fz=[";
while ($row = $res->fetch_assoc()):
  if ($i++ > 0)
    $js_fz_list .= ",\n";
  $js_fz_list .= "[\"" . $row['srvp_plz_source'] . "\", \"" . $row['srvp_plz_target'] . "\", \""
    . $row['srva2_id'] . "\", \"" . $row['srvsam_name'] . "\"]";
endwhile;
$res->free();
$js_fz_list .= "];\n";

$sqlquery = "SELECT mt_sort, mt_value FROM metatype WHERE mt_type = 'vht_product' ORDER BY mt_sort";
$res = $db2->query($sqlquery);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery': " . $res->getMessage());
$vht_product_list = "var vht_product_list = [";
$i = 0;
while ($row = $res->fetch_assoc()):
  if ($i++ > 0)
    $vht_product_list .= ",";
  $vht_product_list .= "[\"" . $row["mt_sort"] . "\", \"" . $row["mt_value"] . "\"]";
endwhile;
$res->free();
$vht_product_list .= "];\n";

// Matrix der Kunden mit speziellen Preisen
// Da Mitarbeiter mit Mandantenrecht Zugriff auf alle Kunden aller Zentralen haben, müssen für jede Zentrale
// demzufolge auch alle Daten aller Zentralen verfügbar sein...
$csSrvLists = "";
if (getParameterValue("0", "MASK_CALCULATOR_SRV_SRC", $hq_id) != "1"): // "1" bedeutet dynamisch, d.h. wenn der Kunde in der Maske als Zahler ausgewählt wird
  $csSrvLists = getCustomerServices($db2, 0, $hq_id);
endif;

//  // wenn MASK_AUTO_REFRESH == 0, dann wird die Kurierliste dynamisch (bei Aufruf) aufgebaut
//  // wenn MASK_AUTO_REFRESH == 1, dann wird die Kurierliste statisch (hier) aufgebaut
//  if (MASK_AUTO_REFRESH == "1"):

// job_courier.inc.php benutzt globale hq_id
writeLog_("../log/job_options.js.inc_", "vor job_courier.inc.php");
include("job_courier.inc.php");
writeLog_("../log/job_options.js.inc_", "nach job_courier.inc.php");
$cr_id_order_list .=
  "var cr_id_order_list2=[];\n" .
  "var vht_id_str=[];\n";
//  endif;

$fileHandle = @fopen("../jobs/job_options_$hq_id.js", 'w');
@fwrite($fileHandle, $courierfilter_list . $sales_tax_rate_sign_list . $js_ph_list . $js_fz_list . $cr_id_order_list . $vht_product_list . $csSrvLists);
@fclose($fileHandle);

//$db_history_date = "var db_history_date[" . $hq_id . "] = '" . getParameterValue("0", "DB_HISTORY_DATE", $hq_id) . "';\n";
//$js_script = file_get_contents("../include/lib_global.js");
//$fileHandle = @fopen("../include/lib_global.js", 'w');
//@fwrite($fileHandle, $db_history_date . $js_script);
//@fclose($fileHandle);

writeLog_("../log/job_options.js.inc_", trace_execution_time_stop() . " '../jobs/job_options_$hq_id.js' updated");

if (!isset($newbies_last_execution) || $newbies_last_execution < time() - (3 * 60)):
  trace_execution_time_start();
  // Unwichtige, aber den Betrieb aufhaltende Parameterabfragen der Kurierliste auslagern

  $vehicletypes = "\$vehicletypes = array(\n";
  $vehicletype_ids_src =  "\$vehicletype_ids = array(\n";
  $sqlQuery = "SELECT mt_sort, mt_value FROM metatype WHERE mt_type = 'vehicletype'";
  $res = $db2->query($sqlQuery);
  if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlQuery': " . $res->getMessage());
  $i = 0;
  while ($row = $res->fetch_assoc()):
    if ($i++ > 0):
      $vehicletypes .= ",\n";
      $vehicletype_ids_src .= ",\n";
    endif;
    $vehicletypes .= "  " . $row["mt_sort"] . " => '" . $row["mt_value"] . "'";
    $vehicletype_ids_src .= "  '" . $row["mt_value"] . "' => " . $row["mt_sort"];
  endwhile;
  $res->free();
  $vehicletypes .= ");\n\n";
  $vehicletype_ids_src .= ");\n\n";

  $newbie_date = getdate(mktime(0, 0, 0, date("m"), date("d") - MASK_COURIER_NEWBIE_TIME, date("Y")));
  $newbie_date_sql = $newbie_date['year'] . "-" . sprintf("%02d", $newbie_date['mon']) . "-" . sprintf("%02d", $newbie_date['mday']) . " 23:59:59";
  $newbie_cr_sids = "\$newbie_cr_sids = array(\n";
  // alle Fahrer finden, die _keine_ newbies sind  (d.h. die mind. einen erledigten Auftrag haben, der älter als einen Monat ist)
  $sqlQuery = "SELECT DISTINCT cr_id FROM job WHERE cr_id > 0 AND jb_status = 2 AND jb_ordertime < '$newbie_date_sql'";
  $res = $db2->query($sqlQuery);
  if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlQuery': " . $res->getMessage());
  $i = 0;
  while ($row = $res->fetch_assoc()):
    if ($row["cr_id"] != '' && $row["cr_id"] != 0):
      if ($i++ > 0)
        $newbie_cr_sids .= ",\n";
      $newbie_cr_sids .=  "  " . $row["cr_id"] . " => 1";
    endif;
  endwhile;
  $res->free();
  $newbie_cr_sids .= ");\n\n";

  // Alle historischen cs_markup_prov-Sätze holen
  $cs_markup_prov_list = "\$cs_markup_prov_list = array(\n";
//  $sqlquery = "SELECT cs_id FROM customer WHERE cs_markup_prov > 0 UNION" .
//   " SELECT DISTINCT srvprch_obj_id FROM servicepricehistory WHERE srvprch_obj_type = 'cs' AND srvprch_fieldname = 'cs_markup_prov' AND srvprch_price > 0";
  $sqlquery = "SELECT DISTINCT srvprch_obj_id AS cs_id FROM servicepricehistory WHERE srvprch_obj_type = 'cs' AND srvprch_fieldname = 'cs_markup_prov' AND srvprch_price > 0";
  $res = $db2->query($sqlquery);
  if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery': " . $res->getMessage());
  $cs_ids = "";
  while ($row = $res->fetch_assoc()):
    if ($cs_ids != "")
      $cs_ids .= ",";
    $cs_ids .= $row["cs_id"];
  endwhile;
  $res->free();
  if ($cs_ids != ""):
    $i = 0;
//    $sqlquery = "SELECT cs_id, cs_markup_prov, cs_validfrom FROM ((" .
//      "  SELECT cs_id, cs_markup_prov, '1970-01-01 00:00:00' AS cs_validfrom FROM customer WHERE cs_id IN (" . $cs_ids . ")) UNION (" .
//      "  SELECT srvprch_obj_id, srvprch_price, srvprch_validfrom FROM servicepricehistory, customer" .
//      "  WHERE srvprch_obj_type = 'cs' AND srvprch_fieldname = 'cs_markup_prov' AND servicepricehistory.srvprch_obj_id = customer.cs_id AND srvprch_obj_id IN (" . $cs_ids . "))) AS schlonz" .
//      "  ORDER BY cs_id ASC, cs_validfrom DESC";
    $sqlquery =       
      "  SELECT srvprch_obj_id AS cs_id, srvprch_price AS cs_markup_prov, srvprch_validfrom AS cs_validfrom FROM servicepricehistory, customer" .
      "  WHERE srvprch_obj_type = 'cs' AND srvprch_fieldname = 'cs_markup_prov' AND servicepricehistory.srvprch_obj_id = customer.cs_id AND srvprch_obj_id IN (" . $cs_ids . ")" .
      "  ORDER BY cs_id ASC, cs_validfrom DESC";
    $res = $db2->query($sqlquery);
    if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery': " . $res->getMessage());
    while ($row = $res->fetch_assoc()):
      if ($i++ > 0)
        $cs_markup_prov_list .= ",\n";
      $cs_markup_prov_list .= "  array(" . $row["cs_id"] . ", '" . $row["cs_validfrom"] . "', '" . $row["cs_markup_prov"] . "')";
    endwhile;
    $res->free();
  endif;
  $cs_markup_prov_list .= ");\n\n";

  $fileHandle = @fopen("../jobs/job_courier.inc.newbies.php", 'w');
  @fwrite($fileHandle, "<?php\n" . $vehicletypes . $vehicletype_ids_src . $newbie_cr_sids . $cs_markup_prov_list . "?>\n");
  @fclose($fileHandle);
  writeLog_("../log/job_options.js.inc_", trace_execution_time_stop() . " '../jobs/job_courier.inc.newbies.php' updated");
  $newbies_last_execution = time();
endif;
?>
