<?
include "inc/conf.php";
$cache_filename = $conf["cache_path"].md5(serialize($_GET)).".html";

if(!$DEV && file_exists($cache_filename) && date("Y-m-d")==date("Y-m-d",filemtime($cache_filename))){
    include $cache_filename;
}else{
    ob_start();
    $lang = "sl"; // language
    // translations
    include "var/terms.".$lang.".php";

    include "inc/functions.php";
    include "inc/class.minify.php";

    $oMinify = new minify();
    $oMinify->setPath("tmp/", "tmp/");
    $oMinify->setCacheVersion(25);

    $oMinify->addCss("js/select2/css/select2.min.css", "basic");
    $oMinify->addCss("css/basic.css", "basic");

    $oMinify->addJs("js/jquery-3.6.0.min.js", "js");
    $oMinify->addJs("js/jquery.sticky.js", "js");
    $oMinify->addJs("js/select2/js/select2.min.js", "js");
    $oMinify->addJs("js/select2/js/i18n/sl.js", "js");
    $oMinify->addJs("js/inc.js", "js");

    // STOPS
    $handle = fopen("tmp/csv/all_stops.txt", "r");
    $contents = fread($handle, filesize("tmp/csv/all_stops.txt"));
    fclose($handle);
    $aStops = unserialize($contents);

    // LINES
    $handle = fopen("tmp/csv/all_lines.txt", "r");
    $contents = fread($handle, filesize("tmp/csv/all_lines.txt"));
    fclose($handle);
    $aLines = unserialize($contents);
    $aLinesBySlug = array();

    foreach($aLines as $lk => $line){
        $ok = true;
        $lineNameSufix = "";
        $today = time();
        //$today = strtotime("2014-10-15");
        if(!empty($line["stops"])){
            $dir1stops = [];
            foreach($line["stops"] as $dir => $val){
                foreach($val as $k=>$v) {
                    if($dir == 1){
                        $dir1stops[$v["code"]] = $k;
                    }else {
                        if (!isset($dir1stops[($v["code"] + 1)]) && !isset($dir1stops[($v["code"] - 1)])) {
                            // two way
                            if(isset($dir1stops[$v["code"]])) {
                                $aLines[$lk]["stops"][1][$dir1stops[$v["code"]]]["two_way"] = 1;
                            }
                            $aLines[$lk]["stops"][2][$k]["two_way"] = 1;
                        }

                        if(isset($dir1stops[$v["code"]])){
                            //$aLines[$lk]["stops"][1][$dir1stops[$v["code"]]]["multi_dir"] = 1;
                            //$aLines[$lk]["stops"][2][$k]["multi_dir"] = 1;

                            //$aLines[$lk]["stops"][2][$k]["altStop"] = $v["code"];
                            //$aLines[$lk]["stops"][1][$dir1stops[$v["code"]]]["altStop"] = $v["code"];
                        }
                        if(isset($dir1stops[($v["code"] + 1)]) || (isset($dir1stops[($v["code"] - 1)]))){
                            if(isset($dir1stops[($v["code"] + 1)])){
                                $altStopKey = $dir1stops[($v["code"] + 1)];
                                $altStop = $v["code"] + 1;
                            }else{
                                $altStopKey = $dir1stops[($v["code"] - 1)];
                                $altStop = $v["code"] - 1;
                            }
                            $aLines[$lk]["stops"][2][$k]["altStop"] = $altStop;
                            $aLines[$lk]["stops"][1][$altStopKey]["altStop"] = $v["code"];
                        }

                        $line = $aLines[$lk];
                    }
                }
            }
        }

        if(!$line["active"]) {
            $ok = false;
        }

        if($line["type"]>0){
            if($line["type"]==1){
                // v pripravi
                $lineNameSufix = ".v-pripravi";
                if(dateIsSet($line["active_from"]) && strtotime($line["active_from"])<=strtotime(date("Y-m-d",$today))){
                    $override[$line["line"]] = $line["line_id"];
                    $line["type"] = 0;
                    $lineNameSufix = "";
                }
            }else if(in_array($line["type"],array(2,3))){
                // posebni - vidni so tudi preden zacnejo veljati, po koncu veljavnosti pa se deaktivirajo
                if($line["type"] == 2) {
                    $lineNameSufix = ".posebni";
                } else {
                    $lineNameSufix = ".pocitniski";
                }
                if((dateIsSet($line["active_to"]) && strtotime($line["active_to"])<strtotime(date("Y-m-d 00:00:00",$today)))){
                    // deactivate
                    $ok = false;
                }
            }
        }

        $line["slug"] = mb_strtoupper(cleanString($line["line"])) . $lineNameSufix;
        $aLines[$lk]["slug"] = $line["slug"];

        if(!$ok){
            $aNotActive[$line["line_id"]] = $line["line_id"];
        }else{
            $aValidLines[$line["line_id"]] = $line;
            $aLineNames[$line["line"].$lineNameSufix] = $line["line_id"];
            $aLinesBySlug[$line["slug"]] = $line["line_id"];
            $aConnectedLines[$line["line"]][$line["line_id"]] = $line["line_id"];
        }
    }

    if($override){
        // override old ones
        foreach($aLines as $line){
            if($override[$line["line"]] && $line["line_id"]!=$override[$line["line"]]){
                $aNotActive[$line["line_id"]] = $line["line_id"];
                if($aValidLines[$line["line_id"]]) unset($aValidLines[$line["line_id"]]);
                if($aConnectedLines[$line["line"]][$line["line_id"]]) unset($aConnectedLines[$line["line"]][$line["line_id"]]);

                // 'redirect' na novo veljavno linijo ce stara ni vec aktivna
                $oldRedirect[$line["line_id"]] = $override[$line["line"]];
            }else if($override[$line["line"]] && $line["line_id"]==$override[$line["line"]]){
                // ce je override, je treba nastaviti pravi id da bi $_GET["l"] deloval pravilno
                $aLineNames[$line["line"]] = $line["line_id"];
                $aLinesBySlug[$line["slug"]] = $line["line_id"];
            }
        }
    }

    if(!empty($_GET["line"]) || !empty($_GET["ref"])) {
        /*
         * Redirect
         */
        $url = $_SERVER["REQUEST_URI"];
        if(!empty($_GET["line"])) {
            $lineSlug = getRedirectLineSlug($_GET["line"], $aLines, $aValidLines, $aLinesBySlug);
            $url = preg_replace('/([&?])line=[^&]{1,}/i', $lineSlug ? "$1l=" . $lineSlug : "", $url);
        }
        if(!empty($_GET["ref"])) {
            $lineSlug = getRedirectLineSlug($_GET["ref"], $aLines, $aValidLines, $aLinesBySlug);
            $url = preg_replace('/([&?])ref=\d+/', $lineSlug ? "$1lref=" . $lineSlug : "", $url);
        }

        header("HTTP/1.1 301 Moved Permanently");
        header("Location: $url", true, 301);
        exit();
    }

    function isActiveSpecialTimetable($a)
    {
        /*
         * Special timetables with from/to dates which are currently active should be shown before regular timetable
         */
        if(!empty($a["active"]) && !empty($a["active_to"]) && $a["active_to"] !== "0000-00-00" && !empty($a["active_from"]) && $a["active_from"] !== "0000-00-00") {
            $from = strtotime($a["active_from"]);
            $to = strtotime($a["active_to"]);
            $ts = strtotime(date("Y-m-d 00:00:00"));

            return $from <= $ts && $to >= $ts;
        }
    }

    function linesSort($a, $b){

        $aIsSpecialActive = isActiveSpecialTimetable($a);
        $bIsSpecialActive = isActiveSpecialTimetable($b);

        $atype = $a["type"];
        $btype = $b["type"];
        $a = $a["line"];
        $b = $b["line"];
        $a = preg_replace('/\/.*/', "B", $a);
        $b = preg_replace('/\/.*/', "B", $b);
        $a2 = $a;
        $b2 = $b;
        $a = preg_replace('/[^0-9]/', "", $a);
        $b = preg_replace('/[^0-9]/', "", $b);
        if ($a == $b) {
            $ret =  strcmp($a2,$b2);
            if($ret==0){
                if($aIsSpecialActive) {
                    return -1;
                } else if($bIsSpecialActive) {
                    return 1;
                }

                return ($atype < $btype) ? -1 : 1;
            }else{
                return $ret;
            }
            return 0;
        }
        return ($a < $b) ? -1 : 1;
    }
    uasort($aValidLines, "linesSort");
    $layout = "basic";

    ob_start();
    include "layouts/".$layout.".php";
    $html = ob_get_clean();

    $bodyClass[] = "layout".ucfirst($layout);
    ?>
    <!DOCTYPE html>
    <html lang="<?=$lang?>">
        <head>
            <meta http-equiv="X-UA-Compatible" content="IE=EDGE">
            <title><?=getTerm("Iskanje postajališčnega voznega reda")?></title>
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
            <link rel="preconnect" href="https://fonts.googleapis.com">
            <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
            <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600;700&display=swap" rel="stylesheet">
            <?=$oMinify->getCss("basic") ?>
        </head>

        <body <?=combineCssClasses($bodyClass)?>>
            <?=$html?>
            <?=$oMinify->getJs("js") ?>
            <?=$footer_html?>
        </body>
    </html>
    <?
    $html = ob_get_flush();
    // write cache file
    if($html && strlen($html)>10 && !$is404){
        $fp = fopen($cache_filename, 'w');
        fwrite($fp,$html);
        fclose($fp);

        if(!filesize($cache_filename)){
            unlink($cache_filename);
        }
    }
}

function getRedirectLineSlug($lineId, $aLines, $aValidLines, $aLinesBySlug)
{
    if(!empty($aValidLines[$lineId])){
        return $aValidLines[$lineId]["slug"];
    }

    if(!empty($aLines[$lineId]) && preg_match('/^([^.]*?)(\..*)?$/', $aLines[$lineId]["slug"], $matches)){
        if(!empty($aLinesBySlug[$matches[1]])){
            return $matches[1];
        }
    }

    if(!empty($aLinesBySlug[$lineId])) {
        return $lineId;
    }
}