<?php

namespace App\Http\Controllers\Persona;

use App\Http\Controllers\Controller;
use App\Http\Requests\Persona\PersonaRequest;
use App\Models\Persona\Persona;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class PersonaController extends Controller
{
    private function searchPersona(string $search): Builder
    {
        return Persona::where(function ($query) use ($search) {
            $query
                ->where('dni', 'like', "%$search%")
                ->orWhere('nombres', 'like', "%$search%")
                ->orWhere('apellido_paterno', 'like', "%$search%")
                ->orWhere('apellido_materno', 'like', "%$search%")
                ->orWhere('celular', 'like', "%$search%")
                ->orWhere('domicilio', 'like', "%$search%");
        });
    }

    public function getAll(Request $request): JsonResponse
    {
        $pagination = $request->input('pagination', 10);
        $search = $request->input('search');
        $query = Persona::query();

        if ($search) {
            $query = $this->searchPersona($search);
        }

        $personas = $query->paginate($pagination)->appends($request->query());
        
        return response()->json(
            [
                'personas' => $personas,
                'params' => $request->query() ?: null,
            ],
            200,
        );
    }

    public function show($dni): JsonResponse
    {
        $persona = Persona::where('dni', $dni)->first();

        if (!$persona) {
            $TOKEN_RENIEC = env('VITE_TOKEN_API_RENIEC');
            $client = new Client();

            try {
                $response = $client->request('GET', "https://dniruc.apisperu.com/api/v1/dni/{$dni}?token={$TOKEN_RENIEC}", [
                    'headers' => [
                        'Accept' => 'application/json',
                    ],
                    'verify' => false,
                ]);

                $data = json_decode($response->getBody(), true);

                if ($data['success'] ?? false) {
                    $persona = Persona::create([
                        'dni' => $data['dni'] ?? 0,
                        'nombres' => $data['nombres'] ?? 'NN',
                        'apellido_paterno' => $data['apellidoPaterno'] ?? 'NN',
                        'apellido_materno' => $data['apellidoMaterno'] ?? 'NN',
                    ]);

                    return response()->json(
                        [
                            'persona' => $persona,
                            'message' => 'La persona: ' . $persona->nombre . ', se ha encontrado exitosamente!.',
                        ],
                        200,
                    );
                }

                return response()->json(['message' => 'Persona no encontrada.'], 404);
            } catch (RequestException $e) {
                return response()->json(['message' => 'Error en la conexión a la API.'], 500);
            }
        }
        return response()->json(
            [
                'persona' => $persona,
                'message' => 'La persona: ' . $persona->nombre . ', se ha encontrado exitosamente!.',
            ],
            200,
        );
    }

    public function save(PersonaRequest $request): JsonResponse
    {
        $persona = Persona::create($request->validated());
        $persona->save();
        return response()->json(
            [
                'persona' => $persona,
                'message' => 'La persona: ' . $persona->nombre . ', se ha creado exitosamente!.',
            ],
            201,
        );
    }

    public function update($id, PersonaRequest $request): JsonResponse
    {
        $persona = Persona::findOrFail($id);

        if (!$persona) {
            return response()->json(['message' => 'El persona' . $request->name . ', no encontrado.'], 404);
        }

        $persona->update($request->validated());
        $persona->save();

        return response()->json(
            [
                'persona' => $persona,
                'message' => 'La persona: ' . $persona->nombre . ', se ha actualizado exitosamente!.',
            ],
            200,
        );
    }

    public function delete($id): JsonResponse
    {
        $persona = Persona::findOrFail($id);

        if (!$persona) {
            return response()->json(['message' => 'Persona no encontrado.'], 404);
        }

        $persona->delete();

        return response()->json(
            [
                'message' => 'El persona: ' . $persona->name . ', se ha eliminado exitosamente!.',
            ],
            200,
        );
    }
}
