<?php
namespace App\Http\Controllers\Api;

use App\Models\Cliente;
use Illuminate\Http\Request;

class ClienteController extends Controller
{
    public function index(Request $request)
    {
        $query = Cliente::where('activo', 1);

        if ($request->has('buscar')) {
            $query->where(function($q) use ($request) {
                $q->where('nombre',    'like', '%' . $request->buscar . '%')
                  ->orWhere('telefono', 'like', '%' . $request->buscar . '%')
                  ->orWhere('documento','like', '%' . $request->buscar . '%');
            });
        }

        return response()->json($query->orderBy('nombre')->get());
    }

    public function store(Request $request)
    {
        $request->validate([
            'nombre'    => 'required|string|max:255',
            'telefono'  => 'nullable|string|max:20',
            'email'     => 'nullable|email|max:255',
            'documento' => 'nullable|string|max:20'
        ]);
        $cliente = Cliente::create([
            ...$request->only(['nombre', 'telefono', 'email', 'documento']),
            'activo' => 1
        ]);
        return response()->json($cliente, 201);
    }

    public function show($id)
    {
        return response()->json(Cliente::findOrFail($id));
    }

    public function update(Request $request, $id)
    {
        $cliente = Cliente::findOrFail($id);
        $request->validate([
            'nombre'    => 'required|string|max:255',
            'telefono'  => 'nullable|string|max:20',
            'email'     => 'nullable|email|max:255',
            'documento' => 'nullable|string|max:20'
        ]);
        $cliente->update($request->only(['nombre', 'telefono', 'email', 'documento']));
        return response()->json($cliente);
    }

    public function destroy($id)
    {
        $cliente = Cliente::findOrFail($id);
        $cliente->update(['activo' => 0]);
        return response()->json(['message' => 'Cliente desactivado']);
    }
}