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

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

class ColorController extends Controller
{
    public function index()
    {
        return response()->json(Color::where('activo', 1)->orderBy('nombre')->get());
    }

    public function store(Request $request)
    {
        $request->validate([
            'nombre'     => 'required|string|max:255|unique:colores,nombre',
            'codigo_hex' => 'nullable|string|max:7'
        ]);
        $color = Color::create([
            'nombre'     => $request->nombre,
            'codigo_hex' => $request->codigo_hex,
            'activo'     => 1
        ]);
        return response()->json($color, 201);
    }

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

    public function update(Request $request, $id)
    {
        $color = Color::findOrFail($id);
        $request->validate([
            'nombre'     => 'required|string|max:255|unique:colores,nombre,' . $id,
            'codigo_hex' => 'nullable|string|max:7'
        ]);
        $color->update([
            'nombre'     => $request->nombre,
            'codigo_hex' => $request->codigo_hex
        ]);
        return response()->json($color);
    }

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