<?php

namespace App\Models;

use CodeIgniter\I18n\Time;
use CodeIgniter\Model;


class AuthLoginModel extends Model
{
    protected $table          = 'user_auth_login';
    protected $primaryKey     = 'id';

    protected $useSoftDeletes = false;
    protected $allowedFields  = [
        'ip',
        'user_agent',
        'id_type',
        'identifier',
        'user_id',
        'is_admin',
        'success',
        'updated_at',
    ];

    protected $useTimestamps = false;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';


    //Check for already Active User
	public function CheckuserIsLoggedIn($email)
	{
	    $builder = $this->db->table('user_auth_login');
		$builder->where('identifier', $email);
		if($builder->countAllResults()==1){
			return true;
		}else
		{
			return false;
		}
	}

    //For already existing session
    public function updateUserSession($id, $data)
	{
	   $builder = $this->db->table('user_auth_login');
	   $builder->where('user_id', $id);
	   $builder->update($data);
	   if($this->db->affectedRows()==1){ 
			 return true;
		 }else{
			 return false;
		 }
	   
	}

    //Check if that particular user session code is available or if still active.
	public function chkIsAlive($cde){
		$builder = $this->db->table('user_auth_login');
		$builder->where('id_type', $cde);
		$result = $builder->get()->getRow();
		return $result;
	}

    //User details to display in session
    public function getUserDetails($sessionId)
    {
        $builder = $this->db->table('user_auth_login as a');
        $builder->select('a.*,u.email, u.position, u.gender, u.birthday, u.address, first_name, last_name, mobile, u.photo, g.name, ag.group_id,');
        $builder->join('users as u', 'u.id=a.user_id');
        $builder->join('user_auth_group as ag', 'ag.user_id = a.user_id');
        $builder->join('user_groups as g', 'g.id=ag.group_id');
        $builder->where('is_admin', '1');
        $builder->where('id_type', $sessionId);
        $result = $builder->get()->getRow();
        return $result;
    }

    // updating User logout time in system.
	public function logoutTime($id, $time)
	{
		$builder = $this->db->table('user_auth_login');
		$builder->where('id_type', $id);
		$builder->update(['deleted_at' =>$time]);
		if($this->db->affectedRows()==1){
			 return true;
			 
		 }else{
			 return false;
		 }
	}

    public function previousLogin($user)
    {
        return $this->where('success', 1)
            ->where('user_id', $user)
            ->orderBy('id', 'desc')
            ->limit(1, 1)->first();
    }

    /**
     * Returns the last login information for the user
     */
    public function lastLogin($userId)
    {
        $result = $this->where('user_id', $userId)
            ->orderBy('updated_at', 'DESC')
            ->asObject()
            ->first();
    
        if ($result !== null) {
            $lastLoginTime = $result->updated_at;
            return $lastLoginTime;
        }
    
        return null;
    }

    //User Exists basing on IP and 
    public function checkUserExists($ip, $code){
        $builder = $this->db->table('user_auth_login');
        $builder->where('ip', $ip);
		$builder->where('id_type', $code);
        return $results = $builder->get()->getRow();
    }
}
