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

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

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

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

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

function getPrice_MC($zipcode1, $zipcode2, $cs_invmode = -1, $fuel_markup, $vht_id, $jb_ordertime, $hq_id) {
  global $db;

  if (strlen($zipcode1) == 5 && strlen($zipcode2) == 5 && is_numeric($zipcode1) && is_numeric($zipcode2)):
    if ($cs_invmode > -1):
      $cs_id = $cs_invmode * -1;
    else:
      $cs_id = 0;
    endif;
    // $cs_id decides about invmode
    // if 0, then default invmode from hq_id is taken
    // for Berlin, $cs_id directly takes invmode in negative form (in order to distinguish from ordinary cs_id, that always are postive)
    // Grundpreis
    // Servicetype-Name (Fahrrad etc.)
    $srvt_name = $db->getOne(
      "SELECT mt_value FROM metatype WHERE mt_sort = '$vht_id' AND mt_type = 'vehicletype'");
    list ($grundpreis, $fd, $fpm, $customer_specific) =
      saveServiceCosts("Grundpreis", $srvt_name, $hq_id, $cs_id, 0 /* $jb_id */, 0, $jb_ordertime, 0 /* count */, 1 /* $costsplit_count */, 1 /* $getPriceOnly */, false /* $jb_cash */, "0" /* $csc_id_payer */, 0 /* $jb_storno */, false /* zipcode1 */, false /* zipcode2 */, false, $fuel_markup, $vht_id);
    //$fullPrice += $fp * ((100-$fd)/100);
    //$discount_sign = ($fd > 0 || $customer_specific || $discount_sign == "*" ? "*" : "");
    // PLZ-Preis
    list ($plzpreis, $fd, $fpm, $customer_specific) =
      saveServiceCosts($zipcode1, $zipcode2, $hq_id, $cs_id, 0 /* $jb_id */, 0, $jb_ordertime, 0 /* count */, 1 /* $costsplit_count */, 1 /* $getPriceOnly */, false /* $jb_cash */, "0" /* $csc_id_payer */, 0 /* $jb_storno */, false /* zipcode1 */, false /* zipcode2 */, true, $fuel_markup, $vht_id);
    //$fullPrice += $fp * ((100-$fd)/100);
    //$discount_sign = ($fd > 0 || $customer_specific || $discount_sign == "*" ? "*" : "");
  else:
    $zipcode1 = "";
    $zipcode2 = "";
    $grundpreis = 0;
    $plzpreis = 0;
  endif;
  
  return array($grundpreis, $plzpreis);
}


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

priceRequestLogFile($currentTime);
priceRequestLogFile($priceReq);


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

getLanguage(__FILE__);
getCurrentScript(__FILE__);

$err = array();
$priceResponse = "";
$xmlPrice = "";


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

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

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


// *** Convert result array to usable parameters ***
// Authentication data
$csEid          = convertSpecial($priceArray["xml"]["costs"]["auth"]["customer"]);
$csId           = getFieldValueFromId("customer","cs_eid",$csEid,"cs_id");
$usrAccount     = convertSpecial($priceArray["xml"]["costs"]["auth"]["account"]);
$usrPassword    = convertSpecial($priceArray["xml"]["costs"]["auth"]["password"]);
$sessionId      = convertSpecial($priceArray["xml"]["costs"]["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($priceArray["xml"]["costs"]["auth"]["group_no"]);
$csGroupName    = convertSpecial($priceArray["xml"]["costs"]["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($priceArray["xml"]["costs"]["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 costs data
   $operation       = convertSpecial($priceArray["xml"]["costs"]["operation"]);
   $serviceFunction = convertSpecial($priceArray["xml"]["costs"]["service_function"]);
   $debugOn         = convertSpecial($priceArray["xml"]["costs"]["debug_on"]);
   $vhtId           = convertSpecial($priceArray["xml"]["costs"]["vehicle_type_id"]);
   $zipcodeFrom     = convertSpecial($priceArray["xml"]["costs"]["zipcode_from"]);
   $zipcodeTo       = convertSpecial($priceArray["xml"]["costs"]["zipcode_to"]);
   $day             = convertSpecial($priceArray["xml"]["costs"]["day"]);
   $month           = convertSpecial($priceArray["xml"]["costs"]["month"]);
   $year            = convertSpecial($priceArray["xml"]["costs"]["year"]);
   $priceMode       = convertSpecial($priceArray["xml"]["costs"]["price_mode"]);


   $debugOut .= "operation: " . $operation . "<br>\n";
   $debugOut .= "serviceFunction: " . $serviceFunction . "<br>\n";
   $debugOut .= "vhtId: " . $vhtId . "<br>\n";
   $debugOut .= "zipcodeFrom: " . $zipcodeFrom . "<br>\n";
   $debugOut .= "zipcodeTo: " . $zipcodeTo . "<br>\n";
   $debugOut .= "day: " . $day . "<br>\n";
   $debugOut .= "month: " . $month . "<br>\n";
   $debugOut .= "year: " . $year . "<br>\n";
   $debugOut .= "priceMode: " . $priceMode . "<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

   // Check <day>, <month> and <year> here
   // ...
   $cDateTime = $currentTimestamp;

   $retVal = 0;
   $retVal_1 = 0;
   $retVal_2 = 0;
   if ($serviceFunction == "") : $serviceFunction = "default"; endif;
   $zipcodeFrom = pad($zipcodeFrom, 5);
   $zipcodeTo = pad($zipcodeTo, 5);
   if ($priceMode == "") : $priceMode = "1"; endif;

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

   if ($operation == "SET") :

      // TO BE DONE!

   else :

      if ($serviceFunction == "default" || $serviceFunction == "zipcode") :

         // Get IDs from zipcodes
         // $srvpIdFrom = getFieldValueFromId("phoenix.serviceplz", "srvp_plz", $zipcodeFrom, "srvp_id");
         // $srvpIdTo   = getFieldValueFromId("phoenix.serviceplz", "srvp_plz", $zipcodeTo, "srvp_id");
         // $retVal_1 = getZipcodeServiceValues($srvpIdFrom, $srvpIdTo, $csId, $hqId, $cDateTime, $priceMode, $vhtId);
         $csInvMode = getFieldValueFromId("phoenix.customer", "cs_id", $csId, "cs_invmode");
         $fuelMarkup = 0;

         // if ($srvpIdFrom != "" && $srvpIdTo != "") :
         if ($zipcodeFrom != "" && $zipcodeTo != "") :
            $mode = "1";
            $retArr = getPrice_MC($zipcodeFrom, $zipcodeTo, $csInvMode, $fuelMarkup, $vhtId, $cDateTime, $hqId);
            $retVal_1 = $retArr[0];
            $retVal_2 = $retArr[1];
            if (is_numeric($retVal_1) && is_numeric($retVal_2)):
               $retVal = $retVal_1 + $retVal_2;
            endif;
            /*
            $retVal = getZipCodeServiceValuesWrapper($srvpIdFrom, $srvpIdTo, $csId, $hqId, $cDateTime, $mode, $vhtId);
            if ($retVal == "0") :
               $retVal = getZipCodeServiceValuesWrapper($srvpIdFrom, $srvpIdTo, $csId, $hqId, $cDateTime, $mode);
               if ($retVal == "0") :
                  $retVal = getZipCodeServiceValuesWrapper($srvpIdFrom, $srvpIdTo, "0", $hqId, $cDateTime, $mode, $vhtId);
                  if ($retVal == "0") :
                     $retVal = getZipCodeServiceValuesWrapper($srvpIdFrom, $srvpIdTo, "0", $hqId, $cDateTime, $mode);
                  endif;
               endif;
            endif;
            */
         endif;
      endif;

      // Check for ERRORS
      if ($retVal != "") :
         $xmlPrice .= "<costs>";
             $xmlPrice .= "<date>" .             substr($cDateTime, 0, 10) . "</date>";
             $xmlPrice .= "<vehicle_type_id>" .  $vhtId                    . "</vehicle_type_id>";
             $xmlPrice .= "<zipcode_from>" .     $zipcodeFrom              . "</zipcode_from>";
             $xmlPrice .= "<zipcode_to>" .       $zipcodeTo                . "</zipcode_to>";
             $xmlPrice .= "<price_mode>" .       $priceMode                . "</price_mode>";
             $xmlPrice .= "<price_value_1>" .    $retVal_1                 . "</price_value_1>";
             $xmlPrice .= "<price_value_2>" .    $retVal_2                 . "</price_value_2>";
             $xmlPrice .= "<price_value_sum>" .  $retVal                   . "</price_value_sum>";
         $xmlPrice .= "</costs>";
      else :
         $err[] = array("103", getLngt("Kein Preis!"));
      endif;
      $debugOut .= "<br><br>xmlPrice: " . $xmlPrice . "<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
$priceResponse .= "<xml>";   
if ($errLen > 0) :
   priceRequestLogFile("ERRORS", 1);
   $priceResponse .= "<state>NOT OK</state>";
   $priceResponse .= "<errors>";
   for ($i = 0; $i < $errLen; $i++) :
       $priceResponse .= "<error>";
       $priceResponse .= "<err_no>" . $err[$i][0] . "</err_no>";
       $priceResponse .= "<err_desc><![CDATA[" . mcEncode($err[$i][1]) . "]]></err_desc>";
       $priceResponse .= "</error>";
       if ($debug) :
          $priceResponse .= "<debug>" . $debugOut . "</debug>";
       endif;
       priceRequestLogFile($err[$i][0] . " : " . mcEncode($err[$i][1]), 1);
   endfor;
   $priceResponse .= "</errors>";
else :
   $priceResponse .= "<state>OK</state>" . $xmlPrice;
   if ($debug) :
      $priceResponse .= "<debug>" . $debugOut . "</debug>";
   endif;
endif;
$priceResponse .= "</xml>";

// Log entries
priceRequestLogFile($priceResponse);    // Write response into log
priceRequestLogFile("___________________________________________________________________________________");

// Return output
echo $priceResponse;



/*
// REQUEST
<xml>
  <costs>                                      // Preisanfrage
    <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 costs(s), default is "GET" if emty tag)
    <service_function>...</service_function>   // Leer <=> Preisermittlung nach Kundeneinstellungen | "zipcode" <=> PLZ-Preis | ....
    <vehicle_type_id>...</vehicle_type_id>     // ID des Fahrzeugtyps
    <zipcode_from>...</zipcode_from>           // Start-PLZ
    <zipcode_to>...</zipcode_to>               // Ziel-PLZ
    <day>...</day>                             // Tag
    <month>...</month>                         // Monat
    <year>...</year>                           // Jahr
    <price_mode>...</price_mode>               // Preismodus (Leer oder "1" = Preis | "0" = Rabatt)
  </costs>
</xml>


// RESPONSE for GET
<xml>
  <state>OK</state>
  <costs>
    <date>....</date>                          // Angefordeter Tag
    <vehicle_type_id>....</vehicle_type_id>    // ID des Fahrzeugtyps
    <zipcode_from>....</zipcode_from>          // Start-PLZ
    <zipcode_to>....</zipcode_to>              // Ziel-PLZ
    <price_mode>....</price_mode>              // Preismodus (Leer oder "1" = Preis | "0" = Rabatt)
    <price_value>....</price_value>            // Preis
  </costs>
</xml>
*/
?>

