<?php
/**
 * User: David Camacho
 * Date: 30/03/2015
 * Time: 17:18
 */
include_once "./controllers/Core.php";

class Login extends Core{

    var $user;
    var $errors_output;
    var $errors;

    public function Login()
    {

        parent::Core();

        $this->errors_output = "";
        $this->errors = array();
        $this->user = new User();


        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"]);

            }
        }


        if (isset($_SESSION["token"])) {
            if(!$this->validateToken($_SESSION["token"]))
                $this->displayTemplate();
            else
                header('Location: ./main.php');
        }else
            $this->displayTemplate();



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


    private function validateToken($token)
    {

        if ( !isset($token) || $token == -1 ){
            array_push($this->errors, $this->langs->translate->getTranslate('wrong_user_or_pass'));
            return false;
        }

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

        if( $is_logged ) {
            return true;
        }

        array_push($this->errors, $this->langs->translate->getTranslate('wrong_user_or_pass'));
        return false;
    }

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

        if (strlen($word)<3 || strlen($word)>20){
            array_push($this->errors, $this->langs->translate->getTranslate('error_login_length'));
            return false;
        }
        for ($i=0; $i<strlen($word); $i++) {
            if (!strpos($allowed_chars, $word[$i])) {
                echo $word[$i];
                array_push($this->errors, $this->langs->translate->getTranslate('error_login_chars'). $allowed_chars . ".");
                return false;
            }
        }

        return true;
    }

    private function displayTemplate()
    {

        if( count($this->errors)>0){
            $this->errors_output = '<div data-alert class="alert-box alert">';
            foreach($this->errors as $err)
                $this->errors_output = $this->errors_output  . $err. '<br>';
         $this->errors_output = $this->errors_output . ' <a href="#" class="close">&times;</a></div>';

        }

        include_once('./templates/' . _template . '/views/login.html');
    }



}