<?php
namespace App\Http\Controllers\Admin\Service;
use App\Http\Controllers\Controller;
use App\Models\Service\ServiceItem;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ServiceItemController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = ServiceItem::query();
        $query->when($request->name, fn($q, $v) => $q->where('name', 'like', "%{$v}%"));
        $query->when($request->category, fn($q, $v) => $q->where('category', $v));
        $query->when($request->has('status'), fn($q) => $q->where('status', $request->status));
        return $this->paginate($query->latest()->paginate($request->input('per_page', 15)));
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'category' => 'nullable|integer|in:1,2,3,4',
            'price' => 'required|numeric|min:0',
            'duration' => 'nullable|integer|min:1',
            'description' => 'nullable|string',
            'image' => 'nullable|string|max:255',
            'status' => 'sometimes|integer|in:0,1',
        ]);
        return $this->success(ServiceItem::create($validated));
    }

    public function show(ServiceItem $serviceItem): JsonResponse { return $this->success($serviceItem); }

    public function update(Request $request, ServiceItem $serviceItem): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'sometimes|string|max:100',
            'category' => 'nullable|integer|in:1,2,3,4',
            'price' => 'sometimes|numeric|min:0',
            'duration' => 'nullable|integer|min:1',
            'description' => 'nullable|string',
            'image' => 'nullable|string|max:255',
            'status' => 'sometimes|integer|in:0,1',
        ]);
        $serviceItem->update($validated);
        return $this->success($serviceItem);
    }

    public function destroy(ServiceItem $serviceItem): JsonResponse { $serviceItem->delete(); return $this->success(null); }
}
