<?php
/**
 * MailerPress Delete Contact Action
 *
 * Handles deleting contacts in MailerPress 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\WordPress_Action;
use SRFM_Pro\Inc\Traits\Get_Instance;

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

/**
 * Delete Contact Action Class
 *
 * @since 2.3.0
 */
class Delete_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 = 'delete_contact';

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

			// Sanitize email.
			$email = sanitize_email( $email );

			// MailerPress table names.
			$contact_table       = $wpdb->prefix . 'mailerpress_contact';
			$contact_lists_table = $wpdb->prefix . 'mailerpress_contact_lists';
			$contact_tags_table  = $wpdb->prefix . 'mailerpress_contact_tags';

			// 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 * FROM {$contact_table} WHERE email = %s",
					$email
				)
			);

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

			$contact_id = $contact->contact_id;

			// Delete contact from lists.
			$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 ],
				[ '%d' ]
			);

			// Delete contact from tags.
			$wpdb->delete( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- We need to delete data from a custom table of MailerPress.
				$contact_tags_table,
				[ 'contact_id' => $contact_id ],
				[ '%d' ]
			);

			// Delete the contact.
			$contact_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_table,
				[ 'contact_id' => $contact_id ],
				[ '%d' ]
			);

			if ( false === $contact_result ) {
				throw new \Exception( 'Failed to delete contact.' );
			}

			$return_data = [
				'contact_id' => $contact_id,
				'email'      => $email,
				'first_name' => $contact->first_name,
				'last_name'  => $contact->last_name,
				'full_name'  => trim( $contact->first_name . ' ' . $contact->last_name ),
			];

			return [
				'success' => true,
				'message' => __( 'Contact deleted successfully.', 'sureforms-pro' ),
				'data'    => $return_data,
			];

		} catch ( \Exception $e ) {
			return [
				'success' => false,
				'message' => sprintf(
					// translators: %s: Error message.
					__( 'Failed to delete 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' );
	}
}

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