<?php
/**
 * Created by IntelliJ IDEA.
 * User: torbenfischer
 * Date: 10.05.20
 * Time: 08:10
 */

include_once ("../include/inc_parseXML.inc.php");

// define("VOTIAN_SERVER", "172.16.0.136/trans-portal/service/");
// define("VOTIAN_SERVER", "172.16.0.147/test_php7_sb/service/");
// define("VOTIAN_SERVER", "apache-3.assecutor.de/test_php7_sb/service/");
// define("VOTIAN_SESSION_ID", "7415zfnd05fehrz3d347319d0rt94975f415ehr");
define("VOTIAN_SERVER", "sb.assecutor.de/service/");
define("VOTIAN_SESSION_ID", "7xkrudn305fed347h19rz33d0rt94975f41zf72");


$requestResultXML = array();
$requestType = "";
$type = "";

Class SimpleXMLExtended extends SimpleXMLElement {
    public function addCData($name, $value = NULL) {
        $new_child = $this->addChild($name);

        if ($new_child !== NULL) {
            $node = dom_import_simplexml($new_child);
            $no   = $node->ownerDocument;
            $node->appendChild($no->createCDATASection($value));
        }

        return $new_child;
    }
}



function get_url($request_url, $data) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $request_url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 100);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}

function create_url($key, $xml_) {
    $request_url = $key."=" . urlencode($xml_);
    return $request_url;
}

function createAndSendXMLRec($server, $key, $skript, $requestXML) {
    $rfcProt = "https://";
    $rfcUrl = $server . $skript;
    $request_url = $rfcProt . $rfcUrl;
    $data = create_url($key, $requestXML);
    return get_url($request_url, $data);
}

/*  Customer_Request XML
 *
 *  <xml>
 *      <customer>
 *          <auth>
 *              <session_id>XXX</session_id>
 *              <passphrase>XXX</passphrase>
 *          </auth>
 *          <operation>GET</operation>
 *          <debug_on>YES</debug_on>
 *          <cs_id>CS_ID</cs_id>
 *      </customer>
 *  </xml>
 *
 * */
function createGetReqXML($requestData) {
    // $session_id = "949734773drt319d05f415ehrzfnd05f415ehrz";
    $session_id = VOTIAN_SESSION_ID;
    $passphrase = getPwd("34a78d91s83g");

    $xml = new SimpleXMLExtended('<xml/>');
    $customer = $xml->addChild($requestData['xmlTag']);
    $auth = $customer->addChild('auth');

    $auth->addChild("session_id", $session_id);
    $auth->addChild("passphrase", $passphrase);

    if($requestData['operation']) {

        $customer->addChild("operation", $requestData['operation']);

    }

    $customer->addChild("debug_on", $requestData['debug_on']);

    if($requestData['idKey'] && $requestData['id']) {

        $customer->addChild($requestData['idKey'], $requestData['id']);

    }


    foreach ($requestData['dynRequestData'] as $key=>$value) {
        $customer->addChild($key, $value);
    }

    $dom = dom_import_simplexml($xml);

    return $dom->ownerDocument->saveXML($dom->ownerDocument->documentElement);
}

function getDashData($type, $tag, $id, $brArr = array(), $styleArr = array(), $dateformat = "", $structureType = "div", $structureHeadline = "", $linkArr = array()) {
    global $requestResultXML;

    $styleArr['style'][] = "width: 100%";
    $headerStyle = "style = 'background-color: #BBBBFF;'";
    $contentStyle = "style = 'background-color: #DDDDDD;'";
    $structure = $structureType;
    $reportVal = "";
    $appointmentVal = "";

    if($structure == "line" || is_array($tag) && is_array($structureHeadline) && count($tag) == count($structureHeadline)) {

        $structureType = "table";
    }

    $html = "<". $structureType ."";
    if(count($styleArr) > 0) {

        foreach ($styleArr as $htmlOpt=>$value) {
            $html .= " ". $htmlOpt ."='";

            foreach ($value as $htmlOptContent) {
                $html .= $htmlOptContent . " ";
            }

            $html .= "' ";
        }

        $html .= ">";
    } else {
        $html .= ">";
    }

    $requestData['operation'] = "GET";
    $requestData['debug_on'] = "NO";
    $requestData['id'] = $id;

    if($type == "cs") {

        $requestData['xmlTag'] = "customer";
        $requestData['idKey'] = "cs_id";
        $requestData['key'] = "cs";
        $requestData['dynRequestData'] = array();

        $requestData['dynRequestData']['cs_last_job'] = "ON";

        if(!is_array($tag)) {

            if(strpos($tag, "reports_num_since_last_login") !== false) {

                $reportVal = explode(":", $tag);

                $requestData['dynRequestData']['cs_reports_data_since_last_login'] = $reportVal[1];

            } else if(strpos($tag, "reports_data_since_last_login") !== false) {

                $reportVal = explode(":", $tag);

                $requestData['dynRequestData']['cs_reports_data_since_last_login'] = $reportVal[1];

            } else if(strpos($tag, "appointments_num_since_last_login") !== false || strpos($tag, "appointments_data_since_last_login") !== false) {

                $appointmentVal = explode(":", $tag);

                $requestData['dynRequestData']['cs_appointments_num_since_last_login'] = $appointmentVal[1];
                $requestData['dynRequestData']['cs_appointments_data_since_last_login'] = $appointmentVal[1];

            }

        }

        $key = "customerReq";
        $skript = "customer_request.php";

    } else if($type == "cr") {

        $requestData['xmlTag'] = "contractor";
        $requestData['idKey'] = "cr_id";
        $requestData['key'] = "cr";
        $requestData['dynRequestData'] = array();

        $key = "contractorReq";
        $skript = "contractor_request.php";

    }

    if(!array_key_exists($type, $requestResultXML)) {

        $requestResultText = utf8_encode(createAndSendXMLRec(VOTIAN_SERVER, $key, $skript, createGetReqXML($requestData)));
        $requestResultXML[$type][$id]['xml'] = simplexml_load_string($requestResultText, null, LIBXML_NOCDATA);

        $requestResultXML[$type][$id]['reportNum'] = array();
        $requestResultXML[$type][$id]['reportData'] = array();

        $requestResultXML[$type][$id]['appointmentNum'] = array();
        $requestResultXML[$type][$id]['appointmentData'] = array();

        if(strpos($tag, "reports_num_since_last_login") !== false) {

            $requestResultXML[$type][$id]['reportNum'][$reportVal[1]] = $requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->reports;

        } else if(strpos($tag, "reports_data_since_last_login") !== false) {

            $requestResultXML[$type][$id]['reportData'][$reportVal[1]] = $requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->reports;

        } else if(strpos($tag, "appointments_data_since_last_login") !== false || strpos($tag, "appointments_num_since_last_login") !== false) {

            $requestResultXML[$type][$id]['appointmentData'][$appointmentVal[1]] = $requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->appointments;
            $requestResultXML[$type][$id]['appointmentNum'][$appointmentVal[1]] = $requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->cs_appointments_num_since_last_login;

        }

    } else if(!array_key_exists($id, $requestResultXML[$type])) {

        $requestResultText = utf8_encode(createAndSendXMLRec(VOTIAN_SERVER, $key, $skript, createGetReqXML($requestData)));
        $requestResultXML[$type][$id]['xml'] = simplexml_load_string($requestResultText, null, LIBXML_NOCDATA);

        if(strpos($tag, "reports_num_since_last_login") !== false) {

            $requestResultXML[$type][$id]['reportNum'][$reportVal[1]] = $requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->reports;

        } else if(strpos($tag, "reports_data_since_last_login") !== false) {

            $requestResultXML[$type][$id]['reportData'][$reportVal[1]] = $requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->reports;

        } else if(strpos($tag, "appointments_data_since_last_login") !== false || strpos($tag, "appointments_num_since_last_login") !== false) {

            $requestResultXML[$type][$id]['appointmentData'][$appointmentVal[1]] = $requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->appointments;
            $requestResultXML[$type][$id]['appointmentNum'][$appointmentVal[1]] = $requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->cs_appointments_num_since_last_login;

        }

    }

    if(!is_array($tag)) {

        if(strpos($tag, "reports_num_since_last_login") !== false && !array_key_exists($reportVal[1], $requestResultXML[$type][$id]['reportNum'])) {

            $requestResultText = utf8_encode(createAndSendXMLRec(VOTIAN_SERVER, $key, $skript, createGetReqXML($requestData)));
            $requestResultXML[$type][$id]['reportNum'][$reportVal[1]] = simplexml_load_string($requestResultText, null, LIBXML_NOCDATA)->{$requestData['xmlTag']}->reports;

        } else if(strpos($tag, "reports_data_since_last_login") !== false && !array_key_exists($reportVal[1], $requestResultXML[$type][$id]['reportData'])) {

            $requestResultText = utf8_encode(createAndSendXMLRec(VOTIAN_SERVER, $key, $skript, createGetReqXML($requestData)));
            $requestResultXML[$type][$id]['reportData'][$reportVal[1]] = simplexml_load_string($requestResultText, null, LIBXML_NOCDATA)->{$requestData['xmlTag']}->reports;

        } else if((strpos($tag, "appointments_data_since_last_login") !== false && !array_key_exists($reportVal[1], $requestResultXML[$type][$id]['appointmentData'])) || (strpos($tag, "appointments_num_since_last_login") !== false && !array_key_exists($reportVal[1], $requestResultXML[$type][$id]['appointmentData']))) {

            $requestResultText = utf8_encode(createAndSendXMLRec(VOTIAN_SERVER, $key, $skript, createGetReqXML($requestData)));
            $requestResultXML[$type][$id]['appointmentData'][$appointmentVal[1]] = simplexml_load_string($requestResultText, null, LIBXML_NOCDATA)->{$requestData['xmlTag']}->appointments;
            $requestResultXML[$type][$id]['appointmentNum'][$appointmentVal[1]] = simplexml_load_string($requestResultText, null, LIBXML_NOCDATA)->{$requestData['xmlTag']}->cs_appointments_num_since_last_login;

        }

    }

    if($requestResultXML[$type][$id]['xml']->state == "OK") {

        $divContent = array(
            'content' => array(),
            'style' => array(),
            'onclick' => array()
        );

        if(!is_array($tag) && (strpos($tag, 'stat_year') !== false || strpos($tag, 'stat_chart') !== false)) {

            getVehicles($type, $tag, $id, $requestData);

        }

        if(is_array($tag) && is_array($structureHeadline) && count($tag) == count($structureHeadline) ) {

            for ($x = 0; $x < count($tag); $x++) {

                if(strpos($tag[$x], 'stat_year') !== false || strpos($tag[$x], 'stat_chart') !== false) {

                    getVehicles($type, $tag[$x], $id, $requestData);

                }

                $found = parseXML($tag[$x], $requestResultXML[$type][$id]);
                $divContent['content'][$structureHeadline[$x]] = dataOut($found);

                if(!empty($linkArr)) {

                    array_push($divContent['onclick'], ...array_fill(0, 1, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $requestResultXML[$type][$id])->__toString()) . "')\""));

                }

            }

        } else if($tag == "vehicle") {

            return;

        } else if (!is_array($tag) && strpos($tag, 'stat_year') !== false) {

            array_push($divContent['content'], ...dataOut($requestResultXML[$type][$id]['statistic'][$tag]['count_jobs']));
            array_push($divContent['content'], ...dataOut($requestResultXML[$type][$id]['statistic'][$tag]['business_volume']));

            if(!empty($linkArr)) {

                array_push($divContent['onclick'], ...array_fill(0, 2, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $requestResultXML[$type][$id])->__toString()) . "')\""));

            }

        } else if($tag == "company") {

            array_push($divContent['content'], ...dataOut($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->company->cmp_comp));

            if(!empty($linkArr)) {

                array_push($divContent['onclick'], ...array_fill(0, 1, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $requestResultXML[$type][$id])->__toString()) . "')\""));

            }

            for($i = 2; $i < 4 ; $i++) {

                $companyCounter = "cmp_comp" . $i;

                if($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->company->{$companyCounter}->__toString()) {

                    array_push($divContent['content'], ...dataOut($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->company->{$companyCounter}));

                    if(!empty($linkArr)) {

                        array_push($divContent['onclick'], ...array_fill(0, 1, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $requestResultXML[$type][$id])->__toString()) . "')\""));

                    }

                }

            }

        } else if($tag == "address") {

            $tmpStreet  = $requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->company->ad_street;
            $tmpHsno    = $requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->company->cmp_hsno;
            $tmpZipcode = $requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->company->ad_zipcode;
            $tmpCity    = $requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->company->ad_city;
            $tmpCountry = $requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->company->ad_country;
            array_push($divContent['content'], $tmpStreet[0] . "&nbsp;" . $tmpHsno[0]);
            array_push($divContent['content'], $tmpZipcode[0] . "&nbsp;" . $tmpCity[0] . "&nbsp;" . "[" . $tmpCountry[0] . "]");

            if(!empty($linkArr)) {

                array_push($divContent['onclick'], ...array_fill(0, 2, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $requestResultXML[$type][$id])->__toString()) . "')\""));

            }

        } else if($tag == "phoneFax") {

            array_push($divContent['content'], ...dataOut($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->user->usr_phone));
            array_push($divContent['content'], ...dataOut($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->user->usr_phone2));
            array_push($divContent['content'], ...dataOut($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->user->usr_fax));

            if(!empty($linkArr)) {

                array_push($divContent['onclick'], ...array_fill(0, 3, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $requestResultXML[$type][$id])->__toString()) . "')\""));

            }

        } else if($tag == "id") {

            array_push($divContent['content'], ...dataOut($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->{$requestData['key'] . "_eid"}));

            if(!empty($linkArr)) {

                array_push($divContent['onclick'], ...array_fill(0, 1, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $requestResultXML[$type][$id])->__toString()) . "')\""));

            }

        } else if($tag == "user_since") {

            array_push($divContent['content'], ...dataOut($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->{$requestData['key'] . "_become_" . $requestData['key'] . "_date"}));

            if(!empty($linkArr)) {

                array_push($divContent['onclick'], ...array_fill(0, 1, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $requestResultXML[$type][$id])->__toString()) . "')\""));

            }

        } else if($tag == "last_order") {

            array_push($divContent['content'], ...dataOut($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->cs_last_job));

            if(!empty($linkArr)) {

                array_push($divContent['onclick'], ...array_fill(0, 1, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $requestResultXML[$type][$id])->__toString()) . "')\""));

            }

        } else if($tag == "sector") {

            /* DUMMY */
            array_push($divContent['content'], ...dataOut("Spedition"));

            if(!empty($linkArr)) {

                array_push($divContent['onclick'], ...array_fill(0, 1, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $requestResultXML[$type][$id])->__toString()) . "')\""));

            }

        } else if($tag == "yearly_sales_sum") {

            /* DUMMY */
            array_push($divContent['content'], ...dataOut("448000 &euro;"));

            if(!empty($linkArr)) {

                array_push($divContent['onclick'], ...array_fill(0, 1, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $requestResultXML[$type][$id])->__toString()) . "')\""));

            }

        } else if($tag == "bank") {

            $cellColor = "#DDDDDD";
            $clickCounter = 0;

            if($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->company->cmp_bank != "") {

                array_push($divContent['content'], ...dataOut($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->company->cmp_bank));
                array_push( $divContent['style'], "background-color: ". $cellColor . ";");
                $clickCounter++;

            }

            if($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->company->cmp_bankacc != "") {

                array_push($divContent['content'], ...dataOut($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->company->cmp_bankacc));
                array_push( $divContent['style'], "background-color: ". $cellColor . ";");
                $clickCounter++;

            }

            if($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->company->cmp_bankno != "") {

                array_push($divContent['content'], ...dataOut($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->company->cmp_bankno));
                array_push( $divContent['style'], "background-color: ". $cellColor . ";");
                $clickCounter++;

            }

            if($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->company->cmp_iban != "") {

                array_push($divContent['content'], ...dataOut($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->company->cmp_iban));
                array_push( $divContent['style'], "background-color: ". $cellColor . ";");
                $clickCounter++;

            }

            if($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->company->cmp_swift != "") {

                array_push($divContent['content'], ...dataOut($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->company->cmp_swift));
                array_push( $divContent['style'], "background-color: ". $cellColor . ";");
                $clickCounter++;

            }

            if(!empty($linkArr)) {

                array_push($divContent['onclick'], ...array_fill(0, $clickCounter, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $requestResultXML[$type][$id])->__toString()) . "')\""));

            }

        } else if($tag == "costcenteraddresses") {

            $dataFieldCounter = 0;

            foreach ($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->costcenters->costcenter->costcenteraddresses->costcenteraddress->children() as $costcenters) {

                if ($dataFieldCounter % 2 == 0) : $cellColor = "#DDDDDD"; endif;
                if ($dataFieldCounter % 2 == 1) : $cellColor = "#EEEEEE"; endif;

                array_push($divContent['content'], ...dataOut($costcenters->cscad_comp));
                array_push( $divContent['style'], "background-color: ". $cellColor . ";");

                array_push($divContent['content'], ...dataOut($costcenters->cscad_comp2));
                array_push( $divContent['style'], "background-color: ". $cellColor . ";");

                array_push($divContent['content'], ...dataOut($costcenters->cscad_phone));
                array_push( $divContent['style'], "background-color: ". $cellColor . ";");

                $tmpStreet  = dataOut($costcenters->ad_street);
                $tmpHsno    = dataOut($costcenters->cscad_hsno);
                $tmpZipcode = dataOut($costcenters->ad_zipcode);
                $tmpCity    = dataOut($costcenters->ad_city);
                $tmpCountry = dataOut($costcenters->ad_country);
                array_push($divContent['content'], $tmpStreet[0] . "&nbsp;" . $tmpHsno[0]);
                array_push( $divContent['style'], "background-color: ". $cellColor . ";");

                array_push($divContent['content'], $tmpZipcode[0] . "&nbsp;" . $tmpCity[0] . "&nbsp;" . "[" . $tmpCountry[0] . "]");
                array_push( $divContent['style'], "background-color: ". $cellColor . ";");

                if(!empty($linkArr)) {

                    array_push($divContent['onclick'], ...array_fill(0, 5, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $costcenters)->__toString()) . "')\""));

                }

                $dataFieldCounter++;

            }

        } else if($tag == "costcenters") {

            $dataFieldCounter = 0;

            foreach ($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->costcenters->costcenter as $costcenters) {

                if ($dataFieldCounter % 2 == 0) : $cellColor = "#DDDDDD"; endif;
                if ($dataFieldCounter % 2 == 1) : $cellColor = "#EEEEEE"; endif;

                array_push($divContent['content'], ...dataOut($costcenters->csc_name));
                array_push( $divContent['style'], "background-color: ". $cellColor . ";");

                if(!empty($linkArr)) {

                    array_push($divContent['onclick'], ...array_fill(0, 1, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $costcenters)->__toString()) . "')\""));

                }

                $dataFieldCounter++;

            }

        } else if($tag == "cr_fav") {

            $dataFieldCounter = 0;

            if(count($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->customercouriers) > 0) {

                foreach ($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->customercouriers->customercourier as $cr_fav) {

                    if ($dataFieldCounter % 2 == 0) : $cellColor = "#DDDDDD"; endif;
                    if ($dataFieldCounter % 2 == 1) : $cellColor = "#EEEEEE"; endif;

                    getDashData("cr", "vehicle", $cr_fav->cr_id->__toString());

                    $vehicleData = $requestResultXML["cr"][$cr_fav->cr_id->__toString()]['xml'];

                    array_push($divContent['content'], ...dataOut($vehicleData->contractor->company->cmp_comp));
                    array_push( $divContent['style'], "background-color: ". $cellColor . ";");
                    array_push($divContent['content'], ...dataOut($vehicleData->contractor->company->cmp_comp2));
                    array_push( $divContent['style'], "background-color: ". $cellColor . ";");
                    array_push($divContent['content'], ...dataOut($vehicleData->contractor->user->usr_name));
                    array_push( $divContent['style'], "background-color: ". $cellColor . ";");
                    array_push($divContent['content'], ...dataOut($vehicleData->contractor->user->usr_firstname));
                    array_push( $divContent['style'], "background-color: ". $cellColor . ";");
                    array_push($divContent['content'], ...dataOut($vehicleData->contractor->vehicles->vehicle->crvh_sid));
                    array_push( $divContent['style'], "background-color: ". $cellColor . ";");
                    array_push($divContent['content'], ...dataOut($vehicleData->contractor->cr_eid));
                    array_push( $divContent['style'], "background-color: ". $cellColor . ";");

                    $tmpStreet  = dataOut($vehicleData->contractor->company->ad_street);
                    $tmpHsno    = dataOut($vehicleData->contractor->company->cmp_hsno);
                    $tmpZipcode = dataOut($vehicleData->contractor->company->ad_zipcode);
                    $tmpCity    = dataOut($vehicleData->contractor->company->ad_city);
                    $tmpCountry = dataOut($vehicleData->contractor->company->ad_country);
                    array_push($divContent['content'], $tmpStreet[0] . "&nbsp;" . $tmpHsno[0]);
                    array_push( $divContent['style'], "background-color: ". $cellColor . ";");
                    array_push($divContent['content'], $tmpZipcode[0] . "&nbsp;" . $tmpCity[0] . "&nbsp;" . "[" . $tmpCountry[0] . "]");
                    array_push( $divContent['style'], "background-color: ". $cellColor . ";");

                    $dataFieldCounter++;

                    if(!empty($linkArr)) {

                        array_push($divContent['onclick'], ...array_fill(0, 8, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $vehicleData)->__toString()) . "')\""));

                    }

                }

            }

        } else if($tag == "cr_block") {

            $dataFieldCounter = 0;

            if(count($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->customercouriers_blocked) > 0) {

                foreach ($requestResultXML[$type][$id]['xml']->{$requestData['xmlTag']}->customercouriers_blocked->customercourier as $cr_block) {

                    if ($dataFieldCounter % 2 == 0) : $cellColor = "#DDDDDD"; endif;
                    if ($dataFieldCounter % 2 == 1) : $cellColor = "#EEEEEE"; endif;

                    getDashData("cr", "vehicle", $cr_block->cr_id->__toString());

                    $vehicleData = $requestResultXML["cr"][$cr_block->cr_id->__toString()]['xml'];

                    array_push($divContent['content'], ...dataOut($vehicleData->contractor->company->cmp_comp));
                    array_push($divContent['style'], "background-color: " . $cellColor . ";");
                    array_push($divContent['content'], ...dataOut($vehicleData->contractor->company->cmp_comp2));
                    array_push($divContent['style'], "background-color: " . $cellColor . ";");
                    array_push($divContent['content'], ...dataOut($vehicleData->contractor->user->usr_name));
                    array_push($divContent['style'], "background-color: " . $cellColor . ";");
                    array_push($divContent['content'], ...dataOut($vehicleData->contractor->user->usr_firstname));
                    array_push($divContent['style'], "background-color: " . $cellColor . ";");
                    array_push($divContent['content'], ...dataOut($vehicleData->contractor->vehicles->vehicle->crvh_sid));
                    array_push($divContent['style'], "background-color: " . $cellColor . ";");
                    array_push($divContent['content'], ...dataOut($vehicleData->contractor->cr_eid));
                    array_push($divContent['style'], "background-color: " . $cellColor . ";");

                    $tmpStreet = dataOut($vehicleData->contractor->company->ad_street);
                    $tmpHsno = dataOut($vehicleData->contractor->company->cmp_hsno);
                    $tmpZipcode = dataOut($vehicleData->contractor->company->ad_zipcode);
                    $tmpCity = dataOut($vehicleData->contractor->company->ad_city);
                    $tmpCountry = dataOut($vehicleData->contractor->company->ad_country);
                    array_push($divContent['content'], $tmpStreet[0] . "&nbsp;" . $tmpHsno[0]);
                    array_push($divContent['style'], "background-color: " . $cellColor . ";");
                    array_push($divContent['content'], $tmpZipcode[0] . "&nbsp;" . $tmpCity[0] . "&nbsp;" . "[" . $tmpCountry[0] . "]");
                    array_push($divContent['style'], "background-color: " . $cellColor . ";");

                    $dataFieldCounter++;

                    if(!empty($linkArr)) {

                        array_push($divContent['onclick'], ...array_fill(0, 8, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $vehicleData)->__toString()) . "')\""));

                    }

                }

            }

        } else if(strpos($tag, "reports_num_since_last_login") !== false) {

            if($requestResultXML[$type][$id]['reportNum'][$reportVal[1]]->report[0]->rp_reporttypename && $requestResultXML[$type][$id]['reportNum'][$reportVal[1]]->report[0]->rp_createtime) {

                array_push($divContent['content'], ...dataOut(strval(count($requestResultXML[$type][$id]['reportNum'][$reportVal[1]]->report))));

            } else {

                array_push($divContent['content'], ...dataOut("0"));

            }

            if(!empty($linkArr)) {

                array_push($divContent['onclick'], ...array_fill(0, 1, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $requestResultXML[$type][$id])->__toString()) . "')\""));

            }

        } else if(strpos($tag, "reports_data_since_last_login") !== false) {

            $dataFieldCounter = 0;

            foreach($requestResultXML[$type][$id]['reportData'][$reportVal[1]]->report as $report) {

                if($report->rp_reporttypename && $report->rp_createtime) {

                    if ($dataFieldCounter % 2 == 0) : $cellColor = "#DDDDDD"; endif;
                    if ($dataFieldCounter % 2 == 1) : $cellColor = "#EEEEEE"; endif;

                    array_push($divContent['content'], ...dataOut($report->rp_reporttypename));
                    array_push($divContent['style'], "background-color: " . $cellColor . ";");
                    array_push($divContent['content'], ...dataOut(date("d.m.Y", strtotime($report->rp_createtime))));
                    array_push($divContent['style'], "background-color: " . $cellColor . ";");

                    if(!empty($linkArr)) {

                        array_push($divContent['onclick'], ...array_fill(0, 2, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $report)->__toString()) . "')\""));

                    }

                    $dataFieldCounter++;

                }

            }

        } else if(strpos($tag, "appointments_data_since_last_login") !== false) {

            $dataFieldCounter = 0;

            foreach($requestResultXML[$type][$id]['appointmentData'][$appointmentVal[1]]->appointment as $appointment) {

                if($appointment->ap_appointmenttypename->__toString() && $appointment->ap_execdate->__toString() && $appointment->ap_text->__toString()) {

                    if ($dataFieldCounter % 2 == 0) : $cellColor = "#DDDDDD"; endif;
                    if ($dataFieldCounter % 2 == 1) : $cellColor = "#EEEEEE"; endif;

                    array_push($divContent['content'], ...dataOut($appointment->ap_appointmenttypename->__toString()));
                    array_push($divContent['style'], "background-color: " . $cellColor . ";");
                    array_push($divContent['content'], ...dataOut($appointment->ap_text->__toString()));
                    array_push($divContent['style'], "background-color: " . $cellColor . ";");
                    array_push($divContent['content'], ...dataOut(date("d.m.Y", strtotime($appointment->ap_execdate->__toString()))));
                    array_push($divContent['style'], "background-color: " . $cellColor . ";");

                    if(!empty($linkArr)) {

                        array_push($divContent['onclick'], ...array_fill(0, 3, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $appointment)->__toString()) . "')\""));

                    }

                    $dataFieldCounter++;

                }

            }

        } else if(strpos($tag, "appointments_num_since_last_login") !== false) {

            if($requestResultXML[$type][$id]['appointmentNum'][$appointmentVal[1]]->__toString()) {

                array_push($divContent['content'], ...dataOut($requestResultXML[$type][$id]['appointmentNum'][$appointmentVal[1]]->__toString()));

            } else {

                array_push($divContent['content'], ...dataOut("0"));

            }

            if(!empty($linkArr)) {

                array_push($divContent['onclick'], ...array_fill(0, 1, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $requestResultXML[$type][$id])->__toString()) . "')\""));

            }

        } else if(strpos($tag, "stat_chart") !== false) {

            $dataArray = array();

            for($c = 0; $c < count($requestResultXML[$type][$id]['statistic'][$tag]->jb_finishtime); $c++) {

                $finishTime = explode("-", $requestResultXML[$type][$id]['statistic'][$tag]->jb_finishtime[$c]->__toString());

                if(!key_exists($finishTime[0], $dataArray)) {

                    $dataArray[$finishTime[0]]['count_jobs'] = array(
                        "01"=>"0",
                        "02"=>"0",
                        "03"=>"0",
                        "04"=>"0",
                        "05"=>"0",
                        "06"=>"0",
                        "07"=>"0",
                        "08"=>"0",
                        "09"=>"0",
                        "10"=>"0",
                        "11"=>"0",
                        "12"=>"0",
                    );
                    $dataArray[$finishTime[0]]['business_volume'] = array(
                        "01"=>"0",
                        "02"=>"0",
                        "03"=>"0",
                        "04"=>"0",
                        "05"=>"0",
                        "06"=>"0",
                        "07"=>"0",
                        "08"=>"0",
                        "09"=>"0",
                        "10"=>"0",
                        "11"=>"0",
                        "12"=>"0",
                    );

                }


                $dataArray[$finishTime[0]]['count_jobs'][$finishTime[1]] = $requestResultXML[$type][$id]['statistic'][$tag]->count_jobs[$c]->__toString();
                $dataArray[$finishTime[0]]['business_volume'][$finishTime[1]] = number_format($requestResultXML[$type][$id]['statistic'][$tag]->business_volume[$c]->__toString(), 2,".","");
//                array_push($dataArray[$finishTime[0]]['count_jobs'], $requestResultXML[$type][$id]['statistic'][$tag]->count_jobs[$c]->__toString());
//                array_push($dataArray[$finishTime[0]]['business_volume'], number_format($requestResultXML[$type][$id]['statistic'][$tag]->business_volume[$c]->__toString(), 2,".",""));
//                $dataArray[$finishTime[0]][$finishTime[1]]['count_jobs'] = $requestResultXML[$type][$id]['statistic'][$tag]->count_jobs[$c]->__toString();
//                $dataArray[$finishTime[0]][$finishTime[1]]['business_volume'] = floatval(str_replace(',', '.', str_replace('.', ',', $requestResultXML[$type][$id]['statistic'][$tag]->business_volume[$c]->__toString())));
            }

            $toggle = "";

            if(strpos($tag, "jobs") !== false) {

                $toggle = "count_jobs";

            } else if(strpos($tag, "sales") !== false) {

                $toggle = "business_volume";

            }

            $chartString = '
                <script>

                    function r(f){/in/.test(document.readyState)?setTimeout(\'r(\'+f+\')\',9):f()}

                        r(function(){
                            
                            var ctx = document.getElementById(\''. $tag .'\');
                            var myChart'. $toggle .' = new Chart(ctx, {

                                type: \'line\',
                                data: {
                                labels: [\'Jan.\', \'Feb.\', \'M\u00e4rz\', \'Apr.\', \'Mai\', \'Jun.\', \'Jul.\', \'Aug.\', \'Sept.\', \'Okt.\', \'Nov.\', \'Dez.\'],
                                datasets: [
                                    ';

            $chartCounter = 0;

            foreach($dataArray as $key=>$value) {

                $color = getColor($chartCounter);

                $chartString .= '{
                                    lineTension: 0,
                                    label: \'' . $key . '\',
                                    data: ['. implode(",", $value[$toggle]) .'],
                                    borderColor: [
                                        \'rgba('. $color[0] .', '. $color[1] .', '. $color[2] .', 1)\',
                                    ],
                                    fill: false,
                                    ';
                if(date('Y') == $key) {

                    $chartString .= 'borderDash: [10,5]';

                }

                $chartString .='},';
                $chartCounter++;

            }

            $chartString .= '   ]

                            },
                            options: {
                                scales: {
                                    yAxes: [{
                                        scaleLabel: {
                                        display: true,
                                        labelString: ';
                                    if($toggle == "business_volume") {

                                        $chartString .= '\'Umsatz [\u20AC]\',';

                                    } else {

                                        $chartString .= '\'Auftragsanzahl\',';

                                    }
            $chartString .= '                            },ticks: {
                                            beginAtZero: true,';

                            if($toggle == "business_volume") {

                                $chartString .= 'userCallback: function(value, index, values) {
                                    // Convert the number to a string and splite the string every 3 charaters from the end
                                    value = value.toString();
                                    value = value.split(/(?=(?:...)*$)/);
                                    
                                                // Convert the array to a string and format the output
                                                value = value.join(\'.\');
                                                return \'\u20AC\' + value;
                                            }';

                            }

            $chartString .= '                                       }
                                    }]
                                },';

                                $chartString .= 'tooltips: {
                                    enabled: false,
                                    mode: \'index\',
                                    intersect: false,
                                    custom: function(tooltip) {
                                        $(this._chart.canvas).css(\'cursor\', \'pointer\');
                
                                        var positionY = this._chart.canvas.offsetTop;
                                        var positionX = this._chart.canvas.offsetLeft;
                
                                        $(\'.chartjs-tooltip\').css({
                                            opacity: 0,
                                        });
                
                                        if (!tooltip || !tooltip.opacity) {
                                            return;
                                        }
                
                                        if (tooltip.dataPoints.length > 0) {
                                            var parentX = 0;
                                            var parentY = 0;
                                        
                                            tooltip.dataPoints.forEach(function(dataPoint) {';
                                            if($toggle == "business_volume") {
                                            
                                                $chartString .= 'var content = [dataPoint.xLabel, "\u20AC"+(""+(dataPoint.yLabel).toFixed(2)).replace(".", ",")].join(\': \');';
                                            
                                            } else {
                                            
                                                $chartString .= 'var content = [dataPoint.xLabel, dataPoint.yLabel].join(\': \');';
                                            
                                            }
                                               
                                                $chartString .= 'var tooltip = $(\'#tooltip-'.$toggle.'-\' + dataPoint.datasetIndex);
                
                                                tooltip.html(content);
                                                
                                                tooltip.css({
                                                    opacity: 1,
                                                    top:  tooltip.parent().offset()["top"] + positionY + dataPoint.y + \'px\',
                                                    left: tooltip.parent().offset()["left"] + positionX + dataPoint.x + \'px\',
                                                });
                                                
                                            });
                                        }
                                    },
                                }';

                            $chartString .= '}
                        });
                    });

                </script>
                <div id="canvas-holder'.$toggle.'" style="width: 40vw;">
                    <canvas class="chartjs-render-monitor" id="'. $tag .'" style="background-color: white; display: block; height: 534px; width: 1068px; cursor: pointer;"></canvas>';

            for($c = 0; $c < count(array_keys($dataArray)); $c++) {

                $chartString .= '    <div style="opacity: 0" class="chartjs-tooltip" id="tooltip-'.$toggle.'-'.$c.'"></div>';

            }

             $chartString .= '</div>';

            array_push($divContent['content'], $chartString);

        } else {

            $found = parseXML($tag, $requestResultXML[$type][$id]);
            array_push($divContent['content'], ...dataOut($found));

            if(!empty($linkArr)) {

                array_push($divContent['onclick'], ...array_fill(0, 1, "onclick=\"openLinkByContentObject('" . $linkArr[0] . "','" . ec(parseXML($linkArr[1], $requestResultXML[$type][$id])->__toString()) . "')\""));

            }

        }

        if($dateformat != "") {

            foreach ($divContent['content'] as $key=>$content) {

                $strTime = strtotime($content);

                if($strTime) {

                    $formatedDate = date($dateformat, $strTime);

                    if($formatedDate) {
                        $divContent['content'][$key] = $formatedDate;
                    }

                }

            }

        }

        $htmlContent = "";
        $rowCounter = 0;
        $colorCounter = 0;
        $brCounter = 0;

        $maxRowLenght = findMaxDiff($brArr);
        $colCounter = 0;

        if(is_array($tag) && is_array($structureHeadline) && count($tag) == count($structureHeadline)) {

            $cellCounter = 0;

            foreach ($divContent['content'] as $key => $value) {

                $cellColor = "#EEEEEE";

                $htmlContent .= "<tr>";

                $htmlContent .= "<td ". $headerStyle .">";
                $htmlContent .= $key;
                $htmlContent .= "</td>";

                $cellCounter++;
                $array = preg_grep('/^stat_year\.*/', $tag);

                if(count($array) > 0) {

                    $htmlContent .= "<td style='text-align: right; background-color: " . $cellColor . "'";

                    if($divContent['onclick']) {

                        $htmlContent .= " ". $divContent['onclick'][$rowCounter] .">";

                    } else {

                        $htmlContent .= ">";

                    }

                    $htmlContent .= "&euro;&nbsp;" . number_format(floatval(str_replace(',', '.', str_replace('.', '', $value[1]))), 2, ',', '.') . "<br> " . $value[0];
                    $htmlContent .= "</td>";
                    $htmlContent .= "</tr>";

                } else {

                    foreach ($value as $content) {

                        $htmlContent .= "<td style='background-color: " . $cellColor . "'>";
                        $htmlContent .= $content;
                        $htmlContent .= "</td>";
                        $htmlContent .= "</tr>";

                    }

                }

                $rowCounter++;

            }

            $htmlContent .= "<tr style='height: 5px;'></tr>";

        } else if(is_array($tag) && is_array($structureHeadline) && count($tag) != count($structureHeadline)) {

            $html .= "<p style='color: red'>Es ist ein Fehler aufgetreten.</p>";

        } else {

            if($structure == "line") {

                $htmlContent .= "<tr>";
                $htmlContent .=     "<td  ". $headerStyle ." >";
                $htmlContent .=         $structureHeadline;
                $htmlContent .=     "</td>";
                $htmlContent .=     "<td ". $contentStyle .">";

                for($i = 0; $i < count($divContent['content']); $i++) {

                    $htmlContent .= "<div";

                    if($divContent['onclick']) {

                        $htmlContent .= " ". $divContent['onclick'][$i] .">";

                    } else {

                        $htmlContent .= ">";

                    }

                    $htmlContent .= $divContent['content'][$i];

                    if(in_array($i, $brArr)) {

                        $htmlContent .= "<br>";
                    } else {

                        $htmlContent .= " ";
                    }

                    $htmlContent .= "</div>";

                }

                $htmlContent .=     "</td>";
                $htmlContent .= "</tr>";
            } else {

                if($structureHeadline != "") {

                    $htmlContent .= "<tr>";
                    $htmlContent .= "<td colspan='" . $maxRowLenght . "' ". $headerStyle .">";
                    $htmlContent .= $structureHeadline;
                    $htmlContent .= "</td>";
                    $htmlContent .= "</tr>";

                    if(count($divContent['style']) == 0) {

                        $divContent['style'] = array_fill(0, count($divContent['content']), "background-color: #EEEEEE;");

                    }

                    $htmlContent .= "<tr";

                    if($divContent['onclick']) {

                        $htmlContent .= " ". $divContent['onclick'][0] .">";

                    } else {

                        $htmlContent .= ">";

                    }

                } else {

                    $htmlContent .= "<tr";

                    if($divContent['onclick']) {

                        $htmlContent .= " ". $divContent['onclick'][0] .">";

                    } else {

                        $htmlContent .= ">";

                    }

                }

                for($i = 0; $i < count($divContent['content']); $i++) {

                    if(array_key_exists($i, $divContent['style'])) {

                        $style = $divContent['style'][$i];

                    } else {

                        if ($rowCounter % 2 == 0 && $i % 2 == 0) : $style = "background-color: #BBBBFF;"; endif;
                        if ($rowCounter % 2 == 0 && $i % 2 == 1) : $style = "background-color: #CCCCFF;"; endif;
                        if ($rowCounter % 2 == 1 && $i % 2 == 0) : $style = "background-color: #DDDDDD;"; endif;
                        if ($rowCounter % 2 == 1 && $i % 2 == 1) : $style = "background-color: #EEEEEE;"; endif;

                    }

                    if(strpos($tag, "stat_chart") !== false) {

                        $htmlContent .= "<td>" . $divContent['content'][$i] . "</td>";

                    } else if($structureType == "table") {

                        $htmlContent .= "<td";

                        if(in_array($brCounter, $brArr)) {

                            $colspan = $maxRowLenght - $colCounter;

                            $htmlContent .= " colspan='". $colspan ."' style='". $style ."'>" . $divContent['content'][$i] . "</td>";

                        } else {

                            $htmlContent .= " style='". $style ."'>" . $divContent['content'][$i] . "</td>";

                        }

                        $colCounter++;

                        if(in_array($brCounter, $brArr)) {

                            $htmlContent .= "</tr>";
                            $htmlContent .= "<tr";

                            $rowCounter++;

                            if($divContent['onclick']) {

                                if($i+1 < count($divContent['onclick'])) {

                                    $htmlContent .= " ". $divContent['onclick'][$i+1] .">";

                                } else {

                                    $htmlContent .= ">";

                                }

                            } else {

                                $htmlContent .= ">";

                            }

                            $colCounter = 0;

                        }
                    } else {

                        $htmlContent .= "<span style='". $style ."'";

                        if($divContent['onclick']) {

                            $htmlContent .= " ". $divContent['onclick'][$rowCounter] .">";

                        } else {

                            $htmlContent .= ">";

                        }

                        $htmlContent .= $divContent['content'][$i] . "</span>";

                        if(in_array($brCounter, $brArr)) {

                            $htmlContent .= "<br>";
                            $rowCounter++;

                        } else {

                            $htmlContent .= " ";

                        }

                    }

                    if($brCounter == end($brArr)) {

                        $brCounter = 0;

                    } else {

                        $brCounter++;

                    }

                }

                if($structureType == "table") {

                    $htmlContent .= "</tr>";
                    $htmlContent .= "<tr style='height: 5px;'></tr>";

                }

            }

        }

        $html .= $htmlContent;

    } else if($requestResultXML[$type][$id]['xml']->state == "NOT OK") {

        /*  Beispiel Fehlermeldung:
         *
         *  <xml>
         *      <state>NOT OK</state>
         *      <errors>
         *           <error>
         *              <err_no>102</err_no>
         *              <err_desc>
         *                  <![CDATA[Die PLZ ist keiner Zone zugeordnet! [96317]]]>
         *              </err_desc>
         *          </error>
         *      </errors>
         *  </xml>
         * */

        foreach($requestResultXML[$type][$id]['xml']->errors->error as $error) {

            $html .= "<p style='color: red'>Fehler: ". $error->err_no ." " . $error->err_desc . "</p>";
            unset($requestResultXML[$type][$id]['xml']);

        }

    } else {

        $html .= "<p style='color: red'>Es ist ein Fehler aufgetreten.</p>";

    }

    $html .= "</". $structureType .">";

    return mcDecode($html);
}

function findMaxDiff($brArr) {
    $max = 0;

    if(count($brArr) == 1) {

        $max = $brArr[0] + 1;

    } else {

        for($i = 0; $i < count($brArr) - 1; $i++) {

            $diff = abs($brArr[$i] - $brArr[$i+1]);

            if($diff > $max) {

                $max = $diff;

            }
        }

    }

    return $max;
}

function parseXML($tag, $xml) {

    if(strpos($tag, ".") !== false) {

        $tagArray = explode(".", $tag);

        for($i = 0; $i < count($tagArray); $i++) {

            $xml = parseXML($tagArray[$i], $xml);

        }

        return $xml;

    }

    foreach ($xml as $key=>$value) {

        if($key == $tag) {

            return $value;

        } else if(is_object($value) || is_array($value)) {

            $rec = parseXML($tag, $value);

            if($rec != "") {

                return $rec;

            }
        }
    }

    return "";
}

function dataOut($data) {

    $divContent = array();

    if(is_array($data)) {

        foreach ($data as $content) {

            if($content != "") {

                if(is_string($content)) {

                    $divContent[] = $content;

                } else {

                    $divContent[] = $content->__toString();

                }

            } else {

                $divContent[] = "&nbsp;";

            }
        }
    } else {

        if($data != "") {

            if(is_string($data)) {

                $divContent[] = $data;

            } else {

                $divContent[] = $data->__toString();

            }

        } else {

            $divContent[] = "&nbsp;";

        }
    }

    return $divContent;
}

function getVehicles($type, $tag, $id, $requestData) {

    global $requestResultXML;

    $statTag = str_replace("stat_year_", "", $tag);

    $dayFrom = "01";
    $monthFrom = "01";

    $dayTo = "31";
    $monthTo = "12";

    if ($statTag == "last") {

        $lastYear = strtotime(date("Y") . " -1 Year");

        $yearFrom = date("Y", $lastYear);

        $yearTo = date("Y", $lastYear);

    } else if (strpos($statTag, 'last') !== false) {

        $yearPast = explode("_", $statTag);
        $yearPastLast = intval($yearPast[0]) + 1;

        $lastYear = strtotime(date("Y") . " -" . $yearPastLast . " Year");

        $yearFrom = date("Y", $lastYear);

        $yearTo = date("Y", $lastYear);

    } else {

        $yearFrom = date("Y");

        $yearTo = date("Y");

    }

    $hourFrom = "00";
    $minuteFrom = "00";

    $hourTo = "23";
    $minuteTo = "59";

    $requestData['xmlTag'] = "statistic";
    $requestData['idKey'] = "";
    $requestData['key'] = "";
    $requestData['operation'] = "";
    $requestData['dynRequestData'] = array();

    $requestData['dynRequestData']['obj_type'] = $type;
    $requestData['dynRequestData']['obj_id'] = $id;
    $requestData['dynRequestData']['obj_eid'] = $requestResultXML[$type][$id]['xml']->customer->cs_eid;

    if(strpos($tag, "stat_chart") !== false) {

        $requestData['dynRequestData']['statistic_format'] = 61;

        $chartYearsBack = explode(":", $tag);

        $time = strtotime("-". $chartYearsBack[1] ." year", time());

        $dayFrom = "01";
        $monthFrom = "01";
        $yearFrom = date("Y", $time);

        $dayTo = "31";
        $monthTo = "12";
        $yearTo = date("Y");

    }

    $requestData['dynRequestData']['day_from'] = $dayFrom;
    $requestData['dynRequestData']['month_from'] = $monthFrom;
    $requestData['dynRequestData']['year_from'] = $yearFrom;

    $requestData['dynRequestData']['day_to'] = $dayTo;
    $requestData['dynRequestData']['month_to'] = $monthTo;
    $requestData['dynRequestData']['year_to'] = $yearTo;

    $requestData['dynRequestData']['hour_from'] = $hourFrom;
    $requestData['dynRequestData']['minute_from'] = $minuteFrom;

    $requestData['dynRequestData']['hour_to'] = $hourTo;
    $requestData['dynRequestData']['minute_to'] = $minuteTo;

    $key = "statisticReq";
    $skript = "statistic_request.php";

    if (!array_key_exists("statistic", $requestResultXML[$type][$id])) {

        $requestResultText = utf8_encode(createAndSendXMLRec(VOTIAN_SERVER, $key, $skript, createGetReqXML($requestData)));
        $statisticResult = simplexml_load_string($requestResultText, null, LIBXML_NOCDATA);

        if(strpos($tag, "stat_chart") !== false) {

            $requestResultXML[$type][$id]['statistic'][$tag] = $statisticResult;

        } else {

            $requestResultXML[$type][$id]['statistic'][$tag]['count_jobs'] = $statisticResult->count_jobs->__toString();
            $requestResultXML[$type][$id]['statistic'][$tag]['business_volume'] = number_format(floatval(str_replace(',', '.', str_replace('.', ',', $statisticResult->business_volume->__toString()))), 2, ',', '.') . "&euro;";

        }

    } else if (!array_key_exists($tag, $requestResultXML[$type][$id]['statistic'])) {

        $requestResultText = utf8_encode(createAndSendXMLRec(VOTIAN_SERVER, $key, $skript, createGetReqXML($requestData)));
        $statisticResult = simplexml_load_string($requestResultText, null, LIBXML_NOCDATA);

        if(strpos($tag, "stat_chart") !== false) {

            $requestResultXML[$type][$id]['statistic'][$tag] = $statisticResult;

        } else {

            $requestResultXML[$type][$id]['statistic'][$tag]['count_jobs'] = $statisticResult->count_jobs->__toString();
            $requestResultXML[$type][$id]['statistic'][$tag]['business_volume'] = number_format(floatval(str_replace(',', '.', str_replace('.', ',', $statisticResult->business_volume->__toString()))), 2, ',', '.') . "&euro;";

        }

    }

}

function getColor($num) {
    $hash = md5('color' . $num); // modify 'color' to get a different palette
    return array(
        hexdec(substr($hash, 0, 2)), // r
        hexdec(substr($hash, 2, 2)), // g
        hexdec(substr($hash, 4, 2))); //b
}

?>