<?php
include_once ("../include/global.inc.php");
getSecHttpVars("1",array("cr_sid","hq_id","customer_special","jb_id","f_act"));
include_once ("../locating/map.inc.php");

//header("Content-Type: text/html; charset=ISO-8859-1\n");

//echo "alert('" . $cr_sid . "');";
if ($f_act == "setCourier" && $cr_sid != "" && $jb_id != ""):
  $currentSessionUsrId = $usr_id;
  setCourier($cr_sid, $jb_id);
  echo "alert('Auftrag Nr. " . $jb_id . " wurde " . $cr_sid . " zugewiesen.');";
else:  
  $sqlquery = "SELECT cr_sid, vht_id, cr_locationzipcode, cr_available, cr_availabletime, cr_gps_long, cr_gps_lat, cr_gps_time, cr_gps_type, cr_mobile_pda, usr_phone, usr_phone2 FROM courier, user WHERE courier.hq_id = '$hq_id' AND cr_gps_time > '" . $start_time . "' AND courier.usr_id = user.usr_id"; //AND cr_available = 1 ORDER BY cr_gps_time, cr_sid";
  if ($hq_id == 0 /*nur cr_sid*/ || $customer_special == 1):
    $cr_sid = str_replace("\\", "", $cr_sid);
    $sqlquery = "SELECT cr_sid, vht_id, cr_locationzipcode, cr_available, cr_availabletime, cr_gps_long, cr_gps_lat, cr_gps_time, cr_gps_type, cr_mobile_pda, usr_phone, usr_phone2 FROM courier, user WHERE cr_sid IN ($cr_sid) AND courier.usr_id = user.usr_id;";
  //  $sqlquery = "SELECT cr_sid, vht_id, cr_locationzipcode, cr_available, cr_availabletime, cr_gps_long, cr_gps_lat, cr_gps_time FROM courier WHERE cr_sid = '$cr_sid'";
  endif;
  $res = $db->query($sqlquery);
  if (DB::isError($res)) die ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
  
  $ret_value = "";
  while ($row = $res->fetch_assoc()):
    $cr_sid = $row["cr_sid"];
    $ret_value .= "retValue['" . $cr_sid . "'] = new Array('" . $row["cr_gps_time"] . "', " . $row["cr_gps_lat"] . ", " . $row["cr_gps_long"] . ", " .
      mk_text($row["cr_locationzipcode"], $row["cr_availabletime"], $row["cr_gps_time"], $row["cr_gps_type"], $row["cr_available"], $cr_sid, $row["vht_id"], $row["cr_mobile_pda"], $row["usr_phone"], $row["usr_phone2"], $jb_id) . ");\n";
  endwhile;
  $res->free();
//echo "alert(\"" . str_replace('"', "'", $ret_value) . "\");";
  if ($jb_id != "")
    echo $vht_id_str_js;
  echo "retValue = new Array();\n$ret_value";
endif;

function setCourier($f_cr_sid, $f_jb_id, $f_cr_availabletime_reset = "0") {
  global $db, $hq_id, $jb_status, $currentSessionUsrId;
  
  // Get current cr_id of the job before changing the courier
  $crIdCurrent = getFieldValueFromId("job","jb_id",$f_jb_id,"cr_id");
  $crIdOrderCurrent = getFieldValueFromId("job","jb_id",$f_jb_id,"cr_id_order");
  $jbHqId = getFieldValueFromId("job","jb_id",$f_jb_id,"hq_id");
  if ($jbHqId == "" || !is_numeric($jbHqId)) : $jbHqId = $hq_id; endif;
  if ($f_cr_availabletime_reset != "1") : $f_cr_availabletime_reset = "0"; endif;

  // getDbFieldValues("courier",array("cr_id","cr_occupied"),array("cr_sid",$f_cr_sid));
  $cr_id = getFieldValueFromClause("courier","cr_id","cr_sid = '" . $f_cr_sid . "' ORDER BY cr_logintime");
  if ($cr_id != "") :
  
     // RANKING
     // Special treatment according to vehicletype ("BUS" or greater will NOT be revoked if job-order is "PKW")
     // Get cr.vht_id and jb.vht_id
     /*
     $arLooseRanking = "1";    // Init: Loose ranking "yes"
     $courierVhtId = getFieldValueFromId("courier","cr_id",$cr_id,"vht_id");
     $jobVhtId = getFieldValueFromId("job","jb_id",$f_jb_id,"vht_id");
     if ($courierVhtId != "" && $jobVhtId != "" && $courierVhtId >= '5' && $jobVhtId <= "3") :
        $arLooseRanking = "0";   // Loose ranking "no"
     endif;
     */
     // Special treatment according areas
     $jbAdressIdStart = getFieldValueFromClause("tour", "ad_id", "jb_id = '" . $f_jb_id . "' AND tr_sort = '1'");
     $jbZipcodeStart = getFieldValueFromId("address", "ad_id", $jbAdressIdStart, "ad_zipcode");
     $arLooseRanking = looseRanking($cr_id, $jbZipcodeStart, $jbHqId);


     // Check first that courier is NOT occupied
     // $cr_occupied = getFieldValueFromId("courier", "cr_id", $cr_id, "cr_occupied");
     // if ($cr_occupied == "0") :
     // if (getCountOfTable("job","cr_id_order = '" . $cr_id . "' AND (jb_status = '1' OR jb_status = '0') AND (isnull(jb_globaljob) or jb_globaljob = '0')") == 0) :

        $currentTime = getDateTime("0");

        TA("B");            

        // Update job
        // According to be TA-safe the WHERE-Clause depends on the current list the user is in
        $jbStatusString = " (jb_status = '8' OR jb_status = '9' OR jb_status = '0' OR jb_status = '1') ";
        if (is_numeric($jb_status)) : $jbStatusString = "jb_status = '" . $jb_status . "'"; endif;
        $res = updateStmt("job", "jb_id", $f_jb_id, array("cr_id", "", "cr_id_order", $cr_id, "jb_status", "0", "cr_sid", $f_cr_sid, "jb_globaljob", "0", "jb_autoranking", "0"), $jbStatusString);

        // if ($db->affected_rows > 0) :
        if ($res > 0) :

           // Set current assigning time for revoking a job if not taken by the courier
           if (existsEntry("autoranking",array("jb_id",$f_jb_id,"cr_id",$cr_id))) :
              updateStmt("autoranking", "jb_id", $f_jb_id, array("ar_challenge", "0", "ar_lastassigntime", $currentTime, "ar_looseranking", $arLooseRanking, "ar_locating", "0"),"cr_id = '" . $cr_id . "'");
           else :
              insertStmt("autoranking", array("jb_id", $f_jb_id, "cr_id", $cr_id, "ar_challenge", "0", "ar_lastassigntime", $currentTime, "ar_looseranking", $arLooseRanking, "ar_locating", "0"));
           endif;

           // Insert PDA command to remove job (take cr_id/cr_id_order before changing)
           $currentTimePDA = getDateTime("datetime_plus_offset", array(0,0,30,0,0,0), $formatStr = "Y-m-d H:i:s");
           if ($crIdCurrent != "" && $crIdCurrent != "0") :
              insertPDACommand($jbHqId, $crIdCurrent, "4", "1", $f_jb_id, $currentTimePDA, "");
           endif;
           if ($crIdOrderCurrent != "" && $crIdOrderCurrent != "0" && $crIdOrderCurrent != $crIdCurrent) :
              insertPDACommand($jbHqId, $crIdOrderCurrent, "4", "1", $f_jb_id, $currentTimePDA, "");
           endif;

           // Reset availabletime of the OLD courier if requested by the disposition manually
           if ($f_cr_availabletime_reset == "1") :
              updateStmt("courier", "cr_id", $crIdCurrent, array("cr_availabletime", $currentTime));
           endif;

           // Write logdata into log database
           writeToLogDB("7",$jbHqId,$f_jb_id,$currentSessionUsrId,$cr_id,$f_cr_sid,"","LOST_RANKING=" . ($arLooseRanking == "1" ? "YES" : "NO"));
        endif;

        TA("C");
        TA("E");
     // else :
     //    $statusMessage = getLngt("Dem Fahrzeug") . " " . $f_cr_sid . " " . getLngt("wurde zwischenzeitlich ein Auftrag zugewiesen! Bitte ein anderes Fahrzeug wählen.");
     // endif;
  endif;
}
?>