<?php

namespace App\Http\Controllers\Administracion;

use App\Http\Controllers\Controller;
use App\Models\Postulante;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PostulanteController extends Controller
{
    public function obtenerPostulantes(Request $request)
    {
        $query = Postulante::query();

        if ($request->buscar) {
            $query->where(function ($q) use ($request) {
                $q->where('name', 'like', "%{$request->buscar}%")
                ->orWhere('email', 'like', "%{$request->buscar}%")
                ->orWhere('dni', 'like', "%{$request->buscar}%");
            });
        }

        $postulantes = $query->orderBy('id', 'desc')
            ->paginate(20);

        return response()->json([
            'success' => true,
            'data' => $postulantes
        ]);
    }

    public function actualizarPostulante(Request $request, $id)
    {
        $postulante = Postulante::findOrFail($id);

        $request->validate([
            'name'  => 'required|string|max:255',
            'email' => 'required|email|unique:postulantes,email,' . $postulante->id,
            'dni'   => 'required|string|max:20|unique:postulantes,dni,' . $postulante->id,
            'password' => 'nullable|string|min:6'
        ]);

        $postulante->update([
            'name'  => $request->name,
            'email' => $request->email,
            'dni'   => $request->dni,
        ]);

        // 🔹 Solo si envían nueva contraseña
        if ($request->filled('password')) {
            $postulante->password = $request->password; 
            $postulante->save();
        }

        return response()->json([
            'success' => true,
            'message' => 'Postulante actualizado correctamente',
            'data'    => $postulante
        ]);
    }


}
