<?php

include_once("../include/global.inc.php");
include_once("../include/auth.inc.php");
include_once("../locating/xServer.inc.php");

$f_formsubmit = isset($_GET["formsubmit"]) ? $_GET["formsubmit"] : (isset($_POST["formsubmit"]) ? $_POST["formsubmit"] : "");

if ($f_formsubmit == "Start") {
  $file = fopen("BWV-Dummy-Kreditoren_2.0.csv","r");
  $i = 1;
  while(!feof($file))  {
    $tmp_arr = fgetcsv($file, 0, ";");
    if ($tmp_arr[5] != "Fahrer" && $tmp_arr[11] != "") {
  //    print_r($tmp_arr);
  writeLog_reset (($i++) . ", Nr.: " .  $tmp_arr[0] . ", Fahrer: " . $tmp_arr[5] . ", Termin: " . $tmp_arr[7] . ", Standort: " . $tmp_arr[11] . ", Wunsch-PLZ: " . $tmp_arr[12] . ", Station1 erl.: " . $tmp_arr[13] . ", Station2 erl.: " . $tmp_arr[14]);
      $sqlquery = "SELECT cr_id, cr_sid, cr_available, cr_availabletime, cr_gps_lat, cr_gps_long, cr_gps_time, cr_desiredzipcode, cr_gps_lat_home, cr_gps_long_home FROM courier WHERE cr_sid = '" . $tmp_arr[5] . "'";
  writeLog_reset($sqlquery);
      $res = $db->query($sqlquery);
      if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
      if (mysqli_num_rows($res) == 0) {
  writeLog_reset($tmp_arr[5] . " not found");
        die(); // HH1491
      }
      while ($row = $res->fetch_assoc()):
  writeLog_reset("cr_id = " . $row["cr_id"] . ", cr_sid = " . $row["cr_sid"] . ", cr_available = " . $row["cr_available"] . ", cr_gps_lat = " . $row["cr_gps_lat"] . ", cr_gps_long = " . $row["cr_gps_long"] . ", cr_gps_time = " . $row["cr_gps_time"] . ", cr_desiredzipcode = " . $row["cr_desiredzipcode"] . ", cr_gps_lat_home = " . $row["cr_gps_lat_home"] . ", cr_gps_long_home = " . $row["cr_gps_long_home"]);
        $cr_id = $row["cr_id"];
        $cr_sid = $row["cr_sid"];
        $update_sql = "cr_locationzipcode = '" . $tmp_arr[11] . "', cr_available = 1, cr_availabletime = NOW(), cr_gps_time = NOW()";
        //  print_r(get_address($row["cr_gps_lat"], $row["cr_gps_long"]));
  
        $tmp_coords = check_zipcode_coords($tmp_arr[11], $row["cr_gps_lat"], $row["cr_gps_long"]);
        if ($tmp_coords[0] != $row["cr_gps_lat"] || $tmp_coords[1] != $row["cr_gps_long"])
          $update_sql .= ($update_sql != "" ? ", " : "") . "cr_gps_lat = " . $tmp_coords[0] . ", cr_gps_long = " . $tmp_coords[1];
  
        $tmp_coords = check_zipcode_coords($tmp_arr[12], $row["cr_gps_lat_home"], $row["cr_gps_long_home"]);
        if ($tmp_coords[0] != $row["cr_gps_lat_home"] || $tmp_coords[1] != $row["cr_gps_long_home"])
          $update_sql .= ($update_sql != "" ? ", " : "") . "cr_desiredzipcode = '" . $tmp_arr[12] . "', cr_gps_lat_home = " . $tmp_coords[0] . ", cr_gps_long_home = " . $tmp_coords[1];
  
        if ($update_sql != "") {
  writeLog_reset("UPDATE courier SET " . $update_sql . " WHERE cr_id = " . $row["cr_id"]);
          $db->query("UPDATE courier SET " . $update_sql . " WHERE cr_id = " . $row["cr_id"]);
        }
      endwhile;
      $res->free();     
  
      if ($tmp_arr[0] != "") {
        $sqlquery = "SELECT tr_id, tr_sort, tr_status, tr_sign, tr_signname, tr_finishtime FROM tour WHERE jb_id = " . $tmp_arr[0];
  writeLog_reset($sqlquery);
        $res = $db->query($sqlquery);
        if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
        if (mysqli_num_rows($res) == 0) {
  writeLog_reset($tmp_arr[0] . " not found");
          die();
        }
        while ($row = $res->fetch_assoc()):
          $update_sql = "";
  writeLog_reset("tr_id = " . $row["tr_id"] . ", tr_sort = " . $row["tr_sort"] . ", tr_status = " . $row["tr_status"]. ", tr_signname = " . $row["tr_signname"] . ", tr_finishtime = " . $row["tr_finishtime"] . ", tr_sign = " . $row["tr_sign"]);
          if (($row["tr_sort"] == "1" && $tmp_arr[13] == "x") || ($row["tr_sort"] == "2" && $tmp_arr[14] == "x")) {
            $update_sql = "tr_status = 1, tr_finishtime = NOW()";
          } else {
            $update_sql = "tr_status = NULL, tr_sign = NULL, tr_signname = NULL, tr_finishtime = NULL";
          }
  writeLog_reset("UPDATE tour SET " . $update_sql . " WHERE tr_id = " . $row["tr_id"]);
          $db->query("UPDATE tour SET " . $update_sql . " WHERE tr_id = " . $row["tr_id"]);
        endwhile;
        $res->free();
  
        $sqlquery = "SELECT jb_id, jb_ordertime, cr_sid, cr_id, cr_id_order, jb_status, jb_finishtime FROM job WHERE jb_id = " . $tmp_arr[0];
  writeLog_reset($sqlquery);
        $res = $db->query($sqlquery);
        if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
        if (mysqli_num_rows($res) == 0) {
  writeLog_reset($tmp_arr[0] . " not found");
          die();
        }
        while ($row = $res->fetch_assoc()):
  writeLog_reset("jb_id = " . $row["jb_id"] . ", jb_ordertime = " . $row["jb_ordertime"] . ", cr_id = " . $row["cr_id"] . ", cr_sid = " . $row["cr_sid"] . ", cr_id_order = " . $row["cr_id_order"] . ", jb_status = " . $row["jb_status"] . ", jb_finishtime = " . $row["jb_finishtime"]);
        endwhile;
  
        if ($tmp_arr[7] != "")
          $tmp_arr[7] = "'" . $tmp_arr[7] . "'";
        else 
          $tmp_arr[7] = "RIGHT(jb_ordertime, 8)";
  
  writeLog_reset("UPDATE job SET jb_ordertime = CONCAT('" . date("Y-m-d ") . "', " . $tmp_arr[7] . "), cr_id = " . $cr_id . ", cr_sid = '" . $cr_sid . "', cr_id = " . $cr_id . ", jb_status = 1, jb_finishtime = NULL WHERE jb_id = " . $tmp_arr[0]);
        $db->query("UPDATE job SET jb_ordertime = CONCAT('" . date("Y-m-d ") . "', " . $tmp_arr[7] . "), cr_id = " . $cr_id . ", cr_sid = '" . $cr_sid . "', cr_id = " . $cr_id . ", jb_status = 1, jb_finishtime = NULL WHERE jb_id = " . $tmp_arr[0]);
      }
  writeLog_reset("");
  //if ($i == 12) die();
    }
  }
  fclose($file);
}

function check_zipcode_coords($zipcode, $gps_lat, $gps_long) {
  if ($gps_lat != 0 && $gps_long != 0)
    $tmp_locationArr = get_address($gps_lat, $gps_long);
  else
    $tmp_locationArr = array("","","","","","");
  if ($tmp_locationArr[2] != $zipcode) {
writeLog_reset("(" . $gps_lat . ", " . $gps_long . ") liegt nicht in PLZ " . $zipcode);
    $tmp_coords = get_coords("DE", $zipcode, ".", ".", ".", true);
    return(array($tmp_coords[0], $tmp_coords[1]));
  } else {
writeLog_reset("(" . $gps_lat . ", " .  $gps_long . ") liegt in PLZ " . $zipcode);
    return(array($gps_lat, $gps_long));
  }
}

function writeLog_reset($log_text) {
  $today = getdate();
  $log_name = "BWV-Dummy-Kreditoren_reset";

  $fileHandle = @fopen("../log/" . $log_name . "_" . $today['year'] . sprintf("%02d", $today['mon']) . ".log", 'a');
  if (!$fileHandle) {
    $fileHandle = @fopen("../log/" . $log_name . "_" . $today['year'] . sprintf("%02d", $today['mon']) . ".web.log", 'a');
  }
  fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] " . $log_text .  "\n");
  @fclose($fileHandle);
  return;
}
?>
<html>
<head>
<title>Reset der BWV Dummy-Kreditoren</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>
</head>
<body>
  <table border="0" width="100%" cellspacing="0" cellpadding="0" vspace="0" hspace="0">
    <tr>
      <td>
      </td>
      <td align="center">
        &nbsp;<br>
        &nbsp;<br>
        &nbsp;<br>
<form name="reset" action="BWV-Dummy-Kreditoren_reset.php" method="post"><div class="f10bp1_blue">
        <table border="0" cellspacing="0" cellpadding="0" vspace="0" hspace="0">
          <tr>
            <td align="center"> <div class="f12bp1_blue">
<!--
<input type="file" id="myFile" name="filename">
-->
    BWV Dummy-Kreditoren resetten<br>
        &nbsp;<br>
<?php if ($f_formsubmit == "Start") echo "<!--"; ?>
    <input type="submit" name="formsubmit" size="2" value="Start" class="submit">
<?php if ($f_formsubmit == "Start") echo "--><span style=\"color:red\">Fertig!</span>"; ?>
            </td>
          </tr>
          <tr>
            <td align="center">              
              <span style="color:red"> <?php echo $error_text; ?> </span>
              <?php echo $content; ?>
            </td>
          </tr>
        </table>
</form>              
      </td>
      <td>
        &nbsp;
      </td>
    </tr>
      </td>
    </tr>
  </table>
</body>
</html>

