<?php
namespace App\Http\Middleware;
use App\Models\AuditLog;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class AuditRequest {
    public function handle(Request $request, Closure $next, string $module='system'): Response {
        $response=$next($request);
        if ($request->user() && !$request->isMethodSafe()) {
            $pathParts=array_values(array_filter(explode('/',$request->path())));
            $derivedModule=$module==='system' ? ($pathParts[0] ?? 'system') : $module;
            $orgId=$request->user()->organization_id;
            if($request->user()->isSuperAdmin() && $request->filled('organization_id')) $orgId=(int)$request->input('organization_id');
            AuditLog::create([
                'organization_id'=>$orgId ?: null,
                'user_id'=>$request->user()->id,
                'action'=>strtolower($request->method()),
                'module'=>$derivedModule,
                'description'=>$request->user()->name.' melakukan '.$request->method().' pada '.$request->path(),
                'ip_address'=>$request->ip(),
                'user_agent'=>substr((string)$request->userAgent(),0,500),
                'meta'=>['route'=>optional($request->route())->getName()],
                'created_at'=>now(),
            ]);
        }
        return $response;
    }
}
