<?php

defined('BASEPATH') or exit('direct script access not allowed');

class Usersmodel extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    protected $table = 'users';

    // protected $user_details = ['id userId', 'name', 'email', 'wallet', 'image', 'password'];

    var $order = array('id', 'name', 'email', 'wallet');


    private function _get_data_query($where)
    {
        $searchTerm = $this->input->post('search')['value'] ?? null;

        $this->db->select("{$this->table}.*")
                ->from($this->table)
                ->where($where)
                ->where("{$this->table}.deleted", '0'); // Exclude deleted users

        if ($searchTerm) {
            $this->db->group_start();
            $this->db->like("{$this->table}.email", $searchTerm);
            $this->db->or_like("{$this->table}.wallet", $searchTerm);
            $this->db->or_like("{$this->table}.name", $searchTerm);
            $this->db->group_end();
        }

        if (isset($_POST['order'])) {
            $columnIndex = $_POST['order'][0]['column'];
            $direction = $_POST['order'][0]['dir'];

            if (isset($this->order[$columnIndex])) {
                $this->db->order_by($this->order[$columnIndex], $direction);
            } else {
                $this->db->order_by('id', 'desc');
            }
        } else {
            $this->db->order_by('id', 'desc');
        }
    }




    public function get_data_table($where)
    {
        // print_r($where);exit;
        $this->_get_data_query($where);
        if ($_POST['length'] != -1) {
            $this->db->limit($_POST['length'], $_POST['start']);
        }

        $query = $this->db->get();
        // $b = $query->result_array();
        // print_r($this->db->last_query());
        // exit;
        return $query->result_array();
    }

    public function count_filtered_data($where)
    {
        $this->_get_data_query($where);
        $query = $this->db->get();
        return $query->num_rows();
    }

    public function count_all_data()
    {
        $this->db->from($this->table);
        $this->db->where("{$this->table}.deleted", '0'); // Add this line
        return $this->db->count_all_results();
    }
    

    public function get_user_from_auth_token($token){

        
        $data = $this->db->get_where('user_tokens', ['auth_token' => $token, 'logout_time' => NULL])->row_array();
        

        return $data;
        
    }

    public function log_out($token)
    {

        $this->db->set(['logout_time' => date('Y-m-d H:i:s')])->where(['auth_token' => $token])->update('user_tokens');
    }

    

    
  
}
