<?php

namespace App\Models;

use CodeIgniter\Model;

class ActivityLogModel extends Model
{
    protected $table         = 'activity_logs';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = false;

    protected $allowedFields = [
        'user_id', 'module', 'action', 'description', 'record_id',
        'ip_address', 'browser', 'operating_system', 'created_at',
    ];

    /**
     * Convenience logger. Call from any Service:
     *   (new ActivityLogModel())->log('auth', 'login', $userId, 'Successful login');
     */
    public function log(string $module, string $action, ?int $userId = null, ?string $description = null, ?string $recordId = null): void
    {
        $request = service('request');
        $agent   = $request->getUserAgent();

        $this->insert([
            'user_id'          => $userId,
            'module'           => $module,
            'action'           => $action,
            'description'      => $description,
            'record_id'        => $recordId,
            'ip_address'       => $request->getIPAddress(),
            'browser'          => $agent->getBrowser() ?: null,
            'operating_system' => $agent->getPlatform() ?: null,
            'created_at'       => date('Y-m-d H:i:s'),
        ]);
    }
}
