<?php
/**
 * MailPoet Remove Subscriber Action
 *
 * Handles removing subscribers from MailPoet lists through SureForms.
 *
 * @package SureForms
 * @since 2.1.0
 */

namespace SRFM_Pro\Inc\Pro\Native_Integrations\Integrations\MailPoet\Actions;

use SRFM_Pro\Inc\Pro\Native_Integrations\Integrations\MailPoet\MailPoet_Integration;
use SRFM_Pro\Inc\Pro\Native_Integrations\WordPress_Action;
use SRFM_Pro\Inc\Traits\Get_Instance;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Remove Subscriber Action Class
 *
 * @since 2.1.0
 */
class Remove_Subscriber extends WordPress_Action {
	use Get_Instance;

	/**
	 * Integration name
	 *
	 * @var string
	 * @since 2.1.0
	 */
	protected $integration = 'mailpoet';

	/**
	 * Action name
	 *
	 * @var string
	 * @since 2.1.0
	 */
	protected $action = 'remove_subscriber';

	/**
	 * Execute the remove subscriber action
	 *
	 * @param array $data Form submission data.
	 * @return array Action result.
	 * @throws \Exception If subscriber removal fails.
	 * @since 2.1.0
	 */
	protected function execute( $data ) {
		// Ensure MailPoet APIException class exists.
		if ( ! class_exists( '\MailPoet\API\MP\v1\APIException' ) ) {
			return [
				'success' => false,
				'message' => __( 'MailPoet API is unavailable. Please ensure MailPoet is installed and activated.', 'sureforms-pro' ),
			];
		}
		try {
			// Validate required API.
			if ( ! class_exists( '\MailPoet\API\API' ) ) {
				throw new \Exception( 'MailPoet plugin is not installed or activated.' );
			}

			// Validate email.
			if ( empty( $data['email'] ) || ! is_email( $data['email'] ) ) {
				throw new \Exception( 'Invalid email address.' );
			}

			// Get MailPoet API.
			$mailpoet_api = \MailPoet\API\API::MP( 'v1' );

			// Get subscriber email.
			$subscriber_email = sanitize_email( $data['email'] );

			// Check if subscriber exists.
			$subscriber = $mailpoet_api->getSubscriber( $subscriber_email );
			if ( ! $subscriber ) {
				return [
					'success' => false,
					'message' => sprintf(
						// translators: %s: Email address.
						__( 'Subscriber with email %s does not exist in MailPoet.', 'sureforms-pro' ),
						$subscriber_email
					),
				];
			}

			// Process list IDs.
			$list_ids   = [];
			$list_names = [];
			if ( ! empty( $data['list_ids'] ) ) {
				$list_ids = MailPoet_Integration::process_lists( $data['list_ids'], $list_names );
			}

			if ( empty( $list_ids ) ) {
				throw new \Exception( 'Please select at least one list.' );
			}

			// Get subscriber's current subscriptions.
			$current_subscriptions = $subscriber['subscriptions'] ?? [];
			$subscribed_list_ids   = array_column( $current_subscriptions, 'segment_id' );

			// Filter out lists the subscriber is not subscribed to.
			$lists_to_remove = array_intersect( $list_ids, $subscribed_list_ids );

			if ( empty( $lists_to_remove ) ) {
				return [
					'success' => false,
					'message' => sprintf(
						// translators: %s: Email address.
						__( 'Subscriber %s is not subscribed to any of the selected lists.', 'sureforms-pro' ),
						$subscriber_email
					),
				];
			}

			// Remove subscriber from lists.
			$mailpoet_api->unsubscribeFromLists( $subscriber['id'], $lists_to_remove );

			$return_data = [
				'subscriber_id' => $subscriber['id'],
				'email'         => $subscriber['email'],
				'first_name'    => $subscriber['first_name'] ?? '',
				'last_name'     => $subscriber['last_name'] ?? '',
				'list_names'    => implode( ', ', $list_names ),
			];

			return [
				'success' => true,
				'message' => __( 'Subscriber removed from list(s) successfully!', 'sureforms-pro' ),
				'data'    => $return_data,
			];
		} catch ( \MailPoet\API\MP\v1\APIException $e ) {
			return [
				'success' => false,
				'message' => sprintf(
					// translators: %s: Error message.
					__( 'MailPoet API error: %s', 'sureforms-pro' ),
					$e->getMessage()
				),
			];
		} catch ( \Exception $e ) {
			return [
				'success' => false,
				'message' => sprintf(
					// translators: %s: Error message.
					__( 'Failed to remove subscriber: %s', 'sureforms-pro' ),
					$e->getMessage()
				),
			];
		}
	}

	/**
	 * Check if MailPoet plugin is active
	 *
	 * @return bool True if MailPoet is active, false otherwise.
	 * @since 2.1.0
	 */
	protected function is_plugin_active() {
		return class_exists( '\MailPoet\Config\Activator' );
	}
}

// Initialize the class.
Remove_Subscriber::get_instance();
