<?php
/**
 * Lead Forwarder
 *
 * @package MBMaxCf7Relay
 */

namespace MBMaxCf7Relay\Includes\Services;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Отправляет заявки с сайта через портал CACR.
 */
class LeadForwarder {

	/**
	 * Сервис лицензий.
	 *
	 * @var LicenseService
	 */
	private $license_service;

	/**
	 * Дедупликация отправок в рамках одного HTTP-запроса.
	 *
	 * @var array<string, bool>
	 */
	private $processed_signatures = array();

	/**
	 * Конструктор.
	 *
	 * @param LicenseService $license_service Сервис лицензий.
	 */
	public function __construct( LicenseService $license_service ) {
		$this->license_service = $license_service;
	}

	/**
	 * Отправить лид, полученный из Contact Form 7.
	 *
	 * @param \WPCF7_ContactForm $contact_form Объект формы.
	 * @return void
	 */
	public function forward_from_cf7( $contact_form ) {
		$form_id = ( $contact_form && method_exists( $contact_form, 'id' ) ) ? (int) $contact_form->id() : 0;
		$form_title = ( $contact_form && method_exists( $contact_form, 'title' ) ) ? sanitize_text_field( (string) $contact_form->title() ) : 'Contact Form 7';
		$this->debug_log( 'CF7 hook fired. form_id=' . $form_id . '; form_title=' . $form_title . '.' );

		if ( ! class_exists( '\\WPCF7_Submission' ) ) {
			$this->debug_log( 'WPCF7_Submission class not found.' );
			return;
		}

		$submission = \WPCF7_Submission::get_instance();
		if ( ! $submission ) {
			$this->debug_log( 'Submission object is empty.' );
			return;
		}

		$posted_data = $submission->get_posted_data();
		if ( ! is_array( $posted_data ) ) {
			$posted_data = array();
		}

		$lead_data = array(
			'source'          => 'cf7',
			'form_id'         => method_exists( $contact_form, 'id' ) ? (int) $contact_form->id() : 0,
			'form_title'      => method_exists( $contact_form, 'title' ) ? sanitize_text_field( (string) $contact_form->title() ) : 'Contact Form 7',
			'mail_recipient'  => $this->resolve_cf7_mail_recipient( $contact_form ),
			'submitted_at'    => gmdate( 'c' ),
			'page_url'        => esc_url_raw( (string) $submission->get_meta( 'url' ) ),
			'user_ip'         => sanitize_text_field( (string) $submission->get_meta( 'remote_ip' ) ),
			'user_agent'      => sanitize_text_field( (string) $submission->get_meta( 'user_agent' ) ),
			'fields'          => $this->sanitize_fields( $posted_data ),
		);

		if ( empty( $lead_data['fields'] ) ) {
			$this->debug_log( 'CF7 fields are empty after sanitization, forwarding skipped.' );
			return;
		}

		$this->relay_lead( $lead_data, 'cf7' );
	}

	/**
	 * Отправить лид из любой формы, которая отправила email через wp_mail.
	 *
	 * @param array $mail_data Результат wp_mail_succeeded.
	 * @return void
	 */
	public function forward_from_wp_mail( $mail_data ) {
		if ( ! is_array( $mail_data ) ) {
			return;
		}

		if ( ! $this->is_post_request_context() ) {
			$this->debug_log( 'wp_mail_succeeded ignored: request is not POST.' );
			return;
		}

		if ( wp_doing_cron() ) {
			$this->debug_log( 'wp_mail_succeeded ignored: cron context.' );
			return;
		}

		if ( $this->is_blocked_request_context() ) {
			$this->debug_log( 'wp_mail_succeeded ignored: blocked admin/auth request context.' );
			return;
		}

		if ( $this->is_cf7_submission_context() ) {
			$this->debug_log( 'wp_mail_succeeded ignored: CF7 request handled by dedicated hooks.' );
			return;
		}

		if ( $this->is_comment_submission( $mail_data ) ) {
			$this->debug_log( 'wp_mail_succeeded ignored: detected comment notification flow.' );
			return;
		}

		if ( $this->is_system_notification_mail( $mail_data ) ) {
			$this->debug_log( 'wp_mail_succeeded ignored: detected system notification mail.' );
			return;
		}

		$fields = $this->extract_fields_from_mail( $mail_data );
		if ( ! $this->is_probable_lead_fields( $fields ) ) {
			$this->debug_log( 'wp_mail_succeeded ignored: mail body does not look like a lead form.' );
			return;
		}

		$signature = $this->build_signature( $fields );
		if ( isset( $this->processed_signatures[ $signature ] ) ) {
			$this->debug_log( 'wp_mail_succeeded ignored: duplicate payload in current request.' );
			return;
		}
		$this->processed_signatures[ $signature ] = true;

		$lead_data = array(
			'source'       => 'generic_mail_form',
			'form_id'      => 0,
			'form_title'   => $this->resolve_generic_form_title( $fields, $mail_data ),
			'mail_recipient' => $this->resolve_mail_data_recipient( $mail_data ),
			'submitted_at' => gmdate( 'c' ),
			'page_url'     => $this->resolve_request_page_url(),
			'user_ip'      => $this->resolve_remote_ip(),
			'user_agent'   => $this->resolve_user_agent(),
			'fields'       => $fields,
		);

		$this->relay_lead( $lead_data, 'generic_mail_form' );
	}

	/**
	 * Отправить лид через CACR с проверкой ключа и лицензии.
	 *
	 * @param array  $lead_data Полезная нагрузка лида.
	 * @param string $source Источник заявки.
	 * @return void
	 */
	private function relay_lead( $lead_data, $source ) {
		$options = \MBMaxCf7Relay\Includes\Plugin::get_options();

		if ( '' === $options['integration_key'] ) {
			$this->debug_log( 'Integration key is empty, lead forwarding skipped. source=' . $source . '.' );
			return;
		}

		$license = $this->license_service->check_license();
		if ( empty( $license['active'] ) ) {
			$this->debug_log( 'License inactive, lead forwarding blocked. source=' . $source . '; reason=' . ( $license['reason'] ?? 'unknown' ) . '.' );
			return;
		}

		$payload = wp_parse_args(
			$lead_data,
			array(
				'integration_key' => (string) $options['integration_key'],
				'site_url'        => home_url( '/' ),
				'site_domain'     => (string) wp_parse_url( home_url( '/' ), PHP_URL_HOST ),
				'source'          => 'generic_mail_form',
				'form_id'         => 0,
				'form_title'      => '',
				'mail_recipient'  => '',
				'submitted_at'    => gmdate( 'c' ),
				'page_url'        => $this->resolve_request_page_url(),
				'user_ip'         => $this->resolve_remote_ip(),
				'user_agent'      => $this->resolve_user_agent(),
				'fields'          => array(),
			)
		);

		if ( empty( $payload['fields'] ) || ! is_array( $payload['fields'] ) ) {
			$this->debug_log( 'Lead payload has no fields, forwarding skipped. source=' . $source . '.' );
			return;
		}

		$url = untrailingslashit( \MBMaxCf7Relay\Includes\Plugin::get_portal_base_url() ) . '/wp-json/mb/v1/max-cf7/lead';
		$response = \MBMaxCf7Relay\Includes\Plugin::post_portal_json( $url, $payload, 15 );

		if ( is_wp_error( $response ) ) {
			$this->debug_log( 'Lead relay request failed. source=' . $source . '; error=' . $response->get_error_message() . '.' );
			return;
		}

		$code = (int) wp_remote_retrieve_response_code( $response );
		$body = wp_remote_retrieve_body( $response );

		if ( $code < 200 || $code >= 300 ) {
			$this->debug_log( 'Lead relay rejected. source=' . $source . '; HTTP ' . $code . '; Body: ' . $body );
			if ( 402 === $code || 401 === $code ) {
				$this->license_service->check_license( true );
			}
			return;
		}

		$this->debug_log( 'Lead forwarded successfully via CACR. source=' . $source . '; HTTP ' . $code . '; Body: ' . $body );
	}

	/**
	 * Нормализовать значения полей формы.
	 *
	 * @param array $fields Поля формы.
	 * @return array
	 */
	private function sanitize_fields( $fields ) {
		$clean = array();

		foreach ( $fields as $name => $value ) {
			$name_raw = $this->normalize_field_name( $name );
			if ( '' === $name_raw || $this->should_skip_field( $name_raw ) ) {
				continue;
			}

			if ( is_array( $value ) ) {
				$parts = array();
				foreach ( $value as $item ) {
					$parts[] = sanitize_textarea_field( (string) $item );
				}
				$joined = trim( implode( ', ', array_filter( $parts ) ) );
				if ( '' !== $joined ) {
					$clean[ $name_raw ] = $joined;
				}
				continue;
			}

			$item = sanitize_textarea_field( (string) $value );
			if ( '' !== trim( $item ) ) {
				$clean[ $name_raw ] = $item;
			}
		}

		return $clean;
	}

	/**
	 * Проверить, что текущий запрос является POST.
	 *
	 * @return bool
	 */
	private function is_post_request_context() {
		$method = isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( sanitize_text_field( wp_unslash( (string) $_SERVER['REQUEST_METHOD'] ) ) ) : '';
		return 'POST' === $method;
	}

	/**
	 * Исключить admin/auth запросы, которые не являются пользовательскими лидами.
	 *
	 * Важно: frontend-формы нередко отправляются через /wp-admin/admin-post.php и должны
	 * оставаться в обработке, если инициированы не из админки.
	 *
	 * @return bool
	 */
	private function is_blocked_request_context() {
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Value is immediately unslashed and sanitized.
		$request_uri    = isset( $_SERVER['REQUEST_URI'] ) ? strtolower( sanitize_text_field( (string) wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) : '';
		$referer        = wp_get_referer();
		$referer_string = is_string( $referer ) ? strtolower( $referer ) : '';
		$is_login       = false !== strpos( $request_uri, 'wp-login.php' ) || false !== strpos( $request_uri, 'wp-signup.php' );

		if ( $is_login ) {
			return true;
		}

		$is_admin_post = false !== strpos( $request_uri, '/wp-admin/admin-post.php' );
		if ( $is_admin_post ) {
			$is_admin_post_from_dashboard = '' !== $referer_string && false !== strpos( $referer_string, '/wp-admin/' );
			if ( $is_admin_post_from_dashboard ) {
				return true;
			}

			$this->debug_log( 'wp_mail_succeeded admin-post flow accepted.' );

			return false;
		}

		$is_admin_ui   = ( is_admin() && ! wp_doing_ajax() ) || ( false !== strpos( $request_uri, '/wp-admin/' ) && ! wp_doing_ajax() );
		$is_admin_ajax = wp_doing_ajax() && '' !== $referer_string && false !== strpos( $referer_string, '/wp-admin/' );

		return $is_admin_ui || $is_admin_ajax;
	}

	/**
	 * Проверка, что текущий запрос относится к Contact Form 7.
	 *
	 * @return bool
	 */
	private function is_cf7_submission_context() {
		if ( ! class_exists( '\\WPCF7_Submission' ) ) {
			return false;
		}

		$submission = \WPCF7_Submission::get_instance();
		return $submission && is_array( $submission->get_posted_data() );
	}

	/**
	 * Отсечь комментарии WordPress (уведомления автору/админу о комментариях).
	 *
	 * @param array $mail_data Данные отправленного письма.
	 * @return bool
	 */
	private function is_comment_submission( $mail_data ) {
		$subject = isset( $mail_data['subject'] ) ? strtolower( sanitize_text_field( (string) $mail_data['subject'] ) ) : '';
		$message = isset( $mail_data['message'] ) ? strtolower( sanitize_textarea_field( (string) $mail_data['message'] ) ) : '';
		if ( false !== strpos( $subject, 'comment' ) && false !== strpos( $message, 'comment.php' ) ) {
			return true;
		}

		return false;
	}

	/**
	 * Отсечь служебные уведомления WordPress и плагинов.
	 *
	 * @param array $mail_data Данные отправленного письма.
	 * @return bool
	 */
	private function is_system_notification_mail( $mail_data ) {
		$subject = isset( $mail_data['subject'] ) ? strtolower( sanitize_text_field( (string) $mail_data['subject'] ) ) : '';
		$message = isset( $mail_data['message'] ) ? strtolower( sanitize_textarea_field( (string) $mail_data['message'] ) ) : '';

		$blocked_patterns = array(
			'[wordpress]',
			'automatic update',
			'auto-update',
			'автоматическое обновление',
			'обновление wordpress',
			'обновление плагина',
			'обновление темы',
			'plugin update',
			'theme update',
			'новый пользователь',
			'new user registration',
			'password reset',
			'сброс пароля',
			'reset password',
			'comment awaiting moderation',
			'комментарий ожидает проверки',
			'новый комментарий',
			'новый запрос на экспорт персональных данных',
			'новый запрос на удаление персональных данных',
			'подтверждение удаления персональных данных',
		);

		foreach ( $blocked_patterns as $pattern ) {
			if ( '' !== $subject && false !== strpos( $subject, $pattern ) ) {
				return true;
			}
			if ( '' !== $message && false !== strpos( $message, $pattern ) ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Проверка, что payload выглядит как заявка, а не техническая форма.
	 *
	 * @param array $fields Очищенные поля.
	 * @return bool
	 */
	private function is_probable_lead_fields( $fields ) {
		if ( empty( $fields ) || ! is_array( $fields ) ) {
			return false;
		}

		$lead_patterns = array(
			'name',
			'phone',
			'tel',
			'email',
			'mail',
			'message',
			'msg',
			'question',
			'contact',
			'whatsapp',
			'telegram',
			'имя',
			'телефон',
			'почта',
			'сообщение',
			'вопрос',
			'контакт',
		);

		$filled_count    = 0;
		$contains_signal = false;

		foreach ( $fields as $name => $value ) {
			$value = trim( (string) $value );
			if ( '' === $value ) {
				continue;
			}

			++$filled_count;

			foreach ( $lead_patterns as $pattern ) {
				if ( false !== strpos( (string) $name, $pattern ) ) {
					$contains_signal = true;
					break;
				}
			}
		}

		if ( $contains_signal && $filled_count >= 1 ) {
			return true;
		}

		return $filled_count >= 2;
	}

	/**
	 * Извлечь поля лида из уже сформированного письма.
	 *
	 * @param array $mail_data Данные отправленного письма.
	 * @return array
	 */
	private function extract_fields_from_mail( $mail_data ) {
		$message = isset( $mail_data['message'] ) ? (string) $mail_data['message'] : '';
		$text    = $this->normalize_mail_message_text( $message );

		if ( '' === $text ) {
			return array();
		}

		$lines       = preg_split( '/\R+/u', $text );
		$raw_fields  = array();
		$current_key = '';

		if ( ! is_array( $lines ) ) {
			$lines = array();
		}

		foreach ( $lines as $line ) {
			$line = trim( preg_replace( '/[ \t]+/u', ' ', (string) $line ) );
			if ( '' === $line ) {
				continue;
			}

			$field = $this->parse_mail_field_line( $line );
			if ( is_array( $field ) ) {
				$current_key = $field['name'];
				if ( ! isset( $raw_fields[ $current_key ] ) ) {
					$raw_fields[ $current_key ] = '';
				}
				if ( '' !== $field['value'] ) {
					$raw_fields[ $current_key ] = '' === $raw_fields[ $current_key ]
						? $field['value']
						: $raw_fields[ $current_key ] . "\n" . $field['value'];
				}
				continue;
			}

			if ( '' !== $current_key ) {
				$raw_fields[ $current_key ] = '' === $raw_fields[ $current_key ]
					? $line
					: $raw_fields[ $current_key ] . "\n" . $line;
			}
		}

		$fields = $this->sanitize_fields( $raw_fields );
		if ( ! empty( $fields ) ) {
			return $fields;
		}

		if ( $this->looks_like_lead_message( $text ) ) {
			return array(
				'message' => sanitize_textarea_field( $text ),
			);
		}

		return array();
	}

	/**
	 * Пропустить системные поля, nonce и технические токены.
	 *
	 * @param string $name Имя поля.
	 * @return bool
	 */
	private function should_skip_field( $name ) {
		if ( '' === $name || 0 === strpos( $name, '_' ) ) {
			return true;
		}

		$exact_skips = array(
			'action',
			'submit',
			'form_id',
			'formid',
			'redirect_to',
			'post_id',
			'page_id',
			'comment_post_id',
			'comment_parent',
			'g-recaptcha-response',
			'recaptcha',
			'referer',
			'wp_http_referer',
		);

		if ( in_array( $name, $exact_skips, true ) ) {
			return true;
		}

		$contains_skips = array(
			'nonce',
			'token',
			'captcha',
			'security',
			'session',
			'password',
			'passwd',
			'pwd',
		);

		foreach ( $contains_skips as $pattern ) {
			if ( false !== strpos( $name, $pattern ) ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Вычислить подпись payload для дедупликации в одном запросе.
	 *
	 * @param array $fields Поля формы.
	 * @return string
	 */
	private function build_signature( $fields ) {
		$data = array(
			'fields'  => $fields,
			'path'    => isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( (string) $_SERVER['REQUEST_URI'] ) ) : '',
			'referer' => $this->resolve_request_page_url(),
		);

		return md5( (string) wp_json_encode( $data ) );
	}

	/**
	 * Название формы для generic-потока.
	 *
	 * @param array $fields Поля письма.
	 * @param array $mail_data Данные отправленного письма.
	 * @return string
	 */
	private function resolve_generic_form_title( $fields, $mail_data ) {
		$name_keys = array(
			'form_name',
			'form_title',
			'form',
			'subject',
			'form name',
			'form title',
		);

		foreach ( $name_keys as $key ) {
			if ( isset( $fields[ $key ] ) ) {
				$value = sanitize_text_field( (string) $fields[ $key ] );
				if ( '' !== $value ) {
					return $value;
				}
			}
		}

		if ( isset( $mail_data['subject'] ) ) {
			$subject = sanitize_text_field( (string) $mail_data['subject'] );
			if ( '' !== $subject ) {
				return 'Mail form: ' . $subject;
			}
		}

		return 'Generic mail form';
	}

	/**
	 * Получить адрес получателя из настроек письма CF7.
	 *
	 * @param \WPCF7_ContactForm $contact_form Объект формы.
	 * @return string
	 */
	private function resolve_cf7_mail_recipient( $contact_form ) {
		if ( ! $contact_form || ! method_exists( $contact_form, 'prop' ) ) {
			return '';
		}

		$mail = $contact_form->prop( 'mail' );
		if ( ! is_array( $mail ) ) {
			return '';
		}

		return $this->normalize_mail_recipients( $mail['recipient'] ?? '' );
	}

	/**
	 * Получить адрес получателя из wp_mail payload.
	 *
	 * @param array $mail_data Данные отправленного письма.
	 * @return string
	 */
	private function resolve_mail_data_recipient( $mail_data ) {
		$mail_data = is_array( $mail_data ) ? $mail_data : array();

		return $this->normalize_mail_recipients( $mail_data['to'] ?? '' );
	}

	/**
	 * Нормализовать список адресов получателей в строку.
	 *
	 * @param mixed $value Исходные адреса.
	 * @return string
	 */
	private function normalize_mail_recipients( $value ) {
		$items = is_array( $value ) ? $value : preg_split( '/[,;]+/', (string) $value );
		if ( ! is_array( $items ) ) {
			$items = array();
		}

		$clean = array();
		foreach ( $items as $item ) {
			$item = trim( sanitize_text_field( (string) $item ) );
			if ( preg_match( '/<([^>]+)>/', $item, $matches ) ) {
				$item = trim( sanitize_text_field( (string) $matches[1] ) );
			}
			if ( '' !== $item ) {
				$clean[] = $item;
			}
		}

		return implode( ', ', array_unique( $clean ) );
	}

	/**
	 * Получить URL страницы отправки формы.
	 *
	 * @return string
	 */
	private function resolve_request_page_url() {
		$referer = wp_get_referer();
		if ( is_string( $referer ) && '' !== $referer ) {
			return esc_url_raw( $referer );
		}

		$request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( (string) $_SERVER['REQUEST_URI'] ) ) : '';
		if ( '' === $request_uri ) {
			return home_url( '/' );
		}

		return esc_url_raw( home_url( $request_uri ) );
	}

	/**
	 * Получить IP клиента.
	 *
	 * @return string
	 */
	private function resolve_remote_ip() {
		return isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( (string) $_SERVER['REMOTE_ADDR'] ) ) : '';
	}

	/**
	 * Получить user-agent клиента.
	 *
	 * @return string
	 */
	private function resolve_user_agent() {
		return isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( (string) $_SERVER['HTTP_USER_AGENT'] ) ) : '';
	}

	/**
	 * Нормализовать тело письма в plain text для последующего разбора.
	 *
	 * @param string $message Тело письма.
	 * @return string
	 */
	private function normalize_mail_message_text( $message ) {
		$text = (string) $message;

		if ( '' === trim( $text ) ) {
			return '';
		}

		if ( false !== strpos( $text, '<' ) && false !== strpos( $text, '>' ) ) {
			$text = preg_replace( '#</td>\s*<td[^>]*>#i', ': ', $text );
			$text = preg_replace( '#</th>\s*<td[^>]*>#i', ': ', $text );
			$text = preg_replace( '#<(br|/p|/div|/li|/tr|/h[1-6])[^>]*>#i', "\n", $text );
			$text = preg_replace( '#</(td|th)>#i', ' ', $text );
			$text = wp_strip_all_tags( $text, false );
		}

		$charset = get_bloginfo( 'charset' );
		if ( ! is_string( $charset ) || '' === $charset ) {
			$charset = 'UTF-8';
		}

		$text = html_entity_decode( $text, ENT_QUOTES, $charset );
		$text = str_replace( array( "\r\n", "\r" ), "\n", $text );
		$text = preg_replace( "/\n{3,}/", "\n\n", $text );

		return trim( (string) $text );
	}

	/**
	 * Попытаться распознать одну строку письма как поле формы.
	 *
	 * @param string $line Строка письма.
	 * @return array|null
	 */
	private function parse_mail_field_line( $line ) {
		$patterns = array(
			'/^(.{1,80}?)\s*[:=]\s*(.+)$/u',
			'/^(.{1,80}?)\s+[—–-]\s+(.+)$/u',
		);

		foreach ( $patterns as $pattern ) {
			$matches = array();
			if ( ! preg_match( $pattern, $line, $matches ) ) {
				continue;
			}

			$name  = $this->normalize_field_name( $matches[1] );
			$value = trim( sanitize_textarea_field( (string) $matches[2] ) );

			if ( '' === $name || '' === $value ) {
				continue;
			}

			if ( ! preg_match( '/[\p{L}]/u', $name ) ) {
				continue;
			}

			return array(
				'name'  => $name,
				'value' => $value,
			);
		}

		return null;
	}

	/**
	 * Нормализовать имя поля формы.
	 *
	 * @param string $name Исходное имя поля.
	 * @return string
	 */
	private function normalize_field_name( $name ) {
		$name = trim( sanitize_text_field( (string) $name ), " \t\n\r\0\x0B*-:=" );
		if ( '' === $name ) {
			return '';
		}

		if ( function_exists( 'mb_strtolower' ) ) {
			return mb_strtolower( $name, 'UTF-8' );
		}

		return strtolower( $name );
	}

	/**
	 * Эвристика: тело письма похоже на реальную заявку.
	 *
	 * @param string $text Тело письма в plain text.
	 * @return bool
	 */
	private function looks_like_lead_message( $text ) {
		$text = trim( (string) $text );
		if ( '' === $text ) {
			return false;
		}

		if ( preg_match( '/[A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,}/i', $text ) ) {
			return true;
		}

		if ( preg_match( '/\+?\d[\d\-\s\(\)]{5,}\d/u', $text ) ) {
			return true;
		}

		$haystack = function_exists( 'mb_strtolower' ) ? mb_strtolower( $text, 'UTF-8' ) : strtolower( $text );
		$patterns = array(
			'name:',
			'phone:',
			'tel:',
			'email:',
			'message:',
			'contact',
			'имя:',
			'телефон:',
			'почта:',
			'e-mail:',
			'сообщение:',
			'заявка',
		);

		foreach ( $patterns as $pattern ) {
			if ( false !== strpos( $haystack, $pattern ) ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Логировать debug-сообщения только в debug_mode.
	 *
	 * @param string $message Сообщение.
	 * @return void
	 */
	private function debug_log( $message ) {
		$options = \MBMaxCf7Relay\Includes\Plugin::get_options();
		if ( empty( $options['debug_mode'] ) ) {
			return;
		}

		/**
		 * Allow integrators to handle relay debug messages without hardcoded logging.
		 *
		 * @param string $message Debug message.
		 */
		do_action( 'mb_max_cf7_relay_debug_log', '[mb-max-cf7-relay] ' . sanitize_textarea_field( (string) $message ) );
	}
}
