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

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

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

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

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


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

orderDataRequestLogFile($currentTime);
orderDataRequestLogFile($orderDataReq);


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

getLanguage(__FILE__);
getCurrentScript(__FILE__);

$err = array();
$orderDataResponse = "";
$xmlorderData = "";


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

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

// *** Parse request ***
$orderDataArray = xml2array($orderDataReq);
if ($debug) :
   echo "Order data:<br><br>\n\n";
   print_r($orderDataArray); echo "<br><br><br>";
endif;


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

   if (!$debug && $debugOn == "ON" || $debugOn == "YES") :
      $debug = true;
      
      echo "csId: " . $csId . "<br>";
      echo "csEid: " . $csEid . "<br>";
   endif;


   if ($operation == "SET") :

      // TO BE DONE!


   else :

      $orderNumbers = convertSpecial($orderDataArray["xml"]["order_data"]["order_numbers"]);
      $orderNumberArray = explode("|", $orderNumbers);
      $orderNumberArrayLen = count($orderNumberArray);
      
      $dataFields = convertSpecial($orderDataArray["xml"]["order_data"]["data_fields"]);
      $dataFieldArray = explode("|", $dataFields);
      $dataFieldArrayLen = count($dataFieldArray);

      if ($debug) :
         print_r($orderNumberArray); echo "\n\n<br><br>";
         echo $orderNumberArrayLen . "<br><br>";
         print_r($dataFieldArray); echo "\n\n<br><br>";
         echo $dataFieldArrayLen . "<br><br>";
      endif;

      // Iterate array
      $xmlorderData .= "<order_data>";
      for ($i = 0; $i < $orderNumberArrayLen; $i++) :

          $xmlorderData .= "<order>";

          $jbIdOrg = $orderNumberArray[$i];
          $xmlorderData .= "<order_no>" . $jbIdOrg . "</order_no>";

          // First check valid association between authenticated customer and requested job(s) !!!!
          // $cscIdPayer = $jobData["job"]["csc_id_payer"];
          $cscIdPayer = getFieldValueFromId("job","jb_id",$jbIdOrg,"csc_id_payer");
          $csIdPayer = getFieldValueFromId("costcenter","csc_id",$cscIdPayer,"cs_id");

          // Get operational job of requested job (!!!!)
          $tmpValue = getFieldValueFromClause("phoenix.genericdatacontainer","gdc_content","gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'is_operative' AND gdc_obj_id = '" . $jbIdOrg . "'");
          $tmpArray = explode("|", $tmpValue);
          $jbId = $tmpArray[0];
          $xmlorderData .= "<order_op_no>" . $jbId . "</order_op_no>";

          if ($jbId != "" && is_numeric($jbId)) :

             getDBData("job", $jbId);

             if ($debug) :
                print_r($jobData); echo "\n\n<br><br>";
             endif;          

             $xmlorderData .= "<fields>";
             if ($csIdPayer == $csId) :

                // getDBData("tour", $jbId);

                for ($j = 0; $j < $dataFieldArrayLen; $j++) :

                    $fieldName = $dataFieldArray[$j];
                    $fieldVal = $jobData["job"][$dataFieldArray[$j]];
                    if ($fieldName == "vht_id" || $fieldName == "vht_id_real") :
                       $fieldVal = getFieldValueFromClause("phoenix.metatype","mt_value","mt_type = 'vehicletype' AND mt_sort = '" . $fieldVal . "'");
                    endif;

                    $xmlorderData .= "<field>";
                    $xmlorderData .= "<field_name><![CDATA[" . $fieldName . "]]></field_name>";
                    $xmlorderData .= "<field_value><![CDATA[" . $fieldVal . "]]></field_value>";
                    $xmlorderData .= "</field>";
                endfor;
             else :

                $xmlorderData .= "<field>";
                $xmlorderData .= "<field_name><![CDATA[" . "ERR" . "]]></field_name>";
                $xmlorderData .= "<field_value><![CDATA[" . "NOT_AUTHENTICATED" . "]]></field_value>";
                $xmlorderData .= "</field>";
             endif;
             $xmlorderData .= "</fields>";
          else :

             $xmlorderData .= "<fields>";
             $xmlorderData .= "<field>";
             $xmlorderData .= "<field_name><![CDATA[" . "ERR" . "]]></field_name>";
             $xmlorderData .= "<field_value><![CDATA[" . "NO_OPERATIVE_TOUR_FOUND" . "]]></field_value>";
             $xmlorderData .= "</field>";             
             $xmlorderData .= "</fields>";
          endif;

          $xmlorderData .= "</order>";
      endfor;
      $xmlorderData .= "</order_data>";

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

// Log entries
orderDataRequestLogFile($orderDataResponse);    // Write response into log
orderDataRequestLogFile("___________________________________________________________________________________");

// Return output
echo $orderDataResponse;



/*
// REQUEST
<xml>
  <order_data>                                         // Request for all orderData 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)

    <order_numbers><![CDATA[....]]></order_numbers>    // List of votian order numbers "17310234|17310296|17310242|...."
    <data_fields><![CDATA[....]]></data_fields>        // List of data field like "vh_id_real|jb_finishtime|...."

  </order_data>
</xml>


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

  <order_data>

    <order>                                   // Single order
      <order_no>....</order_no>               // votian (requested) order number
      <order_op_no>....</order_op_no>         // votian operational order number with real vehicle id
      <fields>
        <field>
          <field_name>....</field_name>       // (Requested) field name
          <field_value>....</field_value>     // Field value
        </field>
        
        <field>
          ....
        </field>
      </fields>
    </order>
    
    <order>                                   // Next single order
      ....
    </order>

  </order_data>
</xml>
*/
?>

