prefix . 'vizyt_booking_events'; } /** * @param array $meta Small details (source, by, reason, email kind…) — never addresses or rendered email text. * @param int|null $actor WP user id; null = the current user (0 = customer / system). */ public static function add( int $booking_id, string $type, array $meta = [], ?int $actor = null ): bool { global $wpdb; if ( $booking_id <= 0 || ! in_array( $type, self::TYPES, true ) ) { return false; } $actor = null === $actor ? get_current_user_id() : $actor; return false !== $wpdb->insert( self::table(), [ 'booking_id' => $booking_id, 'type' => $type, 'actor_id' => $actor > 0 ? $actor : null, 'meta' => $meta ? wp_json_encode( $meta ) : null, 'created_at' => current_time( 'mysql', true ), ] ); } /** * Events oldest first, ready for the drawer. * * @return array}> * at = UTC "Y-m-d H:i:s" (reminder_scheduled: the planned send time). */ public static function forBooking( int $booking_id ): array { global $wpdb; $rows = (array) $wpdb->get_results( $wpdb->prepare( 'SELECT type, actor_id, meta, created_at FROM %i WHERE booking_id = %d ORDER BY id ASC', self::table(), $booking_id ) ); $out = []; $created = false; foreach ( $rows as $row ) { $meta = $row->meta ? json_decode( (string) $row->meta, true ) : []; $meta = is_array( $meta ) ? $meta : []; $at = (string) $row->created_at; if ( 'reminder_scheduled' === $row->type && ! empty( $meta['at'] ) ) { $at = (string) $meta['at']; } $created = $created || 'created' === $row->type; $out[] = [ 'type' => (string) $row->type, 'at' => $at, 'actor' => self::actorName( $row->actor_id ? (int) $row->actor_id : 0 ), 'meta' => $meta, ]; } if ( ! $created ) { $booking = Booking::getById( $booking_id ); if ( $booking ) { array_unshift( $out, [ 'type' => 'created', 'at' => (string) $booking->created_at, 'actor' => '', 'meta' => [ 'source' => (string) $booking->source ], ] ); } } return $out; } public static function deleteForBooking( int $booking_id ): void { global $wpdb; $wpdb->delete( self::table(), [ 'booking_id' => $booking_id ], [ '%d' ] ); } private static function actorName( int $user_id ): string { if ( $user_id <= 0 ) { return ''; } $user = get_userdata( $user_id ); return $user ? (string) $user->display_name : ''; } }