<?php
/**
 * MailerPress Remove Contact Action
 *
 * Handles removing contacts from MailerPress lists through SureForms.
 *
 * @package SureForms
 * @since 2.3.0
 */

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

use SRFM_Pro\Inc\Pro\Native_Integrations\Integrations\MailerPress\MailerPress_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 Contact Action Class
 *
 * @since 2.3.0
 */
class Remove_Contact extends WordPress_Action {
	use Get_Instance;

	/**
	 * Integration name
	 *
	 * @var string
	 * @since 2.3.0
	 */
	protected $integration = 'mailerpress';

	/**
	 * Action name
	 *
	 * @var string
	 * @since 2.3.0
	 */
	protected $action = 'remove_contact';

	/**
	 * Execute the remove contact action
	 *
	 * @param array $data Form submission data.
	 * @return array Action result.
	 * @throws \Exception If contact removal fails.
	 * @since 2.3.0
	 */
	protected function execute( $data ) {
		global $wpdb;

		try {
			// Validate email.
			$email = $data['email'] ?? '';
			if ( empty( $email ) || ! is_email( $email ) ) {
				throw new \Exception( 'Valid email address is required.' );
			}

			// Validate lists.
			if ( empty( $data['list_ids'] ) ) {
				throw new \Exception( 'Lists are required for removing contact from lists.' );
			}

			$email = sanitize_email( $email );

			// MailerPress table names.
			$contact_table = $wpdb->prefix . 'mailerpress_contact';

			// Check if contact exists.
			$contact = $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(
					// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- We are using prepare method and adding placeholder for table name will also add quotes which will give error for the query.
					"SELECT contact_id, email, first_name, last_name FROM {$contact_table} WHERE email = %s",
					$email
				)
			);

			if ( ! $contact ) {
				throw new \Exception( 'Contact not found in MailerPress.' );
			}

			// Remove contact from specified lists.
			$removed_items = $this->remove_from_lists( $contact, $data );

			return [
				'success' => true,
				'message' => __( 'Contact removed from lists successfully.', 'sureforms-pro' ),
				'data'    => $removed_items,
			];

		} catch ( \Exception $e ) {
			return [
				'success' => false,
				'message' => sprintf(
					// translators: %s: Error message.
					__( 'Failed to remove contact: %s', 'sureforms-pro' ),
					$e->getMessage()
				),
			];
		}
	}

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

	/**
	 * Remove contact from specified lists
	 *
	 * @param object $contact MailerPress contact object.
	 * @param array  $data Form submission data.
	 * @return array Removal result data.
	 * @throws \Exception If list removal fails.
	 * @since 2.3.0
	 */
	private function remove_from_lists( $contact, $data ) {
		if ( ! $contact ) {
			throw new \Exception( 'Invalid contact data.' );
		}

		$contact_id    = $contact->contact_id ?? 0;
		$contact_email = $contact->email ?? '';
		$first_name    = $contact->first_name ?? '';
		$last_name     = $contact->last_name ?? '';

		global $wpdb;

		$list_ids   = [];
		$list_names = [];

		$list_ids = MailerPress_Integration::process_lists( $data['list_ids'], $list_names );

		if ( empty( $list_ids ) ) {
			throw new \Exception( 'No valid lists specified for removal.' );
		}

		$contact_lists_table = $wpdb->prefix . 'mailerpress_contact_lists';
		$removed_list_names  = [];
		$removed_list_ids    = [];

		foreach ( $list_ids as $list_id ) {
			// Check if contact is in this list.
			$exists = $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(
					// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- We are using prepare method and adding placeholder for table name will also add quotes which will give error for the query.
					"SELECT COUNT(*) FROM {$contact_lists_table} WHERE contact_id = %d AND list_id = %d",
					$contact_id,
					$list_id
				)
			);

			if ( $exists ) {
				// Remove contact from list.
				$result = $wpdb->delete( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- We need to delete data from a custom table of MailerPress.
					$contact_lists_table,
					[
						'contact_id' => $contact_id,
						'list_id'    => $list_id,
					],
					[ '%d', '%d' ]
				);

				if ( false !== $result ) {
					$removed_list_ids[] = $list_id;

					// Get list name for reporting.
					$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 ) {
						$removed_list_names[] = esc_html( $list_name );
					}
				}
			}
		}

		if ( empty( $removed_list_ids ) ) {
			throw new \Exception( 'Contact was not found in any of the specified lists.' );
		}

		return [
			'contact_id'       => $contact_id,
			'email'            => $contact_email,
			'full_name'        => trim( $first_name . ' ' . $last_name ),
			'first_name'       => $first_name,
			'last_name'        => $last_name,
			'removed_lists'    => implode( ', ', $removed_list_names ),
			'removed_list_ids' => implode( ', ', $removed_list_ids ),
			'action_type'      => 'remove_from_lists',
			'lists_count'      => count( $removed_list_ids ),
		];
	}
}

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