if ( ! function_exists('manual_inject_google_meet_link_definitive') ) {

    add_filter('wp_mail', 'manual_inject_google_meet_link_definitive');
    
    function manual_inject_google_meet_link_definitive($args) {
        
        $target_subject = 'Vous avez passé une commande';

        if ( $args['subject'] !== $target_subject ) {
            return $args;
        }

        $message_body = $args['message'];
        $meet_link_html = 'Non applicable';

        
        preg_match('/<td>URL du service<\/td>\s*<td>([^<]+)<\/td>/', $message_body, $matches);
        
        
        if ( isset($matches[1]) ) {
            $service_url = trim( strip_tags( $matches[1] ) ); // Trim and strip tags for safety.
            $service_slug = basename( untrailingslashit($service_url) );
            $service_post = get_page_by_path($service_slug, OBJECT, 'service');

            if ( $service_post ) {
                $service_id = $service_post->ID;
                $meet_link = get_post_meta($service_id, 'googlemeetlink', true);
                
                if ( !empty($meet_link) && filter_var($meet_link, FILTER_VALIDATE_URL) ) {
                    $meet_link_html = '<a href="' . esc_url($meet_link) . '" target="_blank">' . esc_html($meet_link) . '</a>';
                }
            }
        }

        $args['message'] = str_replace('{{service_google_meet_link}}', $meet_link_html, $message_body);

        return $args;
    }
}