<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User_model extends CI_Model {

    public function __construct() {
        log_message('info', 'User_model initialized');
    }

    public function validate_user($username, $password) {
        $this->db->where('username', $username);
        $query = $this->db->get('users');
        
        if ($query->num_rows() == 1) {
            $user = $query->row();
            if (password_verify($password, $user->password)) {
                // Update last login and login count
                $this->update_login_info($user->id);
                // Record login history
                $this->record_login_history($user->id);
                return $user;
            }
        }
        return false;
    }

    public function get_user_by_id($id) {
        $this->db->where('id', $id);
        return $this->db->get('users')->row();
    }

    public function get_all_users() {
        $this->db->order_by('created_at', 'DESC');
        return $this->db->get('users')->result();
    }

    public function create_user($user_data) {
        // Hash password
        $user_data['password'] = password_hash($user_data['password'], PASSWORD_DEFAULT);
        $user_data['created_at'] = date('Y-m-d H:i:s');
        
        $this->db->insert('users', $user_data);
        return $this->db->insert_id();
    }

    public function update_user($user_id, $user_data) {
        // If password is being updated, hash it
        if (isset($user_data['password']) && !empty($user_data['password'])) {
            $user_data['password'] = password_hash($user_data['password'], PASSWORD_DEFAULT);
        } else {
            unset($user_data['password']);
        }
        
        $this->db->where('id', $user_id);
        return $this->db->update('users', $user_data);
    }

    public function delete_user($user_id) {
        // First delete login history
        $this->db->where('user_id', $user_id);
        $this->db->delete('user_login_history');
        
        // Then delete user
        $this->db->where('id', $user_id);
        return $this->db->delete('users');
    }

    public function username_exists($username, $exclude_id = null) {
        $this->db->where('username', $username);
        if ($exclude_id) {
            $this->db->where('id !=', $exclude_id);
        }
        return $this->db->get('users')->num_rows() > 0;
    }

    private function update_login_info($user_id) {
        $this->db->where('id', $user_id);
        $this->db->set('last_login', date('Y-m-d H:i:s'));
        $this->db->set('login_count', 'login_count+1', FALSE);
        $this->db->update('users');
    }

    private function record_login_history($user_id) {
        $data = array(
            'user_id' => $user_id,
            'login_time' => date('Y-m-d H:i:s'),
            'ip_address' => $this->input->ip_address()
        );
        $this->db->insert('user_login_history', $data);
    }

    public function get_login_history($user_id, $limit = 10) {
        $this->db->where('user_id', $user_id);
        $this->db->order_by('login_time', 'DESC');
        $this->db->limit($limit);
        return $this->db->get('user_login_history')->result();
    }

    public function get_user_stats() {
        $stats = array();
        
        // Total users
        $stats['total_users'] = $this->db->count_all('users');
        
        // Active users (logged in last 30 days)
        $thirty_days_ago = date('Y-m-d H:i:s', strtotime('-30 days'));
        $this->db->where('last_login >=', $thirty_days_ago);
        $stats['active_users'] = $this->db->count_all_results('users');
        
        // Admin users
        $this->db->where('role', 'admin');
        $stats['admin_users'] = $this->db->count_all_results('users');
        
        // Regular users
        $this->db->where('role', 'user');
        $stats['regular_users'] = $this->db->count_all_results('users');
        
        return $stats;
    }
}
?>