<?php

class login_model extends CI_Model {

    function __construct() {
        parent::__construct();
    }

	function login($username, $password) {
	    $fusername  = strip_tags(mysqli_real_escape_string($this->db->conn_id, trim($username)));
	    $fpassword  = strip_tags(mysqli_real_escape_string($this->db->conn_id, trim($password)));
	    
	    $this->db->select('salt');
		$this->db->from('users');
		$this->db->where('email', $fusername);
		$this->db->or_where('username', $fusername);
		$this->db->or_where('phone', $fusername);
		$this->db->limit(1);
		$query = $this->db->get();
		$salt = $query->row('salt');

        if(empty($salt)) return false;
        $saltedPW =  $fpassword . $salt;
		$hashedPW = hash('sha256', $saltedPW);
        $this->db->select('userId, firstname, lastname, email, password, userLevel, typeId, adminId, allowNewLead, allowedSuppliers, allowedCampaigns, chatUsername');
		$this->db->from('users');
        $this->db->where('isActive', 1);
		$this->db->where('email', $fusername);
		$this->db->where('password', $hashedPW);
		$this->db->or_where('username', $fusername);
		$this->db->where('password', $hashedPW);
		$this->db->or_where('phone', $fusername);
		$this->db->where('password', $hashedPW);
		$this->db->limit(1);
        $queryU = $this->db->get();
        if($queryU -> num_rows() == 1) {
	        $user = $queryU->row();
            return $user;
		}else {
			return false;
		}
	}
}
