<?php

namespace App\Exceptions;

// ... other use statements
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Request;
use Throwable;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler extends ExceptionHandler
{
    // ... other methods

    /**
     * Render an exception into an HTTP response.
     */
    public function render($request, Throwable $exception)
    {
        // Handle ValidationException globally
        // if ($exception instanceof ValidationException) {
        //     return response()->json([
        //         'status' => 'error',
        //         'message' => 'The given data was invalid.',
        //         'errors' => $exception->errors(),
        //     ], 422);
        // }

        // return parent::render($request, $exception);

        // Check if the request is asking for a JSON response
        if ($request->wantsJson()) {
            
            // Handle 404 Not Found for API requests
            if ($exception instanceof NotFoundHttpException) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Resource not found.',
                ], 404);
            }

            // Handle Validation Errors for API requests
            if ($exception instanceof ValidationException) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'The given data was invalid.',
                    'errors' => $exception->errors(),
                ], 422);
            }
        }

        // For all other requests (e.g., from a browser), use the default handler
        // which will render the standard HTML error pages.
        return parent::render($request, $exception);
    }

    protected function unauthenticated($request, \Illuminate\Auth\AuthenticationException $exception)
    {
        if ($request->is('api/*')) {
            return response()->json(['message' => 'Unauthenticated.'], 401);
        }

        return redirect()->guest(route('login'));
    }

}