<?php

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

error_reporting(E_ERROR | E_PARSE);

date_default_timezone_set('Europe/Vienna');

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

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

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

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

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

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

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

unlink('../../Clients/' . $clientId . '/01_Realtime.svg');
unlink('../../Clients/' . $clientId . '/01_Realtime_Blind.svg');
unlink('../../Clients/' . $clientId . '/Data/tts.txt');

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

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

$input_data = '';

// set status depending on input file ----------------------------------------------------- */

if (file_exists('../../Clients/' . $clientId . '/Data/realtime.json')) {
    // if filetime > 60s, then do not process file!

    $ts = filemtime('../../Clients/' . $clientId . '/Data/realtime.json');

    if ((time() - $ts > 600)) {
        print('Daten veraltet!<br />');

        exit;
    }

    $json = file_get_contents('../../Clients/' . $clientId . '/Data/realtime.json');

    $departures = json_decode($json, true);
} else {
    print('Keine Echtzeitdaten!<br />');

    exit;
}


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

    $line_height = 64;

    $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: "TitilliumWeb-Regular"; src: url(\'./Fonts/TitilliumWeb-Regular.ttf\') format("truetype"); fill:white; font-weight: normal; fill-opacity:1.0; stroke-opacity:1.0;}' . "\n";
    $svg .= '		@font-face { font-family: "TitilliumWeb-SemiBold"; src: url(\'./Fonts/TitilliumWeb-SemiBold.ttf\') format("truetype"); 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 .= '	<image href="./Images/00_Base.png" x="0" y="0" width="1200" height="1600" />' . "\n";
    $svg .= '</g>' . "\n";

    $svg .= '<g id="header">' . "\n";
    $svg .= '	<rect x="0" y="0" width="1200" height="136" fill="#333" />' . "\n";
    $svg .= '	<text x="30" y="87" font-family="TitilliumWeb-Regular" font-size="56px" fill="#fff">' . date('H:i') . '</text>' . "\n";
    $svg .= '	<text x="220" y="87" font-family="TitilliumWeb-Regular" font-size="56px" fill="#fff">' . $stationName . '</text>' . "\n";
    $svg .= '	<rect x="0" y="136" width="1200" height="54" fill="#808080" />' . "\n";
    $svg .= '	<text x="1160" y="173" font-family="TitilliumWeb-Regular" text-anchor="end" font-size="30px" fill="#fff">Service: +43 5522 83951</text>' . "\n";
    $svg .= '</g>' . "\n";

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


    $y = 191;
    $row = 0;

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

    $maxRows = 12;

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

    // lets clean this bs array first
    foreach ($departures as $key => $departure) {

        $abfahrt = $departure['scheduled_arrival_time'];
        $echtzeit = $departure['actual_arrival_time'];

        // prüfen ob das überhaupt heute ist
        $isToday = date('Y-m-d', $abfahrt) === date('Y-m-d') && date('Y-m-d', $echtzeit) === date('Y-m-d');

        if (($echtzeit != '') and ($echtzeit != $abfahrt)) {
            $differ = true;
            $countdown = round(($abfahrt - time()) / 60); // in minutes

        } else {
            $differ = false;
            $countdown = round(($echtzeit - time()) / 60); // in minutes

        }

        $abfahrt = date('H:i', $abfahrt);
        $echtzeit = date('H:i', $echtzeit);

        // wir verwenden die fahrt nur dann, wenn sie heute stattfindet und noch nicht abgefahren ist
        if ($isToday && $countdown > 0) {
            // Build cleaned array
            $cleanedArray[] = [
                'ist' => $echtzeit,
                'soll' => $abfahrt,
                'ziel' => $departure['destination_text'],
                'steig' => $departure['platform_name'],
                'linie' => $departure['line_name'],
                'delay' =>  $differ ? "true" : "false",
                'countdown' => $countdown,
            ];
        }
    }

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

    foreach ($cleanedArray as $key => $value) {
        if ($row < $maxRows) {
            $abfahrt = $value['soll'];
            $echtzeit = $value['ist'];
            $linie = $value['linie'];
            $endstation = $value['ziel'];
            $steig = $value['steig'];
            $differ = $value['delay'];
            $countdown = $value['countdown'];


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

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

            $svg .= '	<rect x="0" y="' . $y . '" width="1200" height="' . $line_height . '" fill="' . $bgColor . '" />' . "\n";

            $svg .= '	<text x="30" y="' . ($y + $line_height - 20) . '" font-family="TitilliumWeb-Regular" font-size="34px" fill="#000">' . $linie . '</text>' . "\n";
            $svg .= '	<text x="200" y="' . ($y + $line_height - 20) . '" font-family="TitilliumWeb-Regular" font-size="34px" fill="#000">' . $endstation . '</text>' . "\n";


            if ($countdown < 5) {

                $svg .= '	<text x="1155" y="' . ($y + $line_height - 20) . '" font-family="TitilliumWeb-Regular" text-anchor="end" font-size="34px" fill="#000">' . $countdown . ' min</text>' . "\n";
            } else {

                if ($differ) {
                    $svg .= '	<text x="1155" y="' . ($y + $line_height - 20) . '" font-family="TitilliumWeb-Regular" text-anchor="end" font-size="34px" fill="#000">' . $echtzeit . '</text>' . "\n";
                } else {
                    $svg .= '	<text x="1155" y="' . ($y + $line_height - 20) . '" font-family="TitilliumWeb-Regular" text-anchor="end" font-size="34px" fill="#000">' . $abfahrt . '</text>' . "\n";
                }
            }


            $y += $line_height;

            $row++;
        }
    }

    if (file_exists('../../Clients/' . $clientId . '/Data/specialTexts.json')) {
        // the file will look like this: 
        //[{"kind":"INFO","text":"Dies ist ein Test des Laufttextes und des Text-To-Speech Systems"}]

        if (file_exists('../../Clients/' . $clientId . '/Data/specialTexts.json')) {
            $y += 20;

            // Load XML and decode
            $json = file_get_contents('../../Clients/' . $clientId . '/Data/specialTexts.json');

            $lines = json_decode($json, true);

            $lineCount = count($departures);
            $lineHeight = 100; // idk

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

            foreach ($lines as $index => $line) {

                // text settings
                $x = 600;
                $fontFamily = "TitilliumWeb-Regular";
                $size = 20;
                $alignAttr = ' text-anchor="middle"';

                $rectY = round($y, 2);
                $rectHeight = round($lineHeight, 2);
                $textY = round($y + ($lineHeight / 2) + ($size / 2.8), 2);

                $svg .= '<rect x="0" y="' . $rectY . '" width="1200" height="' . $rectHeight . '" fill="#333" />';
                $svg .= '<text x="' . $x . '" y="' . $textY . '" font-family="' . $fontFamily . '" font-size="' . $size . 'px" fill="#fff"' . $alignAttr . '>' . htmlspecialchars($line['text']) . '</text>' . "\n";

                $y += $lineHeight;
            }

            $svg .= '</g>' . "\n";
        }
    } else {
        echo "keine infotexte!";
    }

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

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

    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', '', '', '', 0, 0, '', $svg);

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


/* ========================================================================================
   01_Realtime_Blind.svg
   ======================================================================================== */

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

if (1 == 1) {
    $line_height = 267;

    $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: "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="1200" height="1600" fill="#000" />' . "\n";
    $svg .= '</g>' . "\n";

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

    $y = 0;

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

    if (count($departures) < 1) {
        $svg .= '	<text x="40" y="' . ($y + $line_height - 8) . '" font-family="TitilliumWeb-Regular" font-size="40px" fill="#000">Derzeit keine Abfahrten</text>' . "\n";
        $tts = 'Es ist ' . date('H') . ' Uhr ' . date('i') . '. Derzeit keine Abfahrten';
    }

    foreach ($cleanedArray as $key => $value) {
        if ($key < 6) // key starts at 0!
        {

            $abfahrt = $value['soll'];
            $echtzeit = $value['ist'];
            $linie = $value['linie'];
            $endstation = $value['ziel'];
            $steig = $value['steig'];
            $differ = $value['delay'];
            $countdown = $value['countdown'];

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

            if ($echtzeit != '') {
                $abfahrt = $echtzeit;
            }

            $svg .= '	<text x="240" y="' . ($y + 100) . '" font-family="TitilliumWeb-Regular" text-anchor="end" font-size="52px" fill="#fff">' . $linie . '</text>' . "\n";
            $svg .= '	<text x="280" y="' . ($y + 100) . '" font-family="TitilliumWeb-Regular" font-size="52px" fill="#fff">' . $endstation . '</text>' . "\n";
            $svg .= '	<text x="240" y="' . ($y + 220) . '" font-family="TitilliumWeb-Regular" text-anchor="end" font-size="70px" fill="#fff">' . $abfahrt . '</text>' . "\n";

            $svg .= '	<rect x="0" y="' . ($y + $line_height) . '" width="1200" height="1" fill="#fff" />' . "\n";

            $tts .= 'Linie ' . $linie . ', nach ' . $endstation . ', um ' . $abfahrt . ' Uhr, ';

            $row++;

            $y += $line_height;
        }
    }

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

    /* Bild speichern ------------------------------------------------------------------------- */

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

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

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

    if ($tts != '') {
        file_put_contents('../../Clients/' . $clientId . '/Data/tts.txt', $tts);
    }
} else {
    print('Derzeit keine Abfahrten!<br />');
}
