<?php

namespace App\Http\Controllers\Api\V1\Admin;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Support\ApiResponse;
use Illuminate\Http\Request;

class AuditLogController extends Controller
{
    use ApiResponse;

    public function index(Request $request)
    {
        $query = AuditLog::query()
            ->with('user:id,name,email')
            ->where('organization_id', $request->user()->organization_id);

        if ($request->filled('event')) {
            $query->where('event', 'like', $request->string('event').'%');
        }
        if ($request->filled('user_id')) {
            $query->where('user_id', $request->integer('user_id'));
        }
        if ($request->filled('date_from')) {
            $query->where('created_at', '>=', $request->date('date_from')->startOfDay());
        }
        if ($request->filled('date_to')) {
            $query->where('created_at', '<=', $request->date('date_to')->endOfDay());
        }

        $paginator = $query->orderByDesc('id')
            ->paginate(min(100, max(1, $request->integer('per_page', 30))));

        return $this->paginated($paginator, $paginator->getCollection());
    }
}
