guard( 'manage_woocommerce', 'manage_options', 'wpcafe_manage_reservations', 'wpcafe_view_all_reservations', 'wpcafe_view_own_reservations' ); if ( $check ) { return $check; } $start = sanitize_text_field( $date ); $end = ! empty( $end_date ) ? sanitize_text_field( $end_date ) : $start; if ( ! $this->is_valid_date( $start ) || ! $this->is_valid_date( $end ) ) { return [ 'error' => 'date and end_date must be valid calendar dates in Y-m-d format.' ]; } if ( \DateTime::createFromFormat( 'Y-m-d', $end ) < \DateTime::createFromFormat( 'Y-m-d', $start ) ) { return [ 'error' => 'end_date must be on or after date.' ]; } $min_seats = ( null !== $min_seats ) ? max( 0, $min_seats ) : 0; try { $params = [ 'start_date' => $start, 'end_date' => $end, ]; if ( null !== $branch_id && $branch_id > 0 ) { $params['location_id'] = $branch_id; } $request = new \WP_REST_Request( 'GET', '/wpcafe/v2/reservations/time-slots' ); $request->set_query_params( $params ); $controller = new \WpCafe\Reservation\Controllers\Reservation_Controller(); $result = $this->extract_response( $controller->get_slots( $request ), 'Failed to retrieve reservation availability.' ); if ( isset( $result['error'] ) ) { return $result; } return [ 'availability' => $this->shape_availability( $result, $min_seats ) ]; } catch ( \Throwable $e ) { Log::error( 'Wpcafe_Get_Reservation_Availability_Tool error', [ 'error' => $e->getMessage() ] ); return [ 'error' => 'Failed to retrieve reservation availability: ' . $e->getMessage() ]; } } /** * Curate the scheduler output to the available slots the agent needs. * * The scheduler returns a date-keyed map; for each open date we keep only * the available slots (optionally filtered by free seats) and cap the count * to stay token-friendly. * * @param array $data Date-keyed scheduler output. * @param int $min_seats Minimum free seats filter (0 = no filter). * @return array */ private function shape_availability( array $data, int $min_seats ): array { $out = []; foreach ( $data as $day => $info ) { if ( ! is_array( $info ) ) { continue; } $slots = []; foreach ( $info['slots'] ?? [] as $slot ) { if ( ! is_array( $slot ) || 'available' !== ( $slot['status'] ?? '' ) ) { continue; } $seats = (int) ( $slot['available_seat'] ?? 0 ); if ( $min_seats > 0 && $seats < $min_seats ) { continue; } $slots[] = [ 'start' => $slot['start'] ?? '', 'end' => $slot['end'] ?? '', 'available_seat' => $seats, ]; if ( count( $slots ) >= 24 ) { break; } } $out[] = [ 'date' => is_string( $day ) ? $day : (string) $day, 'day_status' => $info['status'] ?? '', 'available_slots' => $slots, ]; } return $out; } /** * Validate a Y-m-d date string. * * @param string $value Date string. * @return bool */ private function is_valid_date( string $value ): bool { $parsed = \DateTime::createFromFormat( 'Y-m-d', $value ); return $parsed && $parsed->format( 'Y-m-d' ) === $value; } }