<?php 
/*=======================================================================
 *
 * appointment_request.php
 *
 * Autor: Marc Vollmann
 *
  =======================================================================*/


include_once ("../include/mcglobal.inc.php");
include_once ("../include/caglobal.inc.php");    // For pricing and invoice-text only
// include_once ('../include/email/htmlMimeMail.php');
include_once ("../include/services_func.inc.php");
include_once ("../include/inc_parseXML.inc.php");
include_once ("../include/inc_mtf_func.inc.php");
include_once ("../include/inc_customer.inc.php");
include_once ("../include/inc_job.inc.php");
include_once ("../include/inc_vehicle.inc.php");
include_once ("../include/inc_disposition.inc.php");
// include_once ("../include/inc_disposition_DEV.inc.php");
// include_once ("../geo/geocode.inc.php");


// Write logdata into log file
$currentTime = getDateTime("0");
$currentDate = getDateTime("3");

$debug = false;
$debugOut = "";

// $appointmentReq = file_get_contents('php://input');

// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "appointmentReq", "selectedLanguage"));

if ($appointmentReq == "") :
   if (isset($argv[1])) : 
      $appointmentReq = $argv[1];
   endif;
endif;

function appointmentRequestLogFile ($msg, $logLevel = 0) {
  XMLRequestLogFile($msg, $logLevel, $logFile = "appointmentReq.log");
}


$appointmentReq = urldecode($appointmentReq);
$appointmentReq = str_replace("'", "", $appointmentReq);
$appointmentReq = mcEncode($appointmentReq);
$appointmentReq = str_replace("'", "", $appointmentReq);
// echo $appointmentReq . "<br><br>";

appointmentRequestLogFile($currentTime);
appointmentRequestLogFile($appointmentReq);


if ($selectedLanguage == "" || !is_numeric($selectedLanguage)) : $selectedLanguage = "1"; endif;  // Default in English
$languageSelected = $selectedLanguage;

getLanguage(__FILE__);
getCurrentScript(__FILE__);

$err = array();
$appointmentResponse = "";
$xmlVehiclesAvailable = "";


// ---------------------------------------------------------------------------

// GLOBAL MODE OF USAGE
$globalParUseRelatedCustomer = getParameterValue("0", "GLOBAL_USE_RELATED_CUSTOMER", "0");

// *** Parse request ***
$appointmentArray = xml2array($appointmentReq);
if ($debug) :
   print_r($appointmentArray); echo "<br><br><br>";
endif;


// *** Convert result array to usable parameters ***
// Authentication data
$csEid          = convertSpecial($appointmentArray["xml"]["appointment"]["auth"]["customer"]);
$csId           = getFieldValueFromId("customer","cs_eid",$csEid,"cs_id");
$usrAccount     = convertSpecial($appointmentArray["xml"]["appointment"]["auth"]["account"]);
$usrPassword    = convertSpecial($appointmentArray["xml"]["appointment"]["auth"]["password"]);
$sessionId      = convertSpecial($appointmentArray["xml"]["appointment"]["auth"]["session_id"]);
// Optional customer group data (needed to find e.g. an article price automatically). Has to be set explicitly, because a customer could belong to more groups !!!!
$csGroupId      = convertSpecial($appointmentArray["xml"]["appointment"]["auth"]["group_no"]);
$csGroupName    = convertSpecial($appointmentArray["xml"]["appointment"]["auth"]["group_name"]);
if ($csGroupId != "" && is_numeric($csGroupId)) :
   $csGroupName = getFieldValueFromId("groups","grp_id",$csGroupId,"grp_name");
elseif ($csGroupName != "") :
   $csGroupId = getFieldValueFromId("groups","grp_name",$csGroupName,"grp_id");
endif;
// Reset customer group data if it could not be identified
if ($csGroupId == "" || $csGroupName == "") :
   $csGroupId = "";
   $csGroupName = "";
endif;

$debugOut .= "usrAccount: " . $usrAccount . "<br>\n";
$debugOut .= "usrPassword: " . $usrPassword . "<br>\n";
$debugOut .= "sessionId: " . $sessionId . "<br>\n";

if (checkRequestAuthenticationData($usrAccount, $usrPassword, $sessionId, $csId)) :
   $debugOut .= "Authentication okay!<br><br>\n";

   // Data
   $hqId            = getFieldValueFromId("customer","cs_id",$csId,"hq_id");
   $cscName         = convertSpecial($appointmentArray["xml"]["appointment"]["auth"]["costcenter_name"]);
   $cscId = "";
   if ($cscName != "") :
      $cscId        = getFieldValueFromClause("costcenter","csc_id","cs_id = '" . $csId . "' AND csc_name = '" . $cscName . "'");
   endif;
   if ($cscId == "" || !is_numeric($cscId)) :
      $cscId        = getFieldValueFromClause("costcenter","csc_id","cs_id = '" . $csId . "' AND isnull(csc_pre_id)");   // Root costcenter
   endif;


   // Get job or appointment data
   $operation               = convertSpecial($appointmentArray["xml"]["appointment"]["operation"]);
   $debugOn                 = convertSpecial($appointmentArray["xml"]["appointment"]["debug_on"]);
   $jbId                    = convertSpecial($appointmentArray["xml"]["appointment"]["order_id"]);
   $ecoZipcode              = convertSpecial($appointmentArray["xml"]["appointment"]["eco_zipcode"]);
   $ecoNeededTimeUnits      = convertSpecial($appointmentArray["xml"]["appointment"]["eco_needed_time_units"]);
   $sortSequence            = convertSpecial($appointmentArray["xml"]["appointment"]["sort_sequence"]);
   $ecoServices             = convertSpecial($appointmentArray["xml"]["appointment"]["eco_services"]);
   $ecoWeight               = convertSpecial($appointmentArray["xml"]["appointment"]["eco_weight"]);
   $ecoPositions            = convertSpecial($appointmentArray["xml"]["appointment"]["eco_positions"]);
   $maxLimitOfRows          = convertSpecial($appointmentArray["xml"]["appointment"]["max_limit_of_rows"]);
   $deliveryTimeValue       = convertSpecial($appointmentArray["xml"]["appointment"]["delivery_time_value"]);
   $day_from                = convertSpecial($appointmentArray["xml"]["appointment"]["day_from"]);
   $month_from              = convertSpecial($appointmentArray["xml"]["appointment"]["month_from"]);
   $year_from               = convertSpecial($appointmentArray["xml"]["appointment"]["year_from"]);
   $day_to                  = convertSpecial($appointmentArray["xml"]["appointment"]["day_to"]);
   $month_to                = convertSpecial($appointmentArray["xml"]["appointment"]["month_to"]);
   $year_to                 = convertSpecial($appointmentArray["xml"]["appointment"]["year_to"]);
   $jbTimedFilter           = convertSpecial($appointmentArray["xml"]["appointment"]["jb_timed_filter"]);
   $dateSelectionByCalendar = convertSpecial($appointmentArray["xml"]["appointment"]["date_selection_by_calendar"]);
   $futureDaysOffset        = convertSpecial($appointmentArray["xml"]["appointment"]["future_days_offset"]);

   $debugOut .= "operation: " . $operation . "<br>\n";
   $debugOut .= "jbId: " . $jbId . "<br>\n";
   $debugOut .= "ecoZipcode: " . $ecoZipcode . "<br>\n";
   $debugOut .= "ecoNeededTimeUnits: " . $ecoNeededTimeUnits . "<br>\n";
   $debugOut .= "sortSequence: " . $sortSequence . "<br>\n";
   $debugOut .= "ecoServices: " . $ecoServices . "<br>\n";
   $debugOut .= "ecoWeight: " . $ecoWeight . "<br>\n";
   $debugOut .= "ecoPositions: " . $ecoPositions . "<br>\n";
   $debugOut .= "maxLimitOfRows: " . $maxLimitOfRows . "<br>\n";
   $debugOut .= "deliveryTimeValue: " . $deliveryTimeValue . "<br>\n";
   $debugOut .= "day_from: " . $day_from . "<br>\n";
   $debugOut .= "month_from: " . $month_from . "<br>\n";
   $debugOut .= "year_from: " . $year_from . "<br>\n";
   $debugOut .= "day_to: " . $day_to . "<br>\n";
   $debugOut .= "month_to: " . $month_to . "<br>\n";
   $debugOut .= "year_to: " . $year_to . "<br>\n";
   $debugOut .= "jbTimedFilter: " . $jbTimedFilter . "<br>\n";
   $debugOut .= "dateSelectionByCalendar: " . $dateSelectionByCalendar . "<br>\n";
   $debugOut .= "futureDaysOffset: " . $futureDaysOffset . "<br>\n";

   // Daytimes
   $ecoDayTimeArray = array();
   $tmpEcoDayTimes = count($appointmentArray["xml"]["appointment"]["eco_day_time"]["val"]);
   if ($tmpEcoDayTimes > 0) :
      if ($tmpEcoDayTimes == 1) : 
         $ecoDayTimeArray[0] = convertSpecial($appointmentArray["xml"]["appointment"]["eco_day_time"]["val"]);
      else :
         for ($k = 0; $k < $tmpEcoDayTimes; $k++) :
             $tmpVal = convertSpecial($appointmentArray["xml"]["appointment"]["eco_day_time"]["val"][$k]);
             $tmpVal = trim($tmpVal);
             if ($tmpVal != "") :
                $ecoDayTimeArray[] = $tmpVal;
             endif;
         endfor;
      endif;
   endif;
   // $debugOut .= "ecoDayTimeArray: " . print_r($ecoDayTimeArray) . "<br><br>\n";

   // Weekdays
   $ecoWeekdayArray = array();
   $tmpEcoWeekday = count($appointmentArray["xml"]["appointment"]["eco_weekday"]["val"]);
   if ($tmpEcoWeekday > 0) :
      if ($tmpEcoWeekday == 1) : 
         $ecoWeekdayArray[0] = convertSpecial($appointmentArray["xml"]["appointment"]["eco_weekday"]["val"]);
      else :
         for ($k = 0; $k < $tmpEcoWeekday; $k++) :
             $tmpVal = convertSpecial($appointmentArray["xml"]["appointment"]["eco_weekday"]["val"][$k]);
             $tmpVal = trim($tmpVal);
             if ($tmpVal != "") :
                $ecoWeekdayArray[] = $tmpVal;
             endif;
         endfor;
      endif;
   endif;
   // $debugOut .= "ecoWeekdayArray: " . print_r($ecoWeekdayArray) . "<br><br>\n";

   // Init
   $currentTimestamp = getDateTime("0");
   $currentDay = getDateTime("3");   // "Y-m-d"
   $currentTime = getDateTime("4");  // Current time ("H:i:s")
   $currYear = getDateTime("year");  // Current year
   $combinedJob = false;

   if (!$debug && $debugOn == "ON" || $debugOn == "YES") :
      $debug = true;
   endif;

   if ($operation == "SET") :

      // TO BE DONE!


   else :

      // Get available vehicle data
      $globalParArray = array($jbId, $csId, $ecoDayTimeArray, $ecoWeekdayArray, $ecoZipcode, $ecoNeededTimeUnits, $sortSequence, $ecoServices, $ecoWeight, $ecoPositions,
                              $maxLimitOfRows, $deliveryTimeValue, $deactivateMenu, $day_from, $month_from, $year_from, $day_to, $month_to, $year_to, $jbTimedFilter, 
                              $dateSelectionByCalendar, $futureDaysOffset);
      // $debugOut .= "globalParArray: " . print_r($globalParArray) . "<br><br>\n";
// echo "<br><br>\n"; print_r($globalParArray);
      
      $retArray = getDispositionAppointments("0", $globalParArray);
      // $debugOut .= "<br>RESPONSE DATA:<br><br>retArray: " . print_r($retArray) . "<br><br>\n";
// echo "<br><br>\n"; print_r($retArray);

      // Check for ERRORS
      if (is_array($retArray)) :
         // Vehicles found => Generate output
         $retArrayLen = count($retArray);
         $xmlVehiclesAvailable .= "<vehicles>";
         for ($k = 0; $k < $retArrayLen; $k++) :
             $xmlVehiclesAvailable .= "<vehicle>";

             $xmlVehiclesAvailable .= "<date>" .             $retArray[$k][0]  . "</date>";              // vha_day
             $xmlVehiclesAvailable .= "<start_time>" .       $retArray[$k][4]  . "</start_time>";        // vhat_starttimeunit => converted to clock time (e.g. 14:30)
             $xmlVehiclesAvailable .= "<time_units>" .       $retArray[$k][3]  . "</time_units>";        // vhat_timeunits  (available time units [1 time unit equals 10 minutes])
             $xmlVehiclesAvailable .= "<vh_id>" .            $retArray[$k][7]  . "</vh_id>";             // crvh_id
             $xmlVehiclesAvailable .= "<vh_sid>" .           $retArray[$k][1]  . "</vh_sid>";            // crvh_sid
             $xmlVehiclesAvailable .= "<daytime_raw>" .      $retArray[$k][6]  . "</daytime_raw>";       // vhat_daytime ("0" = 1st defined daytime for the customer, "1" = 2nd daytime, "2" = ....)
             $xmlVehiclesAvailable .= "<daytime>" .          $retArray[$k][2]  . "</daytime>";           // vhat_daytime (e.g. "Vormittag", "Nachmittag", "Abend")
             $xmlVehiclesAvailable .= "<daytime_interval>" . $retArray[$k][10] . "</daytime_interval>";  // vhat_daytime (e.g. "07:00 - 12:00", "12:00 - 16:00", "16:00 - 21:00")
             $xmlVehiclesAvailable .= "<service>" .          $retArray[$k][5]  . "</service>";           // jb_service = ("1" => "LI" = Lieferung, "2" => "MO" = Montage,....)

             $xmlVehiclesAvailable .= "</vehicle>";
         endfor;
         $xmlVehiclesAvailable .= "</vehicles>";
      else :

         if (!(strpos($retArray, "ERR:ZIPCODE_NOT_IN_ANY_ZONE") === FALSE)) :
            $err[] = array("102", getLngt("Die PLZ ist keiner Zone zugeordnet!") . " [" . $ecoZipcode . "]");
         else :
            $err[] = array("103", getLngt("Bereichsfehler!"));
         endif;
      endif;
      $debugOut .= "<br><br>xmlVehiclesAvailable: " . $xmlVehiclesAvailable . "<br>\n";

      // Write logdata into log database for calling reservation page
      /*
      if ($jbId != "") :
         $parLogCallingReservationPage = getParameterValue("0", "DISPOSITION_LOG_PAGE_CALL_ENABLED", $hqId);
         if ($parLogCallingReservationPage == "1") :
            // ZIP = Zipcode, CJ = Combined Job, WD = Whole day request
            writeToLogDB("130",$hqId,$jbId,"","","",$csId,"ZIP=" . $ecoZipcode . "|ZONE=" . $ecoSrvzId . "|CJ=" . ($combinedJob ? "Y" : "N") . "|WD=" . ($ecoHasWholeDayRequest ? "Y" : "N"),"","","");
         endif;
      endif;
      */
   endif;

else :
  // Authentication data not ok
  $err[] = array("101", getLngt("Die Authentifizierungsdaten sind nicht in Ordnung."));
endif;
// print_r($err);

// Check existence of at least one error
$errLen = count($err);

// Output
$appointmentResponse .= "<xml>";   
if ($errLen > 0) :
   appointmentRequestLogFile("ERRORS", 1);
   $appointmentResponse .= "<state>NOT OK</state>";
   $appointmentResponse .= "<errors>";
   for ($i = 0; $i < $errLen; $i++) :
       $appointmentResponse .= "<error>";
       $appointmentResponse .= "<err_no>" . $err[$i][0] . "</err_no>";
       $appointmentResponse .= "<err_desc><![CDATA[" . mcEncode($err[$i][1]) . "]]></err_desc>";
       $appointmentResponse .= "</error>";
       if ($debug) :
          $appointmentResponse .= "<debug>" . $debugOut . "</debug>";
       endif;
       appointmentRequestLogFile($err[$i][0] . " : " . mcEncode($err[$i][1]), 1);
   endfor;
   $appointmentResponse .= "</errors>";
else :
   $appointmentResponse .= "<state>OK</state>" . $xmlVehiclesAvailable;
   if ($debug) :
      $appointmentResponse .= "<debug>" . $debugOut . "</debug>";
   endif;
endif;
$appointmentResponse .= "</xml>";

// Log entries
$currentTimeResponse = getDateTime("0");
appointmentRequestLogFile($appointmentResponse);    // Write response into log
appointmentRequestLogFile($currentTimeResponse . " :: " . $csEid);
appointmentRequestLogFile("___________________________________________________________________________________");

// Return output
echo $appointmentResponse;



/*
// REQUEST
<xml>
  <appointment>                                                   // Terminanfrage
    <auth>                                                        // Identifikation des Kunden
      <customer>...</customer>                                    // Kundennummer (EID) {"STBxxxxxx", ...} => csc_id_payer
      <account>...</account>                                      // Eingetragener Benutzer für den Kunden => cs.cs_admin => emp.emp_id => emp.usr_id => usr.usr_id => usr.usr_account
      <password>...</password>                                    // Passwort für den Benutzer             => usr.usr_password
      <session_id>...</session_id>                                // Zusätzliche Session-ID, die mit dem Kunden ausgehandelt wurde   [mandatory]
      <costcenter_name>...</costcenter_name>                      // Kostenstellenname {"abcd", "efgh", ...} => Mapping csc_id   [optional]
      <group_no>...</group_no>                                    // Nummer der Kundengruppe (Bei einer automatischen Preisfindung muss entweder <group_no> oder <group_name> gesetzt sein)
      <group_name>...</group_name>                                // Name der Kundengruppe (Bei einer automatischen Preisfindung muss entweder <group_name> oder <group_no> gesetzt sein)
    </auth>                                                       
                                                                  
    <debug_on>...</debug_on>                                      // Activates debug output ("ON" or "YES")

    <operation>GET|SET</operation>                                // Operation (GET or SET appointment(s), default is "GET" if emty tag)
    <order_id>...</order_id>                                      // Existing order ID
    <eco_zipcode>...</eco_zipcode>                                // 
    <eco_needed_time_units>...</eco_needed_time_units>            // 
    <sort_sequence>...</sort_sequence>                            // 
    <eco_services>...</eco_services>                              // 
    <eco_weight>...</eco_weight>                                  // 
    <eco_positions>...</eco_positions>                            // 
    <max_limit_of_rows>...</max_limit_of_rows>                    // 
    <delivery_time_value>...</delivery_time_value>                // 
    <day_from>...</day_from>                                      // 
    <month_from>...</month_from>                                  // 
    <year_from>...</year_from>                                    // 
    <day_to>...</day_to>                                          // 
    <month_to>...</month_to>                                      // 
    <year_to>...</year_to>                                        // 
    <jb_timed_filter>...</jb_timed_filter>                        // 
    <date_selection_by_calendar>...</date_selection_by_calendar>  // 
    <future_days_offset>...</future_days_offset>                  // 

    <eco_day_time>                                                  // Tageszeiten
      <val>[optional]</val>
      <val>[optional]</val>
      <val>[optional]</val>
      ...
    </eco_day_time>

    <eco_weekday>                                                  // Wochentage
      <val>[optional]</val>
      <val>[optional]</val>
      <val>[optional]</val>
      ...
    </eco_weekday>
  </appointment>
</xml>


// RESPONSE for GET
<xml>
  <state>OK</state>

  <vehicles>

    <vehicle>
      <date>....</date>                          // Tag, an dem das Fahrzeug verfügbar ist. Wenn nur ein Tag im Request definiert, dann wird dieser auch nur hier in der Antwort zurückgeliefert
      <start_time>....</start_time>              // Uhrzeit, ab wann das Fahrzeug zur Verfügung steht
      <time_units>....</time_units>              // Anzahl Zeiteinheiten, die ab der Startzeit verfügbar sind
      <vh_id>....</vh_id>                        // (Interne) ID des Fahrzeugs
      <vh_sid>....</vh_sid>                      // Fahrzeugnummer (für Kunden nicht zwingend sichtbar)
      <daytime_raw>....</daytime_raw>            // Tageszeit der Verfügbarkeit ("0" = 1. definierte Tageszeit für den Kunden, "1" = 2. Tageszeit, "2" = 3. Tageszeit,....)
      <daytime>....</daytime>                    // Tageszeit der Verfügbarkeit (Text z.B. "Vormittag", "Nachmittag", "Abend")
      <daytime_interval>....</daytime_interval>  // Tageszeit der Verfügbarkeit (Zeitintervall, z.B. "07:00 - 12:00", "12:00 - 16:00", "16:00 - 21:00")
      <service>....</service>                    // Service = ("1" => "LI" = Lieferung, "2" => "MO" = Montage,....)
    </vehicle>
    
    <vehicle>                                    // Weiteres Fahrzeug
      ....
    </vehicle>

  </vehicles>
</xml>
*/
?>

