<?php

namespace App\Models;

use CodeIgniter\Model;
use Config\Services;

class SecurityLogModel extends Model
{
    protected $table = 'security_logs';
    protected $primaryKey = 'id';
    protected $allowedFields = [
        'user_id',
        'ip_address',
        'user_agent',
        'event_type',
        'description',
        'severity',
        'created_at'
    ];
    protected $useTimestamps = false;
    
    /**
     * Log a security event
     *
     * @param int|null $userId
     * @param string $eventType
     * @param string $description
     * @param string $severity (low|medium|high|critical)
     * @return bool
     */
    public function logEvent($userId, $eventType, $description, $severity = 'low')
    {
        $request = Services::request();
        
        $data = [
            'user_id' => $userId,
            'ip_address' => $request->getIPAddress(),
            'user_agent' => $request->getUserAgent() ? $request->getUserAgent()->getAgentString() : '',
            'event_type' => $eventType,
            'description' => $description,
            'severity' => $severity,
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        return $this->insert($data);
    }
    
    /**
     * Get recent security events
     *
     * @param int $limit
     * @param string|null $severity
     * @return array
     */
    public function getRecentEvents($limit = 50, $severity = null)
    {
        $builder = $this->orderBy('created_at', 'DESC')->limit($limit);
        
        if ($severity) {
            $builder->where('severity', $severity);
        }
        
        return $builder->findAll();
    }
    
    /**
     * Get security events by user
     *
     * @param int $userId
     * @param int $limit
     * @return array
     */
    public function getEventsByUser($userId, $limit = 50)
    {
        return $this->where('user_id', $userId)
                    ->orderBy('created_at', 'DESC')
                    ->limit($limit)
                    ->findAll();
    }
}