<?php

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

error_reporting(E_ALL);

date_default_timezone_set('Europe/Vienna');

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

$clientId = '';
$stationName = '';
$system = '';
$gate = '';
$azbid = '';

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

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'];
}

if (isset($_GET['aboId'])) {
	if (str_contains($_GET['aboId'], ',')) {
		$azbidList = explode(',', $_GET['aboId']);
	} else {
		$azbidList = array($_GET['aboId']);
	}
} else {
    $azbidList = [];
}

print_r($_GET);
echo"\n\n";




// 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;
    }
}

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

if (file_exists('../../Clients/' . $clientId . '/01_Realtime.svg')) {
  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) {

    // Layout values
    $fontSize = 100;
    $iconSize = $fontSize; //70;
    $padding = 20;

    //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

    $departures = [];

    foreach ($departureSets as $departureSet) {

        $fps = $departureSet['AZBFahrplanlage'];


        if (isset($fps['AZBID'])) {
            $fps = [$fps];
        }

        foreach ($fps as $fahrplanlage) {
		echo "fahrplanlage.AZBID=".$fahrplanlage['AZBID']." vs ".print_r($azbidList, true)."<br/>";
            if (in_array($fahrplanlage['AZBID'], $azbidList)) {
                $departures[] = $fahrplanlage;
	    } else {
		echo "NOT MATCHING fahrplanlage.AZBID=".$fahrplanlage['AZBID']." vs ".print_r($azbidList, true)."<br/>";
	    }
        }
    }

    print_r($departureSets);


    // 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
    //{


     $clockImage = "clock_".str_pad($hour, 2, '0', STR_PAD_LEFT).str_pad($minute*5, 2, '0', STR_PAD_LEFT).".png";

        $line_height = 180;

        $svg  = '';
        $svg .= '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $svg .= '<svg xmlns="http://www.w3.org/2000/svg" width="2560" height="1440" viewBox="0 0 2560 1440">' . "\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; fill:white; font-weight: normal; fill-opacity:1.0; stroke-opacity:1.0;}' . "\n";
        $svg .= '		@font-face { font-family: "Glober-Bold"; src: url(\'./Fonts/Glober-Bold.ttf\') format("truetype");  font-weight: bold; fill:white; font-weight: normal; fill-opacity:1.0; stroke-opacity:1.0;}' . "\n";
        $svg .= '		@font-face { font-family: "Glober-Heavy"; src: url(\'./Fonts/Glober-Heavy.ttf\') format("truetype");  font-weight: 900; fill:white; font-weight: normal; fill-opacity:1.0; stroke-opacity:1.0;}' . "\n";
        $svg .= '	</style>' . "\n";
        $svg .= '</defs>' . "\n";


        $svg .= '<g id="background">' . "\n";
        $svg .= '	<rect x="0" y="0" width="2560" height="1440" fill="white" />' . "\n";
        $svg .= '	<image href="./Images/Haltestelle.png" x="30" y="10" width="120" height="120" />' . "\n";
        $svg .= '	<text x="190" y="120" font-family="Glober-Bold" font-size="120px" fill="#424242">' . $stationName . '</text>' . "\n";
        $svg .= '	<image href="./Images/Clock.png" x="1850" y="10" width="120" height="120" />' . "\n";
        $svg .= '	<text x="2200" y="100" text-anchor="end" font-family="Glober-Bold" font-size="72px" fill="#424242">' . date('H:i') . '</text>' . "\n";
        $svg .= '	<image href="./Images/Logo.png" x="2250" y="10" width="290" height="120" />' . "\n";
        $svg .= '</g>' . "\n";


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

        // Black rectangle + "Abfahrt"
        $rect_width = 800;
        $rect_height = 230;
        $rect_x = 1800;
        $rect_y = 180;

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


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


        $y = 330;

        $row = 0;

        if (count($departures) < 1) {
            $svg .= '	<rect x="0" y="' . $y . '" width="2560" height="' .$line_height . '" fill="#424242" />' . "\n";
            $svg .= '	<text x="80" y="' . ($y + $line_height - 54) . '" font-family="Glober" font-size="'.$fontSize.'px" fill="white">Derzeit keine Abfahrten</text>' . "\n";
            //$svg .= '	<text x="80" y="270" font-family="Glober" font-size="'.$fontSize.'px" 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;
        $maxLines = 6;

        if(count($departures) > $maxLines)
        {
            $departures = array_slice($departures,0,$maxLines);
        }

        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) . '...';
                    }

                    $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="80" y="' . ($y + 15) . '" width="' . ($line_height - 32) . '" height="' . ($line_height - 32) . '" fill="#808080" rx="5" ry="5" />' . "\n";
                    $linieNameBB = getTextBoundingBox($iconSize, 0, dirname(__FILE__).'/Fonts/Glober-Bold.ttf', escapeForSvg($linie));
                    $svg .= '       <text x="'.(75 + ($line_height - 32) / 2 - $linieNameBB['width'] / 2).'" y="' . ($y + $line_height - 54) . '" text-anchor="start" font-family="Glober-Bold" font-size="' . $iconSize . 'px" fill="white" font-weight="bold">' . escapeForSvg($linie) . '</text>' . "\n";
                    // display rad halter icon
                    // strassenbahn
                    /*if (str_contains($verkehrsmittel, "enbahn")) {
                    $stationNameBB = getTextBoundingBox($fontSize, 0, dirname(__FILE__).'/Fonts/Glober-Regular.ttf', $ziel);
                    print_r($stationNameBB);
                    $radIconX = 400 + $stationNameBB["width"];
                    $svg .= '<image x="'.$radIconX.'" y="'.($y ).'" width="'.$line_height.'" height="'.$line_height.'" href="./Images/Rad.png" /> ';
                    }*/
                    $svg .= '       <text x="350" y="' . ($y + $line_height - 54) . '" font-family="Glober" font-size="' . $fontSize . '" fill="white" font-weight="bold">' . escapeForSvg($ziel) . '</text>' . "\n";

                    if($countdown <= 30) {
                        $svg .= '       <text x="2430" y="' . ($y + $line_height - 54) . '" font-family="Glober" text-anchor="end" font-size="' . $fontSize . '" fill="white" font-weight="bold">' . escapeForSvg($countdown) . '´</text>' . "\n";
                    }
                    else {
                        $svg .= '       <text x="2430" y="' . ($y + $line_height - 54) . '" font-family="Glober" text-anchor="end" font-size="' . $fontSize . '" fill="white" font-weight="bold">' . escapeForSvg($zeit) . '</text>' . "\n";
                    }
                    
                    $svg .= '   </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 = 185;
                    $y += $abstand;
                    $row++;
                }
            }
        }


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

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

	// 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);
	    }
	}

        file_put_contents('../../Clients/' . $clientId . '/01_Realtime.svg', $svg);
        print('../../Clients/' . $clientId . '/01_Realtime.svg wurde erstellt!<br />');
        /* Bild in die Queue stellen -------------------------------------------------------------- */
        sendImagePart($system, $clientId, '01_Realtime.svg', '01_NoData.svg', $tts, '', '', 0, 0, '', $svg);
        print('../../Clients/' . $clientId . '/01_Realtime.svg wurde in die Queue gestellt!<br />');



?>

