<?php

namespace App\Models;

use CodeIgniter\Model;

/**
 * ActivityLogModel — audit trail.
 */
class ActivityLogModel extends Model
{
    protected $table       = 'activity_logs';
    protected $primaryKey  = 'id';
    protected $useTimestamps = false;
    protected $returnType  = 'array';

    protected $allowedFields = [
        'admin_id', 'action', 'module',
        'target_id', 'description', 'ip_address', 'user_agent',
    ];

    /**
     * Write a log entry.
     */
    public function log(
        string $action,
        string $module,
        ?int   $targetId    = null,
        string $description = ''
    ): void {
        $this->insert([
            'admin_id'    => session()->get('admin_id'),
            'action'      => $action,
            'module'      => $module,
            'target_id'   => $targetId,
            'description' => $description,
            'ip_address'  => service('request')->getIPAddress(),
            'user_agent'  => substr((string) service('request')->getUserAgent(), 0, 500),
        ]);
    }

    /**
     * Recent activity with admin name.
     */
    public function getRecent(int $limit = 20): array
    {
        return $this->select('activity_logs.*, admin_users.name AS admin_name')
                    ->join('admin_users', 'admin_users.id = activity_logs.admin_id', 'left')
                    ->orderBy('activity_logs.created_at', 'DESC')
                    ->limit($limit)
                    ->findAll();
    }
}
