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

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

use SRFM_Pro\Inc\Traits\Get_Instance;

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

/**
 * MailerPress Integration Handler Class
 *
 * @since 2.3.0
 */
class MailerPress_Integration {
	use Get_Instance;

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

	/**
	 * Get MailerPress subscription statuses
	 *
	 * @param array $statuses Empty array (default filter value).
	 * @return array Statuses formatted for select dropdown.
	 * @since 2.3.0
	 */
	public function get_subscription_statuses( $statuses = [] ) {
		if ( ! $this->is_plugin_active() ) {
			return $statuses;
		}

		try {
			// Get the standard MailerPress statuses.
			$mailerpress_statuses = [
				'subscribed'   => __( 'Subscribed', 'sureforms-pro' ),
				'unsubscribed' => __( 'Unsubscribed', 'sureforms-pro' ),
				'pending'      => __( 'Pending', 'sureforms-pro' ),
				'bounced'      => __( 'Bounced', 'sureforms-pro' ),
				'complained'   => __( 'Complained', 'sureforms-pro' ),
			];

			$formatted_statuses = [];

			foreach ( $mailerpress_statuses as $status_key => $status_label ) {
				$formatted_statuses[] = [
					'value' => $status_key,
					'label' => $status_label,
				];
			}

			return $formatted_statuses;

		} catch ( \Exception $exception ) {
			// Log error silently and return default statuses.
			unset( $exception );
			return $statuses;
		}
	}

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

		global $wpdb;

		try {
			$results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- We need to query custom table.
				"SELECT list_id, name FROM {$wpdb->prefix}mailerpress_lists ORDER BY name ASC"
			);

			$formatted_lists = [];

			if ( ! empty( $results ) ) {
				foreach ( $results as $list ) {
					if ( ! empty( $list->list_id ) ) {
						$formatted_lists[] = [
							'value' => $list->list_id,
							'label' => $list->name ?? 'List #' . $list->list_id,
						];
					}
				}
			}

			return $formatted_lists;

		} catch ( \Exception $exception ) {
			// Log error silently and return default lists.
			unset( $exception );
			return $lists;
		}
	}

	/**
	 * Get MailerPress tags
	 *
	 * @param array $tags Empty array (default filter value).
	 * @return array Tags formatted for select dropdown.
	 * @since 2.3.0
	 */
	public function get_tags( $tags = [] ) {
		if ( ! $this->is_plugin_active() ) {
			return $tags;
		}

		global $wpdb;

		try {
			$results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- We need to query custom table and caching is not required.
				"SELECT tag_id, name FROM {$wpdb->prefix}mailerpress_tags ORDER BY name ASC"
			);

			$formatted_tags = [];

			if ( ! empty( $results ) ) {
				foreach ( $results as $tag ) {
					if ( ! empty( $tag->tag_id ) ) {
						$formatted_tags[] = [
							'value' => $tag->tag_id,
							'label' => $tag->name ?? 'Tag #' . $tag->tag_id,
						];
					}
				}
			}

			return $formatted_tags;

		} catch ( \Exception $exception ) {
			// Log error silently and return default tags.
			unset( $exception );
			return $tags;
		}
	}

	/**
	 * Process tags and return tag IDs with names
	 *
	 * @param mixed $tags Tags data from form.
	 * @param array $tag_names Reference to store tag names.
	 * @return array Array of tag IDs.
	 * @since 2.3.0
	 */
	public static function process_tags( $tags, &$tag_names ) {
		$tag_ids = [];

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

					// Get tag name from MailerPress if available.
					global $wpdb;
					$tag_name = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- We need to query custom table and caching is not required.
						$wpdb->prepare(
							"SELECT name FROM {$wpdb->prefix}mailerpress_tags WHERE tag_id = %d",
							$tag_id
						)
					);
					if ( $tag_name ) {
						$tag_names[] = esc_html( $tag_name );
					}
				} elseif ( is_string( $tag ) && is_numeric( $tag ) ) {
					// Handle string IDs.
					$tag_id    = intval( $tag );
					$tag_ids[] = $tag_id;

					// Get tag name from MailerPress if available.
					global $wpdb;
					$tag_name = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- We need to query custom table and caching is not required.
						$wpdb->prepare(
							"SELECT name FROM {$wpdb->prefix}mailerpress_tags WHERE tag_id = %d",
							$tag_id
						)
					);
					if ( $tag_name ) {
						$tag_names[] = esc_html( $tag_name );
					}
				}
			}
		} elseif ( is_string( $tags ) ) {
			// Handle comma-separated tag IDs or names.
			$tags_arr = array_filter( array_map( 'trim', explode( ',', $tags ) ) );

			foreach ( $tags_arr as $tag ) {
				if ( is_numeric( $tag ) ) {
					// It's a tag ID.
					$tag_id    = intval( $tag );
					$tag_ids[] = $tag_id;

					// Get tag name from MailerPress if available.
					global $wpdb;
					$tag_name = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- We need to query custom table and caching is not required.
						$wpdb->prepare(
							"SELECT name FROM {$wpdb->prefix}mailerpress_tags WHERE tag_id = %d",
							$tag_id
						)
					);
					if ( $tag_name ) {
						$tag_names[] = esc_html( $tag_name );
					}
				} else {
					// It's a tag name - find by name.
					global $wpdb;
					$existing_tag = $wpdb->get_row( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- We need to query custom table and caching is not required.
						$wpdb->prepare(
							"SELECT tag_id, name FROM {$wpdb->prefix}mailerpress_tags WHERE name = %s",
							$tag
						)
					);

					if ( $existing_tag ) {
						$tag_ids[]   = $existing_tag->tag_id;
						$tag_names[] = esc_html( $existing_tag->name );
					}
				}
			}
		}

		return array_unique( array_filter( $tag_ids ) );
	}

	/**
	 * 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.3.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 MailerPress if available.
					global $wpdb;
					$list_name = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- We need to query custom table and caching is not required.
						$wpdb->prepare(
							"SELECT name FROM {$wpdb->prefix}mailerpress_lists WHERE list_id = %d",
							$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 MailerPress if available.
					global $wpdb;
					$list_name = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- We need to query custom table and caching is not required.
						$wpdb->prepare(
							"SELECT name FROM {$wpdb->prefix}mailerpress_lists WHERE list_id = %d",
							$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 MailerPress if available.
					global $wpdb;
					$list_name = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- We need to query custom table and caching is not required.
						$wpdb->prepare(
							"SELECT name FROM {$wpdb->prefix}mailerpress_lists WHERE list_id = %d",
							$list_id
						)
					);
					if ( $list_name ) {
						$list_names[] = esc_html( $list_name );
					}
				}
			}
		}

		return array_unique( array_filter( $list_ids ) );
	}

	/**
	 * Check if MailerPress plugin is active
	 *
	 * @return bool True if MailerPress is active, false otherwise.
	 * @since 2.3.0
	 */
	private function is_plugin_active() {
		return defined( 'MAILERPRESS_VERSION' );
	}

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

		// Register filters for dynamic fields.
		add_filter( 'srfm_mailerpress_get_subscription_statuses', [ $this, 'get_subscription_statuses' ] );
		add_filter( 'srfm_mailerpress_get_lists', [ $this, 'get_lists' ] );
		add_filter( 'srfm_mailerpress_get_tags', [ $this, 'get_tags' ] );

		// 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.3.0
	 * @return void
	 */
	private function load_action_files() {
		$action_files = [
			__DIR__ . '/actions/add-contact.php',
			__DIR__ . '/actions/delete-contact.php',
			__DIR__ . '/actions/remove-contact.php',
		];

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

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