string[], * staff => [ [ id, name ] ], durations => [ [ id, name, minutes, price ] ], group_max, group_min ] */ class Booktics_Public_Gateway { /** * Statuses a visitor may see. */ private const VISIBLE = [ 'publish', 'active' ]; // Pages of 50 read for the service list (500 services at most). private const MAX_SERVICE_PAGES = 10; /** * Extras per service id, for this request: search, slots and the booking * link each ask again. * * @var array */ private array $extras_cache = []; /** * Branches, for this request. * * @var array|null */ private ?array $locations_cache = null; /** * Slot answers for this request, by query: the model sometimes asks the * same range twice in one turn. * * @var array */ private array $slots_cache = []; /** * Whether Booktics is loaded. * * @return bool */ public function is_active(): bool { return function_exists( 'booktics' ); } /** * Whether this Booktics version has the pre-filled link and the manage-links email. * Both ship in the same release, so one signal covers both. * * @return bool */ public function supports_manage_links(): bool { return false !== has_action( 'booktics_send_manage_links' ); } /** * Read a Booktics setting. * * @param string $key Option key. * @param mixed $fallback Fallback. * @return mixed */ public function option( string $key, $fallback = null ) { return function_exists( 'booktics_get_option' ) ? booktics_get_option( $key, $fallback ) : $fallback; } /** * The shop currency symbol, decoded for plain-text display. * * @return string */ /** * A price as Booktics shows it: its decimals, thousands separator and * symbol position settings. * * @param float $price Price. * @return string e.g. "$1,234.50" or "1.234,50 €". */ public function price_text( float $price ): string { return self::format_price( $price, $this->currency_symbol(), (string) $this->option( 'currency_symbol_position', 'left' ), (string) $this->option( 'currency_price_separator', ',' ), (int) $this->option( 'currency_decimals', 2 ) ); } /** * Format a price the way Booktics' Pricing component does. * * @param float $price Price. * @param string $symbol Currency symbol. * @param string $position left, right, left_space or right_space. * @param string $separator Thousands separator. * @param int $decimals Decimals. * @return string */ public static function format_price( float $price, string $symbol, string $position, string $separator, int $decimals ): string { $number = number_format( $price, max( 0, $decimals ), '.', $separator ); switch ( $position ) { case 'right': return $number . $symbol; case 'left_space': return $symbol . ' ' . $number; case 'right_space': return $number . ' ' . $symbol; default: return $symbol . $number; } } public function currency_symbol(): string { static $currencies = null; $code = (string) $this->option( 'currency', 'USD' ); // booktics_get_currencies() uses require_once, so only the first call in a // request returns the list; later calls get `true`. Keep the first answer. if ( null === $currencies ) { $list = function_exists( 'booktics_get_currencies' ) ? booktics_get_currencies() : []; $currencies = is_array( $list ) ? $list : []; } foreach ( $currencies as $currency ) { if ( is_array( $currency ) && ( $currency['name'] ?? '' ) === $code ) { return html_entity_decode( (string) ( $currency['symbol'] ?? $code ), ENT_QUOTES, 'UTF-8' ); } } return $code; } /** * Current site time. * * @return \DateTimeImmutable */ public function now(): \DateTimeImmutable { return new \DateTimeImmutable( 'now', wp_timezone() ); } /** * Visible services. * * @param array $query Optional `search` and `category_id`. * @return array List of services in the shape above. */ public function services( array $query ): array { $out = []; // Page by page: one page of 50 left later services out of every search. for ( $page = 1; $page <= self::MAX_SERVICE_PAGES; $page++ ) { $request = new \WP_REST_Request( 'GET', '/booktics/v1/services' ); $request->set_query_params( array_filter( [ 'per_page' => 50, 'paged' => $page, 'search' => $query['search'] ?? '', 'category_id' => $query['category_id'] ?? '', ] ) ); $data = $this->data_of( ( new \Booktics\Service\Controllers\Service_Controller() )->get_items( $request ) ); $items = is_array( $data['items'] ?? null ) ? $data['items'] : []; foreach ( $items as $item ) { $service = is_array( $item ) ? self::shape_service( $item ) : null; if ( null !== $service ) { $out[] = $service; } } if ( count( $items ) < 50 ) { break; } } return $out; } /** * One visible service, or null. * * @param int $id Service id. * @return array|null */ public function service( int $id ): ?array { // Service_Model::find() loads any post: a page id must not pass as a service. if ( 'booktics-service' !== get_post_type( $id ) ) { return null; } $model = \Booktics\Models\Service_Model::find( $id ); if ( ! $model ) { return null; } $item = $model->to_array(); $item['team_member_details'] = \Booktics\Service\Helpers\Service_Helper::team_member_details( (array) ( $item['team_member'] ?? [] ) ); // Same filter Booktics' own service routes run; Pro adds `group_booking` here. // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Booktics' own filter. $item = apply_filters( 'booktics_service_format', $item ); return is_array( $item ) ? self::shape_service( $item ) : null; } /** * Extra services (Pro) connected to a service. * * @param int $service_id Service id. * @return array [ [ id, name, price, minutes, max_qty ] ] */ public function extras( int $service_id ): array { if ( ! class_exists( '\BookticsPro\Models\Extra_Service_Model' ) ) { return []; } if ( isset( $this->extras_cache[ $service_id ] ) ) { return $this->extras_cache[ $service_id ]; } $ids = get_posts( [ 'post_type' => 'booktics-ex-service', 'post_status' => self::VISIBLE, 'posts_per_page' => 50, 'fields' => 'ids', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Same lookup Booktics uses for connected extras. 'meta_query' => [ [ 'key' => 'connected_services', 'value' => 'i:' . $service_id . ';', 'compare' => 'LIKE', ], ], ] ); $out = []; foreach ( $ids as $id ) { $model = \BookticsPro\Models\Extra_Service_Model::find( (int) $id ); if ( ! $model ) { continue; } $extra = $model->to_array(); // The LIKE above also matches serialized index keys ("i:1;"), so // confirm this extra really belongs to the service. if ( ! in_array( $service_id, array_map( 'intval', (array) ( $extra['connected_services'] ?? [] ) ), true ) ) { continue; } $out[] = [ 'id' => (int) $id, 'name' => self::text( $extra['title'] ?? '' ), 'price' => (float) ( $extra['charge_amount'] ?? 0 ), 'minutes' => (int) ( $extra['duration_minutes'] ?? 0 ), 'max_qty' => max( 1, (int) ( $extra['max_quantity'] ?? 1 ) ), ]; } $this->extras_cache[ $service_id ] = $out; return $out; } /** * Branches (Pro locations). * * @return array [ [ id, name, team_ids ] ] */ public function locations(): array { if ( ! class_exists( '\BookticsPro\Models\Location_Model' ) ) { return []; } if ( null !== $this->locations_cache ) { return $this->locations_cache; } $ids = get_posts( [ 'post_type' => 'booktics-location', 'post_status' => self::VISIBLE, 'posts_per_page' => 50, 'fields' => 'ids', ] ); $out = []; foreach ( $ids as $id ) { $model = \BookticsPro\Models\Location_Model::find( (int) $id ); if ( ! $model ) { continue; } $location = $model->to_array(); $out[] = [ 'id' => (int) $id, 'name' => self::text( $location['title'] ?? '' ), 'team_ids' => array_map( 'intval', (array) ( $location['teams'] ?? [] ) ), ]; } $this->locations_cache = $out; return $out; } /** * Free slots for one staff member, straight from Booktics' time-slot route. * * @param int $service_id Service id. * @param int $team_member_id Staff id. * @param string $start Y-m-d. * @param string $end Y-m-d. * @param array $args Optional additional_duration_id, extra_services (id => qty), total_attendees. * @return array 'Y-m-d' => [ [ start, end, is_available ] ] */ public function slots( int $service_id, int $team_member_id, string $start, string $end, array $args ): array { $key = md5( (string) wp_json_encode( [ $service_id, $team_member_id, $start, $end, $args ] ) ); if ( isset( $this->slots_cache[ $key ] ) ) { return $this->slots_cache[ $key ]; } $request = new \WP_REST_Request( 'GET', '/booktics/v1/appointments/time-slots' ); $request->set_query_params( array_merge( array_filter( $args ), [ 'service_id' => $service_id, 'team_member_id' => $team_member_id, 'start_date' => $start, 'end_date' => $end, ] ) ); $data = $this->data_of( ( new \Booktics\Appointment\Controllers\Appointment_Controller() )->get_time_slots( $request ) ); $this->slots_cache[ $key ] = self::normalize_slots( is_array( $data['slots'] ?? null ) ? $data['slots'] : [] ); return $this->slots_cache[ $key ]; } /** * Shape Booktics' slot map. Booktics returns Time_Slot objects (JsonSerializable) * when the controller is called directly, arrays after a JSON round trip. * * @param array $slots 'Y-m-d' => list of Time_Slot or arrays. * @return array 'Y-m-d' => [ [ start, end, is_available ] ] */ public static function normalize_slots( array $slots ): array { $out = []; foreach ( $slots as $date => $list ) { foreach ( (array) $list as $slot ) { if ( $slot instanceof \JsonSerializable ) { $slot = $slot->jsonSerialize(); } if ( ! is_array( $slot ) || empty( $slot['start'] ) ) { continue; } $out[ (string) $date ][] = [ 'start' => (string) $slot['start'], 'end' => (string) ( $slot['end'] ?? '' ), 'is_available' => false !== ( $slot['is_available'] ?? true ), ]; } } return $out; } /** * Public page of a service. * * @param int $id Service id. * @return string */ public function service_url( int $id ): string { return (string) get_permalink( $id ); } /** * Plain text for visitors. Booktics stores titles HTML-encoded ("Salons & Spas"), * and the chat renders text as-is, so the entity would show. * * @param mixed $value Raw value. * @return string */ private static function text( $value ): string { return html_entity_decode( (string) $value, ENT_QUOTES | ENT_HTML5, 'UTF-8' ); } /** * Unwrap a Booktics controller response (`{ data: ... }`). * * @param mixed $response Controller return value. * @return array */ private function data_of( $response ): array { if ( $response instanceof \WP_Error ) { Log::warning( 'Booktics public gateway error', [ 'message' => $response->get_error_message() ] ); return []; } $body = $response instanceof \WP_HTTP_Response ? $response->get_data() : $response; return is_array( $body['data'] ?? null ) ? $body['data'] : []; } /** * Shape one raw service, or null when a visitor may not see it. * * @param array $item Raw service array, after `booktics_service_format`. * @return array|null */ public static function shape_service( array $item ): ?array { $id = (int) ( $item['id'] ?? 0 ); // No status means hidden: a filter dropping the field must not publish drafts. if ( 0 === $id || ! in_array( (string) ( $item['status'] ?? '' ), self::VISIBLE, true ) ) { return null; } $staff = []; foreach ( (array) ( $item['team_member_details'] ?? [] ) as $member ) { if ( is_array( $member ) && ! empty( $member['id'] ) ) { $staff[] = [ 'id' => (int) $member['id'], 'name' => self::text( $member['display_name'] ?? '' ), ]; } } $durations = []; foreach ( (array) ( $item['additional_durations'] ?? [] ) as $row ) { if ( ! is_array( $row ) ) { continue; } $time = (int) ( $row['duration_time'] ?? 0 ); $durations[] = [ 'id' => (string) ( $row['id'] ?? '' ), // Booktics names its first duration 'default'; that is not a label for visitors. 'name' => 'default' === strtolower( trim( (string) ( $row['name'] ?? '' ) ) ) ? '' : self::text( $row['name'] ?? '' ), 'minutes' => 'hour' === ( $row['duration_unit'] ?? 'min' ) ? $time * 60 : $time, 'price' => (float) ( $row['charge_amount'] ?? 0 ), ]; } $categories = []; foreach ( (array) ( $item['category_details'] ?? [] ) as $category ) { if ( is_array( $category ) && ! empty( $category['name'] ) ) { $categories[] = self::text( $category['name'] ); } } // Pro keeps group booking in its own table and adds it through `booktics_service_format`. $group = is_array( $item['group_booking'] ?? null ) ? $item['group_booking'] : []; $on = ! empty( $group['enable_group_booking'] ); $max = $on ? max( 1, (int) ( $group['max_booking'] ?? 1 ) ) : 1; return [ 'id' => $id, 'title' => self::text( $item['title'] ?? '' ), 'status' => (string) $item['status'], 'description' => self::text( wp_strip_all_tags( (string) ( $item['description'] ?? '' ) ) ), // Cards put these in src and href. 'image' => esc_url_raw( (string) ( $item['image'] ?? '' ) ), 'link' => esc_url_raw( (string) ( $item['link'] ?? '' ) ), 'categories' => $categories, 'staff' => $staff, 'durations' => $durations, 'group_max' => $max, // The booking form refuses fewer people than this. 'group_min' => $on ? min( $max, max( 1, (int) ( $group['min_booking'] ?? 1 ) ) ) : 1, ]; } }