<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Cie\ICD_API_Client;

class ICDController extends Controller
{
    /**
     * Función recursiva para eliminar etiquetas HTML de arrays y objetos.
     *
     * @param mixed $data Datos a procesar.
     * @return mixed Datos sin etiquetas HTML.
     */
    private function recursiveStripTags($data)
    {
        if (is_array($data)) {
            return array_map([$this, 'recursiveStripTags'], $data);
        } elseif (is_object($data)) {
            foreach ($data as $key => $value) {
                $data->$key = $this->recursiveStripTags($value);
            }
            return $data;
        } elseif (is_string($data)) {
            return strip_tags($data);
        }
        return $data;
    }

    /**
     * Obtener datos de entidad ICD
     * 
     * @param string $desease Término a buscar
     * @return JsonResponse
     */
    public function getDesease(string $desease): JsonResponse
    {
        try {
            $releaseId = env("CIE_RELEASE_ID");
            $linearizationName = env("LINEARIZATION_NAME");
            $apiUrl = "https://id.who.int/icd/release/11/{$releaseId}/{$linearizationName}/search?q=" . $desease;

            // Instanciar el cliente API
            $client = new ICD_API_Client($apiUrl);
            
            // Realizar la solicitud
            $response = $client->get();

            // Limpiar la data eliminando etiquetas HTML
            $cleanResponse = $this->recursiveStripTags($response);

            return response()->json([
                'success' => true,
                'data' => $cleanResponse
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error al consultar la API ICD',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
