<?php

namespace App\Libraries;

use CodeIgniter\Debug\ExceptionHandlerInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Throwable;

class JsonExceptionHandler implements ExceptionHandlerInterface
{
    public function handle(
        Throwable $exception,
        RequestInterface $request,
        ResponseInterface $response,
        int $statusCode,
        int $exitCode
    ): void {
        // Get the error details
        $error = [
            'status' => $statusCode,
            'message' => $exception->getMessage(),
            'file' => $exception->getFile(),
            'line' => $exception->getLine(),
        ];

        // In development, add more details
        if (ENVIRONMENT === 'development') {
            $error['trace'] = $exception->getTrace();
        }

        // Set the response
        $response->setStatusCode($statusCode);
        $response->setJSON($error);
        $response->send();
    }
} 