<?php

namespace App\Http\Controllers\API\v1\Admin\ActivityLog;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Spatie\Activitylog\Models\Activity;

class IndexController extends Controller
{
    public function __invoke(Request $request)
    {
        $perPage = (int) $request->query('per_page', 25);
        if ($perPage < 1) $perPage = 25;
        if ($perPage > 200) $perPage = 200;

        $q = Activity::query()
            ->orderByDesc('id');

        if ($request->filled('description')) {
            $q->where('description', 'like', '%' . $request->query('description') . '%');
        }

        if ($request->filled('subject_type')) {
            $q->where('subject_type', (string) $request->query('subject_type'));
        }

        if ($request->filled('causer_id')) {
            $q->where('causer_id', (int) $request->query('causer_id'));
        }

        $p = $q->paginate($perPage);

        $items = collect($p->items())->map(function (Activity $a) {
            return [
                'id' => $a->id,
                'log_name' => $a->log_name,
                'description' => $a->description,
                'subject_type' => $a->subject_type,
                'subject_id' => $a->subject_id,
                'causer_type' => $a->causer_type,
                'causer_id' => $a->causer_id,
                'properties' => $a->properties,
                'created_at' => optional($a->created_at)->toDateTimeString(),
            ];
        })->values();

        return response()->json([
            'data' => $items,
            'meta' => [
                'current_page' => $p->currentPage(),
                'per_page' => $p->perPage(),
                'last_page' => $p->lastPage(),
                'total' => $p->total(),
            ],
        ]);
    }
}

