<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class HandleLivewireErrors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        try {
            $response = $next($request);

            // التحقق من أن الاستجابة صحيحة
            if ($response->getStatusCode() >= 500) {
                Log::error('Livewire 500 Error', [
                    'url' => $request->fullUrl(),
                    'method' => $request->method(),
                    'user_id' => \Illuminate\Support\Facades\Auth::check() ? \Illuminate\Support\Facades\Auth::user()->id : null,
                    'user_agent' => $request->userAgent(),
                    'ip' => $request->ip()
                ]);
            }

            return $response;

        } catch (\Throwable $e) {
            Log::error('Livewire Exception', [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'url' => $request->fullUrl(),
                'method' => $request->method(),
                'user_id' => \Illuminate\Support\Facades\Auth::check() ? \Illuminate\Support\Facades\Auth::user()->id : null,
                'trace' => $e->getTraceAsString()
            ]);

            // إذا كان طلب AJAX (Livewire)
            if ($request->expectsJson() || $request->header('X-Livewire')) {
                return response()->json([
                    'message' => 'حدث خطأ في الخادم. يرجى المحاولة مرة أخرى.',
                    'error' => true
                ], 500);
            }

            // إعادة رفع الاستثناء للمعالجة الافتراضية
            throw $e;
        }
    }
}
