get_meta( self::ORDER_META ); if ( '' === $chat && $order->get_customer_id() ) { $chat = (string) get_user_meta( $order->get_customer_id(), self::USER_META, true ); } return $chat; } /** * Link a chat to an order (and its customer account). * * @param \WC_Order $order Order. * @param string $chat_id Chat. */ public static function link_order( $order, $chat_id ) { $order->update_meta_data( self::ORDER_META, (string) $chat_id ); $order->save(); if ( $order->get_customer_id() ) { update_user_meta( $order->get_customer_id(), self::USER_META, (string) $chat_id ); } } /** * Forget a chat everywhere: orders, accounts, owner list. * * @param string $chat_id Chat. * @return int Orders unlinked. */ public static function unlink_chat( $chat_id ) { $chat_id = (string) $chat_id; $count = 0; foreach ( self::orders_of_chat( $chat_id ) as $order ) { $order->delete_meta_data( self::ORDER_META ); $order->save(); ++$count; } foreach ( get_users( array( 'meta_key' => self::USER_META, 'meta_value' => $chat_id, 'fields' => 'ID' ) ) as $user_id ) { // phpcs:ignore WordPress.DB.SlowDBQuery -- runs only on /stop. delete_user_meta( (int) $user_id, self::USER_META ); } self::remove_owner( $chat_id ); return $count; } /** * Orders linked to a chat, newest first. * * @param string $chat_id Chat. * @param int $limit Limit (-1 = all). * @return \WC_Order[] */ public static function orders_of_chat( $chat_id, $limit = -1 ) { if ( '' === (string) $chat_id ) { return array(); } $orders = wc_get_orders( array( 'limit' => $limit, // By id, not date: two orders placed in the same second have the same date. 'orderby' => 'ID', 'order' => 'DESC', 'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery -- indexed meta key, rare call. array( 'key' => self::ORDER_META, 'value' => (string) $chat_id, ), ), ) ); return is_array( $orders ) ? $orders : array(); } /** * The owner's chats: chat id → label. * * @return array */ public static function owners() { $chats = Settings::get( 'owner_chats' ); return is_array( $chats ) ? array_map( 'strval', $chats ) : array(); } /** * Whether a chat is one of the owner's. * * @param string $chat_id Chat. * @return bool */ public static function is_owner( $chat_id ) { return array_key_exists( (string) $chat_id, self::owners() ); } /** * Add an owner chat. * * @param string $chat_id Chat. * @param string $label Name shown on the settings page. */ public static function add_owner( $chat_id, $label ) { $chats = self::owners(); $chats[ (string) $chat_id ] = sanitize_text_field( $label ); Settings::update( array( 'owner_chats' => $chats ) ); } /** * Remove an owner chat. * * @param string $chat_id Chat. */ public static function remove_owner( $chat_id ) { $chats = self::owners(); if ( isset( $chats[ (string) $chat_id ] ) ) { unset( $chats[ (string) $chat_id ] ); Settings::update( array( 'owner_chats' => $chats ) ); } } }