<?php
/**
 * This sourcel is for saving the relevant user information in Database related to mission portal
 * Most propably book keeping task like , last login and other information is kept here.
 */
class authentication_model_pgsql extends CI_Model
{
    protected $table = 'users';
    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');
    }

    public function get_user($username)
    {
        $where = [
            'username' => $username,
        ];
        $query = $this->db->get_where($this->table, $where, 1);

        $userObj = $query->result_object();
        return !empty($userObj[0]) ? $userObj[0] : null;
    }

    public function is_first_login($username)
    {
        $user = $this->get_user($username);
        if (empty($user)) {
            return true;
        }
        return false;
    }

    public function update_last_login($username)
    {
        $where = [
            'username' => $username,
        ];

        $data = [
            'last_login' => date('Y-m-d H:i:s'),
        ];

        $this->db->update($this->table, $data, $where);

        return true;
    }

    public function add_last_login($username, $source)
    {
        $this->load->helper('date');
        $data = [
            'username' => $username,
            'source' => $source,
            'last_login' => date('Y-m-d H:i:s'),
        ];
        $where = [
            'username' => $username,
        ];

        $user = $this->get_user($username);
        if ($user) {
            $this->db->update($this->table, $data, $where);
        } else {
            $this->db->insert($this->table, $data);
        }

        return true;
    }

    public function update_remmember_code($username, $code)
    {
        $where = [
            'username' => $username,
        ];
        $data = [
            'remember_code' => $code,
        ];
        $result = $this->db->update($this->table, $data, $where);

        return $result;
    }

    public function delete_user_from_logged_in_table($id)
    {
        $where = [
            'username' => $id,
        ];
        $result = $this->db->delete($this->table, $where);
        return $result;
    }
}
