<?php namespace App\Models\Admin;
//use CodeIgniter\Model;
//use CodeIgniter\Database\ConnectionInterface;
class SecureModel{
	protected $db;

    public function __construct()
    {
        $this->db = \Config\Database::connect();
    }
	
	public function getUserDetail($username,$password){
		$builder = $this->db->table('user');
		$query = $builder->where('username',$username)
					->where('password',md5($password))
					->where('is_deleted','No')
					->get();
		return $query->getRowArray();
	}
	
	public function getNewPassword($email_id){
		// Get User Details 
		$builder = $this->db->table('user');
		$query = $builder->where('email_id',$email_id)
					->where('is_deleted','No')
					->get();
		$user_dtl = $query->getRowArray();
		// Set new password
		if($user_dtl){
			$data['c_password'] = random_string('alnum', 6);
			$data['password'] = md5($data['c_password']);
			$builder = $this->db->table('user');
			$builder->set($data);
			$builder->where('email_id', $email_id);
			if($builder->update()){				
				return array_merge($user_dtl,$data);
			}
		}
		return $user_dtl;
	}
	
	public function addAccessLog($userDtl){
		$logData['user_id'] = $userDtl['user_id'];
		$logData['user_type'] = $userDtl['user_type'];
		$logData['user_name'] = $userDtl['name'];
		$logData['login_at'] = date('Y-m-d H:i:s');
		$logData['logout_at'] = '0000-00-00 00:00:00';
		$logData['login_ip'] = $_SERVER['REMOTE_ADDR'];
		$logData['login_mode'] = 'Web_App';
		$logData['fcm_id'] = $userDtl['fcm_id'];
		$logData['latitude'] = '';
		$logData['longitude'] = '';
		$logData['location'] = '';
		$builder = $this->db->table('access_log');
		$builder->insert($logData);		
		return $this->db->insertID();
	}
	
	public function update_access_log($access_log_id){
		$data['logout_at'] = date('Y-m-d H:i:s');
		$builder = $this->db->table('access_log');
		$builder->where('access_log_id', $access_log_id)
				->update($data);
	}
}