<?php

namespace App\Http\Controllers\Educacion;

use App\Http\Controllers\Controller;
use App\Http\Requests\Educacion\AreaRequest;
use App\Models\Educacion\Area;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Builder;

class AreaController extends Controller
{
    private function searchAreas(string $search): Builder
    {
        return Area::where(function ($query) use ($search) {
            $query->where('nombre', 'like', "%$search%");
        });
    }

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

        if ($search) {
            $query = $this->searchAreas($search);
        }
        $areas = $query->with('carreras', 'pivote_areas_cursos_docentes')->latest()->paginate($pagination)->appends($request->query());

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

    public function show($id): JsonResponse
    {
        $area = Area::findOrFail($id);

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

        return response()->json(
            [
                'area' => $area,
                'message' => 'El área: ' . $area->nombre . ', encontrado exitosamente!.',
            ],
            200,
        );
    }

    public function save(AreaRequest $request): JsonResponse
    {
        $area = Area::create($request->validated());
        $area->save();
        return response()->json(
            [
                'area' => $area,
                'message' => 'El área: ' . $area->nombre . ', se ha creado exitosamente!.',
            ],
            201,
        );
    }

    public function update($id, AreaRequest $request): JsonResponse
    {
        $area = Area::findOrFail($id);

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

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

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

    public function delete($id): JsonResponse
    {
        $area = Area::findOrFail($id);

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

        $area->delete();

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