context = $context; $this->voucherService = $voucherService; $this->parentService = $parentService; $this->applyService = $applyService; } public function options(): JsonResponse { $schoolYear = $this->context->getSchoolYear(); $vouchers = $this->voucherService->listActive(); $parents = $this->parentService->listParentsWithDiscounts($schoolYear); return response()->json([ 'ok' => true, 'vouchers' => DiscountVoucherResource::collection($vouchers), 'parents' => DiscountParentResource::collection($parents), 'schoolYear' => $schoolYear, ]); } public function apply(ApplyDiscountVoucherRequest $request): JsonResponse { $guard = $this->authenticatedUserIdOrUnauthorized(); if ($guard instanceof JsonResponse) { return $guard; } $payload = $request->validated(); $result = $this->applyService->applyVoucher( (int) $payload['voucher_id'], $payload['parent_ids'], (bool) ($payload['allow_additional'] ?? false), $guard ); return response()->json($result, $result['ok'] ? 200 : 422); } public function listVouchers(): JsonResponse { $vouchers = $this->voucherService->listAll(); return response()->json([ 'ok' => true, 'vouchers' => DiscountVoucherResource::collection($vouchers), ]); } public function storeVoucher(StoreDiscountVoucherRequest $request): JsonResponse { $voucher = $this->voucherService->create($request->validated()); return response()->json([ 'ok' => true, 'voucher' => new DiscountVoucherResource($voucher), ], 201); } public function updateVoucher(UpdateDiscountVoucherRequest $request, int $id): JsonResponse { $voucher = $this->voucherService->update($id, $request->validated()); return response()->json([ 'ok' => true, 'voucher' => new DiscountVoucherResource($voucher), ]); } public function showVoucher(int $id): JsonResponse { $voucher = $this->voucherService->find($id); return response()->json([ 'ok' => true, 'voucher' => new DiscountVoucherResource($voucher), ]); } public function deleteVoucher(int $id): JsonResponse { $this->voucherService->delete($id); return response()->json([ 'ok' => true, ]); } /** * @return int|JsonResponse */ private function authenticatedUserIdOrUnauthorized(): int|JsonResponse { $userId = (int) (auth()->id() ?? 0); if ($userId <= 0) { return response()->json(['ok' => false, 'message' => 'Unauthorized.'], 401); } return $userId; } }