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

class User_model extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    /**
     * Create new user
     */
    public function create_user($data) {
        $data['password_hash'] = password_hash($data['password'], PASSWORD_BCRYPT);
        unset($data['password']);
        
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');
        
        $this->db->insert('users', $data);
        return $this->db->insert_id();
    }

    /**
     * Get user by ID
     */
    public function get_user($id) {
        return $this->db->where('id', $id)->get('users')->row();
    }

    /**
     * Get user by email
     */
    public function get_user_by_email($email) {
        return $this->db->where('email', $email)->get('users')->row();
    }

    /**
     * Get user by username
     */
    public function get_user_by_username($username) {
        return $this->db->where('username', $username)->get('users')->row();
    }

    /**
     * Update user
     */
    public function update_user($id, $data) {
        $data['updated_at'] = date('Y-m-d H:i:s');
        $this->db->where('id', $id)->update('users', $data);
        return $this->db->affected_rows() > 0;
    }

    /**
     * Verify user credentials
     */
    public function verify_user($username, $password) {
        $user = $this->get_user_by_username($username);
        if (!$user) {
            $user = $this->get_user_by_email($username);
        }
        
        if ($user && password_verify($password, $user->password_hash)) {
            return $user;
        }
        
        return false;
    }

    /**
     * Get users with pagination
     */
    public function get_users($limit = 10, $offset = 0, $search = '') {
        $this->db->select('id, username, email, full_name, nick_name, role, is_verified, is_banned, created_at, date_of_birth, country, gender');
        
        if ($search) {
            $this->db->group_start();
            $this->db->like('username', $search);
            $this->db->or_like('email', $search);
            $this->db->or_like('full_name', $search);
            $this->db->or_like('nick_name', $search);
            $this->db->group_end();
        }
        
        $this->db->order_by('created_at', 'DESC');
        return $this->db->get('users', $limit, $offset)->result();
    }

    /**
     * Count total users
     */
    public function count_users($search = '') {
        if ($search) {
            $this->db->group_start();
            $this->db->like('username', $search);
            $this->db->or_like('email', $search);
            $this->db->or_like('first_name', $search);
            $this->db->or_like('last_name', $search);
            $this->db->group_end();
        }
        
        return $this->db->count_all_results('users');
    }

    /**
     * Ban/unban user
     */
    public function ban_user($user_id, $ban = true) {
        return $this->update_user($user_id, ['is_banned' => $ban]);
    }

    /**
     * Get user violations
     */
    public function get_user_violations($user_id) {
        return $this->db->where('user_id', $user_id)
                       ->order_by('created_at', 'DESC')
                       ->get('user_violations')
                       ->result();
    }

    /**
     * Add user violation
     */
    public function add_violation($user_id, $violation_type, $description, $created_by) {
        $data = [
            'user_id' => $user_id,
            'violation_type' => $violation_type,
            'description' => $description,
            'created_by' => $created_by,
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        $this->db->insert('user_violations', $data);
        return $this->db->insert_id();
    }

    /**
     * Get user subscription count
     */
    public function get_subscription_count($user_id) {
        return $this->db->where('creator_id', $user_id)
                       ->count_all_results('subscriptions');
    }

    /**
     * Check if user is subscribed to creator
     */
    public function is_subscribed($subscriber_id, $creator_id) {
        return $this->db->where('subscriber_id', $subscriber_id)
                       ->where('creator_id', $creator_id)
                       ->count_all_results('subscriptions') > 0;
    }

    /**
     * Subscribe/unsubscribe to creator
     */
    public function toggle_subscription($subscriber_id, $creator_id) {
        $exists = $this->is_subscribed($subscriber_id, $creator_id);
        
        if ($exists) {
            $this->db->where('subscriber_id', $subscriber_id)
                    ->where('creator_id', $creator_id)
                    ->delete('subscriptions');
            return false;
        } else {
            $data = [
                'subscriber_id' => $subscriber_id,
                'creator_id' => $creator_id,
                'created_at' => date('Y-m-d H:i:s')
            ];
            $this->db->insert('subscriptions', $data);
            return true;
        }
    }

    /**
     * Record user login
     */
    public function record_login($user_id, $ip_address = null, $user_agent = null, $session_id = null) {
        $data = [
            'user_id' => $user_id,
            'login_time' => date('Y-m-d H:i:s'),
            'ip_address' => $ip_address,
            'user_agent' => $user_agent,
            'session_id' => $session_id
        ];
        
        $this->db->insert('user_logins', $data);
        return $this->db->insert_id();
    }

    /**
     * Get user login history
     */
    public function get_login_history($user_id, $limit = 10) {
        return $this->db->where('user_id', $user_id)
                       ->order_by('login_time', 'DESC')
                       ->limit($limit)
                       ->get('user_logins')
                       ->result();
    }

    /**
     * Get last login time for user
     */
    public function get_last_login($user_id) {
        return $this->db->select('login_time')
                       ->where('user_id', $user_id)
                       ->order_by('login_time', 'DESC')
                       ->limit(1)
                       ->get('user_logins')
                       ->row();
    }

    /**
     * Get users with login history
     */
    public function get_users_with_login_history($limit = 10, $offset = 0, $search = '') {
        $this->db->select('u.id, u.username, u.email, u.first_name, u.last_name, u.role, u.is_verified, u.is_banned, u.created_at');
        $this->db->select('(SELECT login_time FROM user_logins ul WHERE ul.user_id = u.id ORDER BY login_time DESC LIMIT 1) as last_login');
        $this->db->from('users u');
        
        if ($search) {
            $this->db->group_start();
            $this->db->like('u.username', $search);
            $this->db->or_like('u.email', $search);
            $this->db->group_end();
        }
        
        $this->db->order_by('last_login', 'DESC');
        $this->db->limit($limit, $offset);
        
        return $this->db->get()->result();
    }

    /**
     * Count users with search
     */
    public function count_users_with_search($search = '') {
        if ($search) {
            $this->db->group_start();
            $this->db->like('username', $search);
            $this->db->or_like('email', $search);
            $this->db->group_end();
        }
        
        return $this->db->count_all_results('users');
    }

    /**
     * Update user by email
     */
    public function update_user_by_email($email, $data) {
        $data['updated_at'] = date('Y-m-d H:i:s');
        $this->db->where('email', $email);
        $this->db->update('users', $data);
        return $this->db->affected_rows() > 0;
    }

    /**
     * Delete user by ID
     */
    public function delete_user($id) {
        $this->db->where('id', $id);
        $this->db->delete('users');
        return $this->db->affected_rows() > 0;
    }
}
