$request Request. * @param array $opt staff_rules, except_booking. * @return array */ public function quote( array $request, array $opt = array() ): array { $request = self::request( $request ); $items = $this->prepare( $request, $opt + array( 'check' => false ) ); $quote = $this->price( $items, (string) ( $request['coupon'] ?? '' ), true ); $summary = $this->summary( $items, $quote, (string) ( $request['payment_method'] ?? '' ) ); /** * What the customer sees before booking, e.g. a gift card Pro will take off. * * @param array $summary Summary: quote, methods, items, policy. * @param array $request Request. */ return (array) apply_filters( 'schedulereed_quote_summary', $summary, $request ); } /** * Let Pro reshape a request before it is priced, held or booked, e.g. to * repeat one item weekly. * * @param array $request Request. * @return array */ private static function request( array $request ): array { /** * Change a booking request before anything else looks at it. * * @param array $request Request: items, customer, coupon, ... */ return (array) apply_filters( 'schedulereed_booking_request', $request ); } /** * Hold the chosen time for a few minutes while the customer checks out. * * @param array $request Request with items. * @return array{token: string, expires_at: int} * @throws BookingException When the time is no longer free. */ public function hold( array $request ): array { $token = (string) ( $request['hold'] ?? '' ); $token = 1 === preg_match( '/^[A-Za-z0-9]{20,64}$/', $token ) ? $token : wp_generate_password( 32, false ); $expires = Clock::now() + (int) Settings::scheduling()['hold_minutes'] * MINUTE_IN_SECONDS; $request = self::request( $request ); $result = Services::bookings()->locked( self::LOCK, function () use ( $request, $token, $expires ): array { Services::holds()->release( $token ); $items = $this->prepare( $request, array( 'except_hold' => $token ) ); foreach ( $items as $item ) { Services::holds()->create( $token, $item, $expires ); } return array( 'token' => $token, 'expires_at' => $expires, ); } ); if ( null === $result ) { throw new BookingException( 'schedulereed_busy', __( 'Lots of people are booking right now. Please try again.', 'schedulereed' ), 503 ); } Cache::bump(); return $result; } /** * Let go of a hold, e.g. when the customer goes back. * * @param string $token Token. */ public function release( string $token ): void { Services::holds()->release( $token ); Cache::bump(); } /** * Book a request online. * * @param array $request Request. * @return array The booking, with `next` (what the customer does next). * @throws BookingException When something is missing or the time was taken. */ public function book( array $request ): array { return $this->create( $request, 'online', array() ); } /** * Book on a customer's behalf from the admin: notice and horizon don't * apply, an email is optional, and the booking is confirmed unless asked. * * @param array $request Request; may carry status, force (ignore conflicts) and notify. * @return array * @throws BookingException When the time is taken and force is off. */ public function book_by_staff( array $request ): array { return $this->create( $request, (string) ( $request['source'] ?? 'admin' ), array( 'staff_rules' => true ) ); } /** * Create a booking. * * @param array $request Request. * @param string $source online, admin, import, ... * @param array $opt Options. * @return array * @throws BookingException When it cannot be booked. */ private function create( array $request, string $source, array $opt ): array { $request = self::request( $request ); $by_staff = ! empty( $opt['staff_rules'] ); $customer = $this->customer_input( (array) ( $request['customer'] ?? array() ), $by_staff ); $fields = $this->fields( $request, $by_staff ); $method = $this->method( (string) ( $request['payment_method'] ?? '' ), $by_staff ); if ( ! $by_staff ) { $this->check_consent( (array) ( $request['consent'] ?? array() ) ); } $force = $by_staff && ! empty( $request['force'] ); $hold = (string) ( $request['hold'] ?? '' ); /** * Stop a booking before it is made, e.g. to check a captcha or a membership. * * @param null|\WP_Error $error Return a WP_Error to refuse. * @param array $request Request. * @param string $source Where it comes from. */ $refused = apply_filters( 'schedulereed_before_booking', null, $request, $source ); if ( $refused instanceof \WP_Error ) { throw new BookingException( (string) $refused->get_error_code(), $refused->get_error_message(), 400 ); } $booking_id = Services::bookings()->locked( self::LOCK, function () use ( $request, $opt, $hold, $force, $customer, $fields, $method, $source, $by_staff ): int { $items = $this->prepare( $request, $opt + array( 'except_hold' => $hold, 'check' => ! $force, ) ); $quote = $this->price( $items, (string) ( $request['coupon'] ?? '' ), true ); if ( '' !== $quote->coupon && ! Services::coupons()->use( $quote->coupon ) ) { throw new BookingException( 'schedulereed_invalid_coupon', __( 'That code has just been used up.', 'schedulereed' ) ); } $customer_id = Services::customers()->upsert( $customer + array( 'user_id' => $by_staff ? 0 : get_current_user_id(), 'consent' => $this->consent_record( (array) ( $request['consent'] ?? array() ) ), ) ); /** * Minor units already covered before payment, e.g. Pro's gift * cards and package credits. Runs inside the booking lock; the * covering payments are recorded on schedulereed_booking_prepaid. * * @param int $prepaid Amount covered. * @param array $request Request. * @param int $total Booking total. * @param int $customer_id Customer. * @param array $items Prepared items. */ $prepaid = max( 0, min( $quote->total, (int) apply_filters( 'schedulereed_prepaid', 0, $request, $quote->total, $customer_id, $items ) ) ); $due = $quote->total - $prepaid; $policy = $this->policy_for( $items ); $deposit = min( $due, $this->deposit_for( $items )->due_now( $quote->total ) ); $online = $method instanceof OnlinePaymentMethod && $due > 0; $approval = $by_staff ? 'auto' : $this->approval_for( $items ); $status = Status::CONFIRMED; if ( $by_staff && in_array( $request['status'] ?? '', array( Status::PENDING, Status::CONFIRMED ), true ) ) { $status = (string) $request['status']; } elseif ( 'manual' === $approval ) { $status = Status::PENDING; } elseif ( $online && ! $by_staff ) { $status = Status::AWAITING_PAYMENT; } $booking = array( 'uid' => self::reference(), 'token' => wp_generate_password( 32, false ), 'customer_id' => $customer_id, 'status' => $status, 'source' => $source, 'start' => (int) min( array_column( $items, 'start' ) ), 'end' => (int) max( array_column( $items, 'end' ) ), 'total' => $quote->total, 'deposit' => $method && $method->takes_deposit() ? $prepaid + $deposit : 0, 'currency' => Settings::currency(), 'payment_method' => $method ? $method->id() : '', 'charges' => $quote->to_array(), 'policy' => $policy, 'fields' => $fields, 'timezone' => $customer['timezone'], 'locale' => determine_locale(), 'notes' => (string) ( $customer['notes'] ?? '' ), 'staff_notes' => $by_staff ? sanitize_textarea_field( (string) ( $request['staff_notes'] ?? '' ) ) : '', 'series' => count( $items ) > 1 ? (string) ( $request['series'] ?? '' ) : '', 'coupon' => $quote->coupon, 'meeting_url' => $this->meeting_for( $items ), 'expires_at' => Status::AWAITING_PAYMENT === $status ? Clock::now() + (int) Settings::scheduling()['pay_minutes'] * MINUTE_IN_SECONDS : 0, ); foreach ( $items as $i => $item ) { $items[ $i ]['price'] = (int) ( $quote->lines[ $i ]['subtotal'] ?? 0 ) - (int) ( $quote->lines[ $i ]['discount'] ?? 0 ); } $id = Services::bookings()->create( $booking, $items ); if ( $prepaid > 0 ) { /** * Record what covered part of a new booking (see schedulereed_prepaid). * * @param int $booking_id Booking. * @param int $prepaid Amount covered. * @param array $request Request. * @param int $customer_id Customer. */ do_action( 'schedulereed_booking_prepaid', $id, $prepaid, $request, $customer_id ); } if ( '' !== $hold ) { Services::holds()->release( $hold ); } return $id; } ); if ( null === $booking_id ) { throw new BookingException( 'schedulereed_busy', __( 'Lots of people are booking right now. Please try again.', 'schedulereed' ), 503 ); } Cache::bump(); $booking = Services::bookings()->find( $booking_id ); /** * Fires as soon as a booking is saved, whatever its status, e.g. so * Pro can link uploaded form files to it. * * @param array $booking Booking. * @param array $request Request. */ do_action( 'schedulereed_booking_saved', $booking, $request ); Services::activity()->record( $booking_id, 'created', array( 'source' => $source, 'status' => $booking['status'], ) ); $notify = ! $by_staff || ! empty( $request['notify'] ); if ( Status::AWAITING_PAYMENT !== $booking['status'] ) { /** * Fires once a booking exists and keeps its time (not while it waits for payment). * * @param array $booking Booking. * @param bool $notify Whether the customer should be told. */ do_action( 'schedulereed_booking_created', $booking, $notify ); } $booking['next'] = $this->next_step( $booking ); return $booking; } /** * What the customer does after booking: pay online, or nothing. * * @param array $booking Booking. * @return array */ private function next_step( array $booking ): array { if ( Status::AWAITING_PAYMENT === $booking['status'] ) { try { return array( 'action' => 'redirect', 'url' => Services::payment_flow()->start( $booking ), ); } catch ( \Throwable $e ) { return array( 'action' => 'pay_failed', 'message' => __( 'We could not open the payment page. Please try again from your booking page.', 'schedulereed' ), 'url' => Format::manage_url( $booking ), ); } } return array( 'action' => 'done', 'url' => Format::manage_url( $booking ), ); } /** * The online meeting link for a booking: for services set to a fixed * link, the staff member's own room (Settings → Staff). Pro adds Zoom * and Google Meet through the filter. * * @param array> $items Prepared items. */ private function meeting_for( array $items ): string { $item = $items[0] ?? null; $bookable = null !== $item ? Services::catalog()->bookable( (int) $item['bookable_id'] ) : null; if ( null === $bookable || '' === $bookable->settings['meeting'] ) { return ''; } $url = ''; if ( 'custom' === $bookable->settings['meeting'] && $item['staff_id'] > 0 ) { $staff = Services::staff()->find( (int) $item['staff_id'] ); $url = (string) ( $staff['settings']['meeting_url'] ?? '' ); } /** * The meeting link for a new booking. * * @param string $url Link, or ''. * @param Bookable $bookable Service. * @param array $item First item. */ return esc_url_raw( (string) apply_filters( 'schedulereed_meeting_url', $url, $bookable, $item ) ); } /** * After an online payment: the booking keeps its time for good. * * @param int $booking_id Booking. */ public function paid( int $booking_id ): void { $booking = Services::bookings()->find( $booking_id ); if ( null === $booking || Status::AWAITING_PAYMENT !== $booking['status'] ) { return; } $status = 'manual' === $this->approval_for( $booking['items'] ) ? Status::PENDING : Status::CONFIRMED; Services::bookings()->update( $booking_id, array( 'status' => $status, 'expires_at' => 0, ) ); Cache::bump(); $booking = Services::bookings()->find( $booking_id ); Services::activity()->record( $booking_id, 'paid_online', array( 'status' => $status ) ); do_action( 'schedulereed_booking_created', $booking, true ); } /** * Approve a pending booking. * * @param int $booking_id Booking. * @return array * @throws BookingException When it is not pending. */ public function confirm( int $booking_id ): array { $booking = $this->booking( $booking_id ); if ( Status::PENDING !== $booking['status'] ) { throw new BookingException( 'schedulereed_not_pending', __( 'Only bookings waiting for approval can be approved.', 'schedulereed' ), 409 ); } Services::bookings()->update( $booking_id, array( 'status' => Status::CONFIRMED ) ); Services::activity()->record( $booking_id, 'confirmed' ); $booking = Services::bookings()->find( $booking_id ); /** * Fires when the owner approves a pending booking. * * @param array $booking Booking. */ do_action( 'schedulereed_booking_confirmed', $booking ); return $booking; } /** * Change a booking's status by hand: completed, no_show, confirmed again. * * @param int $booking_id Booking. * @param string $status New status. * @return array * @throws BookingException When the move is not allowed. */ public function set_status( int $booking_id, string $status ): array { $booking = $this->booking( $booking_id ); if ( Status::CANCELLED === $status ) { return $this->cancel( $booking_id, 'staff' ); } if ( Status::CONFIRMED === $status && Status::PENDING === $booking['status'] ) { return $this->confirm( $booking_id ); } if ( ! Status::can_move( $booking['status'], $status ) ) { throw new BookingException( 'schedulereed_bad_status', __( 'The booking cannot move to that status.', 'schedulereed' ), 409 ); } $data = array( 'status' => $status ); if ( Status::COMPLETED === $status && 0 === $booking['checked_in_at'] ) { $data['checked_in_at'] = Clock::now(); } Services::bookings()->update( $booking_id, $data ); Services::activity()->record( $booking_id, 'status', array( 'from' => $booking['status'], 'to' => $status, ) ); $booking = Services::bookings()->find( $booking_id ); /** * Fires after staff change a booking's status. * * @param array $booking Booking. * @param string $from Old status. */ do_action( 'schedulereed_booking_status', $booking, $data['status'] === $status ? $booking['status'] : $status ); if ( Status::NO_SHOW === $status ) { do_action( 'schedulereed_booking_no_show', $booking ); } return $booking; } /** * Mark a customer as arrived (event and class check-in). * * @param int $booking_id Booking. * @return array * @throws BookingException When the booking is cancelled. */ public function check_in( int $booking_id ): array { $booking = $this->booking( $booking_id ); if ( ! in_array( $booking['status'], array( Status::CONFIRMED, Status::COMPLETED, Status::NO_SHOW ), true ) ) { throw new BookingException( 'schedulereed_bad_status', __( 'Only confirmed bookings can be checked in.', 'schedulereed' ), 409 ); } Services::bookings()->update( $booking_id, array( 'checked_in_at' => Clock::now(), 'status' => Status::COMPLETED, ) ); Services::activity()->record( $booking_id, 'checked_in' ); $booking = Services::bookings()->find( $booking_id ); do_action( 'schedulereed_booking_checked_in', $booking ); return $booking; } /** * Cancel a booking and give money back. * * @param int $booking_id Booking. * @param string $by customer, staff, business (the business cancelled; refund all) or system. * @param int|null $refund Amount to refund; null = what the policy gives. * @param bool $refund_online Refund through the payment provider when possible. * @param string $reason Told to the customer. * @return array * @throws BookingException When it is already cancelled or the customer is too late. */ public function cancel( int $booking_id, string $by = 'staff', ?int $refund = null, bool $refund_online = true, string $reason = '' ): array { $booking = $this->booking( $booking_id ); if ( Status::CANCELLED === $booking['status'] ) { throw new BookingException( 'schedulereed_already_cancelled', __( 'This booking is already cancelled.', 'schedulereed' ), 409 ); } $now = Clock::now(); if ( 'customer' === $by && ! Settings::changes()->can_cancel( $booking['start'], $now ) ) { throw new BookingException( 'schedulereed_too_late', __( 'It is too late to cancel online. Please contact us.', 'schedulereed' ), 403 ); } if ( null === $refund ) { $refund = $this->refund_due( $booking, $by, $now ); } $refund = max( 0, min( $booking['paid'], $refund ) ); Services::bookings()->update( $booking_id, array( 'status' => Status::CANCELLED, 'cancelled_at' => $now, 'expires_at' => 0, ) ); if ( '' !== $booking['coupon'] ) { Services::coupons()->release( $booking['coupon'] ); } Cache::bump(); Services::activity()->record( $booking_id, 'cancelled', array( 'by' => $by, 'refund' => $refund, 'reason' => $reason, ) ); $refund_note = ''; if ( $refund > 0 ) { $refund_note = Services::refunds()->refund( $booking_id, $refund, $refund_online, 'customer' === $by ? __( 'Cancelled by the customer', 'schedulereed' ) : __( 'Cancelled', 'schedulereed' ) ); } $booking = Services::bookings()->find( $booking_id ); $booking['refund_note'] = $refund_note; $booking['cancel_reason'] = $reason; /** * Fires after a booking is cancelled. * * @param array $booking Booking, with refund_note and cancel_reason. * @param string $by Who cancelled. */ do_action( 'schedulereed_booking_cancelled', $booking, $by ); return $booking; } /** * What a cancellation gives back under the booking's policy. * * @param array $booking Booking. * @param string $by Who cancels. * @param int $now Now. */ public function refund_due( array $booking, string $by, int $now ): int { if ( in_array( $by, array( 'business', 'system' ), true ) ) { return $booking['paid']; } $policy = null; try { $policy = CancellationPolicy::from_array( $booking['policy']['cancellation'] ?? null ); } catch ( InvalidArgumentException ) { $policy = null; } if ( null === $policy ) { // No terms: customers get nothing automatically, staff decide. return 'customer' === $by ? 0 : $booking['paid']; } return $policy->refund( $booking['total'], $booking['paid'], $booking['start'] - $now )['refund']; } /** * Move a booking to another time, staff member or both. * * @param int $booking_id Booking. * @param array $change items: [{start, staff_id, date, units}] in the booking's item order, or start/staff_id for one item. * @param string $by customer or staff. * @param bool $force Staff only: ignore conflicts. * @return array * @throws BookingException When the new time is not free or the customer may not move it. */ public function reschedule( int $booking_id, array $change, string $by = 'staff', bool $force = false ): array { $booking = $this->booking( $booking_id ); if ( ! Status::holds_time( $booking['status'] ) || in_array( $booking['status'], array( Status::COMPLETED, Status::NO_SHOW ), true ) ) { throw new BookingException( 'schedulereed_bad_status', __( 'This booking cannot be moved.', 'schedulereed' ), 409 ); } $now = Clock::now(); if ( 'customer' === $by && ! Settings::changes()->can_reschedule( $booking['start'], $now, $booking['rescheduled'] ) ) { throw new BookingException( 'schedulereed_too_late', __( 'This booking can no longer be moved online. Please contact us.', 'schedulereed' ), 403 ); } $items = $this->items_from( $booking, isset( $change['items'] ) ? (array) $change['items'] : array( $change ) ); $old = $booking; $result = Services::bookings()->locked( self::LOCK, function () use ( $items, $booking_id, $by, $force ): bool { $prepared = $this->prepare( array( 'items' => $items ), array( 'except_booking' => $booking_id, 'staff_rules' => 'staff' === $by, 'check' => ! $force, ) ); $current = Services::bookings()->find( $booking_id ); foreach ( $prepared as $i => $item ) { $prepared[ $i ]['price'] = $current['items'][ $i ]['price'] ?? 0; } Services::bookings()->replace_items( $booking_id, $prepared ); return true; } ); if ( null === $result ) { throw new BookingException( 'schedulereed_busy', __( 'Lots of people are booking right now. Please try again.', 'schedulereed' ), 503 ); } if ( 'customer' === $by ) { Services::bookings()->update( $booking_id, array( 'rescheduled' => $booking['rescheduled'] + 1 ) ); } Services::messages()->unclaim( $booking_id, 'reminder' ); Cache::bump(); $booking = Services::bookings()->find( $booking_id ); Services::activity()->record( $booking_id, 'rescheduled', array( 'by' => $by, 'from' => $old['start'], 'to' => $booking['start'], ) ); /** * Fires after a booking moves. * * @param array $booking New booking. * @param array $old Booking before the move. * @param string $by Who moved it. * @param bool $notify Whether to tell the customer (staff can choose). */ do_action( 'schedulereed_booking_rescheduled', $booking, $old, $by, 'customer' === $by || ! empty( $change['notify'] ) ); return $booking; } /** * Requested items for an existing booking, with changes applied. * * @param array $booking Booking. * @param array> $wanted Changes per item: start, date, session_id, staff_id, units. * @return array> */ private function items_from( array $booking, array $wanted = array() ): array { $items = array(); foreach ( $booking['items'] as $i => $item ) { $new = (array) ( $wanted[ $i ] ?? array() ); $items[] = array( 'bookable_id' => $item['bookable_id'], 'start' => isset( $new['start'] ) ? (int) $new['start'] : $item['start'], 'date' => (string) ( $new['date'] ?? '' ), 'session_id' => isset( $new['session_id'] ) ? (int) $new['session_id'] : $item['session_id'], 'staff_id' => isset( $new['staff_id'] ) ? (int) $new['staff_id'] : $item['staff_id'], 'location_id' => $item['location_id'], 'units' => (int) ( $new['units'] ?? $this->units_of( $item ) ), 'quantity' => $item['quantity'], 'persons' => $item['persons'], 'tickets' => $item['tickets'], 'extras' => $this->extras_of( $booking, $i ), ); } return $items; } /** * Bring back an online booking that expired before its payment arrived, * if its time is still free. * * @param int $booking_id Booking. * @return bool Whether it is back, waiting for the payment to be recorded. */ public function revive( int $booking_id ): bool { $booking = Services::bookings()->find( $booking_id ); if ( null === $booking || Status::CANCELLED !== $booking['status'] ) { return false; } $ok = Services::bookings()->locked( self::LOCK, function () use ( $booking ): bool { try { $this->prepare( array( 'items' => $this->items_from( $booking ) ), array( 'except_booking' => $booking['id'], 'staff_rules' => true, ) ); } catch ( BookingException ) { return false; } if ( '' !== $booking['coupon'] ) { Services::coupons()->use( $booking['coupon'] ); } Services::bookings()->update( $booking['id'], array( 'status' => Status::AWAITING_PAYMENT, 'cancelled_at' => 0, 'expires_at' => Clock::now() + 10 * MINUTE_IN_SECONDS, ) ); return true; } ); if ( true === $ok ) { Services::activity()->record( $booking_id, 'revived' ); Cache::bump(); } return true === $ok; } /** * Cancel unpaid online bookings whose time ran out; runs every few minutes. */ public function expire_unpaid(): int { $count = 0; foreach ( Services::bookings()->expired_unpaid() as $id ) { $booking = Services::bookings()->find( $id ); if ( null === $booking ) { continue; } Services::bookings()->update( $id, array( 'status' => Status::CANCELLED, 'cancelled_at' => Clock::now(), 'expires_at' => 0, ) ); if ( '' !== $booking['coupon'] ) { Services::coupons()->release( $booking['coupon'] ); } Services::activity()->record( $id, 'expired' ); /** * Fires when an online booking is dropped because it was never paid. * * @param array $booking Booking, before it was cancelled. */ do_action( 'schedulereed_booking_expired', $booking ); ++$count; } if ( $count > 0 ) { Cache::bump(); } Services::holds()->purge(); return $count; } /** * Mark bookings that ended as completed; runs hourly. */ public function complete_past(): void { $now = Clock::now(); foreach ( Services::bookings()->ended( array( Status::CONFIRMED ), $now - 7 * DAY_IN_SECONDS, $now ) as $booking ) { Services::bookings()->update( $booking['id'], array( 'status' => Status::COMPLETED ) ); /** * Fires when a booking's time has passed. * * @param array $booking Booking. */ do_action( 'schedulereed_booking_completed', array_merge( $booking, array( 'status' => Status::COMPLETED ) ) ); } } /** * Resolve and check every item of a request. * * @param array $request Request. * @param array $opt check (default true), staff_rules, except_hold, except_booking. * @return array> Items ready for the repositories, with `line` for pricing. * @throws BookingException When something is wrong or taken. */ public function prepare( array $request, array $opt = array() ): array { $raw = array_values( (array) ( $request['items'] ?? array() ) ); if ( array() === $raw ) { throw new BookingException( 'schedulereed_no_items', __( 'Choose what you would like to book.', 'schedulereed' ) ); } /** * Most items in one booking; 1 without Pro's cart and recurring bookings. * * @param int $max Most items. */ $max = max( 1, (int) apply_filters( 'schedulereed_max_items', 1 ) ); if ( count( $raw ) > $max ) { throw new BookingException( 'schedulereed_too_many_items', __( 'You can book one thing at a time.', 'schedulereed' ) ); } $check = $opt['check'] ?? true; $out = array(); foreach ( $raw as $index => $item ) { $out[] = $this->prepare_item( (array) $item, $opt, (bool) $check, $out, $index ); } return $out; } /** * Resolve one item. * * @param array $item Requested item. * @param array $opt Options. * @param bool $check Check availability. * @param array> $earlier Items already prepared in this request. * @param int $index Position. * @return array * @throws BookingException When something is wrong or taken. */ private function prepare_item( array $item, array $opt, bool $check, array $earlier, int $index ): array { $bookable = Services::catalog()->bookable( (int) ( $item['bookable_id'] ?? 0 ) ); $by_staff = ! empty( $opt['staff_rules'] ); if ( null === $bookable || ( ! $by_staff && ( ! $bookable->is_active() || ! apply_filters( 'schedulereed_show_bookable', ! $bookable->settings['members_only'], $bookable ) ) ) ) { throw new BookingException( 'schedulereed_unknown_bookable', __( 'That service is not available.', 'schedulereed' ), 404 ); } $extras_all = $bookable->extras(); $extras = array(); $extra_min = 0; foreach ( (array) ( $item['extras'] ?? array() ) as $id => $qty ) { if ( isset( $extras_all[ $id ] ) && (int) $qty > 0 ) { $quantity = min( $extras_all[ $id ]->max, (int) $qty ); $extras[] = array( 'extra' => $extras_all[ $id ], 'quantity' => $quantity, ); $extra_min += $extras_all[ $id ]->duration * $quantity; } } [ $quantity, $persons, $person_lines ] = $this->people( $bookable, $item ); $tickets = array(); $session = null; $location_id = max( 0, (int) ( $item['location_id'] ?? 0 ) ); $staff_id = max( 0, (int) ( $item['staff_id'] ?? 0 ) ); $units = max( 1, (int) ( $item['units'] ?? 1 ) ); $avail_opt = array( 'location_id' => $location_id, 'staff_id' => $staff_id, 'quantity' => $quantity, 'units' => $units, 'extra_minutes' => $extra_min, 'except_booking' => (int) ( $opt['except_booking'] ?? 0 ), 'except_hold' => (string) ( $opt['except_hold'] ?? '' ), 'staff_rules' => $by_staff, ); if ( $bookable->uses_sessions() ) { $session = Services::sessions_repo()->find( (int) ( $item['session_id'] ?? 0 ) ); if ( null === $session || $session['bookable_id'] !== $bookable->id || 'scheduled' !== $session['status'] ) { throw new BookingException( 'schedulereed_unknown_session', __( 'That date is no longer on the timetable.', 'schedulereed' ), 404 ); } [ $tickets, $ticket_lines, $ticket_qty ] = $this->tickets( $bookable, $session, $item ); if ( $ticket_qty > 0 ) { $quantity = $ticket_qty; $person_lines = $ticket_lines; } $places = Services::sessions()->with_places( $bookable, array( $session ), $avail_opt['except_booking'], $avail_opt['except_hold'] )[0]; if ( $check ) { [ $earliest, $latest ] = Services::availability()->limits( $bookable, $avail_opt, Services::availability()->zone( $bookable, $avail_opt ) ); if ( $session['start'] < $earliest || $session['start'] > $latest ) { throw new BookingException( 'schedulereed_too_late', __( 'This date can no longer be booked online.', 'schedulereed' ), 409 ); } if ( $places['remaining'] < $quantity + $this->taken_earlier( $earlier, 'session_id', $session['id'] ) ) { throw new BookingException( 'schedulereed_full', /* translators: %d: places left. */ sprintf( _n( 'Only %d place is left.', 'Only %d places are left.', max( 1, $places['remaining'] ), 'schedulereed' ), $places['remaining'] ), 409, array( 'remaining' => $places['remaining'] ) ); } foreach ( $places['tickets'] as $ticket ) { if ( null !== $ticket['remaining'] && ( $tickets[ $ticket['id'] ] ?? 0 ) > $ticket['remaining'] ) { throw new BookingException( 'schedulereed_full', /* translators: %s: ticket type. */ sprintf( __( 'Not enough %s tickets are left.', 'schedulereed' ), $ticket['label'] ), 409 ); } } } $start = $session['start']; $end = $session['end']; $staff_id = $session['staff_id']; $location_id = $session['location_id']; $resources = array(); $slot = null; } else { $start = $this->start_of( $bookable, $item, $avail_opt ); $slot = Services::availability()->check( $bookable, $start, $avail_opt ); if ( null === $slot && $check ) { throw new BookingException( 'schedulereed_slot_taken', __( 'That time was just taken. Here are the next free times.', 'schedulereed' ), 409, array( 'alternatives' => $this->alternatives( $bookable, $start, $avail_opt ) ) ); } if ( null === $slot ) { // Staff forcing a booking into a taken or closed time. $end = $start + $bookable->seconds( $units, $extra_min ); if ( $bookable->by_day() ) { $end = $start + $units * DAY_IN_SECONDS; } $resources = array(); } else { $end = (int) $slot['end']; $location_id = (int) $slot['location_id']; $staff_id = $staff_id > 0 ? $staff_id : $this->assign_staff( $bookable, $slot, $start ); $resources = array(); foreach ( (array) $slot['resources'] as $key => $ids ) { $need = (int) ( $bookable->settings['resources'][ (int) substr( (string) $key, 9 ) ]['need'] ?? 1 ); $resources = array_merge( $resources, array_slice( $ids, 0, $need ) ); } } if ( $check && $this->overlaps_earlier( $earlier, $bookable, $staff_id, $start, $end ) ) { throw new BookingException( 'schedulereed_slot_taken', __( 'Two of your choices are at the same time.', 'schedulereed' ), 409 ); } } $price = $bookable->price; if ( $staff_id > 0 ) { $staff = Services::catalog()->staff_for( $bookable->id )[ $staff_id ] ?? null; if ( null !== $staff && null !== $staff['price_override'] ) { $price = (int) $staff['price_override']; } } $days = $bookable->by_day() ? max( 1, (int) round( ( $end - $start ) / DAY_IN_SECONDS ) ) : 1; if ( Bookable::NIGHTS === $bookable->duration_mode ) { $days = $bookable->clamp_units( $units ); } $line = array( 'bookable_id' => $bookable->id, 'label' => $bookable->name, 'basis' => $bookable->price_basis, 'price' => $price, 'units' => Bookable::RANGE === $bookable->duration_mode && PriceCalculator::PER_HOUR !== $bookable->price_basis ? $bookable->clamp_units( $units ) : $bookable->price_units( $end - $start - $extra_min * 60, $days ), 'people' => $quantity, 'persons' => $person_lines, 'extras' => $extras, ); if ( Bookable::RANGE === $bookable->duration_mode && in_array( $bookable->price_basis, array( PriceCalculator::PER_BOOKING, PriceCalculator::PER_PERSON ), true ) ) { // Price is per duration unit chosen: 2 x 30 minutes costs twice. $line['basis'] = PriceCalculator::PER_BOOKING === $bookable->price_basis ? PriceCalculator::PER_HOUR : PriceCalculator::PER_PERSON; if ( PriceCalculator::PER_BOOKING === $bookable->price_basis ) { $line['units'] = $bookable->clamp_units( $units ); } } /** * Price changes for a line, e.g. Pro's pricing rules. * * @param array $adjustments [{label, amount}]. * @param array $context bookable, start, end, quantity, units, staff_id, location_id, price, base (line price before changes). */ $line['adjustments'] = (array) apply_filters( 'schedulereed_price_adjustments', array(), array( 'bookable' => $bookable, 'start' => $start, 'end' => $end, 'quantity' => $quantity, 'units' => (int) $line['units'], 'staff_id' => $staff_id, 'location_id' => $location_id, 'price' => $price, 'base' => PriceCalculator::line( $line )['base'], ) ); return array( 'bookable_id' => $bookable->id, 'session_id' => $session['id'] ?? 0, 'staff_id' => $staff_id, 'location_id' => $location_id, 'resources' => $resources, 'start' => $start, 'end' => $end, 'block_start' => $start - $bookable->buffer_before * 60, 'block_end' => $end + $bookable->buffer_after * 60, 'quantity' => $quantity, 'persons' => $persons, 'tickets' => $tickets, 'extras' => array_map( static fn( array $e ): array => array( 'id' => $e['extra']->id, 'quantity' => $e['quantity'], ), $extras ), 'line' => $line, 'index' => $index, ); } /** * The start time of a requested item. * * @param Bookable $bookable Bookable. * @param array $item Item. * @param array $opt Availability options. * @throws BookingException When missing. */ private function start_of( Bookable $bookable, array $item, array $opt ): int { if ( $bookable->by_day() ) { $date = (string) ( $item['date'] ?? '' ); if ( '' === $date && ! empty( $item['start'] ) ) { $date = ( new DateTimeImmutable( '@' . (int) $item['start'] ) )->setTimezone( Services::availability()->zone( $bookable, $opt ) )->format( 'Y-m-d' ); } if ( ! DateOverride::is_date( $date ) ) { throw new BookingException( 'schedulereed_no_time', __( 'Choose a date.', 'schedulereed' ) ); } $units = $bookable->clamp_units( (int) ( $item['units'] ?? 1 ) ); if ( (int) ( $item['units'] ?? 1 ) !== $units ) { throw new BookingException( 'schedulereed_bad_length', Bookable::NIGHTS === $bookable->duration_mode /* translators: 1: fewest nights, 2: most nights. */ ? sprintf( __( 'Stays are %1$d to %2$d nights.', 'schedulereed' ), $bookable->settings['min_units'], $bookable->settings['max_units'] ) /* translators: 1: fewest days, 2: most days. */ : sprintf( __( 'Rentals are %1$d to %2$d days.', 'schedulereed' ), $bookable->settings['min_units'], $bookable->settings['max_units'] ) ); } return Services::availability()->day_start( $bookable, $date, Services::availability()->zone( $bookable, $opt ) ); } $start = (int) ( $item['start'] ?? 0 ); if ( $start <= 0 ) { throw new BookingException( 'schedulereed_no_time', __( 'Choose a time.', 'schedulereed' ) ); } return $start; } /** * People in an item and their price lines. * * @param Bookable $bookable Bookable. * @param array $item Item. * @return array{0: int, 1: array, 2: array>} * @throws BookingException When too many or none. */ private function people( Bookable $bookable, array $item ): array { $types = (array) apply_filters( 'schedulereed_person_types', array(), $bookable ); $max = Bookable::APPOINTMENT === $bookable->type && $bookable->capacity <= 1 ? max( 1, (int) $bookable->settings['max_people'] ) : max( (int) $bookable->settings['max_people'], $bookable->capacity ); $persons = array(); $lines = array(); $count = 0; if ( array() !== $types ) { foreach ( $types as $type ) { $n = max( 0, (int) ( $item['persons'][ $type['id'] ] ?? 0 ) ); if ( 0 === $n ) { continue; } $persons[ $type['id'] ] = $n; $lines[] = array( 'label' => $type['label'], 'price' => (int) $type['price'], 'count' => $n, ); if ( ! empty( $type['counts'] ) ) { $count += $n; } } $count = max( 1, $count ); } else { $count = max( 1, (int) ( $item['quantity'] ?? 1 ) ); } if ( $count > $max ) { throw new BookingException( 'schedulereed_too_many', /* translators: %d: most people. */ sprintf( _n( 'You can book for at most %d person.', 'You can book for at most %d people.', $max, 'schedulereed' ), $max ) ); } return array( $count, $persons, $lines ); } /** * Tickets chosen for an event session. * * @param Bookable $bookable Bookable. * @param array $session Session. * @param array $item Item. * @return array{0: array, 1: array>, 2: int} */ private function tickets( Bookable $bookable, array $session, array $item ): array { $chosen = array(); $lines = array(); $total = 0; foreach ( Services::sessions()->tickets( $bookable, $session ) as $ticket ) { $n = max( 0, (int) ( $item['tickets'][ $ticket['id'] ] ?? 0 ) ); if ( 0 === $n ) { continue; } $chosen[ $ticket['id'] ] = $n; $lines[] = array( 'label' => $ticket['label'], 'price' => (int) $ticket['price'], 'count' => $n, ); $total += $n; } return array( $chosen, $lines, $total ); } /** * Pick a staff member when the customer chose "anyone". * * @param Bookable $bookable Bookable. * @param array $slot Slot with free staff. * @param int $start Start. */ private function assign_staff( Bookable $bookable, array $slot, int $start ): int { $free = array_map( 'intval', (array) $slot['staff'] ); if ( array() === $free ) { return 0; } /** * Choose among free staff; Pro adds round robin and least busy. * * @param int $staff_id Chosen staff, the first free one by default. * @param int[] $free Free staff IDs. * @param Bookable $bookable Bookable. * @param int $start Start. * @param string $mode The bookable's staff mode. */ $chosen = (int) apply_filters( 'schedulereed_assign_staff', $free[0], $free, $bookable, $start, Catalog::staff_mode( $bookable ) ); return in_array( $chosen, $free, true ) ? $chosen : $free[0]; } /** * Places already taken in a session by earlier items of the same request. * * @param array> $earlier Items. * @param string $key Field. * @param int $value Value. */ private function taken_earlier( array $earlier, string $key, int $value ): int { $n = 0; foreach ( $earlier as $item ) { if ( (int) $item[ $key ] === $value ) { $n += (int) $item['quantity']; } } return $n; } /** * Whether an item clashes with an earlier one in the same request for * the same staff member or bookable. * * @param array> $earlier Items. * @param Bookable $bookable Bookable. * @param int $staff_id Staff. * @param int $start Start. * @param int $end End. */ private function overlaps_earlier( array $earlier, Bookable $bookable, int $staff_id, int $start, int $end ): bool { foreach ( $earlier as $item ) { $same = ( $staff_id > 0 && $item['staff_id'] === $staff_id ) || ( 0 === $staff_id && $item['bookable_id'] === $bookable->id && $bookable->capacity <= 1 ); if ( $same && $item['start'] < $end && $start < $item['end'] ) { return true; } } return false; } /** * The next free times after one that was taken. * * @param Bookable $bookable Bookable. * @param int $start Wanted start. * @param array $opt Options. * @return array> */ private function alternatives( Bookable $bookable, int $start, array $opt ): array { if ( $bookable->by_day() ) { return array(); } $found = Services::availability()->slots( $bookable, $start, $start + 14 * DAY_IN_SECONDS, $opt )['slots']; return array_slice( array_map( static fn( array $s ): array => array( 'start' => $s['start'], 'end' => $s['end'], ), $found ), 0, 3 ); } /** * Price prepared items. * * @param array> $items Items. * @param string $code Coupon code. * @param bool $strict Throw on a code that cannot be used. * @throws BookingException When the coupon cannot be used and strict is on. */ public function price( array $items, string $code, bool $strict ): \ScheduleReed\Domain\Pricing\Quote { $lines = array_column( $items, 'line' ); $calc = new PriceCalculator( Settings::taxes(), Settings::prices_include_tax() ); $coupon = null; if ( '' !== trim( $code ) ) { $coupon = Services::coupons()->usable( $code ); $problem = null === $coupon ? 'unknown' : $coupon->problem( array_column( $items, 'bookable_id' ), $calc->quote( $lines )->subtotal, wp_date( 'Y-m-d' ) ); if ( null !== $problem ) { if ( $strict ) { throw new BookingException( 'schedulereed_invalid_coupon', self::coupon_message( $problem ), 400, array( 'reason' => $problem ) ); } $coupon = null; } } return $calc->quote( $lines, $coupon ); } /** * Why a coupon cannot be used, for the customer. * * @param string $problem Coupon problem code. */ public static function coupon_message( string $problem ): string { return match ( $problem ) { Coupon::NOT_STARTED => __( 'That code cannot be used yet.', 'schedulereed' ), Coupon::EXPIRED => __( 'That code has expired.', 'schedulereed' ), Coupon::MIN_TOTAL => __( 'That code needs a larger booking.', 'schedulereed' ), Coupon::BOOKABLE => __( 'That code does not apply to this booking.', 'schedulereed' ), default => __( 'That code is not valid.', 'schedulereed' ), }; } /** * What the customer sees before paying. * * @param array> $items Items. * @param \ScheduleReed\Domain\Pricing\Quote $quote Quote. * @param string $method Payment method chosen. * @return array */ private function summary( array $items, \ScheduleReed\Domain\Pricing\Quote $quote, string $method ): array { $deposit = $this->deposit_for( $items ); $methods = array(); foreach ( $this->methods_for( $items ) as $m ) { $methods[] = array( 'id' => $m->id(), 'label' => $m->label(), 'description' => $m->description(), 'online' => $m instanceof OnlinePaymentMethod, 'due_now' => $m->takes_deposit() ? $deposit->due_now( $quote->total ) : 0, ); } $policy = $this->policy_for( $items ); return array( 'quote' => $quote->to_array(), 'currency' => Settings::currency(), 'methods' => $methods, 'method' => $method, 'approval' => $this->approval_for( $items ), 'policy' => $policy['text'], 'items' => array_map( static fn( array $i ): array => array( 'bookable_id' => $i['bookable_id'], 'start' => $i['start'], 'end' => $i['end'], 'staff_id' => $i['staff_id'], 'location_id' => $i['location_id'], 'session_id' => $i['session_id'], 'quantity' => $i['quantity'], ), $items ), ); } /** * Payment methods offered for items: the bookable's own list when set. * * @param array> $items Items. * @return PaymentMethod[] */ public function methods_for( array $items ): array { $enabled = Services::methods()->enabled(); foreach ( $items as $item ) { $bookable = Services::catalog()->bookable( (int) $item['bookable_id'] ); $only = $bookable?->settings['payment_methods']; if ( is_array( $only ) && array() !== $only ) { $narrowed = array_intersect_key( $enabled, array_flip( $only ) ); $enabled = array() !== $narrowed ? $narrowed : $enabled; } } return $enabled; } /** * Deposit: the first item's own policy, else the site's. * * @param array> $items Items. */ private function deposit_for( array $items ): DepositPolicy { $bookable = Services::catalog()->bookable( (int) ( $items[0]['bookable_id'] ?? 0 ) ); if ( null !== $bookable && is_array( $bookable->settings['deposit'] ) ) { try { return DepositPolicy::from_array( $bookable->settings['deposit'] ); } catch ( InvalidArgumentException ) { return Settings::deposit(); } } return Settings::deposit(); } /** * Approval: manual if any item needs it. * * @param array> $items Items. */ private function approval_for( array $items ): string { foreach ( $items as $item ) { $bookable = Services::catalog()->bookable( (int) $item['bookable_id'] ); $own = $bookable?->settings['approval']; if ( 'manual' === ( $own ?? Settings::approval() ) ) { return 'manual'; } } return 'auto'; } /** * The terms copied onto the booking: cancellation and self-service rules. * * @param array> $items Items. * @return array{cancellation: array|null, changes: array, text: string[]} */ private function policy_for( array $items ): array { $policy = Settings::cancellation(); $bookable = Services::catalog()->bookable( (int) ( $items[0]['bookable_id'] ?? 0 ) ); if ( null !== $bookable && is_array( $bookable->settings['cancellation'] ) ) { try { $policy = CancellationPolicy::from_array( $bookable->settings['cancellation'] ); } catch ( InvalidArgumentException ) { $policy = Settings::cancellation(); } } $changes = Settings::changes(); $start = (int) ( $items[0]['start'] ?? 0 ); return array( 'cancellation' => $policy?->to_array(), 'changes' => $changes->to_array(), 'text' => Format::policy( $policy, $changes, $start ), ); } /** * Check and tidy the customer's details. * * @param array $raw Raw details. * @param bool $by_staff Staff may leave the email out. * @return array * @throws BookingException When something required is missing. */ private function customer_input( array $raw, bool $by_staff ): array { $fields = Settings::fields(); $customer = array( 'first_name' => mb_substr( sanitize_text_field( (string) ( $raw['first_name'] ?? '' ) ), 0, 100 ), 'last_name' => mb_substr( sanitize_text_field( (string) ( $raw['last_name'] ?? '' ) ), 0, 100 ), 'email' => sanitize_email( (string) ( $raw['email'] ?? '' ) ), 'phone' => mb_substr( preg_replace( '/[^0-9+()\-. ]/', '', (string) ( $raw['phone'] ?? '' ) ), 0, 40 ), 'notes' => mb_substr( sanitize_textarea_field( (string) ( $raw['notes'] ?? '' ) ), 0, 2000 ), 'timezone' => '', 'address' => mb_substr( sanitize_textarea_field( (string) ( $raw['address'] ?? '' ) ), 0, 500 ), ); $tz = (string) ( $raw['timezone'] ?? '' ); if ( '' !== $tz && in_array( $tz, timezone_identifiers_list(), true ) ) { $customer['timezone'] = $tz; } $customer_id = (int) ( $raw['id'] ?? 0 ); if ( $by_staff && $customer_id > 0 ) { $existing = Services::customers()->find( $customer_id ); if ( null !== $existing ) { foreach ( array( 'first_name', 'last_name', 'email', 'phone' ) as $key ) { $customer[ $key ] = '' !== $customer[ $key ] ? $customer[ $key ] : (string) $existing[ $key ]; } } } if ( '' === $customer['first_name'] ) { throw new BookingException( 'schedulereed_missing_field', __( 'Please enter your name.', 'schedulereed' ), 400, array( 'field' => 'first_name' ) ); } if ( $by_staff ) { return $customer; } if ( '' === $customer['email'] || ! is_email( $customer['email'] ) ) { throw new BookingException( 'schedulereed_missing_field', __( 'Please enter a valid email address.', 'schedulereed' ), 400, array( 'field' => 'email' ) ); } foreach ( array( 'last_name', 'phone', 'notes', 'address' ) as $field ) { if ( 'required' === ( $fields[ $field ] ?? '' ) && '' === trim( $customer[ $field ] ) ) { throw new BookingException( 'schedulereed_missing_field', __( 'Please fill in every required field.', 'schedulereed' ), 400, array( 'field' => $field ) ); } if ( 'hidden' === ( $fields[ $field ] ?? '' ) && 'last_name' !== $field ) { $customer[ $field ] = ''; } } return $customer; } /** * Extra form answers (Pro's form builder), checked by the filter. * * @param array $request Request. * @param bool $by_staff Staff skip required answers. * @return array * @throws BookingException When an answer is missing or wrong. */ private function fields( array $request, bool $by_staff ): array { $answers = array(); $address = (string) ( $request['customer']['address'] ?? '' ); if ( '' !== trim( $address ) && 'hidden' !== Settings::fields()['address'] ) { $answers['address'] = array( 'label' => __( 'Address', 'schedulereed' ), 'value' => sanitize_textarea_field( $address ), ); } /** * Check and label custom form answers. * * @param array|\WP_Error $answers Answers so far, keyed by field ID: {label, value}. * @param array $raw Submitted answers. * @param array $request Whole request. * @param bool $by_staff Whether staff are booking. */ $result = apply_filters( 'schedulereed_form_answers', $answers, (array) ( $request['fields'] ?? array() ), $request, $by_staff ); if ( $result instanceof \WP_Error ) { throw new BookingException( (string) $result->get_error_code(), $result->get_error_message(), 400, (array) $result->get_error_data() ); } return (array) $result; } /** * The payment method chosen, or the only one offered. * * @param string $id Method ID. * @param bool $by_staff Staff may book with no method (pay later). * @throws BookingException When an unknown method is chosen. */ private function method( string $id, bool $by_staff ): ?PaymentMethod { $enabled = Services::methods()->enabled(); if ( '' === $id ) { return $by_staff ? null : reset( $enabled ); } $method = $by_staff ? Services::methods()->find( $id ) : ( $enabled[ $id ] ?? null ); if ( null === $method ) { throw new BookingException( 'schedulereed_invalid_payment', __( 'Choose how you would like to pay.', 'schedulereed' ) ); } return $method; } /** * Check the terms box when the site has terms. * * @param array $consent Consent answers. * @throws BookingException When terms are not accepted. */ private function check_consent( array $consent ): void { if ( '' !== Settings::fields()['terms'] && empty( $consent['terms'] ) ) { throw new BookingException( 'schedulereed_terms', __( 'Please accept the terms to book.', 'schedulereed' ), 400, array( 'field' => 'terms' ) ); } } /** * What the customer agreed to, with the time, for GDPR records. * * @param array $consent Answers. * @return array */ private function consent_record( array $consent ): array { $out = array(); if ( ! empty( $consent['terms'] ) ) { $out['terms'] = gmdate( 'c', Clock::now() ); } if ( Settings::fields()['marketing'] ) { $out['marketing'] = ! empty( $consent['marketing'] ) ? gmdate( 'c', Clock::now() ) : false; } return $out; } /** * Units of an existing item, for moving it. * * @param array $item Item. */ private function units_of( array $item ): int { $bookable = Services::catalog()->bookable( $item['bookable_id'] ); if ( null === $bookable ) { return 1; } if ( $bookable->by_day() ) { return max( 1, (int) round( ( $item['end'] - $item['start'] ) / DAY_IN_SECONDS ) ); } return Bookable::RANGE === $bookable->duration_mode ? max( 1, intdiv( $item['end'] - $item['start'], max( 300, $bookable->duration * 60 ) ) ) : 1; } /** * Extras chosen on an item, from the stored price breakdown. * * @param array $booking Booking. * @param int $index Item position. * @return array */ private function extras_of( array $booking, int $index ): array { $out = array(); foreach ( (array) ( $booking['charges']['lines'][ $index ]['extras'] ?? array() ) as $extra ) { $out[ (string) $extra['id'] ] = (int) $extra['quantity']; } return $out; } /** * A booking or a 404. * * @param int $id Booking. * @return array * @throws BookingException When missing. */ private function booking( int $id ): array { $booking = Services::bookings()->find( $id ); if ( null === $booking ) { throw new BookingException( 'schedulereed_not_found', __( 'Booking not found.', 'schedulereed' ), 404 ); } return $booking; } /** * A short reference customers can read out: 8 characters without 0/O or 1/I. */ public static function reference(): string { $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; $ref = ''; for ( $i = 0; $i < 8; $i++ ) { $ref .= $alphabet[ random_int( 0, strlen( $alphabet ) - 1 ) ]; } return $ref; } }