<?php 
/*=======================================================================
 *
 * costcenter_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 = "";

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

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

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

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


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

costcenterRequestLogFile($currentTime);
costcenterRequestLogFile($costcenterReq);


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

getLanguage(__FILE__);
getCurrentScript(__FILE__);

$err = array();
$costcenterResponse = "";
$xmlCostcenters = "";


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

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

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


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

   $debugOut .= "operation: " . $operation . "<br>\n";
   $debugOut .= "address_type: " . $address_type . "<br>\n";
   

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

   if ($adType == "") : $adType = "4"; endif;  // Pick-up/Delivery address



   if ($operation == "SET") :

      // TO BE DONE!


   else :

      $whereClause = "";
      if ($cscName != "" && $cscId != "") :
         $whereClause = "AND csc.csc_id = '" . $cscId . "'";
      endif;

      $sqlquery = "SELECT ad.ad_id, ad.ad_street, ad.ad_zipcode, ad.ad_city, ad.ad_country, csc.csc_id, csc.csc_name, csc.csc_pre_id, "
                . "       cscad.cscad_comp AS comp, cscad.cscad_comp2 AS comp2, cscad.cscad_comp3 AS comp3, cscad.cscad_comp4 AS comp4,"
                . "       cscad.cscad_hsno AS hsno, cscad.cscad_floor AS floor, cscad.cscad_remark AS remark, cscad.cscad_person AS person, cscad.cscad_phone AS phone, cscad.cscad_email AS email"
                . " FROM address AS ad, costcenteraddress AS cscad, costcenter AS csc, customer AS cs"
                . " WHERE cs.cs_id = '" . $csId . "' AND cs.cs_id = csc.cs_id AND " . $whereClause . " csc.csc_id = cscad.csc_id AND adt_id = '" . $adType . "' AND cscad.ad_id = ad.ad_id";
      
      $result = $db->query($sqlquery);
      if (DB::isError($result)) die ("$PHP_SELF: '$sqlquery'" . $result->getMessage());    
      
      $xmlCostcenters .= "<costcenters>";      
      while ($row = $result->fetch_assoc()):

        $xmlCostcenters .= "<costcenter>";

        $xmlCostcenters .= "<costcenter_name><![CDATA[" .   $row["csc_name"]   . "]]></costcenter_name>";
        $xmlCostcenters .= "<costcenter_pre_no><![CDATA[" . $row["csc_pre_id"] . "]]></costcenter_pre_no>";
        $xmlCostcenters .= "<street><![CDATA[" .            $row["ad_street"]  . "]]></street>";
        $xmlCostcenters .= "<zipcode><![CDATA[" .           $row["ad_zipcode"] . "]]></zipcode>";
        $xmlCostcenters .= "<city><![CDATA[" .              $row["ad_city"]    . "]]></city>";
        $xmlCostcenters .= "<country><![CDATA[" .           $row["ad_country"] . "]]></country>";
        $xmlCostcenters .= "<hsno><![CDATA[" .              $row["hsno"]       . "]]></hsno>";
        $xmlCostcenters .= "<floor><![CDATA[" .             $row["floor"]      . "]]></floor>";
        $xmlCostcenters .= "<person><![CDATA[" .            $row["person"]     . "]]></person>";
        $xmlCostcenters .= "<phone><![CDATA[" .             $row["phone"]      . "]]></phone>";
        $xmlCostcenters .= "<email><![CDATA[" .             $row["email"]      . "]]></email>";
        $xmlCostcenters .= "<remark><![CDATA[" .            $row["remark"]     . "]]></remark>";
        $xmlCostcenters .= "<comp><![CDATA[" .              $row["comp"]       . "]]></comp>";
        $xmlCostcenters .= "<comp2><![CDATA[" .             $row["comp2"]      . "]]></comp2>";
        $xmlCostcenters .= "<comp3><![CDATA[" .             $row["comp3"]      . "]]></comp3>";
        $xmlCostcenters .= "<comp4><![CDATA[" .             $row["comp4"]      . "]]></comp4>";

        $xmlCostcenters .= "</costcenter>";
      endwhile;
      $result->free();  
      $xmlCostcenters .= "</costcenters>";

   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
$costcenterResponse .= "<xml>";   
if ($errLen > 0) :
   costcenterRequestLogFile("ERRORS", 1);
   $costcenterResponse .= "<state>NOT OK</state>";
   $costcenterResponse .= "<errors>";
   for ($i = 0; $i < $errLen; $i++) :
       $costcenterResponse .= "<error>";
       $costcenterResponse .= "<err_no>" . $err[$i][0] . "</err_no>";
       $costcenterResponse .= "<err_desc><![CDATA[" . mcEncode($err[$i][1]) . "]]></err_desc>";
       $costcenterResponse .= "</error>";
       if ($debug) :
          $costcenterResponse .= "<debug>" . $debugOut . "</debug>";
       endif;
       costcenterRequestLogFile($err[$i][0] . " : " . mcEncode($err[$i][1]), 1);
   endfor;
   $costcenterResponse .= "</errors>";
else :
   $costcenterResponse .= "<state>OK</state>" . $xmlCostcenters;
   if ($debug) :
      $costcenterResponse .= "<debug>" . $debugOut . "</debug>";
   endif;
endif;
$costcenterResponse .= "</xml>";

// Log entries
costcenterRequestLogFile($costcenterResponse);    // Write response into log
costcenterRequestLogFile("___________________________________________________________________________________");

// Return output
echo $costcenterResponse;



/*
// REQUEST
<xml>
  <costcenter>                                   // Request for all costcenters of the customer
    <auth>                                       // Customer to be authenticated
      <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 costcenter(s), default is "GET" if emty tag)
                                                 
    <address_type>...</address_type>             // Address type (empty tag = "4" = pickup)

  </costcenter>
</xml>


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

  <costcenters>

    <costcenter>                                 // Kostenstelle
      <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,....)
    </costcenter>
    
    <costcenter>                                 // Weitere Kostenstelle
      ....
    </costcenter>

  </costcenters>
</xml>
*/
?>

