<?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', 'activity_type', 'target_id', 'ip_address', 'user_agent', 'created_at',
    ];

    public function record(string $type, ?int $user_id = null, ?int $target_id = null): void
    {
        $request = service('request');
        $this->insert([
            'user_id'       => $user_id,
            'activity_type' => $type,
            'target_id'     => $target_id,
            'ip_address'    => $request->getIPAddress(),
            'user_agent'    => substr($request->getUserAgent()->getAgentString(), 0, 255),
            'created_at'    => date('Y-m-d H:i:s'),
        ]);
    }

    public function getRecentLogs(int $limit = 50, array $filters = []): array
    {
        $builder = $this->db->table('activity_logs al')
            ->select('al.*, up.name AS user_name, up.role, d.title AS document_title')
            ->join('user_profiles up', 'up.user_id = al.user_id', 'left')
            ->join('documents d', 'd.id = al.target_id', 'left');

        if (!empty($filters['type'])) {
            $builder->where('al.activity_type', $filters['type']);
        }
        if (!empty($filters['user_id'])) {
            $builder->where('al.user_id', $filters['user_id']);
        }
        if (!empty($filters['date_from'])) {
            $builder->where('al.created_at >=', $filters['date_from'] . ' 00:00:00');
        }
        if (!empty($filters['date_to'])) {
            $builder->where('al.created_at <=', $filters['date_to'] . ' 23:59:59');
        }

        return $builder->orderBy('al.created_at', 'DESC')->limit($limit)->get()->getResultArray();
    }
}
