<?php
/**
 * User: David Camacho
 * Date: 30/03/2015
 * Time: 17:38
 */
include_once "./classes/User.php";

class TopBar{

    var $user;
    var $user_login;

    public function TopBar(){

        $this->user = new User();

        //if log out
        if(isset($_POST["log_out"]))
            if($_POST["log_out"]=="EXIT"){

                unset($_SESSION["token"]);

                //header('.login.php');
            }

        //if log in
        if (isset($_POST["user"]) && isset($_POST["pass"])) {

            if ($this->checkCharErrors($_POST["user"]) && $this->checkCharErrors($_POST["pass"])) {

                $_SESSION["token"] = $this->user->loginUser($_POST["user"], $_POST["pass"]);

            }
        }
        $this->user_login = $this->loadLoginSection();
        $this->displayTemplate();

        $this->user->destroy();
    }

    private function validateToken($token)
    {

        if ( !isset($token) || $token == -1 ){

            return false;
        }

        $is_logged = $this->user->validateToken($token);

        if( $is_logged ) {
            return true;
        }

        return false;
    }

    private function checkCharErrors($word)
    {
        $allowed_chars = "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz_1234567890";

        if (strlen($word)<3 || strlen($word)>20){
            return false;
        }
        for ($i=0; $i<strlen($word); $i++) {
            if (!strpos($allowed_chars, $word[$i])) {
                return false;
            }
        }

        return true;
    }

    private function loadLoginSection()
    {
        if(isset($_SESSION["token"]) && $this->validateToken($_SESSION["token"]))
            return '<li class="has-form" > <form method="post"><input type="submit" value="EXIT" name="log_out" class="button alert"></form></li>';
        else
            return '<li class="has-form"><a href="login.php" class="button">LOG IN</a></li>';

    }

    private function displayTemplate(){

        include_once ('./templates/' . _template . '/views/top-bar.html');
    }
}