<?php

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

error_reporting(E_ERROR | E_PARSE);

date_default_timezone_set('Europe/Vienna');

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

$clientId = '';
$stationName = '';
$system = '';

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

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

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

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

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

include('../System/svg-functions.php');
include('../../../__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;
	}
}

/* sort lines by time --------------------------------------------------------------------- */

function SortByTime($a, $b)
{
	$timeA = substr($a['AbfahrtszeitAZBPlan'], 0, 19);
							
	if (isset($a['AbfahrtszeitAZBPrognose']))
	{
		$timeA = substr($a['AbfahrtszeitAZBPrognose'], 0, 19);
	}

	$timeB = substr($b['AbfahrtszeitAZBPlan'], 0, 19);
							
	if (isset($b['AbfahrtszeitAZBPrognose']))
	{
		$timeB = substr($b['AbfahrtszeitAZBPrognose'], 0, 19);
	}

	return strcmp($timeA, $timeB);
}

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

unlink('../../Clients/' . $clientId . '/Data/tts.txt');

$tts = 'Es ist ' . date('H:i') . ' Uhr. Die nächsten Abfahrten: ';

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

unlink('../../Clients/' . $clientId . '/01_Realtime.svg');

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

$timezone = '+01:00'; // + 1h

if (date('I') == 1)
{
	$timezone = '+02:00'; // + 1h summertime
}

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

$input_data = '';

if (file_exists('../../Clients/' . $clientId . '/Data/realtime.xml'))
{
	$input_data = file_get_contents('../../Clients/' . $clientId . '/Data/realtime.xml');
}

if ($input_data != '')
{
	$json = json_encode(simplexml_load_string($input_data, 'SimpleXMLElement', LIBXML_NOCDATA));
	$array = json_decode($json, true);

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

	$departures = $array['AZBNachricht']['AZBFahrplanlage'];

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

		usort($departures, 'SortByTime');
	}

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

	$filter = array();
	
	if (file_exists('../../Clients/' . $clientId . '/Data/filter.php'))
	{
		include('../../Clients/' . $clientId . '/Data/filter.php');
		
		// remove empty items
		
		$filter = array_filter($filter);
	}

	/* ---------------------------------------------------------------------------------------- */
	
	
	$key = 0;
}	

if (1 == 1)
{
	/* ---------------------------------------------------------------------------------------- */
	/* 1_Normal.jpg generieren                                                                    */
	/* ---------------------------------------------------------------------------------------- */

	$line_height = 200;

	$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: "TitilliumWeb-Regular"; src: url(\'./Fonts/TitilliumWeb-Regular.ttf\') format("truetype"); }' . "\n";
	$svg .= '		@font-face { font-family: "TitilliumWeb-SemiBold"; src: url(\'./Fonts/TitilliumWeb-SemiBold.ttf\') format("truetype"); }' . "\n";
	$svg .= '	</style>' . "\n";
	$svg .= '</defs>' . "\n";

	$svg .= '<g id="background">' . "\n";
	$svg .= '	<rect x="0" y="0" width="2560" height="1440" fill="#fff" />' . "\n";
	$svg .= '</g>' . "\n";

	$svg .= '<g id="header">' . "\n";
	$svg .= '	<rect x="0" y="0" width="2560" height="236" fill="#000" />' . "\n";
	$svg .= '	<text x="50" y="160" font-family="TitilliumWeb-SemiBold" font-size="126px" fill="#fff">' . date('H:i') . '</text>' . "\n";
	$svg .= '	<text x="460" y="160" font-family="TitilliumWeb-SemiBold" font-size="126px" fill="#fff">' . $stationName . '</text>' . "\n";
	$svg .= '	<image href="./Images/Logo.png" x="1970" y="50" width="548" height="140" />' . "\n";
	$svg .= '</g>' . "\n";

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

	/* Pro Linie eine Zeile ------------------------------------------------------------------- */

	$y = 236;
	$row = 0;

	if (count($departures) < 1)
	{
		$svg .= '	<rect x="0" y="' . $y . '" width="2560" height="' . $line_height . '" fill="#fff" />' . "\n";
		$svg .= '	<text x="40" y="' . ($y + $line_height - 16) . '" font-family="TitilliumWeb-Regular" font-size="96px" fill="#000">Derzeit keine Abfahrten</text>' . "\n";

		$tts = 'Es ist ' . date('H') . ' Uhr ' . date('i') . '. Derzeit keine Abfahrten';
	}

	$maxRows = 6;


	foreach($departures as $key => $departure)
	{
		if ($row < $maxRows)
		{
			$timePlanned = $departure['AbfahrtszeitAZBPlan'];
			$timePlannedText = date('H:i', strToTime($timePlanned));
			
			$timeReal = '';
			$timeRealText = '';
			
			$time = $timePlanned;
			
			if (isset($departure['AbfahrtszeitAZBPrognose']))
			{
				$timeReal = $departure['AbfahrtszeitAZBPrognose'];
				$timeRealText = date('H:i', strToTime($timeReal));

				$time = $timeReal;
			}

			$serverTime = date('Y-m-d\TH:i:s');

			if ($array['Bestaetigung']['@attributes']['Fehlernummer'] == 0)
			{
				$serverTime = $array['Bestaetigung']['@attributes']['Zst'];
			}

			$countdown = intval((strToTime($time) - strToTime($serverTime)) / 60);

			if (is_array($departure['LinienText']))
			{
				$linie = $departure['LinienText'][0];
			}
			else
			{
				$linie = $departure['LinienText'];
			}
			$direction = $departure['RichtungsID'];
			$endstation = $departure['ZielHst'];
			$endstation_tts = $endstation;

			if (strlen($endstation) > 25)
			{
				$endstation = substr($endstation, 0, 23) . '...';
			}

			$trackId = $departure['FahrtID'];

			$barrierfree = intval($departure['FahrtInfo']['ServiceMerkmal'] == 'Niederflurfahrzeug');

			$platformId = $departure['AbfahrtssteigText'];
			$platformName = $departure['AbfahrtssteigText'];

			$status = $departure['FahrtStatus'];

			if ($status == 'ist')
			{
				$status = 1;
			}
			else
			{
				$status = 0;
			}

			$statusText = $departure['FahrtSpezialText'];


			if ($row % 2 == 0)
			{
				$bgColor = '#fff';
			}
			else
			{
				$bgColor = '#fff';
			}

			if ($countdown >= 0)
			{
				$svg .= '	<rect x="0" y="' . $y . '" width="2560" height="' . $line_height . '" fill="' . $bgColor . '" />' . "\n";

				$svg .= '	<text x="50" y="' . ($y + $line_height - 58) . '" font-family="TitilliumWeb-SemiBold" font-size="120px" fill="#000">' . $linie . '</text>' . "\n";
				$svg .= '	<text x="400" y="' . ($y + $line_height - 58) . '" font-family="TitilliumWeb-SemiBold" font-size="120px" fill="#000">' . $endstation . '</text>' . "\n";

				if ($echtzeit != '')
				{
					$svg .= '	<image href="./Images/Clock.png" x="2100" y="' . ($y + 64) . '" width="72" height="72" />' . "\n";
				}

				if ($timeReal != '')
				{
					$svg .= '	<text x="2150" y="' . ($y + $line_height - 58) . '" font-family="TitilliumWeb-SemiBold" text-anchor="end" font-size="120px" fill="#999">' . substr($timePlanned, 11, 5) . '</text>' . "\n";

					if ($countdown < 5)
					{
						$svg .= '	<text x="2500" y="' . ($y + $line_height - 58) . '" font-family="TitilliumWeb-SemiBold" text-anchor="end" font-size="120px" fill="#000">' . $countdown . ' min</text>' . "\n";
						
						if ($row < 2)
						{
							if ($countdown == 1)
							{
								$tts .= 'Linie ' . $linie . ' nach ' . $endstation_tts . ' in ' . $countdown . ' Minute. ';
							}
							else
							{
								$tts .= 'Linie ' . $linie . ' nach ' . $endstation_tts . ' in ' . $countdown . ' Minuten. ';
							}
						}
					}
					else
					{
						$svg .= '	<text x="2500" y="' . ($y + $line_height - 58) . '" font-family="TitilliumWeb-SemiBold" text-anchor="end" font-size="120px" fill="#000">' . substr($timeReal, 11, 5) . '</text>' . "\n";

						if ($row < 2)
						{
							$tts .= 'Linie ' . $linie . ' nach ' . $endstation_tts . ' um ' . substr($time, 11, 5) . ' Uhr. ';
						}
					}
				}
				else
				{
					if ($countdown < 5)
					{
						$svg .= '	<text x="2150" y="' . ($y + $line_height - 58) . '" font-family="TitilliumWeb-SemiBold" text-anchor="end" font-size="120px" fill="#000">' . $countdown . ' min</text>' . "\n";

						if ($row < 2)
						{
							if ($countdown == 1)
							{
								$tts .= 'Linie ' . $linie . ' nach ' . $endstation_tts . ' in ' . $countdown . ' Minute. ';
							}
							else
							{
								$tts .= 'Linie ' . $linie . ' nach ' . $endstation_tts . ' in ' . $countdown . ' Minuten. ';
							}
						}
					}
					else
					{
						$svg .= '	<text x="2150" y="' . ($y + $line_height - 58) . '" font-family="TitilliumWeb-SemiBold" text-anchor="end" font-size="120px" fill="#000">' . substr($timePlanned, 11, 5) . '</text>' . "\n";

						if ($row < 2)
						{
							$tts .= 'Linie ' . $linie . ' nach ' . $endstation_tts . ' um ' . substr($time, 11, 5) . ' Uhr. ';
						}
					}
				}

				$svg .= '	<rect x="0" y="' . ($y + $line_height - 2) . '" width="2560" height="2" fill="#333" />' . "\n";

				$y += $line_height;

				$row++;
			}
		}
	}

	// 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);
	}
	
	$svg .= '</g>' . "\n";

	if (file_exists('../../Clients/' . $clientId . '/Data/InfoText.xml'))
	{
		include('./00_Infotext.php');
	}

	$svg .= '</svg>' . "\n";
	
	file_put_contents('../../Clients/' . $clientId . '/01_Realtime.svg', $svg);

	// header( 'Content-type: image/svg+xml');

	// print($svg);

	if ($tts != '')
	{
		file_put_contents('../../Clients/' . $clientId . '/Data/tts.txt', $tts);
	}

    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 />');
}
else
{
	print('Derzeit keine Abfahrten!<br />');
}

?>