<?php

set_include_path(get_include_path() . PATH_SEPARATOR . realpath('./libs/'));

require('fns.php');

/**
 * POST to /signin for redirect should be the only POST request sent to this file
 */

// signin post redirect
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if ($_SERVER['REQUEST_URI'] == '/signin') {
        if (!check_redirect_url()) {
            // no redirect url available, then rediret to /
            header('Location: /');
        }
    }
    exit;
}

// GET requests

// check host
$base_path = get_base_path();

if (start_with($_SERVER['REQUEST_URI'], '/adblock')) {
    $html_path = $base_path . 'adblock.html';
} else {
    if (!is_authenticated()) {
        // save the requested url and redirect later
        // do not save urls start with /signin
        if (!start_with($_SERVER['REQUEST_URI'], '/signin') && !start_with($_SERVER['REQUEST_URI'], '/not-found')) {
            save_redirect_url();
        }
        // render signin page
        $html_path = $base_path . 'signin.html';
    } else {
        // render index page
        $html_path = $base_path . 'index.html';
    }
}

if (file_exists(realpath($html_path))) {
    echo file_get_contents($html_path);
} else {
    header("HTTP/1.0 404 Not Found");
    echo 'Requested file path is not present: ' . $html_path;
}
