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

class ServicePackageController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = ServicePackage::query();
        $query->when($request->name, fn($q, $v) => $q->where('name', 'like', "%{$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','items'=>'nullable|array','price'=>'required|numeric|min:0','validity_days'=>'nullable|integer|min:1','status'=>'sometimes|integer|in:0,1']);
        return $this->success(ServicePackage::create($validated));
    }

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

    public function update(Request $request, ServicePackage $servicePackage): JsonResponse
    {
        $validated = $request->validate(['name'=>'sometimes|string|max:100','items'=>'nullable|array','price'=>'sometimes|numeric|min:0','validity_days'=>'nullable|integer|min:1','status'=>'sometimes|integer|in:0,1']);
        $servicePackage->update($validated);
        return $this->success($servicePackage);
    }

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