<?php

$stopId = $_GET['stopId'];
$clientId = $_GET['clientId'];

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

function prettyPrintJson($json)
{
    $result = '';
    $level = 0;
    $in_quotes = false;
    $in_escape = false;
    $ends_line_level = NULL;
    $json_length = strlen( $json );

    for( $i = 0; $i < $json_length; $i++ ) {
        $char = $json[$i];
        $new_line_level = NULL;
        $post = "";
        if( $ends_line_level !== NULL ) {
            $new_line_level = $ends_line_level;
            $ends_line_level = NULL;
        }
        if ( $in_escape ) {
            $in_escape = false;
        } else if( $char === '"' ) {
            $in_quotes = !$in_quotes;
        } else if( ! $in_quotes ) {
            switch( $char ) {
                case '}': case ']':
                    $level--;
                    $ends_line_level = NULL;
                    $new_line_level = $level;
                    break;

                case '{': case '[':
                    $level++;
                case ',':
                    $ends_line_level = $level;
                    break;

                case ':':
                    $post = " ";
                    break;

                case " ": case "\t": case "\n": case "\r":
                    $char = "";
                    $ends_line_level = $new_line_level;
                    $new_line_level = NULL;
                    break;
            }
        } else if ( $char === '\\' ) {
            $in_escape = true;
        }
        if( $new_line_level !== NULL ) {
            $result .= "\n".str_repeat( "\t", $new_line_level );
        }
        $result .= $char.$post;
    }

    return $result;
}

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

$json = '';

$data = '{"id":"7gmehnu82xc6864k","ver":"1.72","lang":"deu","auth":{"type":"AID","aid":"5vHavmuWPWIfetEe"},"client":{"id":"OEBB","type":"WEB","name":"webapp","l":"vs_webapp","v":21506},"formatted":false,"ext":"OEBB.14","svcReqL":[{"req":{"jnyFltrL":[{"type":"PROD","mode":"INC","value":7167}],"pslMode":"IMP","stbLoc":{"name":"Mödling","lid":"A=1@O=Mödling@X=16295582@Y=48085862@U=81@L=1131717@B=1@p=1726134824@","extId":"1131717","eteId":"sq|S|Mödling|1131717|16295582|48085862"},"type":"DEP","sort":"PT","maxJny":100},"meth":"StationBoard","id":"1|6|"}]}';

// suppress https certification check (otherwise $json is empty, because of outdated certificate)
				
//$postdata = http_build_query($data);

$arrContextOptions=array(
 'http'=>array(
		'method'  => 'POST',
		'header'  => 'Content-type: application/x-www-form-urlencoded',
		'content' => $data
	),
  'ssl'=>array(
		'verify_peer'=>false,
		'verify_peer_name'=>false,
	),
);  


$json = file_get_contents('https://fahrplan.oebb.at/bin/mgate.exe?rnd=' . $stopId, false, stream_context_create($arrContextOptions));

if ($json != '')
{
	//file_put_contents('../Clients/' . $clientId . '/Data/realtime.json', $json);

	//json to array
	$array = json_decode($json, true);

	$locL = $array['svcResL']['0']['res']['common']['locL'];
	$prodL = $array['svcResL']['0']['res']['common']['prodL'];
	$remL = $array['svcResL']['0']['res']['common']['remL'];
	$jnyL = $array['svcResL']['0']['res']['jnyL'];

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

	$departures = array();
	
	foreach($jnyL as $journey)
	{
		$departure['linie'] = $prodL[$journey['prodX']]['name'];
		$departure['ziel'] = $journey['dirTxt'];
		$departure['steig'] = $journey['stbStop']['dPltfS']['txt'];
		$departure['soll'] = substr($journey['date'],0,4) . '-' . substr($journey['date'],4,2) . '-' . substr($journey['date'],6,2) . ' ' . substr($journey['stbStop']['dTimeS'],0,2) . ':' . substr($journey['stbStop']['dTimeS'],2,2) . ':' . substr($journey['stbStop']['dTimeS'],4,2);
		$departure['zeit'] = $departure['soll'];
		$departure['perlschnur'] = $journey['stopL'];
		
		if ($journey['stbStop']['dTimeR'] != '')
		{
			$departure['ist'] = substr($journey['date'],0,4) . '-' . substr($journey['date'],4,2) . '-' . substr($journey['date'],6,2) . ' ' . substr($journey['stbStop']['dTimeR'],0,2) . ':' . substr($journey['stbStop']['dTimeR'],2,2) . ':' . substr($journey['stbStop']['dTimeR'],4,2);
			$departure['zeit'] = $departure['ist'];
		}

		//countdown berechnen
		$countdown = ceil((strToTime($departure['zeit']) - time()) / 60);
		
		if (($countdown >= 0) and ($countdown != '-0'))
		{
			$departure['countdown'] = $countdown;

			$departures[] = $departure;
		}
	}

	print('<table border="1">');
	print('<tr><th>Linie</th><th>Ziel</th><th>Soll</th><th>Ist</th><th>Steig</th><th>Minuten</th><th>Perlschnur</th></tr>');

	foreach ($departures as $departure)
	{
		if (substr($departure['linie'],0,3) != 'Bus')
		{
			$perlschnur = '';
			
			foreach ($departure['perlschnur'] as $stop)
			{
				$perlschnur .= ' ~ ' . $locL[$stop['locX']]['name'];
			}

			print('<tr><td>' . $departure['linie'] . '</td><td>' . $departure['ziel'] . '</td><td>' . $departure['soll'] . '</td><td>' . $departure['ist'] . '</td><td>' . $departure['steig'] . '</td><td>' . $departure['countdown'] . '</td><td>' . $perlschnur . '</td></tr>');
		}
	}

	print('</table>');

	print('<hr />');
	
	//header('Content-Type: application/json');

	print('<h1>https://fahrplan.oebb.at/bin/mgate.exe?rnd=' . $stopId . '</h1>');

	print('<h3>Request (POST)</h3>');
	print('<pre>{"id":"7gmehnu82xc6864k","ver":"1.72","lang":"deu","auth":{"type":"AID","aid":"5vHavmuWPWIfetEe"},"client":{"id":"OEBB","type":"WEB","name":"webapp","l":"vs_webapp","v":21506},"formatted":false,"ext":"OEBB.14","svcReqL":[{"req":{"jnyFltrL":[{"type":"PROD","mode":"INC","value":7167}],"pslMode":"IMP","stbLoc":{"name":"Mödling","lid":"A=1@O=Mödling@X=16295582@Y=48085862@U=81@L=1131717@B=1@p=1726134824@","extId":"1131717","eteId":"sq|S|Mödling|1131717|16295582|48085862"},"type":"DEP","sort":"PT","maxJny":100},"meth":"StationBoard","id":"1|6|"}]}</pre>');

	print('<h3>Response</h3>');
	print('<pre>');
	print(prettyPrintJson($json));
	print('</pre>');
}

?>