<?php

namespace App\Http\Controllers\Api;

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

class ActivityLogController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Activity::with('causer')->latest();

        if ($request->event) {
            $query->where('description', 'like', "%{$request->event}%");
        }

        if ($request->date_from) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        $perPage = (int) ($request->per_page ?? 20);
        $data    = $query->paginate($perPage);

        return response()->json([
            'success' => true,
            'data'    => $data->map(fn($log) => [
                'id'          => $log->id,
                'description' => $log->description,
                'causer_name' => $log->causer?->name ?? 'System',
                'created_at'  => $log->created_at->toDateTimeString(),
            ]),
            'meta'    => [
                'current_page' => $data->currentPage(),
                'last_page'    => $data->lastPage(),
                'per_page'     => $data->perPage(),
                'total'        => $data->total(),
            ],
        ]);
    }
}
