/ wordpress / restai / includes / class-restai-email.php
class-restai-email.php
 1  <?php
 2  /**
 3   * AI-personalized transactional emails. Wraps wp_mail's $message before send,
 4   * passing it through the Email Personalizer project.
 5   *
 6   * @package RESTai
 7   */
 8  
 9  namespace RESTai;
10  
11  if ( ! defined( 'ABSPATH' ) ) {
12  	exit;
13  }
14  
15  class Email_Personalization {
16  
17  	/** @var Client */
18  	private $client;
19  
20  	public function __construct( Client $client ) {
21  		$this->client = $client;
22  		add_filter( 'wp_mail', array( $this, 'personalize' ), 99, 1 );
23  	}
24  
25  	public function personalize( $args ) {
26  		$settings = get_option( 'restai_settings', array() );
27  		if ( empty( $settings['enable_email_ai'] ) ) {
28  			return $args;
29  		}
30  		if ( empty( $args['message'] ) ) {
31  			return $args;
32  		}
33  
34  		// Only touch transactional emails — skip if header indicates marketing
35  		// or contains an unsubscribe link.
36  		$msg = (string) $args['message'];
37  		if ( false !== stripos( $msg, 'unsubscribe' ) ) {
38  			return $args;
39  		}
40  
41  		$plugin     = Plugin::instance();
42  		$project_id = $plugin->provisioner->project_for( 'email_personalizer' );
43  		if ( $project_id <= 0 ) {
44  			return $args;
45  		}
46  
47  		$rewritten = $this->client->ask( $project_id, $msg );
48  		if ( is_wp_error( $rewritten ) || '' === trim( (string) $rewritten ) ) {
49  			return $args;
50  		}
51  		$args['message'] = $rewritten;
52  		return $args;
53  	}
54  }