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


include_once ("../include/mcglobal.inc.php");
include_once ("../include/inc_parseXML.inc.php");
include_once ("../include/inc_customer.inc.php");
include_once ("../include/inc_disposition.inc.php");


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

$debug = false;
$debugOut = "";

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

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

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

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


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

zoneRequestLogFile($currentTime);
zoneRequestLogFile($zoneReq);


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

getLanguage(__FILE__);
getCurrentScript(__FILE__);

$err = array();
$zoneResponse = "";
$xmlZone = "";


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

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

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


// *** Convert result array to usable parameters ***
// Authentication data
$csEid          = convertSpecial($zoneArray["xml"]["zone"]["auth"]["customer"]);
$csId           = getFieldValueFromId("customer","cs_eid",$csEid,"cs_id");
$usrAccount     = convertSpecial($zoneArray["xml"]["zone"]["auth"]["account"]);
$usrPassword    = convertSpecial($zoneArray["xml"]["zone"]["auth"]["password"]);
$sessionId      = convertSpecial($zoneArray["xml"]["zone"]["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($zoneArray["xml"]["zone"]["auth"]["group_no"]);
$csGroupName    = convertSpecial($zoneArray["xml"]["zone"]["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($zoneArray["xml"]["zone"]["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 zone data
   $operation  = convertSpecial($zoneArray["xml"]["zone"]["operation"]);
   $debugOn    = convertSpecial($zoneArray["xml"]["zone"]["debug_on"]);
   $ecoZipcode = convertSpecial($zoneArray["xml"]["zone"]["eco_zipcode"]);

   $debugOut .= "operation: " . $operation . "<br>\n";
   $debugOut .= "ecoZipcode: " . $ecoZipcode . "<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

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

   if ($operation == "SET") :

      // TO BE DONE!


   else :

      $zone_no = "";
      $zone_name = "";
      $sqlquery = "SELECT srvz.srvz_no, srvz.srvz_name FROM servicezone AS srvz, serviceplz AS srvp, servicezonemapping AS srvzm "
                . "  WHERE srvp.srvp_plz = '" . $ecoZipcode . "' AND srvp.srvp_id = srvzm.srvp_id AND srvzm.srvz_id = srvz.srvz_id AND srvz.cs_id = '" . $csId . "'";
      $result = $db->query($sqlquery);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
      while ($row = $result->fetch_assoc()):
            $zone_no = $row["srvz_no"];
            $zone_name = $row["srvz_name"];
      endwhile;
      $result->free();


      // Check for ERRORS
      if ($zone_no != "" && $zone_name != "") :
         // Vehicles found => Generate output
         $retArrayLen = count($retArray);
         $xmlZone .= "<zone>";
         $xmlZone .= "<zone_no>"   . $zone_no   . "</zone_no>";          // zone no
         $xmlZone .= "<zone_name>" . $zone_name . "</zone_name>";        // zone name
         $xmlZone .= "</zone>";
      else :

         if (!(strpos($retArray, "ERR:ZIPCODE_NOT_IN_ANY_CUSTOMER_ZONE") === FALSE)) :
            $err[] = array("102", getLngt("Die PLZ ist keiner Zone zugeordnet!") . " [" . $ecoZipcode . "]");
         else :
            $err[] = array("103", getLngt("Bereichsfehler!"));
         endif;
      endif;
      $debugOut .= "<br><br>xmlZone: " . $xmlZone . "<br>\n";
   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
$zoneResponse .= "<xml>";   
if ($errLen > 0) :
   zoneRequestLogFile("ERRORS", 1);
   $zoneResponse .= "<state>NOT OK</state>";
   $zoneResponse .= "<errors>";
   for ($i = 0; $i < $errLen; $i++) :
       $zoneResponse .= "<error>";
       $zoneResponse .= "<err_no>" . $err[$i][0] . "</err_no>";
       $zoneResponse .= "<err_desc><![CDATA[" . mcEncode($err[$i][1]) . "]]></err_desc>";
       $zoneResponse .= "</error>";
       if ($debug) :
          $zoneResponse .= "<debug>" . $debugOut . "</debug>";
       endif;
       zoneRequestLogFile($err[$i][0] . " : " . mcEncode($err[$i][1]), 1);
   endfor;
   $zoneResponse .= "</errors>";
else :
   $zoneResponse .= "<state>OK</state>" . $xmlZone;
   if ($debug) :
      $zoneResponse .= "<debug>" . $debugOut . "</debug>";
   endif;
endif;
$zoneResponse .= "</xml>";

// Log entries
zoneRequestLogFile($zoneResponse);    // Write response into log
zoneRequestLogFile("___________________________________________________________________________________");

// Return output
echo $zoneResponse;



/*
// REQUEST
<xml>
  <zone>                                                   // 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 zone(s), default is "GET" if emty tag)
    <eco_zipcode>...</eco_zipcode>                                // Zipcode to get the zone for

  </zone>
</xml>


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

  <zone>
  
  </zone>
</xml>
*/
?>

