<?php
error_reporting(E_ALL ^ E_NOTICE);
// Test with  21491179 

if (!isset($argv[1]) || trim($argv[1] == "") || !is_numeric($argv[1]) || $argv[1] == 0 ) {
  exit();
}

include_once("../locating/xServer.inc.php");
include_once("../include/caglobal.inc.php");
include_once("../tools/co2e_sendReq.php");

if (!existsEntry("phoenix_log.semaphor",array("sp_obj_type","jb","sp_obj_id",$argv[1],"sp_fieldname","get_job_distance"))):
  $mypid = getmypid();
  insertStmt("phoenix_log.semaphor", array("sp_obj_type", "jb", "sp_obj_id", $argv[1], "sp_fieldname", "get_job_distance", "sp_content", "", "sp_context", $mypid, "sp_createtime", date("Y-m-d H:i:s")));

//  list($total_km, $total_km_osm) = get_job_distance($argv[1]);
  list($total_km, $error_station) = get_job_distance($argv[1]);
  writeLog_("../log/check_cr_agio_", "get_job_distance.php: get_job_distance(" . $argv[1] . "): \$total_km = " . $total_km . ", \$error_station = " . $error_station);
  
  //$dbData = $db;
  // hq_id muss gesetzt sein für sendReqCO2() und mk_jb_invtext_full()
  $hq_id = $db->getOne("SELECT hq_id FROM job WHERE jb_id = " . $argv[1]);
  //$usr_id = ;
  // avoid more than one co2-entry
  $db->query("DELETE FROM jobprice WHERE jb_id = " . $argv[1] . " AND mt_sort = 12");
  list($jbprcPrice, $response, $rspArr, $jbId, $logDescription) = sendReqCO2($argv[1]);
  writeLog_("../log/check_cr_agio_", "get_job_distance.php: sendReqCO2(" . $argv[1] . "): \$response = '" . $response . "', \$logDescription = '" . $logDescription . "'");

  $is_exported = $db->getOne("SELECT jb_export_time FROM job WHERE jb_id = " . $argv[1] . " AND NOT (jb_export_time IS NULL)");
  $cs_commission_no_ok = true;
  if (!$is_exported):
    $csc_id_payer = getFieldValueFromId("job", "jb_id", $argv[1], "csc_id_payer");
    $cs_commission_no = $db->getOne("SELECT cs_commission_no from customer WHERE cs_id = " . getFieldValueFromId("costcenter", "csc_id", $csc_id_payer, "cs_id"));
    if ($cs_commission_no == 1):
      $cs_commission_no_ok = false;
      if ($db->getOne("SELECT COUNT(tr_commission_no) FROM tour WHERE jb_id = '" . $argv[1] . "' AND (TRIM(tr_commission_no) != '' AND tr_commission_no IS NOT NULL)") > 0):
        $cs_commission_no_ok = true;
      endif;
    endif;
  else:
    writeLog_("../log/check_cr_agio_", "get_job_distance.php: job " . $argv[1] . " is already exported");
  endif;
  
  // 01.07.2024 check_jb_incomplete jetzt nicht nur wenn $response == "" sondern grundsätzlich, weil der Kurier die Kommissionsnummer gelöscht haben könnte
  if (($response == "" || !$cs_commission_no_ok) && !$is_exported) {
    $jb_incomplete = $db->getOne("SELECT jb_incomplete FROM job WHERE jb_id = " . $argv[1]);
    writeLog_("../log/check_cr_agio_", "get_job_distance.php: calling check_jb_incomplete(" . $argv[1] . ", " . $jb_incomplete . ") because of empty \$response or \$cs_commission_no_ok = " . ($cs_commission_no_ok ? "true" : "false"));
    check_jb_incomplete($argv[1], $jb_incomplete);
  }
  
  // 01.07,2024 Zusätzlicher check, ob die cr_id gesetzt wurde; sie könnte aufgrund "wilder" Zuweisungsorgien "verloren" gegangen sein
  $cr_id = $db->getOne("SELECT cr_id FROM job WHERE jb_id = " . $argv[1]);
  if ($cr_id == 0 || $cr_id == "") {
    $jb_status = $db->getOne("SELECT jb_status FROM job WHERE jb_id = " . $argv[1]);
    if ($jb_status == 2) {
      $jb_storno = $db->getOne("SELECT jb_storno FROM job WHERE jb_id = " . $argv[1]);
      if ($jb_storno == "0" || $jb_storno == "") {
        updateStmt("job", "jb_id", $argv[1], array("jb_incomplete", 1));
        include_once("../include/email/htmlMimeMail.php");
        $mailObj = new htmlMimeMail();
        $mailObj->setFrom("auto-mailer@assecutor.de");
        $mailObj->setBcc("support@assecutor.de");
        $mailObj->setSubject("Kurier-ID in Auftrag " . $argv[1] . " fehlt");
        $mailObj->setText("Auftrag " . $argv[1] . " hat keine Kurier-ID und kann deshalb nicht an SAP exportiert werden, der Auftrag wurde daher auf unfertig gesetzt.\n");
        $mailResult = $mailObj->send(array(getParameterValue("0", "MAIL_SURVEY_ADDRESS_TO", $hq_id)), 'smtp');
        writeLog_("../log/check_cr_agio_", "get_job_distance.php: get_job_distance(" . $argv[1] . "): \$total_km = " . $total_km . ", \$total_km_osm = " . $total_km_osm);
      }
    }
  }

  // 07.10.2025: Wenn eine Nachhaltigkeitsmail eingetragen ist, dann muss bei einer nicht eindeutig geokodierbaren Adresse eine Extra-Info rausgehen
  if ($error_station > 0 && !$is_exported) {
    $csc_id_payer = getFieldValueFromId("job", "jb_id", $argv[1], "csc_id_payer");
    $cs_id = getFieldValueFromId("costcenter", "csc_id", $csc_id_payer, "cs_id");
    $cmp_sustainability_email = $db->getOne("SELECT cmp_sustainability_email from company WHERE cmp_id = " . $db->getOne("SELECT cmp_id from customer WHERE cs_id = " . $cs_id));
    writeLog_("../log/check_cr_agio_", "\$jb_id = " . $argv[1] . ", \$cs_id_parent = $cs_id_parent, \$cmp_sustainability_email = |$cmp_sustainability_email|");
    if ($cmp_sustainability_email == ""):
      $cs_id_parent = getFieldValueFromId("customer", "cs_id", $cs_id, "cs_id_parent");
      if ($cs_id_parent != 0):
        $cmp_sustainability_email = $db->getOne("SELECT cmp_sustainability_email from company WHERE cmp_id = " . $db->getOne("SELECT cmp_id from customer WHERE cs_id = " . $cs_id_parent));
        writeLog_("../log/check_cr_agio_", "\$jb_id = " . $argv[1] . ", \$cs_id_parent = $cs_id_parent, \$cmp_sustainability_email = |$cmp_sustainability_email|");
      endif;
    endif;
    if ($cmp_sustainability_email != ""):
      include_once("../include/email/htmlMimeMail.php");
      $mailObj = new htmlMimeMail();
      $mailObj->setFrom("auto-mailer@assecutor.de");
      $mailObj->setBcc("support@assecutor.de");
      $mailObj->setSubject("Ermittlung des CO2e-Werts in Auftrag " . $argv[1] . " aufgrund der Adresse in Station Nr. " . $error_station . " nicht möglich");
      $mailObj->setText("Der Zahler von Auftrag " . $argv[1] . " bekommt einen Nachhaltigkeitsreport, die Ermittlung des CO2e-Werts ist aber aufgrund einer falschen Adresse in Station Nr. " . $error_station . " nicht möglich. Deshalb kann der Auftrag ohne die Korrektur der Adresse nicht an SAP exportiert werden.\n");
//      $mailResult = $mailObj->send(array(getParameterValue("0", "MAIL_SURVEY_ADDRESS_TO", $hq_id)), 'smtp');
      $mailResult = $mailObj->send(array("ca@assecutor.de"), 'smtp');
      writeLog_("../log/check_cr_agio_", "\$jb_id = " . $argv[1] . ", Mail sent to " . getParameterValue("0", "MAIL_SURVEY_ADDRESS_TO", $hq_id) . " because of broken address in station no. " . $error_station . " (\$mailResult = " . $mailResult . ")");
    endif;
  }

  mk_jb_invtext_full($argv[1]);
  // 08.04.2025 jb_longhaul_export und jb_hq_id_exec_price für Datenexport eintragen

  $hq_id_exec = $db->getOne("SELECT courier.hq_id FROM job, courier WHERE job.cr_id = courier.cr_id AND job.cr_sid = courier.cr_sid AND jb_id = " . $argv[1]);
  if ($hq_id_exec == "")
    $hq_id_exec = $db->getOne("SELECT hq_id_exec FROM job WHERE jb_id = " . $argv[1]);
  $jb_longhaul_export = 0;
  $jb_longhaul = $db->getOne("SELECT jb_longhaul FROM job WHERE jb_id = " . $argv[1]);
  $jb_bwv = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $argv[1] . " AND gdc_gen_fieldname = 'jb_bwv'"); // BWV-Häkchen gesetzt
//  writeLog_("../log/check_cr_agio_", "\$jb_id = " . $argv[1] . ", jb_bwv = " . $jb_bwv .  ")");
  if ($jb_longhaul == 1 || $hq_id != $hq_id_exec || $jb_bwv == "1")
    $jb_longhaul_export = 1;
  $jb_hq_id_exec_price = 0;
  if ($hq_id != $hq_id_exec) {
    $jb_hq_id_exec_price_rate = (float) getParameterValue("0", "MASK_HQ_ID_EXEC_PRICE_RATE", $hq_id);
    $jb_cr_price = $db->getOne("SELECT jb_cr_price FROM job WHERE jb_id = " . $argv[1]);
    $jb_totalprice = $db->getOne("SELECT jb_totalprice FROM job WHERE jb_id = " . $argv[1]);
// hq darf nicht upgedatet werden wenn andere Niederlassung dden Auftrag bearbeitet!
// hq_id_exec (wird vom JAS-Server geschrieben) wird als Niederlassungskürzel im Export übernommen; hq_id_dispo und hq_id_exec sind für Export irrelevant
    $jb_hq_id_exec_price = (round(($jb_totalprice - $jb_cr_price) * $jb_hq_id_exec_price_rate, 2) + $jb_cr_price);
  }
  updateStmt("job", "jb_id", $argv[1], array("hq_id_exec", $hq_id_exec, "jb_longhaul_export", $jb_longhaul_export, "jb_hq_id_exec_price", $jb_hq_id_exec_price));
  writeLog_("../log/check_cr_agio_", "get_job_distance.php: \$jb_id = " . $argv[1] . ", \$jb_longhaul_export = " . $jb_longhaul_export . ", \$jb_hq_id_exec_price = " . $jb_hq_id_exec_price);

  deleteStmt("phoenix_log.semaphor","sp_obj_type = 'jb' AND sp_obj_id = '" . $argv[1] . "' AND sp_fieldname = 'get_job_distance' AND sp_context = '" . $mypid . "'");
else:
  writeLog_("../log/check_cr_agio_", "get_job_distance.php: double call for " . $argv[1] . ": semaphor already existing!");
endif;
?>
