<?php

namespace App\Models;

use CodeIgniter\Model;

class AuthModel extends Model
{
   protected $users = 'users';
   protected $role_permission = 'role_permission';
   protected $db;

   function get_user_by_mobile($mobile)
   {
       return $this->db->table($this->users)
       ->where('user_mobile', $mobile)
       ->get()
       ->getRow();
   }

   function get_user_by_mobile_and_password($mobile, $password)
   {
       return $this->db->table($this->users)
       ->where(['user_mobile'=> $mobile, 'user_password' => $password])
       ->get()
       ->getRow();
   }
   function update_token($token, $id)
   {
       return $this->db->table($this->users)
       ->where('user_id', $id)
       ->update($token);
   }

   //function get user
    public function get_logged_user()
    {
        if ($this->is_logged_in()) 
        {
            return $this->db->table($this->users)
            ->where(['user_id'=> session()->get('user_id')])
            ->get()
            ->getRow();
        }
    }

    //is logged in
    public function is_logged_in()
    {
        //check if user logged in
        if (session()->get('logged_in') == true &&
            !empty($this->get_user(session()->get('user_id')))) {
            return true;
        } else {
            return false;
        }
    }

    //is logged in
    public function check_session()
    {
        $data = $this->get_user(session()->get('user_id'));
        if (session()->get('user_token') == $data->user_token){
            return true;
        } else {
            return false;
        }
    }

    //get user by id
    public function get_user($id)
    {
         return $this->db->table($this->users)
        ->where(['user_id'=> $id])
        ->get()
        ->getRow();
    }

    //check permission
    public function check_permission($role_key, $section)
    {
        if (user()->user_role == 'Admin') 
        {
            return true;
        }
        else
        {
            $role = $this->get_role_by_key($role_key);
            if($role)
            {
                
                if ($role->$section == 1) {
                    return true;
                }
            }
        }
        
        return false;
    }

    //get role by key
    public function get_role_by_key($key)
    {
         return $this->db->table($this->role_permission)
        ->where(['role_name'=> $key])
        ->get()
        ->getRow();
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to('login');
    }

}
