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


include_once ("../include/mcglobal.inc.php");
// include_once ('../include/email/htmlMimeMail.php');
include_once ("../include/inc_parseXML.inc.php");
// include_once ("../geo/geocode.inc.php");


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

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

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


$maxLogLevel = "2";

function orderRequestLogFile ($msg, $logLevel = 0) {
	global $logLevel;
	$msg = trim($msg);
	if ($logLevel <= $maxLogLevel && $msg != "") :
     writeToFile("../log/orderReq_X.log", $msg);
  endif;
}


$orderReq = urldecode($orderReq);
$orderReq = mcEncode($orderReq);
// echo $orderReq . "<br><br>";

orderRequestLogFile($currentTime);
orderRequestLogFile($orderReq);



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

getLanguage(__FILE__);
getCurrentScript(__FILE__);

$err = array();
$outResponse = "";
$acceptOrder = true;


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

function checkRequestAuthenticationData ($usrAccount, $usrPassword, $sessionId, $csId) {
	global $db, $PHP_SELF;
	global $dbname, $dblogin, $dbpassword, $usr_id;

  $retBool = false;
  if ($usrAccount != "" && $usrPassword != "") :

     // Check for existing user (customer account) with usr_type = '2' !!!
     $sqlquery = "SELECT usr_id, hq_id FROM user WHERE usr_account = '$usrAccount' AND usr_password = PASSWORD('$usrPassword') AND usr_type = '2'";
     $result = $db->query($sqlquery);

     $usr_id = "";
     $hq_id = "";
     if (!(DB::isError($result))):  

       while ($row = $result->fetch_assoc()):
          $usr_id = $row["usr_id"];
          $hq_id = $row["hq_id"];
       endwhile;
       $result->free();
     
       // Get the IP of the current client calling the page
       $currentClientIP = trim($_SERVER['REMOTE_ADDR']);  

       if ($usr_id != "") :
          // Check for correct association to customer
          $tmpEmpId = getFieldValueFromId("employee", "usr_id", $usr_id, "emp_id");
          $tmpCscId = getFieldValueFromId("employee", "emp_id", $tmpEmpId, "csc_id");
          $tmpCsId = getFieldValueFromId("costcenter", "csc_id", $tmpCscId, "cs_id");

          if ($tmpCsId != "" && $tmpCsId == $csId) :
             // Check for "session hash" in remote instance metaobjects
             $sessionHash = "";
             // Get current global number of THIS database instance
             $constGlobalDbInstNo = getParameterValue("0", "GLOBAL_UNIQUE_DB_INSTANCE_NO", "0");
             if ($constGlobalDbInstNo != "" && is_numeric($constGlobalDbInstNo)) :

                // Get database instance connection data of metaobject
                $constExtDbInst = getParameterValue("0", "EXTERNAL_DB_METAOBJECT", "0");
                if ($constExtDbInst == "") : $constExtDbInst = "172.16.0.111:3711"; endif;
                $db_conn = getDbConnectionSpecial($constExtDbInst, $dbname, $dblogin, $dbpassword);
                $tmpSqlQuery = "SELECT mo_hash FROM meta_object.metaobject WHERE mo_obj_type = 'usr' AND mo_id_ref_db = '" . $constGlobalDbInstNo . "' AND mo_obj_id = '" . $usr_id . "'";
                $result = $db_conn->query($tmpSqlQuery);
                while ($row = $result->fetch_assoc()):
                   $sessionHash = $row["mo_hash"];
                endwhile;
                $result->free();
             endif;

             $usrRealName = getFieldValueFromId("user", "usr_id", $usr_id, "usr_name");
             $usrRealFirstname = getFieldValueFromId("user", "usr_id", $usr_id, "usr_firstname");
             $hqName = "";
             $hqMnemonic = "";
             if ($hq_id > "0") :
                $hqName = getFieldValueFromId("headquarters", "hq_id", $hq_id, "hq_name");
                $hqMnemonic = getFieldValueFromId("headquarters", "hq_id", $hq_id, "hq_mnemonic");
             endif;

             if ($sessionHash != "" && $sessionHash == $sessionId) :
                $retBool = true;  // Authenticatin OK !!!
             endif;
          endif;
       endif;    
     endif;
  endif;

  if ($retBool) :
     writeToLogDB("52",$hq_id,"",$usr_id,"","","","ACCOUNT=" . $usrAccount . "|MESS=Login ok|IP=" . $currentClientIP);
  else :
     writeToLogDB("52",$hq_id,"",$usr_id,"","","","ACCOUNT=" . $usrAccount . "|MESS=Login NOT ok|IP=" . $currentClientIP);
  endif;

  return $retBool;
}

function xml2array($contents, $get_attributes = 1, $priority = 'tag') {
	$retArray = array();

  if (function_exists('xml_parser_create')) :
     $contents = trim($contents);
     if ($contents != "") :
        $parser = xml_parser_create('UTF-8');   // ISO-8859-1
        xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($parser, $contents, $xml_values);
        xml_parser_free($parser);

        $xml_array = array ();
        $parents = array ();
        $opened_tags = array ();
        $arr = array ();
        $current = & $xml_array;
        $repeated_tag_index = array ();
        foreach ($xml_values as $data)
        {
            unset ($attributes, $value);
            extract($data);
            $result = array ();
            $attributes_data = array ();
            if (isset ($value))
            {
                if ($priority == 'tag')
                    $result = $value;
                else
                    $result['value'] = $value;
            }
            if (isset ($attributes) and $get_attributes)
            {
                foreach ($attributes as $attr => $val)
                {
                    if ($priority == 'tag')
                        $attributes_data[$attr] = $val;
                    else
                        $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
                }
            }
            if ($type == "open")
            {
                $parent[$level -1] = & $current;
                if (!is_array($current) or (!in_array($tag, array_keys($current))))
                {
                    $current[$tag] = $result;
                    if ($attributes_data)
                        $current[$tag . '_attr'] = $attributes_data;
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    $current = & $current[$tag];
                }
                else
                {
                    if (isset ($current[$tag][0]))
                    {
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                        $repeated_tag_index[$tag . '_' . $level]++;
                    }
                    else
                    {
                        $current[$tag] = array (
                            $current[$tag],
                            $result
                        );
                        $repeated_tag_index[$tag . '_' . $level] = 2;
                        if (isset ($current[$tag . '_attr']))
                        {
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                            unset ($current[$tag . '_attr']);
                        }
                    }
                    $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
                    $current = & $current[$tag][$last_item_index];
                }
            }
            elseif ($type == "complete")
            {
                if (!isset ($current[$tag]))
                {
                    $current[$tag] = $result;
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    if ($priority == 'tag' and $attributes_data)
                        $current[$tag . '_attr'] = $attributes_data;
                }
                else
                {
                    if (isset ($current[$tag][0]) and is_array($current[$tag]))
                    {
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                        if ($priority == 'tag' and $get_attributes and $attributes_data)
                        {
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                        }
                        $repeated_tag_index[$tag . '_' . $level]++;
                    }
                    else
                    {
                        $current[$tag] = array (
                            $current[$tag],
                            $result
                        );
                        $repeated_tag_index[$tag . '_' . $level] = 1;
                        if ($priority == 'tag' and $get_attributes)
                        {
                            if (isset ($current[$tag . '_attr']))
                            {
                                $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                                unset ($current[$tag . '_attr']);
                            }
                            if ($attributes_data)
                            {
                                $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                            }
                        }
                        $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
                    }
                }
            }
            elseif ($type == 'close')
            {
                $current = & $parent[$level -1];
            }
        }
        $retArray = $xml_array;
     endif;
  endif;
  return $retArray;
}

function convertSpecial ($str, $conversionType = "") {
	if (is_array($str) && count($str) == 0) : 
	   $str = "";
	endif;
	$str = trim($str);
	$str = mcDecode($str);
	if ($str != "" && $conversionType == "intval") :
	   $str = intval($str);
	endif;
	return $str;
}

function checkDateTimeFormat($dateTimeToBeChecked, $dateTimeFormat = "Y-m-d H:i:s") {
	// Check compability of format
  if ($dateTimeToBeChecked != "" && $dateTimeFormat != "") :
     $xDate = date_create($dateTimeToBeChecked);
     $dateTimeToBeChecked = "";  // Init
     if ($xDate) :
        $dateTimeToBeChecked = $xDate->format('Y-m-d H:i:s');
     endif;
  else :
     $dateTimeToBeChecked = "";  // Init
  endif;
  // Check special date ranges for
  if ($dateTimeToBeChecked != "") :
     // 
  endif;
  return $dateTimeToBeChecked;
}


// *** Init ***
$maxNumOfOrdersPerDay = 200;
$maxNumOfRunningOrders = 1000;
$hqId = "";
$usr_id = "";
$jbStatus = "9";
$jbType = "";
$jbTourname = "";
$fixprice = 0;
$cmpPostage = 0;
$csInvmode = "";
$txValue = getFieldValueFromId("tax","tx_id","4","tx_value");
$txSign = getFieldValueFromId("tax","tx_id","4","tx_sign");


// *** Parse request ***
$orderArray = xml2array($orderReq);
// print_r($orderArray); echo "<br><br><br>";

// *** Convert result array to usable parameters ***
// Authentication data
$csEid          = convertSpecial($orderArray["xml"]["order"]["auth"]["customer"]);
$csId           = getFieldValueFromId("customer","cs_eid",$csEid,"cs_id");
$usrAccount     = convertSpecial($orderArray["xml"]["order"]["auth"]["account"]);
$usrPassword    = convertSpecial($orderArray["xml"]["order"]["auth"]["password"]);
$sessionId      = convertSpecial($orderArray["xml"]["order"]["auth"]["session_id"]);

if (checkRequestAuthenticationData($usrAccount, $usrPassword, $sessionId, $csId)) :
// echo "Authentication okay! <br><br>";
   // Data
   $hqId           = getFieldValueFromId("customer","cs_id",$csId,"hq_id");
   $cscName        = convertSpecial($orderArray["xml"]["order"]["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;
   $trCommissionNo = convertSpecial($orderArray["xml"]["order"]["no"]);
   $hqMnemonic     = convertSpecial($orderArray["xml"]["order"]["hq"]);
   $hqId_XML       = getFieldValueFromId("headquarters","hq_mnemonic",$hqMnemonic,"hq_id");
   $vhtId          = convertSpecial($orderArray["xml"]["order"]["vehicle"]["type_no"]);
   $vhtType        = convertSpecial($orderArray["xml"]["order"]["vehicle"]["type_name"]);
   if ($vhtId != "" && is_numeric($vhtId)) :
      $vhtType = getFieldValueFromClause("metatype","mt_value","mt_type = 'vehicletype' AND mt_sort = '" . $vhtId . "'");
   elseif ($vhtType != "") :
      $vhtId = getFieldValueFromClause("metatype","mt_sort","mt_type = 'vehicletype' AND mt_value = '" . $vhtType . "'");
   endif;
   $jbCrvhWeight   = convertSpecial($orderArray["xml"]["order"]["vehicle"]["weight"],"intval");
   $jbCrvhLength   = convertSpecial($orderArray["xml"]["order"]["vehicle"]["length"],"intval");
   $jbCrvhWidth    = convertSpecial($orderArray["xml"]["order"]["vehicle"]["width"],"intval");
   $jbCrvhHeight   = convertSpecial($orderArray["xml"]["order"]["vehicle"]["height"],"intval");
   $jbCrvhPosition = convertSpecial($orderArray["xml"]["order"]["vehicle"]["position"],"intval");
   $jbOrdertime    = convertSpecial($orderArray["xml"]["order"]["ordertime"]);
   if ($jbOrdertime == "" || $jbOrdertime == "0000-00-00 00:00:00") :
      $jbOrdertime = $currentTime;
   else :
      $jbOrdertime = checkDateTimeFormat($jbOrdertime);
      if ($jbOrdertime == "") :
         $jbOrdertime = $currentTime;
         $err[] = array("112", getLngt("Das Datum wurde nicht erwartungsgemäß übergeben."));
         $acceptOrder = false;
      endif;
   endif;
   
   $crSid          = convertSpecial($orderArray["xml"]["order"]["courier"]);
   $crIdOrder = "";
   if ($crSid != "") :
      $crIdOrder = getFieldValueFromId("couriervehicle","crvh_sid",$crSid,"cr_id");
      if ($crIdOrder == "") : $crSid = ""; endif;
   endif;
   $jbCrFilter     = convertSpecial($orderArray["xml"]["order"]["filter"]);
   $jbRemark       = convertSpecial($orderArray["xml"]["order"]["remark"]);
   $jbCrRemark     = convertSpecial($orderArray["xml"]["order"]["courier_remark"]);
   
   $jbTourdata = "";
   $jbTourdataZipcode = "";
   $jbTourdataCity = "";
   $jbTourdataCountry = "";

   // "TOUR" data
   $numOfStations = count($orderArray["xml"]["order"]["stations"]["station"]);
   if ($numOfStations > 0) :

      $trWareFromTo = array(); $trCostcenter = array(); $trCompany = array(); $trCompany2 = array();
      $trStreet = array(); $trHouseno = array(); $trZipcode = array(); $trCity = array(); $trAdId = array();
      $trSpecialRemark = array(); $trPerson = array(); $trPhone = array(); $trEmail = array();
      for ($i = 0; $i < $numOfStations; $i++) :
          $trWareFromTo[$i]    = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["ware_from_to"]);
          $trCostcenter[$i]    = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["costcenter"]);
          $trCscId[$i] = "";
          if ($trCostcenter[$i] != "") :
             $trCscId[$i]         = getFieldValueFromClause("costcenter","csc_id","cs_id = '" . $csId . "' AND csc_name = '" . $trCostcenter[$i] . "'");
          endif;
          if ($trCscId[$i] != "" && $trCscId[$i] != "0") :
             $trCompany[$i]       = getFieldValueFromClause("costcenteraddress","cscad_comp","adt_id = '4' AND csc_id = '" . $trCscId[$i] . "'");
             $trCompany2[$i]      = getFieldValueFromClause("costcenteraddress","cscad_comp2","adt_id = '4' AND csc_id = '" . $trCscId[$i] . "'");
             $trAdId[$i]          = getFieldValueFromClause("costcenteraddress","ad_id","adt_id = '4' AND csc_id = '" . $trCscId[$i] . "'");
             $trStreet[$i]        = getFieldValueFromId("address","ad_id",$trAdId[$i],"ad_street");
             $trHouseno[$i]       = getFieldValueFromClause("costcenteraddress","cscad_hsno","adt_id = '4' AND csc_id = '" . $trCscId[$i] . "'");
             $trZipcode[$i]       = getFieldValueFromId("address","ad_id",$trAdId[$i],"ad_zipcode");
             $trCity[$i]          = getFieldValueFromId("address","ad_id",$trAdId[$i],"ad_city");
             
             $trSpecialRemark[$i] = getFieldValueFromClause("costcenteraddress","cscad_remark","adt_id = '4' AND csc_id = '" . $trCscId[$i] . "'");
             $trPerson[$i]        = getFieldValueFromClause("costcenteraddress","cscad_person","adt_id = '4' AND csc_id = '" . $trCscId[$i] . "'");
             $trPhone[$i]         = getFieldValueFromClause("costcenteraddress","cscad_phone","adt_id = '4' AND csc_id = '" . $trCscId[$i] . "'");
             $trEmail[$i]         = getFieldValueFromClause("costcenteraddress","cscad_email","adt_id = '4' AND csc_id = '" . $trCscId[$i] . "'");
          else :
             $trCompany[$i]       = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["company"]);
             $trCompany2[$i]      = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["company2"]);
             $trStreet[$i]        = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["street"]);
             $trHouseno[$i]       = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["houseno"]);
             $trZipcode[$i]       = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["zipcode"]);
             $trCity[$i]          = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["city"]);
             $trSpecialRemark[$i] = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["special_remark"]);
             $trPerson[$i]        = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["person"]);
             $trPhone[$i]         = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["phone"]);
             $trEmail[$i]         = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["email"]);
             
             $trAdId[$i] = "";
             if ($trStreet[$i] != "" && $trZipcode[$i] != "" && $trCity[$i] != "") :
             
                $sqlStmt = "SELECT ad_id FROM address WHERE ad_street = '" . $trStreet[$i] . "' AND ad_zipcode = '" . $trZipcode[$i] . "' AND ad_city = '" . $trCity[$i] . "' AND ad_country = 'DE'";
                $trAdId[$i] = $db->getOne($sqlStmt);
                if (DB::isError($ad_id)) die ("$PHP_SELF: <br>$sqlStmt<br>" . $ad_id->getMessage());
                if ($trAdId[$i] == ""):
                   insertStmt("address", array("ad_street", $trStreet[$i], "ad_zipcode", $trZipcode[$i], "ad_city", $trCity[$i], "ad_country", "DE"));
                   $trAdId[$i] = getLastInsertID();
                endif;
                // $tmpArray = insertAddress($trStreet[$i], $trZipcode[$i], $trCity[$i], "", "DE", true);
                // $trAdId[$i] = $tmpArray[0];
             endif;
      
             // Get "EXTERN" costcenter of the current headquarters
             $trCscId[$i]         = getParameterValue("0", "CSC_ID_PAYER_EXTERN", $hqId);
          endif;
      
          // Generation parts of the field "jb_tourdata" (e.g.: "04109;04316|Leipzig;Leipzig/Mölkau|DE;DE")
          if ($i > 0) :
             $jbTourdataZipcode .= ";";
          endif;
          $jbTourdataZipcode .= $trZipcode[$i];
          $jbTourdataCity .= $trCity[$i];
          $jbTourdataCountry .= "DE";
      
          // Error handling
          if ($jbRemark == "") :
             $err[] = array("105", getLngt("Es wurde kein Rechnungstext übergeben."));
             $acceptOrder = false;
          endif;
          if ($trAdId[$i] == "") :
             $err[] = array("110", getLngt("Die Adressdaten sind nicht vollständig."));
             $acceptOrder = false;
          endif;
      endfor;
      
      // Generation of the field "jb_tourdata" (e.g.: "04109;04316|Leipzig;Leipzig/Mölkau|DE;DE")
      $jbTourdata = $jbTourdataZipcode . "|" . $jbTourdataCity . "|" . $jbTourdataCountry;
   else :
      $err[] = array("111", getLngt("Es konnten keine Stationen generiert werden."));
      $acceptOrder = false;
   endif;
   

   // Store into the database
/*
   echo "csEid:" . $csEid . "<br>";
   echo "csId:" . $csId . "<br>";
   echo "usrAccount:" . $usrAccount . "<br>";
   echo "usrPassword:" . $usrPassword . "<br>";
   echo "cscName:" . $cscName . "<br>";
   echo "cscId:" . $cscId . "<br>";
   echo "hqMnemonic:" . $hqMnemonic . "<br>";
   echo "hqId:" . $hqId . "<br>";
   echo "hqId_XML:" . $hqId_XML . "<br>";
   echo "vhtId:" . $vhtId . "<br>";
   echo "vhtType:" . $vhtType . "<br>";
   echo "jbCrvhWeight:" . $jbCrvhWeight . "<br>";
   echo "jbCrvhLength:" . $jbCrvhLength . "<br>";
   echo "jbCrvhWidth:" . $jbCrvhWidth . "<br>";
   echo "jbCrvhHeight:" . $jbCrvhHeight . "<br>";
   echo "jbCrvhPosition:" . $jbCrvhPosition . "<br>";
   echo "jbOrdertime:" . $jbOrdertime . "<br>";
   echo "crSid:" . $crSid . "<br>";
   echo "crIdOrder:" . $crIdOrder . "<br>";
   echo "jbCrFilter:" . $jbCrFilter . "<br>";
   echo "jbCrRemark:" . $jbCrRemark . "<br>";
   echo "jbTourdata:" . $jbTourdata . "<br>";
   echo "numOfStations:" . $numOfStations . "<br>";
   for ($i = 0; $i < $numOfStations; $i++) :
       echo "<br>";
       echo "STATION " . $i . ":<br>";
       echo $trWareFromTo[$i]   . "<br>";
       echo $trCostcenter[$i]   . "<br>";
       echo $trCscId[$i]        . "<br>";
       echo $trCompany[$i]      . "<br>";
       echo $trCompany2[$i]     . "<br>";
       echo $trAdId[$i]         . "<br>";
       echo $trStreet[$i]       . "<br>";
       echo $trHouseno[$i]      . "<br>";
       echo $trZipcode[$i]      . "<br>";
       echo $trCity[$i]         . "<br>";
       echo $trSpecialRemark[$i]. "<br>";
       echo $trPerson[$i]       . "<br>";
       echo $trPhone[$i]        . "<br>";
       echo $trEmail[$i]        . "<br>";
   endfor;
*/

   $cscIdList = array();

   if ($csId != "" && $csId > "0") :
      $sqlquery = "SELECT csc.csc_id FROM costcenter AS csc WHERE csc.cs_id = '" . $csId . "'";
      $result = $db->query($sqlquery);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
      while ($row = $result->fetch_assoc()):
            $cscIdList[] = $row["csc_id"];
      endwhile;
      $result->free();
   endif;
   if (count($cscIdList) > 0) :
      // Check for maximum number of jobs per day
      $numOfOrdersOfTheCurrentDay = getCountOfTable("job", "jb_modify >= '" . $currentDate . " 00:00:00' AND csc_id_payer IN (" . implode(",", $cscIdList) . ")");
      if ($numOfOrdersOfTheCurrentDay == "" || (is_numeric($numOfOrdersOfTheCurrentDay) && $numOfOrdersOfTheCurrentDay > $maxNumOfOrdersPerDay)) :
         $acceptOrder = false;
         $err[] = array("102", getLngt("Das Limit der Aufträge pro Tag wurde überschritten. Derzeit sind dies") . " " . $maxNumOfOrdersPerDay . " " . getLngt("Aufträge"));
      endif;
      // Check for maximum number of running jobs
      $numOfRunningOrders = getCountOfTable("job", "jb_status != '2' AND csc_id_payer IN (" . implode(",", $cscIdList) . ")");
      if ($numOfRunningOrders > $maxNumOfRunningOrders) :
         $acceptOrder = false;
         $err[] = array("103", getLngt("Das Limit insgesamt laufender Aufträge wurde überschritten. Derzeit sind dies") . " " . $maxNumOfRunningOrders . " " . getLngt("Aufträge"));
      endif;
   endif;   


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

   if ($errLen == 0 && $acceptOrder) :

      TA("B");
   
      insertStmt("job", array("hq_id", $hqId, "csc_id", $cscId, "vht_id", $vhtId, "csc_id_payer", $cscId, "jb_payment", "0",
                              "jb_ordertime", $jbOrdertime, "cr_id", "", "cr_sid", $crSid, "cr_id_order", $crIdOrder,
                              "jb_cr_filter", $jbCrFilter, "jb_cr_filter_opt", "", "jb_waitstorno", "0", 
                              "jb_taketime", "", "jb_status", $jbStatus, "jb_autoranking", "0", "jb_type", $jbType, 
                              "jb_incomplete", "0", "jb_globaljob", "0", "jb_tourname", $jbTourname,
                              "jb_finishtime", "", "emp_id", $usr_id, "jb_fixprice", $fixprice, "jb_totalprice", $fixprice,
                              "jb_postage", $cmpPostage, "jb_invmode", $csInvmode, "jb_freetext_1", "",
                              "jb_weight", $jbCrvhWeight, "jb_crvh_length", $jbCrvhLength, "jb_crvh_width", $jbCrvhWidth, 
                              "jb_crvh_height", $jbCrvhHeight, "jb_crvh_position", $jbCrvhPosition, "jb_invtext", $jbRemark,
                              "jb_tourdata", $jbTourdata, "jb_lockuser", "0", "jb_id_parent", "0", "jb_dispoinfo", "",
                              "jb_sales_tax_rate", $txValue, "jb_sales_tax_rate_sign", $txSign, "jb_booktime", ""));
      $jbIdNew = getLastInsertId();

      for ($i = 0; $i < $numOfStations; $i++) :

          $trSort = $i + 1;

          // Insert tour data for station
          insertStmt("tour", array("jb_id", $jbIdNew, "ad_id", $trAdId[$i], "tr_sort", $trSort, "tr_comp", $trCompany[$i], "tr_comp2", $trCompany2[$i],
                                   "tr_hsno", $trHouseno[$i], "csc_id", $trCscId[$i], "tr_status", "0", 
                                   "tr_commission_no", $trCommissionNo, "tr_ware_from_to", $trWareFromTo[$i], 
                                   "tr_person", $trPerson[$i], "tr_phone", $trPhone[$i], "tr_remark", $trSpecialRemark[$i]));

          // Insert tourservice data
          insertStmt("tourservice", array("jb_id", $jbIdNew, "csc_id", $cscId, "tr_sort", "0", 
                                          "srv_id", "0", "trs_srv_name", "Fixpreis", "srvt_id", "0", "trs_srvt_name", ""));
                                          
          $trCommissionNo = "";   // Reset commission number because associated to the first station only
      endfor;

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


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

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

// End of log entry
orderRequestLogFile("___________________________________________________________________________________");

// Return output
echo $outResponse;




/*
// FELDER UND IHRE BEDEUTUNG
<xml>
  <order>                                         // Fuhrauftrag
    <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]
    </auth>                                       
    <no>...</no>                                  // Order no of the customer  => tr_commission_no
    <hq>...</hq>                                  // {HB, HH, ...} => hq_mnemonic => hq_id
    <vehicle>                                     // Angefordertes Fahrzeug
      <type_no>...</type_no>                      // {1,2,3...} => Mapping "metatype" => vht_id     (entweder <type_no> oder <type_name> ist mandatory)
      <type_name>...</type_name>                  // {"bus", ...} => Mapping "metatype" => vht_id   (entweder <type_no> oder <type_name> ist mandatory)
      <weight>...</weight>                        // Gewicht des Transportguts
      <length>...</length>                        // Angeforderte Mindestlänge des Fahrzeugs
      <width>...</width>                          // Angeforderte Mindestbreite des Fahrzeugs
      <height>...</height>                        // Angeforderte Mindesthöhe des Fahrzeugs
      <position>...</position>                    // Angeforderte Mindestanzahl an Stellplätzen im Fahrzeug
    </vehicle>
    <ordertime>2011-12-24 09:30:00</ordertime>    // Startzeit des Auftrags (wenn leer, dann "adhoc"-Auftrag mit aktuellem Zeitstempel) => jb_ordertime und jb_reserv
    <courier>...</courier>                        // {HH1000, HH1420, ...} Wunschfahrer => jb.cr_sid => Abgleich mit cr.cr_sid => cr.cr_id => jb.cr_id_order   [optional]
    <filter>CK,DE,EN</filter>                     // Fahrzeug-Filter zur Einschränkung der Fahrzeugvermittlung (Aufstellung siehe Anhang)
    <remark>...</remark>                          // Bemerkung zum Auftrag
    <courier_remark>...</courier_remark>          // Bemerkung zum Auftrag für den Fahrer
    <stations>                                    // Stationen
      <station>                                   // Station 1 (Abholung)
        <ware_from_to>...</ware_from_to>          // Abholung   [optional]
        <costcenter>...</costcenter>              // Kostenstellenname {"abcd", "efgh", ...} => Mapping csc_id   [optional, wenn gesetzt, dann weitere Felder leer]
        <company>...</company>                    // Firmenbezeichnung
        <company2>...</company2>                  // Firmenzusatz
        <street>...</street>                      // Straße
        <houseno>...</houseno>                    // Hausnummer
        <zipcode>...</zipcode>                    // PLZ
        <city>...</city>                          // Ort
        <special_remark>...</special_remark>      // Bemerkung zur Station
        <person>...</person>                      // Abgabe der Sendung bei ..., Ansprechpartner   [optional]
        <phone>...</phone>                        // Telefonnummer  [optional]
        <email>...</email>                        // Email  [optional]
      </station>
      <station>                                   // Station 2
        <ware_from_to>...<ware_from_to>           // Abholung, Anlieferung, beides   [optional]
        ...
      </station>
      ...                                         // Weitere Stationen
    </stations>
  </order>
</xml>



// PFLICHTFELDER UND OPTIONALE FELDER
<xml>
  <order>                                         // Fuhrauftrag
    <auth>                                        // Identifikation des Kunden
      <customer>[mandatory]</customer>            // Kundennummer (EID) {"STBxxxxxx", ...}
      <account>[mandatory]</account>              // Eingetragener Benutzer für den Kunden
      <password>[mandatory]</password>            // Passwort für den Benutzer
      <session_id>[mandatory]</session_id>        // Zusätzliche ausgehandelte Session-ID
      <costcenter_name>[optional]</costcenter_name>      // Bekannte Kostenstelle
    </auth>                                       
    <no>[optional]</no>                           // Eigene Auftragsnummer z.B. aus Lotus
    <hq>[mandatory]</hq>                          // HH (HB, B, DD), Städtekürzel
    <vehicle>                                     // Angefordertes Fahrzeug
      <type_no>[mandatory]</type_no>              // {2=PKW, 3=Kombi, 4=Kastenwagen, 5=Bus, 6=Großer Bus, 7=LKW}
      <type_name>[optional]</type_name>           // {PKW, ...}
      <weight>[optional]</weight>                 // Gewicht des Transportguts
      <length>[optional]</length>                 // Angeforderte Mindestlänge des Fahrzeugs
      <width>[optional]</width>                   // Angeforderte Mindestbreite des Fahrzeugs
      <height>[optional]</height>                 // Angeforderte Mindesthöhe des Fahrzeugs
      <position>[optional]</position>             // Angeforderte Mindestanzahl an Stellplätzen im Fahrzeug
    </vehicle>
    <ordertime>[optional]</ordertime>             // Startzeit des Auftrags (wenn leer, dann "adhoc"-Auftrag mit aktuellem Zeitstempel) (Bsp: 2012-02-17 09:30:00)
    <courier>[optional]</courier>                 // {HH1000, HH1420, ...} Wunschfahrer
    <filter>[optional]</filter>                   // Fahrzeug-Filter zur Einschränkung der Fahrzeugvermittlung (Aufstellung siehe Anhang) (Bsp.: EN=Englisch, HW=Hubwagen, ...)
    <remark>[mandatory]</remark>                  // Rechnungstext und Bemerkung zum Auftrag
    <courier_remark>[optional]</courier_remark>   // Bemerkung zum Auftrag für den Fahrer
    <stations>                                    // Stationen
      <station>                                   // Station 1 (Abholung)
        <ware_from_to>[optional]</ware_from_to>   // Abholung
        <costcenter>[optional]</costcenter>       // Kostenstellenname {"abcd", "efgh", ...}
        <company>[mandatory]</company>            // Firmenbezeichnung ODER Person
        <company2>[optional]</company2>           // Firmenzusatz
        <street>[mandatory]</street>              // Straße
        <houseno>[mandatory]</houseno>            // Hausnummer
        <zipcode>[mandatory]</zipcode>            // PLZ
        <city>[mandatory]</city>                  // Ort
        <special_remark>[optional]</special_remark>      // Bemerkung zur Station
        <person>[optional]</person>               // Abgabe der Sendung bei ..., Ansprechpartner   [optional]
        <phone>[optional]</phone>                 // Telefonnummer  [optional]
        <email>[optional]</email>                 // Email  [optional]
      </station>
      <station>                                   // Station 2
        <ware_from_to>[optional]<ware_from_to>    // Abholung, Anlieferung, beides   [optional]
        ...
      </station>
      ...                                         // Weitere Stationen
    </stations>
  </order>
</xml>
*/
?>

