<?php

/* ---------------------------------------------------------------------------------------- */

error_reporting(E_ALL);

date_default_timezone_set('Europe/Vienna');

/* ---------------------------------------------------------------------------------------- */

$clientId = '';
$stationName = '';
$system = '';
$gate = '';
$aboId = "";

/* ---------------------------------------------------------------------------------------- */

if (isset($_GET['clientId'])) {
    $clientId = $_GET['clientId'];
}

if (isset($_GET['stationName'])) {
    $stationName = $_GET['stationName'];
}

if (isset($_GET['system'])) {
    $system = $_GET['system'];
}

if (isset($_GET['gate'])) {
    $gate = $_GET['gate'];
}

// can be received as single value or comma separated list
if (isset($_GET['aboId'])) {
    $azbidList = explode(',', $_GET['aboId']);
} else {
    $azbidList = [];
}


// das brauchma später
function escapeForSvg($text)
{
    return htmlspecialchars($text, ENT_QUOTES | ENT_XML1, 'UTF-8');
}


/* ---------------------------------------------------------------------------------------- */

include_once('../System/svg-functions.php');
include_once('../../../__dcdi/sendImagePart.php');

$fontDirectory = getcwd() . '/../Fonts/';

/* ---------------------------------------------------------------------------------------- */

if (!function_exists('array_key_first')) {
    function array_key_first($arr)
    {
        if (is_array($arr)) {
            foreach ($arr as $key => $unused) {
                return $key;
            }
        }

        return NULL;
    }
}

/* ---------------------------------------------------------------------------------------- */

unlink('../../Clients/' . $clientId . '/01_Realtime.svg');
if (file_exists('../../Clients/' . $clientId . '/Data/tts.txt')) {
  unlink('../../Clients/' . $clientId . '/Data/tts.txt');
}

/* ---------------------------------------------------------------------------------------- */


$input_data = '';

if (file_exists('../../Clients/dfiData.xml')) {
    // if filetime > 2h, then do not process file (VDV can stay as is for longer time)!

    $ts = filemtime('../../Clients/dfiData.xml');

    if ((time() - $ts) > 3600) {
        unlink('../../Clients/' . $clientId . '/01_Realtime_Blind.svg');
        unlink('../../Clients/' . $clientId . '/01_Realtime.svg');

        // exit;
    }

    // sometimes file is in access by VDV-service - so re-read, until we get data - but only 3 times

    $retry = 0;

    while (($input_data == '') and ($retry < 3)) {
        $input_data = file_get_contents('../../Clients/dfiData.xml');

        $retry++;

        sleep(1);
    }
}


if (1 == 1) {

    //xml to json-->(xml to array funktioniert nicht ohne json umweg)
    $json = json_encode(simplexml_load_string($input_data, 'SimpleXMLElement', LIBXML_NOCDATA));
    //json to array
    $array = json_decode($json, true);

    /* ---------------------------------------------------------------------------------------- */
    /* Daten aus JSON einlesen
	/* ---------------------------------------------------------------------------------------- */

    $departures = array();

    $departureSets = $array['AZBNachricht'];

    // Wenn nur ein ABO, dann fehlt die Index-Ebene ($key), daher diese einfügen

    if (array_key_first($departureSets) === 0) {
        // Alles gut - departureSets ist ein indiziertes Array
    } else {
        if (count($departureSets) > 0) {
            $departureSet = $departureSets;
            $departureSets = array();
            $departureSets[0] = $departureSet;
        }
    }

    // Nur Abfahrten für das gewünschte ABO einlesen
    /* foreach ($departureSets as $key => $departureSet) {
        if ($departureSet['@attributes']['AboID'] == $aboId) {
            $departures = $departureSet['AZBFahrplanlage'];
        }
    }*/

    foreach ($departureSets as $departureSet) {
       $fps = $departureSet['AZBFahrplanlage'];
       if (isset($fps['AZBID'])) {
           $fps = [$fps];
       }
       foreach ($fps as $fahrplanlage) {
           if (in_array($fahrplanlage['AZBID'], $azbidList)) {
               $departures[] = $fahrplanlage;
           }
       }
    }


    // Wenn nur eine Abfahrt, dann fehlt die Index-Ebene ($key), daher diese einfügen

    if (array_key_first($departures) === 0) {
        // Alles gut - departures ist ein indiziertes Array
    } else {
        if (count($departures) > 0) {
            $departure = $departures;
            $departures = array();
            $departures[0] = $departure;
        }
    }

    // Countdown für Sortierung berechnen und departures ausfiltern ( < 0 )

    $newDepartures = array();

    echo "<pre>";
    print_r($departures);
    echo "</pre>";


    foreach ($departures as $key => $departure) {
        $soll = trim($departure['AbfahrtszeitAZBPlan']);
        $ist = trim($departure['AbfahrtszeitAZBPrognose']);

        $zeit = $soll;

        if ($ist != '') {
            $zeit = $ist;
        }

        //countdown berechnen
        $countdown = ceil((strToTime($zeit) - time()) / 60);

        if (($countdown >= 0) and ($countdown != '-0')) {
            $departure['Countdown'] = $countdown;
            $departure['Abfahrtszeit'] = $zeit;

            $newDepartures[] = $departure;
        }
    }

    $departures = $newDepartures;

    /* sort departures by countdown ----------------------------------------------------------- */

    function SortByCountdown($a, $b)
    {
        if ($a['Countdown'] == $b['Countdown']) {
            return 0;
        }
        return ($a['Countdown'] < $b['Countdown']) ? -1 : 1;

        // for Strings only:
        // return strcmp($a['Countdown'], $b['Countdown']);
    }

    usort($departures, 'SortByCountdown');


    // determine correct clock

    $date = date('H:i'); // returns a string: 12:30 

    $dateArray = explode(":", $date);
    $hour = (int)$dateArray[0];
    $minute = (int)$dateArray[1];



    // if (is_array($departures) and (count($departures) > 0)) // Ausgabe, wenn mindestens eine Abfahrt in den nächsten 90 Minuten
    // {


    $line_height = 150;
	$line_height_blind = 320;

	$svgBlind = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
    $svgBlind .= '<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="1600" viewBox="0 0 1200 1600">' . "\n";
    $svgBlind .= '<defs>' . "\n";
    $svgBlind .= '	<style type="text/css">' . "\n";
    $svgBlind .= '		@font-face { font-family: "Glober"; src: url(\'./Fonts/Glober-Bold.ttf\') format("truetype");  font-weight: bold;}' . "\n";
    $svgBlind .= '	</style>' . "\n";
    $svgBlind .= '</defs>' . "\n";
    $svgBlind .= '<g>' . "\n";
    $svgBlind .= '	<rect x="0" y="0" width="1200" height="1600" fill="#000" />' . "\n";

    $svg  = '';
    $svg .= '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    $svg .= '<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="1600" viewBox="0 0 1200 1600">' . "\n";
    $svg .= '<defs>' . "\n";
    $svg .= '	<style type="text/css">' . "\n";
    $svg .= '		@font-face { font-family: "Glober"; src: url(\'./Fonts/Glober-Regular.ttf\') format("truetype");   font-weight: normal;}' . "\n";
    $svg .= '		@font-face { font-family: "Glober-Bold"; src: url(\'./Fonts/Glober-Bold.ttf\') format("truetype");  font-weight: bold;}' . "\n";
    $svg .= '		@font-face { font-family: "Glober-Heavy"; src: url(\'./Fonts/Glober-Heavy.ttf\') format("truetype");  font-weight: 900;}' . "\n";
    $svg .= '	</style>' . "\n";
    $svg .= '</defs>' . "\n";


    $svg .= '<g id="background">' . "\n";
    $svg .= '	<rect x="0" y="0" width="1200" height="1600" fill="white" />' . "\n";
    $svg .= '	<image href="./Images/Haltestelle.png" x="30" y="10" width="100" height="100" />' . "\n";
    $svg .= '	<text x="170" y="90" font-family="Glober-Bold" font-size="72px" fill="#424242" font-weight="900">' . $stationName . '</text>' . "\n";
    $svg .= '	<text x="670" y="95" text-anchor="start" font-family="Glober" font-size="72px" fill="#424242" font-weight="800">' . date('H:i') . '</text>' . "\n";


    $svg .= '	<image href="./Images/Logo.png" x="900" y="10" width="280" height="116" />' . "\n";
    $svg .= '</g>' . "\n";


    $svg .= '<g id="header">' . "\n";
    $svg .= '	<text x="80" y="220" font-family="Glober" font-size="50px" fill="#424242" font-weight="600">Linie</text>' . "\n";
    $svg .= '	<text x="250" y="220" font-family="Glober" font-size="50px" fill="#424242" font-weight="600">Richtung</text>' . "\n";

    // Black rectangle + "Abfahrt"
    $rect_width = 800;
    $rect_height = 200;
    $rect_x = 900;
    $rect_y = 160;

    $svg .= '	<rect x="650" y="' . $rect_y . '" width="' . $rect_width . '" height="' . $rect_height . '" fill="#424242" rx="10" ry="10" />' . "\n";
    $svg .= '	<text x="1150" y="' . ($rect_y + 65) . '" text-anchor="end" font-family="Glober" font-size="50px" fill="white" font-weight="600">Abfahrt</text>' . "\n";
    $svg .= '</g>' . "\n";


    $svg .= '<g id="data">' . "\n";


    $y = 250;
    $yBlind = 0;

    $row = 0;

    if (count($departures) < 1) {
        $svg .= '	<rect x="0" y="' . $y . '" width="1200" height="' . $line_height . '" fill="#424242" />' . "\n";
        //$svg .= '	<text x="40" y="' . ($y + $line_height - 8) . '" font-family="Glober" font-size="70px" fill="white">Derzeit keine Abfahrten</text>' . "\n";
        $svg .= '	<text x="80" y="' . ($y + $line_height - 52) . '" font-family="Glober" font-size="70px" fill="white">Derzeit keine Abfahrten</text>' . "\n";
        $tts = 'Es ist ' . date('H') . ' Uhr ' . date('i') . '. Derzeit keine Abfahrten';
	} else {
	    $tts = 'Es ist ' . date('H:i') . ' Uhr. Die nächsten Abfahrten: ';
	}

        $maxRows = 12;

        foreach ($departures as $key => $departure) {
            /* Check filter ---------------------------------------------------------------- */
            $filterOK = false;

            if (isset($filter)) {
                $filterProcessed = 0;

                foreach ($filter as $filterValues) {
                    $filterCount = 0;
                    $filterPassed = 0;

                    foreach ($filterValues as $filterKey => $filterValue) {
                        if ($filterValue != '') {
                            $filterProcessed++;
                            $filterCount++;

                            if ($departure[$filterKey] == $filterValue) {
                                $filterPassed++;
                            }
                        }
                    }

                    if (($filterCount > 0) && ($filterCount == $filterPassed)) {
                        $filterOK = true;
                    }
                }

                if ($filterProcessed == 0) {
                    $filterOK = true;
                }
            } else {
                $filterOK = true;
            }

            /* ----------------------------------------------------------------------------- */


            if ($filterOK) {
                $maxRows = 7;

                if (file_exists('../../Clients/' . $clientId . '/Data/InfoText.xml')) {
                    $maxRows = 5;
                }

                if ($row < $maxRows) {
                    $linie = html_entity_decode($departure['LinienText']);
                    $ziel = html_entity_decode($departure['RichtungsText']);
                    // $steig = $departure['HaltePositionsText'];
                    $soll = trim($departure['AbfahrtszeitAZBPlan']);
                    $ist = trim($departure['AbfahrtszeitAZBPrognose']);
                    $countdown = trim($departure['Countdown']);
					
                    if ($countdown == '-0')
					{
						$countdown = 0;
					}

					if ($countdown < 0)
					{
						$countdown = 0;
					}
                    
                    $verkehrsmittel = $departure['FahrtInfo']['ProduktID'];

                    // Zeitanteil extrahieren
                    $zeit = trim($departure['Abfahrtszeit']);
                    $zeit = substr($zeit, 11, 5);

                    /*if (is_array($steig)) {
                        $steig = '';
                    } else {
                        $steig = html_entity_decode($steig);
		            }*/

                    if ($ist == $soll) {
                        $ist = '';
                    }

                    if (strlen($ziel) > 30) {
                        $ziel = substr($ziel, 0, 27) . '...';
                    }

                    // Layout values
                    $iconSize = 70;
                    $padding = 20;
                    $fontSize = 64;
                    $lineHeight = intval($line_height - 16 + $padding); // override if needed

                    $svg .= '   <g id="row-' . $row . '">' . "\n";
                    $svg .= '       <rect x="0" y="' . $y . '" width="2600" height="' . $lineHeight . '" fill="#424242" rx="5" ry="5" />' . "\n";
                    $svg .= '       <rect x="60" y="' . ($y + 15) . '" width="' . ($line_height - 28) . '" height="' . ($line_height - 32) . '" fill="#808080" rx="5" ry="5" />' . "\n";
                    $svg .= '       <text x="120" y="' . ($y + $line_height - 52) . '" width="118" height="118"  text-anchor="middle" font-family="Glober" font-size="' . $iconSize . 'px" fill="white" font-weight="bold">' . escapeForSvg($linie) . '</text>' . "\n";
                    $svg .= '       <text x="250" y="' . ($y + $line_height - 46) . '" font-family="Glober" font-size="' . $fontSize . '" fill="white" font-weight="bold">' . escapeForSvg($ziel) . '</text>' . "\n";
		            // display rad halter icon
                    // strassenbahn
                    /*if (str_contains($verkehrsmittel, "enbahn")) {
                        $stationNameBB = getTextBoundingBox($iconSize, 0, dirname(__FILE__).'/Fonts/Glober-Regular.ttf', $ziel);
                        print_r($stationNameBB);
                        $radIconX = 250 + $stationNameBB["width"];
                        $svg .= '<image x="'.$radIconX.'" y="'.($y ).'" width="'.$line_height.'" height="'.$line_height.'" href="./Images/Rad.png" /> ';
                    }*/

                    if($countdown <= 30) {
                        $svg .= '       <text x="1150" y="' . ($y + $line_height - 46) . '" font-family="Glober" font-size="' . $fontSize . '" fill="white" font-weight="bold" text-anchor="end">' . escapeForSvg($countdown) . '´</text>' . "\n";
                    }
                    else {
                        $svg .= '       <text x="1150" y="' . ($y + $line_height - 46) . '" font-family="Glober" font-size="' . $fontSize . '" fill="white" font-weight="bold" text-anchor="end">' . escapeForSvg($zeit) . '</text>' . "\n";
                    }
                    
                    $svg .= '   </g>' . "\n";


                    // ------------------------------- blinden svg --------------------------------
                    $svgBlind .= '   <text x="340" y="' . ($yBlind + 100) . '" font-family="Glober" text-anchor="end" font-size="90px" fill="#fff">' . escapeForSvg($linie) . '</text>' . "\n";
                    $svgBlind .= '   <text x="380" y="' . ($yBlind + 100) . '" font-family="Glober" font-size="90px" fill="#fff">' . escapeForSvg($ziel) . '</text>' . "\n";

                    if($countdown <= 30) {
                        $svgBlind .= '   <text x="340" y="' . ($yBlind + 220) . '" font-family="Glober" text-anchor="end" font-size="130px" fill="#fff">' . escapeForSvg($countdown) . '´</text>' . "\n";
                    }
                    else {
                        $svgBlind .= '   <text x="340" y="' . ($yBlind + 220) . '" font-family="Glober" text-anchor="end" font-size="130px" fill="#fff">' . escapeForSvg($zeit) . '</text>' . "\n";
                    }
                                                
                    $svgBlind .= '   <rect x="0" y="' . ($yBlind + $line_height_blind) . '" width="1200" height="1" fill="#fff" />' . "\n";


                    //$svgBlind .= '<g id="row-' . $row . '">' . "\n";
                            //$svgBlind .= '<text x="130" y="' . ($y + $line_height * 2 - 52) . '" text-anchor="middle" font-family="Glober" font-size="' . $fontSize * 2 . 'px" fill="white" font-weight="bold">' . escapeForSvg($linie) . '</text>' . "\n";
                            //$svgBlind .= '<text x="300" y="' . ($y + $line_height * 2 - 46) . '" font-family="Glober" font-size="' . $fontSize * 2 . '" fill="white" font-weight="bold">' . escapeForSvg($ziel) . '</text>' . "\n";
                            //$svgBlind .= '<text x="1150" y="' . ($y + $line_height * 2 - 46) . '" font-family="Glober" font-size="' . $fontSize * 2 . '" fill="white" font-weight="bold" text-anchor="end">' . escapeForSvg($zeit) . '</text>' . "\n";
                    //$svgBlind .= '</g>' . "\n";

                    // tts hinzufügen aber nur  3 einträge                                                      
                    if ($row < 3) {
                        if ($countdown <= 30)
						{
							if ($countdown == 1)
							{
								$tts .= 'Linie ' . $linie . ', nach ' . $ziel . ', in ' . html_entity_decode($countdown) . ' Minute, ';
							}
							else
							{
								$tts .= 'Linie ' . $linie . ', nach ' . $ziel . ', in ' . html_entity_decode($countdown) . ' Minuten, ';
							}
						} else {
                            $tts .= 'Linie ' . $linie . ' nach ' . $ziel . ' um ' . $zeit . ' Uhr. ';
                        }
                    }

                    $abstand = 155;
		            $y += $abstand;
		            $yBlind += $line_height_blind;
                    $row++;
                }
            }
        }


        $svg .= '</g>' . "\n";

        if (file_exists('../../Clients/' . $clientId . '/Data/InfoText.xml'))
        {
            include('./00_Infotext.php');
        }
        
        $svg .= '</svg>' . "\n";

        $svgBlind .= '</g>' . "\n";
        $svgBlind .= '</svg>' . "\n";

        file_put_contents('../../Clients/' . $clientId . '/01_Realtime.svg', $svg);
        file_put_contents('../../Clients/' . $clientId . '/01_Realtime_Blind.svg', $svgBlind);

        print('../../Clients/' . $clientId . '/01_Realtime.svg wurde erstellt!<br />');
        print('../../Clients/' . $clientId . '/01_Realtime_Blind.svg wurde erstellt!<br />');

        /* Bild in die Queue stellen -------------------------------------------------------------- */

        sendImagePart($system, $clientId, '01_Realtime.svg', '01_NoData.svg', '', '', '', 0, 0, '', $svg);


	// wenn eine TTS-Bibliothek vorhanden ist, die Items einlesen und im TTS ersetzen
if (file_exists('../../Clients/ttsBibliothek.txt')) {
    $tts_bibliothek = file('../../Clients/ttsBibliothek.txt');

    if (count($tts_bibliothek) > 0) {
        foreach ($tts_bibliothek as $tts_key => $tts_value) {
            $tts_item = explode('=', $tts_value);
            if (trim($tts_item[0]) != '') {
                $tts = str_replace($tts_item[0], $tts_item[1], $tts);
            }
        }
    }
}

// if TTS is set, then make it JSON compatible (remove CR, LF, TAB, " and \ )
if ($tts != '') {
    $tts = str_replace("\r", '', $tts);
    $tts = str_replace("\n", '', $tts);
    $tts = str_replace("\t", '', $tts);
    $tts = str_replace('"', '', $tts);
    $tts = str_replace('/', '', $tts);
}
if ($tts != '') {
        file_put_contents('../../Clients/' . $clientId . '/Data/tts.txt', $tts);
}
        sendImagePart($system, $clientId, '01_Realtime_Blind.svg', '01_NoData_Blind.svg', $tts, '', '', 0, 0, '', $svgBlind);

        print('../../Clients/' . $clientId . '/01_Realtime.svg wurde in die Queue gestellt!<br />');
    //} else {
    //    print('Derzeit keine Abfahrten!<br />');
    //}

}
