<?php

if (!defined('ABSPATH')) { exit; }

class AIEO_SSO_Newsletter_Wiring {

    public static function register() {
        add_action('aieo_sso_subscribe_intent', array(__CLASS__, 'on_subscribe'), 10, 3);
    }

    
    public static function on_subscribe($email, $provider, array $profile) {
        if (!is_email($email)) { return; }
        if (!class_exists('AIEO_Newsletter_Registry')) { return; }

        $registry = AIEO_Newsletter_Registry::instance();
        $adapter  = $registry->adapter();
        if (!$adapter) {
            
            
            return;
        }

        $contact = array(
            'email'      => (string) $email,
            'first_name' => (string) ($profile['first_name'] ?? ''),
            'last_name'  => (string) ($profile['last_name']  ?? ''),
            'sso'        => array(
                'provider' => sanitize_key($provider),
                'verified' => true,
            ),
        );

        $cohort = apply_filters('aieo_sso_newsletter_cohort', 'sso-' . sanitize_key($provider), $email, $provider);

        try {
            $adapter->sync_contacts(array($contact), (string) $cohort);
            do_action('aieo_sso_newsletter_subscribed', $email, $provider, $profile);
        } catch (\Throwable $e) {
            if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log(sprintf('AIEO SSO newsletter sync failed for %s: %s', $email, $e->getMessage())); }
        }
    }
}
