<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Illuminate\Validation\ValidationException;

class Handler extends ExceptionHandler
{
    /**
     * The list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }
    
      // Add a render method to handle validation exceptions
    public function render($request, Throwable $exception)
    {
        // Check if the request expects a JSON response (i.e., it's an API request)
        if ($request->expectsJson() && $exception instanceof ValidationException) {
            
            $response = [
                'success' => false,
                'status' => 400, 
                'message' => $this->getFirstValidationError($exception),
            ];

            return response()->json($response, 200); 
        }
     
        // Default handling for non-API requests and other exceptions
        return parent::render($request, $exception);
    }
    
    private function getFirstValidationError(ValidationException $exception)
    {
        // Get the first error message from the validation errors array
        $errors = $exception->errors();
        $firstErrorField = array_key_first($errors); // Get the first field with an error
        return $errors[$firstErrorField][0]; // Return the first error message for that field
    }
}
