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

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

class ProveedorController extends Controller
{
    public function index()
    {
        return response()->json(Proveedor::where('activo', 1)->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',
            'notas'    => 'nullable|string'
        ]);
        $proveedor = Proveedor::create([
            ...$request->only(['nombre', 'telefono', 'email', 'notas']),
            'activo' => 1
        ]);
        return response()->json($proveedor, 201);
    }

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

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

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