<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User_model extends MY_Model {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	function __construct(){
		parent::__construct();
		$this->tb_name = "tbl_user";
	}

	public function auth_user($email, $password){
		$query = $this->db->select("*")
						  ->from($this->tb_name)
						  ->where("user_email", $email)
						  ->get();
		if($query->num_rows() >0){
			$query = $this->db->select("*")
							  ->from($this->tb_name)
							  ->where("user_email", $email)
							  ->where("password", md5($password))
							  ->get();
			if($query->num_rows()>0){
				return array("success"=>TRUE, "data"=>$query->row_array());  
			}else{
				return array("success"=>FALSE, "message"=>"Password Incorrect!");
			}
		}else{
			return array("success"=>FALSE, "message"=>"Not registered!");
		}
	}

	public function get_user_id($uuid){
		$query = $this->db->select("id")
						  ->from($this->tb_name)
						  ->where('uuid', $uuid)
						  ->limit(1)
						  ->get();
		if($query->num_rows() > 0){
			$row = $query->row_array();
			return $row['id'];
		}else{
			return 0;
		}
	}

	public function get_users_status(){
		$query = $this->db->select("*, Max(b.last_synch) as created_date")
						  ->from($this->tb_name." as a")
						  ->join("tbl_synch as b", "a.id=b.user_id", "left")
						  ->group_by('a.id')
						  ->order_by('created_date', 'desc')
						  ->get();
		if($query->num_rows() > 0){
			return $query->result_array();
		}else{
			return array();
		}
	}
}
