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

class Log_model extends CI_Model {

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

    /**
     * Log user login attempt
     */
    public function log_login($user_id, $username, $status, $failure_reason = null) {
        $data = [
            'user_id' => $user_id,
            'username' => $username,
            'ip_address' => $this->input->ip_address(),
            'user_agent' => $this->input->user_agent(),
            'browser' => $this->get_browser_name(),
            'device' => $this->get_device_type(),
            'status' => $status,
            'failure_reason' => $failure_reason
        ];
        
        return $this->db->insert('login_logs', $data);
    }

    /**
     * Get login logs with pagination
     */
    public function get_login_logs($limit = 10, $offset = 0, $user_id = null, $status = null) {
        $this->db->select('login_logs.*, users.username as user_name, users.role');
        $this->db->from('login_logs');
        $this->db->join('users', 'users.id = login_logs.user_id', 'left');
        
        if ($user_id) {
            $this->db->where('login_logs.user_id', $user_id);
        }
        
        if ($status) {
            $this->db->where('login_logs.status', $status);
        }
        
        $this->db->limit($limit, $offset);
        $this->db->order_by('login_logs.created_at', 'DESC');
        
        return $this->db->get()->result();
    }

    /**
     * Count login logs
     */
    public function count_login_logs($user_id = null, $status = null) {
        if ($user_id) {
            $this->db->where('user_id', $user_id);
        }
        
        if ($status) {
            $this->db->where('status', $status);
        }
        
        return $this->db->count_all_results('login_logs');
    }

    /**
     * Log audit activity
     */
    public function log_audit($user_id, $action, $module, $description = null) {
        $data = [
            'user_id' => $user_id,
            'action' => $action,
            'module' => $module,
            'description' => $description,
            'ip_address' => $this->input->ip_address(),
            'user_agent' => $this->input->user_agent()
        ];
        
        return $this->db->insert('audit_logs', $data);
    }

    /**
     * Get audit logs with pagination
     */
    public function get_audit_logs($limit = 10, $offset = 0, $user_id = null, $module = null) {
        $this->db->select('audit_logs.*, users.username, users.role');
        $this->db->from('audit_logs');
        $this->db->join('users', 'users.id = audit_logs.user_id', 'left');
        
        if ($user_id) {
            $this->db->where('audit_logs.user_id', $user_id);
        }
        
        if ($module) {
            $this->db->where('audit_logs.module', $module);
        }
        
        $this->db->limit($limit, $offset);
        $this->db->order_by('audit_logs.created_at', 'DESC');
        
        return $this->db->get()->result();
    }

    /**
     * Count audit logs
     */
    public function count_audit_logs($user_id = null, $module = null) {
        if ($user_id) {
            $this->db->where('user_id', $user_id);
        }
        
        if ($module) {
            $this->db->where('module', $module);
        }
        
        return $this->db->count_all_results('audit_logs');
    }

    /**
     * Get recent login activity
     */
    public function get_recent_logins($limit = 5) {
        $this->db->select('login_logs.*, users.username, users.role');
        $this->db->from('login_logs');
        $this->db->join('users', 'users.id = login_logs.user_id', 'left');
        $this->db->where('login_logs.status', 'success');
        $this->db->limit($limit);
        $this->db->order_by('login_logs.created_at', 'DESC');
        
        return $this->db->get()->result();
    }

    /**
     * Get failed login attempts for user
     */
    public function get_failed_attempts($username, $minutes = 30) {
        $this->db->from('login_logs');
        $this->db->where('username', $username);
        $this->db->where('status', 'failed');
        $this->db->where('created_at >=', date('Y-m-d H:i:s', strtotime("-$minutes minutes")));
        
        return $this->db->count_all_results();
    }

    /**
     * Get browser name from user agent
     */
    private function get_browser_name() {
        $user_agent = $this->input->user_agent();
        
        if (strpos($user_agent, 'Firefox') !== false) {
            return 'Firefox';
        } elseif (strpos($user_agent, 'Chrome') !== false) {
            return 'Chrome';
        } elseif (strpos($user_agent, 'Safari') !== false) {
            return 'Safari';
        } elseif (strpos($user_agent, 'Edge') !== false) {
            return 'Edge';
        } elseif (strpos($user_agent, 'Opera') !== false || strpos($user_agent, 'OPR') !== false) {
            return 'Opera';
        } elseif (strpos($user_agent, 'MSIE') !== false || strpos($user_agent, 'Trident') !== false) {
            return 'Internet Explorer';
        }
        
        return 'Unknown';
    }

    /**
     * Get device type from user agent
     */
    private function get_device_type() {
        $user_agent = $this->input->user_agent();
        
        if (preg_match('/mobile|android|iphone|ipad|ipod|blackberry|webos|windows phone/i', $user_agent)) {
            if (preg_match('/ipad|tablet/i', $user_agent)) {
                return 'Tablet';
            }
            return 'Mobile';
        }
        
        return 'Desktop';
    }

    /**
     * Get activity summary for dashboard
     */
    public function get_activity_summary($days = 7) {
        $this->db->select('DATE(created_at) as date, COUNT(*) as total');
        $this->db->from('audit_logs');
        $this->db->where('created_at >=', date('Y-m-d', strtotime("-$days days")));
        $this->db->group_by('DATE(created_at)');
        $this->db->order_by('date', 'ASC');
        
        return $this->db->get()->result();
    }

    /**
     * Get login statistics
     */
    public function get_login_stats() {
        $stats = [];
        
        // Total logins today
        $this->db->from('login_logs');
        $this->db->where('DATE(created_at)', date('Y-m-d'));
        $this->db->where('status', 'success');
        $stats['today_logins'] = $this->db->count_all_results();
        
        // Failed logins today
        $this->db->from('login_logs');
        $this->db->where('DATE(created_at)', date('Y-m-d'));
        $this->db->where('status', 'failed');
        $stats['today_failed'] = $this->db->count_all_results();
        
        // Total unique users logged in today
        $this->db->select('COUNT(DISTINCT user_id) as total');
        $this->db->from('login_logs');
        $this->db->where('DATE(created_at)', date('Y-m-d'));
        $this->db->where('status', 'success');
        $stats['unique_users_today'] = $this->db->get()->row()->total;
        
        return $stats;
    }
}
