<?php
/**
 * File Path: includes/admin/tabs/class-mbs-tab-email-save.php
 *
 * Email Tab Save Handler
 *
 * Encapsulates the credential-encryption and option persistence logic
 * for the Email / ESP settings form. Hooked on admin_init by
 * MBS_Tab_Email's constructor.
 *
 * Delegates platform and key lookups to MBS_ESP_Platform_Registry.
 *
 * Extracted from MBS_Tab_Email::save_settings() (REF-010, Session 136).
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Admin/Tabs
 * @since      1.1.0
 */

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

class MBS_Tab_Email_Save {

	// -------------------------------------------------------------------------
	// Save handler
	// -------------------------------------------------------------------------

	public function save_settings(): void {
		if ( ! isset( $_POST['mbs_email_tab_nonce'] ) ) {
			return;
		}
		if ( ! wp_verify_nonce(
			sanitize_text_field( wp_unslash( $_POST['mbs_email_tab_nonce'] ) ),
			'mbs_email_tab_save'
		) ) {
			return;
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		if ( ! mbs_is_pro() ) {
			return;
		}

		// Platform.
		$allowed_platforms = array_keys( MBS_ESP_Platform_Registry::PLATFORMS );
		$platform = sanitize_key( wp_unslash( $_POST['mbs_email_platform'] ?? '' ) );
		if ( ! in_array( $platform, $allowed_platforms, true ) ) {
			$platform = '';
		}
		update_option( 'mbs_setting_email_platform', $platform, false );

		// API Key (encrypt if non-empty).
		$raw_key = sanitize_text_field( wp_unslash( $_POST['mbs_email_api_key'] ?? '' ) );
		if ( '' !== $raw_key && '' !== $platform ) {
			$key_map = array(
				'mailchimp' => 'mbs_setting_email_mailchimp_api_key',
				'mailerlite' => 'mbs_setting_email_mailerlite_api_key',
				'convertkit' => 'mbs_setting_email_convertkit_api_key',
				'brevo' => 'mbs_setting_email_brevo_api_key',
				'sendy' => 'mbs_setting_email_sendy_api_key',
				'activecampaign' => 'mbs_setting_email_activecampaign_api_key',
				'getresponse' => 'mbs_setting_email_getresponse_api_key',
				'campaignmonitor' => 'mbs_setting_email_campaignmonitor_api_key',
				'moosend' => 'mbs_setting_email_moosend_api_key',
		'authoremail' => 'mbs_setting_email_authoremail_api_key',
			);
			$option_key = $key_map[ $platform ] ?? '';
			if ( '' !== $option_key ) {
				update_option( $option_key, MBS_Encryption::encrypt( $raw_key ), false );
			}
		}

		// Account URL (encrypt if non-empty, Sendy / ActiveCampaign only).
		$raw_url = sanitize_text_field( wp_unslash( $_POST['mbs_email_account_url'] ?? '' ) );
		if ( $raw_url !== '' && in_array( $platform, MBS_ESP_Platform_Registry::URL_PLATFORMS, true ) ) {
			$url_map = array(
				'sendy'          => 'mbs_setting_email_sendy_url',
				'activecampaign' => 'mbs_setting_email_activecampaign_url',
			);
			$option_key = $url_map[ $platform ] ?? '';
			if ( '' !== $option_key ) {
				update_option( $option_key, MBS_Encryption::encrypt( $raw_url ), false );
			}
		}

		// List IDs (plain strings).
		update_option( 'mbs_setting_email_default_list_id',
			sanitize_text_field( wp_unslash( $_POST['mbs_email_default_list_id'] ?? '' ) ), false );
		update_option( 'mbs_setting_email_arc_list_id',
			sanitize_text_field( wp_unslash( $_POST['mbs_email_arc_list_id'] ?? '' ) ), false );
		update_option( 'mbs_setting_email_broadcast_list_id',
			sanitize_text_field( wp_unslash( $_POST['mbs_email_broadcast_list_id'] ?? '' ) ), false );

		// Compliance.
		update_option( 'mbs_setting_email_double_optin',
			isset( $_POST['mbs_email_double_optin'] ) ? '1' : '0', false );
		$allowed_kses = array( 'a' => array( 'href' => array(), 'target' => array() ) );
		update_option( 'mbs_setting_email_consent_text',
			wp_kses( wp_unslash( $_POST['mbs_email_consent_text'] ?? '' ), $allowed_kses ), false );

		// Feature flags.
		update_option( 'mbs_setting_email_widget_enabled',
			isset( $_POST['mbs_email_widget_enabled'] ) ? '1' : '0', false );
		update_option( 'mbs_setting_email_arc_sync_enabled',
			isset( $_POST['mbs_email_arc_sync_enabled'] ) ? '1' : '0', false );
		update_option( 'mbs_setting_email_broadcast_enabled',
			isset( $_POST['mbs_email_broadcast_enabled'] ) ? '1' : '0', false );

		// Tag strategy.
		update_option( 'mbs_setting_email_tag_book',
			isset( $_POST['mbs_email_tag_book'] ) ? '1' : '0', false );
		update_option( 'mbs_setting_email_tag_series',
			isset( $_POST['mbs_email_tag_series'] ) ? '1' : '0', false );
		update_option( 'mbs_setting_email_tag_genre',
			isset( $_POST['mbs_email_tag_genre'] ) ? '1' : '0', false );

		// CAPTCHA provider.
		$_allowed_captcha = array( '', 'recaptcha_v3', 'hcaptcha', 'turnstile' );
		$_captcha_prov    = sanitize_key( wp_unslash( $_POST['mbs_email_captcha_provider'] ?? '' ) );
		if ( ! in_array( $_captcha_prov, $_allowed_captcha, true ) ) {
			$_captcha_prov = '';
		}
		update_option( 'mbs_setting_email_captcha_provider', $_captcha_prov, false );

		// CAPTCHA key pairs (6 encrypted values -- only saved when non-empty).
		$_captcha_fields = array(
			'mbs_email_captcha_recaptcha_v3_site_key'   => 'mbs_setting_email_captcha_recaptcha_v3_site_key',
			'mbs_email_captcha_recaptcha_v3_secret_key' => 'mbs_setting_email_captcha_recaptcha_v3_secret_key',
			'mbs_email_captcha_hcaptcha_site_key'        => 'mbs_setting_email_captcha_hcaptcha_site_key',
			'mbs_email_captcha_hcaptcha_secret_key'      => 'mbs_setting_email_captcha_hcaptcha_secret_key',
			'mbs_email_captcha_turnstile_site_key'       => 'mbs_setting_email_captcha_turnstile_site_key',
			'mbs_email_captcha_turnstile_secret_key'     => 'mbs_setting_email_captcha_turnstile_secret_key',
		);
		foreach ( $_captcha_fields as $_post_key => $_opt_key ) {
			$_raw = sanitize_text_field( wp_unslash( $_POST[ $_post_key ] ?? '' ) );
			if ( '' !== $_raw ) {
				update_option( $_opt_key, MBS_Encryption::encrypt( $_raw ), false );
			}
		}
		unset( $_captcha_fields, $_post_key, $_opt_key, $_raw );

		// ARC Signup Notifications.
		update_option( 'mbs_setting_arc_signup_notification_enabled',
			isset( $_POST['mbs_arc_notify_enabled'] ) ? '1' : '0', false );
		update_option( 'mbs_setting_arc_signup_notification_email',
			sanitize_email( wp_unslash( $_POST['mbs_arc_notify_email'] ?? '' ) ), false );

		// PRG redirect -- prevent double-save on page reload.
		wp_safe_redirect( add_query_arg( array( 'page' => 'my-book-showroom-settings', 'tab' => 'promote', 'updated' => '1' ), admin_url( 'admin.php' ) ) );
		exit;
	}
}
