<?php

class DB_Functions {

    protected $_db;

    //put your code here
    // constructor
    function __construct() {
		require_once 'config.php';
		require_once 'database.php';
        // connecting to database
        $this->_db = new Database();
        //$this->db->connect();
    }

    // destructor
    function __destruct() {
        
    }

    /**
     * Storing new user
     * returns user details
     */
    public function storeUser($name, $email, $password) {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt
        $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");
        // check for successful store
        if ($result) {
            // get user details 
            $uid = mysql_insert_id(); // last inserted id
            $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
            // return user details
            return mysql_fetch_array($result);
        } else {
            return false;
        }
    }

    /**
     * Get user by email and password
     */
    public function getUserByEmailAndPassword($p_user_email, $p_user_password) {
        // $result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
        // // check for result 
        // $no_of_rows = mysql_num_rows($result);
        // if ($no_of_rows > 0) {
            // $result = mysql_fetch_array($result);
            // $salt = $result['salt'];
            // $encrypted_password = $result['encrypted_password'];
            // $hash = $this->checkhashSSHA($salt, $password);
            // // check for password equality
            // if ($encrypted_password == $hash) {
                // // user authentication details are correct
                // return $result;
            // }
        // } else {
            // // user not found
            // return false;
        // }
		
		$query = $this->_db->selectOne("SELECT user_id,
										user_gender,
										user_email,
										user_password_hash,
										user_active,
										user_account_type,
										user_failed_logins,
										user_last_failed_login,
										user_creation_hash_salt
									FROM ".PREFIX."usr
									WHERE user_email = :user_email
										AND user_provider_type = :provider_type"
										,array(':user_email' => $p_user_email
										,':provider_type' => 'DEFAULT'));//,$DFSSD);
		// if there's NOT one result
			error_log("select one");
			error_log($query["user_password_hash"]);
			error_log($query);
			error_log($query->user_email);
			error_log($query->user_creation_hash_salt);

		if(!$query){
			// here LOGIN_FAILED to prevent potential attackers showing if the user exists
			//Session::set("feedback_negative", 'LOGIN_FAILED');
			return false;
		}
		//echo $query->user_last_failed_login;
		// check if hash of provided password matches the hash in the database
		// crypt(p_user_password, BLOWFISH_HASH_COST.user_creation_hash_salt)
		// crypt using current (BLOWFISH_HASH_COST) Blowfish + only 04 iterations the salt those the magic
		
			error_log(" users crypt ");
			error_log(crypt($p_user_password, BLOWFISH_HASH_COST.$query->user_creation_hash_salt));
		if(crypt($p_user_password, BLOWFISH_HASH_COST.$query["user_creation_hash_salt"]) == $query["user_password_hash"]){
			if ($query->user_active != 1)
				return false;
			else{
				$queryUser = $this->_db->selectOne("SELECT *
									FROM ".PREFIX."usr_i
									WHERE user_id = :user_id"
										,array(':user_id' => $query["user_id"]));
				if(!$queryUser)
					return false;
				else{
					foreach ($query as $k => $v) {
						//echo "Current value of \$a: $v.\n";
						$result[$k] = $v;
					}
					foreach ($queryUser as $k => $v) {
						//echo "Current value of \$a: $v.\n";
						$result[$k] = $v;
					}
					//$queryUser['user_id'] = $query["user_id"];
					return $result;
				}
			}
		
		}
    }

	/** 
	* Returns all users by decreasing ID
	* @param INT current page considering with users limit per page
	* @return ARRAY of users with information or BOOL on false or none meet criteria
	**/
	public function get_Users($pageId=0,$limit=12){
		$data['usr'] = $this->_db->select("SELECT SQL_CALC_FOUND_ROWS * 
								FROM ".PREFIX."usr_i
								ORDER BY ".PREFIX."usr_i.user_id DESC LIMIT ".$limit * ($pageId)." , ".$limit." ");
		if($data){
			$data['add'] = $this->_db->select("SELECT FOUND_ROWS() AS `total_found`");
			return $data;
		}else{
			return false;
		}
	}
	
	/** 
	* Returns all user information by given ID
	* @param INT current page considering with users limit per page
	* @return ARRAY of users with information or BOOL on false or none meet criteria
	**/
	public function get_UserInfo($userId=0){
		if($userId == 0)
			return false;
		$data['usr'] = $this->_db->select("SELECT *
									FROM ".PREFIX."usr_i 
									WHERE user_id = :user_id"
									,array(':user_id' => $userId));
		if($data){
			$data['add'] = $this->_db->select("SELECT FOUND_ROWS() AS `total_found`");
			return $data;
		}else{
			return false;
		}
	}
	
	/** 
	* Returns true if such email dose not exists
	* @param STRING email to check for
	* @return BOOL false on email exists else email free
	**/
	public function get_EmailTaken($userEmail=""){
		if($userEmail == "")
			return true;
		$data = $this->_db->select("SELECT *
									FROM ".PREFIX."usr 
									WHERE user_email = :user_email"
									,array(':user_email' => $userEmail));
		if($data){
			return true;
		}else{
			return false;
		}
	}
	
	
    /**
     * Check user is existed or not
     */
    public function isUserExisted($email) {
        $result = mysql_query("SELECT email from users WHERE email = '$email'");
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            // user existed 
            return true;
        } else {
            // user not existed
            return false;
        }
    }

    /**
     * Encrypting password
     * @param password
     * returns salt and encrypted password
     */
    public function hashSSHA($password) {

        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }

    /**
     * Decrypting password
     * @param salt, password
     * returns hash string
     */
    public function checkhashSSHA($salt, $password) {

        $hash = base64_encode(sha1($password . $salt, true) . $salt);

        return $hash;
    }

}
