<?php
/**
 * File Path: includes/admin/tabs/class-mbs-tab-email.php
 *
 * Email / Newsletter Settings Tab (Tab 14) -- My Book Showroom
 *
 * PRO-gated. Platform selection, API key storage, list config,
 * GDPR compliance toggles, feature flags, tag strategy.
 *
 * Save flow: custom admin_init handler (nonce: mbs_email_tab_save /
 * mbs_email_tab_nonce). Not routed through options.php / Settings API.
 * AJAX: wp_ajax_mbs_esp_test_connection (admin-only, PRO-gated).
 *
 * Sprint F-026: Email Channel Integration.
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Admin/Tabs
 * @since      1.1.0
 */

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

class MBS_Tab_Email {

	// -------------------------------------------------------------------------
	// Boot
	// -------------------------------------------------------------------------

	public function __construct() {
		$save = new MBS_Tab_Email_Save();
		add_action( 'admin_init', array( $save, 'save_settings' ) );
		add_action( 'wp_ajax_mbs_esp_test_connection', array( $this, 'ajax_test_connection' ) );
	}

	// -------------------------------------------------------------------------
	// Asset enqueuing
	// -------------------------------------------------------------------------

	/**
	 * Enqueue Email tab assets when this tab is active.
	 *
	 * @param string $current_tab Active tab slug.
	 */
	public function enqueue( string $current_tab ): void {
		if ( 'email' !== $current_tab ) {
			return;
		}
		if ( ! mbs_is_pro() ) {
			return;
		}
		wp_enqueue_script(
			'mbs-admin-email-tab',
			plugins_url( 'assets/js/adminjs/admin-email-tab.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'jquery' , 'wp-i18n' ),
			MBS_VERSION,
			true
		);
		wp_set_script_translations( 'mbs-admin-email-tab', 'my-book-showroom', MBS_DIR . 'languages' );
		wp_localize_script( 'mbs-admin-email-tab', 'MBS_EmailTab', array(
			'ajaxUrl'      => admin_url( 'admin-ajax.php' ),
			'testNonce'    => wp_create_nonce( 'mbs_esp_test' ),
			'platform'     => (string) get_option( 'mbs_setting_email_platform', '' ),
			'urlPlatforms' => MBS_ESP_Platform_Registry::URL_PLATFORMS,

		) );
	}

	// -------------------------------------------------------------------------
	// Render
	// -------------------------------------------------------------------------

	public function render(): void {
		if ( ! mbs_is_pro() ) {
			return;
		}
		$platform          = (string) get_option( 'mbs_setting_email_platform', '' );
		$default_list_id   = (string) get_option( 'mbs_setting_email_default_list_id', '' );
		$arc_list_id       = (string) get_option( 'mbs_setting_email_arc_list_id', '' );
		$broadcast_list_id = (string) get_option( 'mbs_setting_email_broadcast_list_id', '' );
		$double_optin      = (string) get_option( 'mbs_setting_email_double_optin', '0' );
		$consent_text      = (string) get_option( 'mbs_setting_email_consent_text',
			__( 'I agree to receive email updates about new books and author news. You can unsubscribe at any time.', 'my-book-showroom' ) );
		$widget_enabled    = (string) get_option( 'mbs_setting_email_widget_enabled', '0' );
		$arc_sync_enabled  = (string) get_option( 'mbs_setting_email_arc_sync_enabled', '0' );
		$broadcast_enabled = (string) get_option( 'mbs_setting_email_broadcast_enabled', '0' );
		$tag_book          = (string) get_option( 'mbs_setting_email_tag_book', '1' );
		$tag_series        = (string) get_option( 'mbs_setting_email_tag_series', '1' );
		$tag_genre         = (string) get_option( 'mbs_setting_email_tag_genre', '1' );

		// Detect if a key is already stored for the active platform.
		$has_key = false;
		if ( '' !== $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',
			);
			$opt     = $key_map[ $platform ] ?? '';
			$has_key = $opt && '' !== get_option( $opt, '' );
		}
		$key_placeholder = $has_key
			? __( '(API key saved -- enter new key to replace)', 'my-book-showroom' )
			: '';

		// Account URL for Sendy / ActiveCampaign.
		$has_url = false;
		$is_url_platform = in_array( $platform, MBS_ESP_Platform_Registry::URL_PLATFORMS, true );
		if ( $is_url_platform ) {
			$url_map = array(
				'sendy'          => 'mbs_setting_email_sendy_url',
				'activecampaign' => 'mbs_setting_email_activecampaign_url',
			);
			$opt     = $url_map[ $platform ] ?? '';
			$has_url = $opt && '' !== get_option( $opt, '' );
		}
		$url_placeholder = $has_url
			? __( '(URL saved -- enter new URL to replace)', 'my-book-showroom' )
			: __( 'https://your-account.example.com', 'my-book-showroom' );

		// CAPTCHA configuration.
		$captcha_provider   = (string) get_option( 'mbs_setting_email_captcha_provider', '' );
		$captcha_key_hints  = array();
		foreach ( array( 'recaptcha_v3', 'hcaptcha', 'turnstile' ) as $_prov ) {
			$captcha_key_hints[ $_prov . '_site' ]   = '' !== get_option( 'mbs_setting_email_captcha_' . $_prov . '_site_key', '' );
			$captcha_key_hints[ $_prov . '_secret' ] = '' !== get_option( 'mbs_setting_email_captcha_' . $_prov . '_secret_key', '' );
		}
		unset( $_prov );

		// ARC Signup Notifications.
		$arc_notify_enabled = (string) get_option( 'mbs_setting_arc_signup_notification_enabled', '1' );
		$arc_notify_email   = (string) get_option( 'mbs_setting_arc_signup_notification_email', '' );

		// Pre-compute class constants and URLs for the template (self:: not available there).
		$platforms    = MBS_ESP_Platform_Registry::PLATFORMS;
		$url_platforms = MBS_ESP_Platform_Registry::URL_PLATFORMS;
		$mbs_sub_url  = ( '' !== $broadcast_list_id )
			? self::get_subscriber_list_url( MBS_ESP_Registry::get_platform(), $broadcast_list_id )
			: '';
		$mbs_auto_url = self::get_automation_url( MBS_ESP_Registry::get_platform() );

		mbs_get_template_part( 'admin/tab-email', compact(
			'platform', 'platforms', 'url_platforms', 'is_url_platform',
			'default_list_id', 'arc_list_id', 'broadcast_list_id',
			'double_optin', 'consent_text',
			'widget_enabled', 'arc_sync_enabled', 'broadcast_enabled',
			'tag_book', 'tag_series', 'tag_genre',
			'has_key', 'key_placeholder', 'has_url', 'url_placeholder',
			'mbs_sub_url', 'mbs_auto_url',
			'captcha_provider', 'captcha_key_hints',
			'arc_notify_enabled', 'arc_notify_email'
		) );
	}
	// -------------------------------------------------------------------------
	// AJAX: Test Connection
	// -------------------------------------------------------------------------

	/**
	 * Return the automation URL for a platform.
	 *
	 * @param string $platform Platform slug.
	 * @return string
	 */
	public static function get_automation_url( string $platform ): string {
		$urls = array(
			'mailchimp'       => 'https://us1.admin.mailchimp.com/automations/',
			'mailerlite'      => 'https://dashboard.mailerlite.com/automations',
			'convertkit'      => 'https://app.kit.com/automations',
			'brevo'           => 'https://app.brevo.com/automation/list',
			'activecampaign'  => 'https://www.activecampaign.com/automations/',
			'getresponse'     => 'https://app.getresponse.com/automation',
			'campaignmonitor' => 'https://login.campaignmonitor.com/',
			'moosend'         => 'https://app.moosend.com/automations',
			'sendy'           => '',
			'flodesk'         => 'https://app.flodesk.com/workflows',
		);
		return $urls[ $platform ] ?? '';
	}

	/**
	 * Return the subscriber list URL for a platform and list ID.
	 *
	 * @param string $platform Platform slug.
	 * @param string $list_id  List identifier.
	 * @return string
	 */
	public static function get_subscriber_list_url( string $platform, string $list_id ): string {
		if ( '' === $list_id ) {
			return '';
		}
		switch ( $platform ) {
			case 'mailchimp':
				return 'https://us1.admin.mailchimp.com/lists/members/?id=' . rawurlencode( $list_id );
			case 'mailerlite':
				return 'https://dashboard.mailerlite.com/subscribers';
			case 'convertkit':
				return 'https://app.kit.com/subscribers';
			case 'brevo':
				return 'https://app.brevo.com/contact/list/id/' . rawurlencode( $list_id );
			case 'activecampaign':
				return 'https://www.activecampaign.com/lists/';
			case 'getresponse':
				return 'https://app.getresponse.com/contacts';
			case 'campaignmonitor':
				return 'https://login.campaignmonitor.com/';
			case 'moosend':
				return 'https://app.moosend.com/audience';
			case 'flodesk':
				return 'https://app.flodesk.com/subscribers';
			default:
				return '';
		}
	}

	public function ajax_test_connection(): void {
		check_ajax_referer( 'mbs_esp_test', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'my-book-showroom' ) ), 403 );
		}
		if ( ! mbs_is_pro() ) {
			wp_send_json_error( array( 'message' => __( 'PRO license required.', 'my-book-showroom' ) ), 403 );
		}
		$platform    = sanitize_key( wp_unslash( $_POST['platform'] ?? '' ) );
		$api_key     = sanitize_text_field( wp_unslash( $_POST['api_key'] ?? '' ) );
		$account_url = sanitize_text_field( wp_unslash( $_POST['account_url'] ?? '' ) );
		if ( '' === $platform || '' === $api_key ) {
			wp_send_json_error( array( 'message' => __( 'Platform and API key are required.', 'my-book-showroom' ) ) );
		}
		$adapter = MBS_ESP_Registry::make_adapter( $platform, $api_key, $account_url );
		if ( null === $adapter ) {
			wp_send_json_error( array( 'message' => __( 'Unknown platform.', 'my-book-showroom' ) ) );
		}
		if ( ! $adapter->connect() ) {
			wp_send_json_error( array( 'message' => __( 'Connection failed. Check your API key.', 'my-book-showroom' ) ) );
		}
		$lists = $adapter->get_lists();
		wp_send_json_success( array(
			'message' => __( 'Connected successfully.', 'my-book-showroom' ),
			'lists'   => $lists,
		) );
	}
}
