<?php
/**
 * FluentCRM Remove Contact Action
 *
 * Handles removing contacts from FluentCRM lists/tags or deleting contacts completely through SureForms.
 *
 * @package SureForms
 * @since 1.13.0
 */

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

use SRFM_Pro\Inc\Pro\Native_Integrations\Integrations\FluentCRM\FluentCRM_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 1.13.0
 */
class Remove_Contact extends WordPress_Action {
	use Get_Instance;

	/**
	 * Integration name
	 *
	 * @var string
	 * @since 1.13.0
	 */
	protected $integration = 'fluentcrm';

	/**
	 * Action name
	 *
	 * @var string
	 * @since 1.13.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 1.13.0
	 */
	protected function execute( $data ) {
		try {
			// Validate required functions.
			if ( ! function_exists( 'FluentCrmApi' ) ) {
				throw new \Exception( 'FluentCRM API functions not found.' );
			}

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

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

			$contact_api = FluentCrmApi( 'contacts' );
			$contact     = $contact_api->getContact( trim( $email ) );

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

			// 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 FluentCRM plugin is active
	 *
	 * @return bool True if FluentCRM is active, false otherwise.
	 * @since 1.13.0
	 */
	protected function is_plugin_active() {
		return defined( 'FLUENTCRM' );
	}

	/**
	 * Remove contact from specified lists
	 *
	 * @param object $contact FluentCRM contact object.
	 * @param array  $data Form submission data.
	 * @return array Removal result data.
	 * @throws \Exception If list removal fails.
	 * @since 1.13.0
	 */
	private function remove_from_lists( $contact, $data ) {
		$list_ids   = [];
		$list_names = [];

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

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

		// Remove contact from lists.
		// @phpstan-ignore-next-line -- Method from FluentCRM.
		$contact->detachLists( $list_ids );

		return [
			'contact_id'       => $contact->id ?? '',
			'email'            => $contact->email ?? '',
			'full_name'        => $contact->full_name ?? '',
			'removed_lists'    => implode( ', ', $list_names ),
			'removed_list_ids' => implode( ', ', $list_ids ),
			'action_type'      => 'remove_from_lists',
		];
	}
}

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