<?php
/**
 * MailPoet Add Subscriber Action
 *
 * Handles adding/updating subscribers in MailPoet 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.
}

/**
 * Add Subscriber Action Class
 *
 * @since 2.1.0
 */
class Add_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 = 'add_subscriber';

	/**
	 * Execute the add subscriber action
	 *
	 * @param array $data Form submission data.
	 * @return array Action result.
	 * @throws \Exception If subscriber creation 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' );

			// Prepare subscriber data.
			$subscriber_data = [
				'email' => sanitize_email( $data['email'] ),
			];

			if ( ! empty( $data['first_name'] ) ) {
				$subscriber_data['first_name'] = sanitize_text_field( $data['first_name'] );
			}

			if ( ! empty( $data['last_name'] ) ) {
				$subscriber_data['last_name'] = sanitize_text_field( $data['last_name'] );
			}

			// 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.' );
			}

			// Confirmation email option.
			$send_confirmation = isset( $data['send_confirmation_email'] ) && '1' === $data['send_confirmation_email'];

			$options = [
				'send_confirmation_email' => $send_confirmation,
			];

			// Check if subscriber already exists.
			try {
				$existing_subscriber = $mailpoet_api->getSubscriber( $subscriber_data['email'] );
				if ( $existing_subscriber ) {
					// Subscriber already exists - don't update, just notify.
					return [
						'success' => false,
						'message' => sprintf(
							// translators: %s: Email address.
							__( 'Subscriber with email %s already exists in MailPoet.', 'sureforms-pro' ),
							$subscriber_data['email']
						),
					];
				}
			} catch ( \MailPoet\API\MP\v1\APIException $e ) {
				// phpcs:ignore -- this is added to prevent an empty catch block warning.
				$e = $e;
				// Subscriber doesn't exist - continue to create.
			}

			// Create new subscriber.
			$new_subscriber = $mailpoet_api->addSubscriber( $subscriber_data, $list_ids, $options );

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

			return [
				'success' => true,
				'message' => __( 'Subscriber added 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 add 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.
Add_Subscriber::get_instance();
