<?php
/**
 * File Path: includes/class-mbs-esp-arc-sync.php
 *
 * ESP ARC Reviewer Cron Sync -- F-026-6
 *
 * Subscribes ARC reviewers to the configured ESP list via a deferred
 * WP Cron event. Triggered 60 seconds after ARC metabox save.
 * Deduplication via 30-day transient prevents double-subscribing.
 *
 * @package MyBookShowroom
 * @since   1.1.0
 */

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

class MBS_ESP_Arc_Sync {

	/**
	 * Cron handler -- subscribed to hook mbs_esp_arc_reviewer_sync.
	 *
	 * @param int $post_id  Book post ID whose reviewers should be synced.
	 */
	public static function register_hooks(): void {
		add_action( 'mbs_esp_arc_reviewer_sync', array( __CLASS__, 'handle' ) );
	}

	public static function handle( int $post_id ): void {
		try {
			// 1. PRO gate.
			if ( ! mbs_is_pro() ) {
				return;
			}

			// 2. Feature toggle.
			if ( '1' !== mbs_get_setting( 'email', 'arc_sync_enabled', '0' ) ) {
				return;
			}

			// 3. Get adapter.
			$adapter = MBS_ESP_Registry::get_adapter();
			if ( null === $adapter ) {
				return;
			}

			// 4. List ID for ARC reviewers.
			$arc_list_id = mbs_get_setting( 'email', 'arc_list_id', '' );
			if ( '' === $arc_list_id ) {
				return;
			}

			// 5. Double opt-in setting.
			$double_optin = '1' === mbs_get_setting( 'email', 'double_optin', '0' );

			// 6. Tag toggles (ARC Team is always added regardless of toggles).
			$tag_book   = '1' === mbs_get_setting( 'email', 'tag_book',   '1' );
			$tag_series = '1' === mbs_get_setting( 'email', 'tag_series', '1' );
			$tag_genre  = '1' === mbs_get_setting( 'email', 'tag_genre',  '1' );

			// 7. Resolve book-level tags once (same for all reviewers).
			$book_tags = array( 'ARC Team' );
			if ( $tag_book ) {
				$title = get_the_title( $post_id );
				if ( ! empty( $title ) ) {
					$book_tags[] = $title;
				}
			}
			if ( $tag_series ) {
				$series_terms = get_the_terms( $post_id, MBS_TAX_SERIES );
				if ( ! empty( $series_terms ) && ! is_wp_error( $series_terms ) ) {
					$book_tags[] = $series_terms[0]->name;
				}
			}
			if ( $tag_genre ) {
				$genre_terms = get_the_terms( $post_id, MBS_TAX_GENRE );
				if ( ! empty( $genre_terms ) && ! is_wp_error( $genre_terms ) ) {
					$book_tags[] = $genre_terms[0]->name;
				}
			}

			// 8. Get reviewers for this book.
			$reviewers = MBS_Arc_Recipient_DAO::get_by_book( $post_id );

			// 9. Subscribe each email-type reviewer.
			foreach ( $reviewers as $reviewer ) {
				// Only process rows where contact_type is email.
				if ( 'email' !== ( $reviewer->contact_type ?? '' ) ) {
					continue;
				}
				$email = sanitize_email( $reviewer->contact_method ?? '' );
				if ( ! is_email( $email ) ) {
					continue;
				}

				// Deduplication transient -- 30 days.
				$dedup_key = 'mbs_esp_arc_' . md5( $email . (string) $post_id );
				if ( get_transient( $dedup_key ) ) {
					continue;
				}

				$name = sanitize_text_field( $reviewer->reviewer_name ?? '' );

				// Subscribe.
				$subscribed = $adapter->subscribe( $email, $name, $arc_list_id, $double_optin );
				if ( ! $subscribed ) {
					continue;
				}

				// Apply tags (ARC Team always first, plus configured book tags).
				if ( $adapter->supports_tags() ) {
					$adapter->tag_contact( $email, $book_tags, $arc_list_id );
				}

				// Mark as synced -- 30 days TTL.
				set_transient( $dedup_key, 1, 30 * DAY_IN_SECONDS );
			}
		} catch ( Throwable $e ) {
			// Swallow all exceptions -- cron handler must never bubble.
			return;
		}
	}
}
