<?php

    /**
     * Controller file.
     *
     * Provides a class to handle all posible request.
     * 
     * @category Constroller
     */

    /**
     * Include some required files.
     */
    require_once(__DIR__ . "/config.php");
    require_once(PATH::HELPER . "DB_Helper.php");
    require_once(PATH::HELPER . "TEXT_Helper.php");
    require_once(PATH::HELPER . "NET_Helper.php");
    require_once(PATH::HELPER . "HTML_Helper.php");
    require_once(PATH::HELPER . "APPLICATION_Helper.php");
    require_once(__DIR__ . "/Constant.php");

    /**
     * @global int $UID.
     */
    $UID = 0;

    /**
     * Application controller.
     *
     * Handles every request, creating the required models and selecting the
     * view.
     *
     * @category Controller
     */
    class Controller {

        /**
         * Constructor.
         *
         * Handles every request, creating the required models and selecting the
         * view.
         *
         * @param mixed[] $params POST parameters of the request.
         * @return int HTTP status codes 200 or 404;
         * @global int User ID.
         */
        public function __construct($params){

            global $UID;
            $page = null;

            session_start();
            $db = DB::start();

            // Parse parameters, get lang and build the route.
            $pars = [];
            foreach($params as $p){
                if (strlen($p) > 0){
                    array_push($pars, $p);
                }
            }

            // Special case: Actions.
            // Not redirecting to page, just execute a function
            if (count($pars) > 1 && strtoupper($pars[0]) == "ACTION"){
                switch (strtoupper($pars[1])){
                    case "LOGIN":
                        require_once(PATH::ACTION . "login.php");
                        action($db);
                        return;
                        break;
                    case "LOGOUT":
                        require_once(PATH::ACTION . "logout.php");
                        action($db);
                        return;
                        break;
                    case "NEW_TEAM":
                        require_once(PATH::ACTION . "new_team.php");
                        action($db);
                        return;
                        break;
                    case "SAVE_RUN_TEAM":
                        require_once(PATH::ACTION . "save_run_team.php");
                        action($db);
                        return;
                        break;
                    case "EDIT_PROFILE":
                        require_once(PATH::ACTION . "edit_profile.php");
                        $response = action($db);
                        if (strlen($response) > 1){
                            echo($response);
                            return;
                        }
                        else{
                            return;
                        }
                        break;
                    default:
                        require_once(PATH::PAGE . "Error_Page.php");
                        $page = new Error_Page($db, 404);
                        http_response_code(404);
                }
            }

            if (isset($_COOKIE["uid"]) && isset($_SESSION["uid"]) && $_COOKIE["uid"] != $_COOKIE["uid"]){
                // Both cookie and session are set, but they are different. Delete them both.
                setcookie("uid", "", time() - 3600);
                $_SESSION["session"] = false;
                $_SESSION["uid"] = "";
                require_once(PATH::PAGE . "Landing_Page.php");
                $page = new Landing_Page($db);
                require_once($page->view);
                return;
            }
            elseif (isset($_COOKIE["uid"]) && !isset($_SESSION["uid"])){
                $_SESSION["session"] = true;
                $_SESSION["uid"] = $_COOKIE["uid"];
            }
            elseif (!isset($_COOKIE["uid"]) && isset($_SESSION["uid"])){
                setcookie("uid", $_SESSION["uid"], time() + 5 * 24 * 60 * 60);
            }

            // Validate session
            $UID = $_SESSION["uid"];
            $q = $db->query("SELECT count(uid) AS c FROM player WHERE uid = '$UID';");
            $r = $q->fetchArray(SQLITE3_ASSOC);
            if ($r["c"] == 0){
                require_once(PATH::PAGE . "Landing_Page.php");
                $page = new Landing_Page($db);
                require_once($page->view);
                return;
            }
            else{
                // Reset cokie and renew session.
                setcookie("uid", $_SESSION["uid"], time() + 5 * 24 * 60 * 60);
                $_SESSION["session"] = true;
                $_SESSION["uid"] = $UID;
                // Recover username if lost
                if (!isset($_SESSION["name"]) || strlen($_SESSION["name"]) == 0){
                    $q = $db->query("SELECT name FROM player WHERE uid = '$UID';");
                    $r = $q->fetchArray(SQLITE3_ASSOC);
                    $_SESSION["name"] = $r["name"];
                }
            }

            // If UID not in URL, redirect and end.
            if ($pars[0] != $UID){
                header("Location: /$UID" . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH));
                return;
            }

            // Select the model to load.
            array_shift($pars); // Remove first one, should be UID
            if (sizeof($pars) == 0){
                require_once(PATH::PAGE . "Home_Page.php");
                $page = new Home_Page($db);
            }
            else{
                if (strtoupper($pars[0]) == "FUSION"){
                    require_once(PATH::PAGE . "Fusion_Page.php");
                    $page = new Fusion_Page($db);
                }
                elseif (strtoupper($pars[0]) == "RUNES"){
                    require_once(PATH::PAGE . "Runes_Page.php");
                    $page = new Runes_Page($db);
                }
                elseif (strtoupper($pars[0]) == "GUILD"){
                    require_once(PATH::PAGE . "Guild_Page.php");
                    $page = new Guild_Page($db);
                }
                elseif (strtoupper($pars[0]) == "RUNS"){
                    require_once(PATH::PAGE . "Runs_Page.php");
                    $page = new Runs_Page($db);
                }
                elseif (strtoupper($pars[0]) == "TEAMS"){
                    require_once(PATH::PAGE . "Teams_Page.php");
                    $page = new Teams_Page($db);
                }
                elseif (strtoupper($pars[0]) == "PROFILE"){
                    require_once(PATH::PAGE . "Profile_Page.php");
                    $page = new Profile_Page($db);
                }
                elseif (strtoupper($pars[0]) == "MONSTERS"){
                    if (count($pars) == 1){
                        require_once(PATH::PAGE . "Monsters_Page.php");
                        $page = new Monsters_Page($db);
                    }
                    else{
                        require_once(PATH::PAGE . "Monster_Page.php");
                        $page = new Monster_Page($db, $pars[1]);
                    }
                }
                elseif (strtoupper($pars[0]) == "CATALOG"){
                    if (count($pars) == 1){
                        require_once(PATH::PAGE . "Catalog_Page.php");
                        $page = new Catalog_Page($db);
                    }
                    else{
                        require_once(PATH::PAGE . "Monster_Info_Page.php");
                        $page = new Monster_Info_Page($db, $pars[1]);
                    }
                }
                elseif (strtoupper($pars[0]) == "REPORT"){
                    if (count($pars) == 1){
                        require_once(PATH::PAGE . "Report_Page.php");
                        $page = new Report_Page($db);
                    }
                    elseif (strtoupper($pars[1]) == "SKILLUP"){
                        require_once(PATH::PAGE . "Report_Skillup_Page.php");
                        $page = new Report_Skillup_Page($db, $pars[1]);
                    }
                    elseif (strtoupper($pars[1]) == "RUNEUPGRADE"){
                        require_once(PATH::PAGE . "Report_Runeupgrade_Page.php");
                        $page = new Report_Runeupgrade_Page($db, $pars[1]);
                    }
                    elseif (strtoupper($pars[1]) == "RUNECRAFT"){
                        require_once(PATH::PAGE . "Report_Runecraft_Page.php");
                        $page = new Report_Runecraft_Page($db, $pars[1]);
                    }

                }
            }
            // Load the view, or set an error code.
            if (isset($page)){
                require_once($page->view);
                return 200;
            }
            else{
                require_once(PATH::PAGE . "Error_Page.php");
                $page = new Error_Page($db, 404);
                http_response_code(404);
                return 404;
            }
        }
    }
?>
