<?php
    if ( isset ( $GLOBALS [ 'request_uri' ] [ 1 ] ) ) {
        $link_id = $GLOBALS [ 'request_uri' ] [ 1 ];
        if ( ! ctype_digit ( $link_id ) ) {
            die ( "You can't be forwarded to a non numerical URL link ID. If you think this is incorrect, please send an email to shorte@dev.bryanpedini.it with this URL: https://sh.bjphoster.com/go/" . $link_id . " for more investigations" );
        }
        $link_id = (int) $link_id;
        $database = new Database ( $GLOBALS [ 'config' ] [ 'db' ] );
        $database->connect ( );
        $database->prepare ( "SELECT links.URL FROM links WHERE links.ID = :link_id" );
        $database->bind ( [ ':link_id' => $link_id ] );
        $database->execute ( );
        $result = $database->get_result ( );
        if ( $result->rowCount ( ) == 0 ) {
            http_response_code ( 404 );
            include ( $GLOBALS [ 'config' ] [ 'installation_path' ] . '/lib/errors/404.html' );
            exit;
        }
        else {
            $row = $result->fetchAll ( ) [ 0 ];
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <link href="<?=$GLOBALS['config']['installation_path']?>/favicon.ico" rel="icon" type="image/x-icon">
        <title id="title">Redirect in 5 seconds | <?=$GLOBALS['config']['website_name']?></title>
    </head>
    <body>
        <center>
            <h1>You will be redirected to <?=$row['URL']?> in <span id="body-timeout">5</span></h1>
        </center>
        <script>
            window.onload = function() {
                var seconds = 5;
                function update_timeout (interval) {
                    document.getElementById("title").innerHTML = "Redirect in " + seconds +" seconds | <?=$GLOBALS['config']['website_name']?>";
                    document.getElementById("body-timeout").innerHTML = seconds;
                    if (seconds == 0) {
                        window.location.href = "<?=$row['URL']?>";
                        clearInterval (interval);
                    }
                }
                interval = setInterval (function() {update_timeout(interval); seconds = seconds - 1;}, 1000);
            }
        </script>
    </body>
</html>
<?php
        }
    }
    else {
        header ( "Location: " . substr ( $_SERVER [ 'SCRIPT_NAME' ], 0, -10 ) );
    }