<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Brand;

class BrandController extends Controller
{
    public function index()
    {
        return response()->json([
            'success' => true,
            'data' => Brand::orderBy('name', 'asc')->get(),
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|unique:brands,name|max:255',
            'logo' => 'nullable|string',
            'status' => 'nullable|in:active,inactive',
        ]);

        $brand = Brand::create($validated);
        return response()->json(['success' => true, 'data' => $brand], 201);
    }

    public function update(Request $request, $id)
    {
        $brand = Brand::find($id);
        if (!$brand) return response()->json(['success' => false, 'message' => 'Brand not found'], 404);

        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:brands,name,' . $id,
            'logo' => 'nullable|string',
            'status' => 'nullable|in:active,inactive',
        ]);

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

    public function destroy($id)
    {
        $brand = Brand::find($id);
        if (!$brand) return response()->json(['success' => false, 'message' => 'Brand not found'], 404);
        $brand->delete();
        return response()->json(['success' => true, 'message' => 'Brand deleted']);
    }
}
