<?php
/**
 * User: David Camacho
 * Date: 29/03/2015
 * Time: 15:27
 */

class User extends DataBaseController
{

    public function User()
    {
        parent::DataBaseController();

    }

    public function getStudentsList($name)
    {
        $res = array("id_user" => array(),
            "name" => array()
        );
        $name = "%". $name . "%";
        $sql = "SELECT id_user, name
				FROM " . _db_prefix . "_user
				WHERE role = 0
				AND name LIKE ?";

        if (isset($this->db)){
            $tmp = $this->db->prepare($sql);
            $tmp->bind_param('s',$name);
            $tmp->execute();
            $tmp->bind_result($result1,$result2);
            while ($tmp->fetch()) {
                array_push($res["id_user"],$result1);
                array_push($res["name"],$result2);
            }
            $tmp->close();
            return $res;


        }
        return -1;
    }


    public function getUserTestMark($id_user, $id_test){


        $mark = -1;
        $total_test_points = 0;
        $total_user_points = 0;
        $questions = array("id_question" => array(),
            "points" => array());



        //Loop Questions
        $sql = "SELECT id_question, points
				FROM " . _db_prefix . "_question
				WHERE id_test = ?";

        if (isset($this->db)){
            $tmp = $this->db->prepare($sql);

            $tmp->bind_param('i',$id_test);
            $tmp->execute();
            $tmp->bind_result($id_question, $points);


            while ($tmp->fetch()) {

                array_push($questions["id_question"], $id_question);
                array_push($questions["points"], $points);

                $total_test_points = $total_test_points + $points;


            }
            $tmp->close();



            for($i=0; $i<count($questions["id_question"]);$i++) {
                // Loop correct answers
                $sql = "SELECT id_answer
                     FROM " . _db_prefix . "_answer
                     WHERE id_question = " . $questions["id_question"][$i] . "
                     AND is_correct = 1";

                $result = mysqli_query($this->db, $sql) ;

                $answered = false; // For multi-answer
                while($obj = $result->fetch_object()){

                    if (!$answered) {
                        if ($this->hasUserAnsweredThis($id_user, $obj->id_answer)) {
                            $total_user_points = $total_user_points + $questions["points"][$i];
                            $answered = true;
                        }
                    }
                }
            }

            if ($total_test_points>0) $mark = ($total_user_points/$total_test_points)*10;
            else $mark = 0;
            return $mark;


        }
        return -1;

    }


    public function hasUserAnsweredThis($id_user, $id_answer)
    {
        $sql = "SELECT count(id_user_answer)
                FROM " . _db_prefix . "_user_answer
                WHERE id_user = ? AND
                id_answer = ?";

        if (isset($this->db)) {
            $tmp = $this->db->prepare($sql);
            $tmp->bind_param('ii', $id_user, $id_answer);
            $tmp->execute();
            $tmp->bind_result($total_answers);
            $tmp->fetch();
            $tmp->close();
            if($total_answers>0)return true;
            return false;

        }
        return false;
    }

    public function getUserName($id_user)
    {

        $sql = "SELECT name
				FROM " . _db_prefix . "_user
				WHERE id_user = ?";

        if (isset($this->db)){
            $tmp = $this->db->prepare($sql);
            $tmp->bind_param('i',$id_user);
            $tmp->execute();
            $tmp->bind_result($result1);
            if ($tmp->fetch()) {
                return $result1;
            }
            $tmp->close();
            return false;
        }
        return false;
    }


    public function getRole()
    {
        $token = $_SESSION["token"];

        $sql = "SELECT role
				FROM " . _db_prefix . "_user
				WHERE token = ?";

        if (isset($this->db)){
            $tmp =  $this->db->prepare($sql);
            $tmp->bind_param('s',$token);
            $tmp->execute();
            $tmp->bind_result($role);
            $tmp->fetch();
            $tmp->close();
            if(isset($role)){
                return $role;
            }

        }
        return -1;
    }

    //Used to verify if user is logged
    public function validateToken()
    {

        $token = $_SESSION['token'];
        $sql = "SELECT true
				FROM " . _db_prefix . "_user
				WHERE token = ?
				AND expires_session > NOW()";

        if (isset($this->db)){
            $tmp =  $this->db->prepare($sql);
            $tmp->bind_param('s',$token);
            $tmp->execute();
            $tmp->bind_result($logged);
            $tmp->fetch();
            $tmp->close();
            if(isset($logged)){
                return true;
            }

        }
        return false;
    }


    public function registerUser($role, $name, $user, $pass)
    {
        $pass = md5($pass);

        $sql = "INSERT INTO " . _db_prefix . "_user( role, name, user, pass)
        VALUES (?, ?, ?, ?)";

        $tmp = $this->db->prepare($sql);
        $tmp->bind_param('isss',$role, $name, $user, $pass);
        $tmp->execute();
        $tmp->close();

        return true;
    }

    //Returns id_user
    public function getIdUser(){


            $token = $_SESSION['token'];
            $sql = "SELECT id_user
				FROM " . _db_prefix . "_user
				WHERE token = ?";

            if (isset($this->db)){
                $tmp =  $this->db->prepare($sql);
                $tmp->bind_param('s',$token);
                $tmp->execute();
                $tmp->bind_result($user);
                $tmp->fetch();
                $tmp->close();
                if(isset($user)){
                    return $user;
                }

            }
            return -1;

    }

    public function loginUser($login, $pass)
    {

        $sql = "SELECT TRUE
				FROM " . _db_prefix . "_user
				WHERE user = ? AND pass = sha1(?)";
        if (isset($this->db)){
            $tmp =  $this->db->prepare($sql);
            $tmp->bind_param('ss',$login,$pass);
            $tmp->execute();
            $tmp->bind_result($success);
            $tmp->fetch();
            $tmp->close();


            if(isset($success)){
                #Update token
                $token = md5(uniqid(mt_rand(), true));
                $sql = "UPDATE " . _db_prefix . "_user
                SET token = ?,
                expires_session = DATE_ADD(NOW(), INTERVAL 2 HOUR)
				WHERE user = ?
				AND pass = sha1(?)";

                $tmp = $this->db->prepare($sql);
                $tmp->bind_param('sss', $token, $login, $pass);
                $tmp->execute();
                $tmp->close();

                return $token;
            }
        }
        return -1;
    }

    public function destroy()
    {
        // close the mysqli connection
        $this->db->close();

    }

}