<?php
/**
 * MailPoet Integration Handler
 *
 * Handles all MailPoet integration functionality including filters and actions.
 *
 * @package SureForms
 * @since 2.1.0
 */

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

use SRFM_Pro\Inc\Traits\Get_Instance;

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

/**
 * MailPoet Integration Handler Class
 *
 * @since 2.1.0
 */
class MailPoet_Integration {
	use Get_Instance;

	/**
	 * Constructor
	 *
	 * @since 2.1.0
	 */
	public function __construct() {
		$this->register_filters();
	}

	/**
	 * Get MailPoet lists
	 *
	 * @param array $lists Empty array (default filter value).
	 * @return array Lists formatted for select dropdown.
	 * @since 2.1.0
	 */
	public function get_lists( $lists = [] ) {
		if ( ! $this->is_plugin_active() || ! class_exists( '\MailPoet\API\API' ) ) {
			return $lists;
		}

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

			// Get all lists using MailPoet API.
			$lists_data = $mailpoet_api->getLists();

			$formatted_lists = [];
			if ( ! empty( $lists_data ) && is_array( $lists_data ) ) {
				foreach ( $lists_data as $list ) {
					if ( ! empty( $list['id'] ) && ! empty( $list['name'] ) ) {
						$formatted_lists[] = [
							'value' => (string) $list['id'],
							'label' => $list['name'],
						];
					}
				}
			}

			return $formatted_lists;

		} catch ( \Exception $e ) {
			return $lists;
		}
	}

	/**
	 * Get list name by ID from MailPoet
	 *
	 * @param int $list_id List ID.
	 * @return string|null List name or null if not found.
	 * @since 2.1.0
	 */
	public static function get_list_name_by_id( $list_id ) {
		static $all_lists = null;

		// Fetch all lists once and cache.
		if ( null === $all_lists ) {
			$all_lists = [];
			if ( class_exists( '\MailPoet\API\API' ) ) {
				try {
					$mailpoet_api = \MailPoet\API\API::MP( 'v1' );
					$lists_data   = $mailpoet_api->getLists();
					if ( is_array( $lists_data ) ) {
						foreach ( $lists_data as $list ) {
							if ( is_array( $list ) && isset( $list['id'], $list['name'] ) && is_string( $list['name'] ) ) {
								$all_lists[ intval( $list['id'] ) ] = $list['name'];
							}
						}
					}
				} catch ( \Exception $e ) {
					return null;
				}
			}
		}

		return $all_lists[ intval( $list_id ) ] ?? null;
	}

	/**
	 * Process lists and return list IDs with names
	 *
	 * @param mixed $lists Lists data from form.
	 * @param array $list_names Reference to store list names.
	 * @return array Array of list IDs.
	 * @since 2.1.0
	 */
	public static function process_lists( $lists, &$list_names ) {
		$list_ids = [];

		if ( is_array( $lists ) ) {
			foreach ( $lists as $list ) {
				// Handle object format with value/label (from form field selection).
				if ( is_array( $list ) && isset( $list['value'], $list['label'] ) ) {
					$list_ids[]   = intval( $list['value'] );
					$list_names[] = esc_html( $list['label'] );
				} elseif ( is_numeric( $list ) ) {
					// Handle simple array of IDs (from multi-select-async).
					$list_id    = intval( $list );
					$list_ids[] = $list_id;

					// Get list name from MailPoet if available.
					$list_name = self::get_list_name_by_id( $list_id );
					if ( $list_name ) {
						$list_names[] = esc_html( $list_name );
					}
				} elseif ( is_string( $list ) && is_numeric( $list ) ) {
					// Handle string IDs.
					$list_id    = intval( $list );
					$list_ids[] = $list_id;

					// Get list name from MailPoet if available.
					$list_name = self::get_list_name_by_id( $list_id );
					if ( $list_name ) {
						$list_names[] = esc_html( $list_name );
					}
				}
			}
		} elseif ( is_string( $lists ) ) {
			// Handle comma-separated list IDs.
			$lists_arr = array_filter( array_map( 'trim', explode( ',', $lists ) ) );
			foreach ( $lists_arr as $list ) {
				if ( is_numeric( $list ) ) {
					$list_id    = intval( $list );
					$list_ids[] = $list_id;

					// Get list name from MailPoet if available.
					$list_name = self::get_list_name_by_id( $list_id );
					if ( $list_name ) {
						$list_names[] = esc_html( $list_name );
					}
				}
			}
		}

		return array_unique( array_filter( $list_ids ) );
	}

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

	/**
	 * Register WordPress filters for MailPoet field discovery
	 *
	 * @since 2.1.0
	 * @return void
	 */
	private function register_filters() {
		if ( ! $this->is_plugin_active() ) {
			return;
		}

		// Register filters for dynamic fields.
		add_filter( 'srfm_mailpoet_get_lists', [ $this, 'get_lists' ] );

		// Load action files (they will auto-register when loaded).
		$this->load_action_files();
	}

	/**
	 * Load action files - they auto-register their handlers when loaded
	 *
	 * @since 2.1.0
	 * @return void
	 */
	private function load_action_files() {
		$action_files = [
			__DIR__ . '/actions/add-subscriber.php',
			__DIR__ . '/actions/remove-subscriber.php',
		];

		foreach ( $action_files as $file ) {
			if ( file_exists( $file ) ) {
				require_once $file;
			}
		}
	}
}

// Initialize the class using the singleton pattern.
MailPoet_Integration::get_instance();
