=== NotifyKit for MAX Messenger and Contact Form 7 ===
Contributors: notifykit
Tags: max messenger, bot notifications, cf7, form notifications, chat
Requires at least: 6.2
Tested up to: 6.9
Requires PHP: 7.4
Stable tag: 1.0.5
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: notifykit-for-max-cf7

Forwards Contact Form 7 submissions to MAX Messenger via the official Bot API. Unofficial, independent integration (not by VK).

== Description ==

**NotifyKit — уведомления о новых заявках с сайта сразу в чат MAX.**

NotifyKit — независимый (неофициальный) плагин, не связанный с командой мессенджера MAX (правообладатель — VK) и не связанный с проектом Contact Form 7. Плагин пересылает заявки из форм Contact Form 7 в чат мессенджера MAX через официальный MAX Bot API (`https://botapi.max.ru`). Команда видит каждую заявку в реальном времени, не перегружая почтовый ящик.

Если вы раньше использовали Telegram-боты для уведомлений о заявках, этот плагин закроет ту же задачу, но для MAX — российского мессенджера, доступного без VPN и ограничений.

**Кому подойдёт:**

* Клиники, салоны, сервисы — заявки сразу видит весь ресепшн в общем чате
* Интернет-магазины, сайты услуг — менеджеры реагируют быстрее, не ждут письма
* Агентства и фрилансеры — клиентские заявки в отдельном чате команды
* Любые сайты на WordPress + Contact Form 7, работающие с русскоязычной аудиторией

**Основные возможности:**

* Пересылка заявок из Contact Form 7 в групповой чат MAX
* Мгновенные push-уведомления членам команды в чате
* Настройка отдельного чата для каждой формы
* Гибкий шаблон сообщения с подстановкой полей формы
* Автоматический поиск и подстановка Chat ID — не надо искать вручную
* Пошаговый мастер настройки прямо в админке WordPress
* Журнал отправок с кодами ошибок
* Токен бота шифруется в базе (AES-256-GCM)

---

NotifyKit is an unofficial plugin developed independently. It is **not affiliated with**, endorsed by, or sponsored by the MAX Messenger team (the trademark "MAX Messenger" belongs to its owner, VK), nor is it affiliated with the Contact Form 7 project. The plugin only acts as a client of the official MAX Bot API (`https://botapi.max.ru`) — the same way an end user does — and integrates with Contact Form 7 through its public hooks.

When a visitor submits any CF7 form, the plugin delivers the submission to a chosen chat in MAX (in addition to the usual email notification). Team members added to that chat receive submissions in real time.

The plugin is an alternative to Telegram-based notification plugins for sites where MAX is the preferred channel.

**Features:**

* Sends CF7 form submissions to a MAX group chat using the official Bot API
* Per-form Chat ID override, plus a global default chat
* Flexible message template with CF7 placeholders (`[your-name]`, `[your-email]`, `[all-fields]`, etc.)
* HTML and Markdown formatting support
* "MAX Messenger" tab added to the CF7 form editor
* One-click bot verification (calls `/me` to validate your token)
* "Fetch chats" button — no need to look up chat_id manually; the first discovered chat is pre-filled automatically
* Step-by-step settings page that visually guides you through setup (token → chat → test send)
* Submission log with error details
* Bot token encrypted at rest (AES-256-GCM, key derived from wp-config.php salts)
* Optional `CF7_MAX_TOKEN` constant for storing the token outside the database
* Built-in step-by-step setup guide in Russian

**Who is this for:**

Site owners in Russia, CIS, and any market where MAX Messenger is used as a primary communication channel. Small businesses, clinics, service providers who want form submissions pushed instantly to a team chat.

This plugin requires the [Contact Form 7](https://wordpress.org/plugins/contact-form-7/) plugin to be installed and active.

== Installation ==

1. Upload the plugin folder to `/wp-content/plugins/notifykit-for-max-cf7/` or install it through the WordPress Plugins screen.
2. Activate the plugin.
3. Make sure Contact Form 7 is installed and active (the plugin requires it).
4. Go to **MAX Messenger** in the admin menu and open the **Setup guide** tab — a step-by-step walkthrough is built into the plugin: registering at business.max.ru, creating a bot, building a group chat, adding your bot to it, and obtaining the chat_id.
5. On the Settings tab, paste the bot token and click **Save token**.
6. Click **Fetch chats** — the first chat your bot is a member of is automatically set as the default.
7. Click **Send test message** to verify everything works.
8. Open any Contact Form 7 form — a new **MAX Messenger** tab appears in the form editor where you can set a per-form Chat ID or message template.

== Frequently Asked Questions ==

= How do I get a MAX bot token? =

Register at [business.max.ru](https://business.max.ru/self), create a bot, pass moderation, and copy the token from the bot's "Integration" section. The plugin ships with a full step-by-step guide (admin menu: **MAX Messenger → Setup guide**).

= How do I find a chat_id? =

Add your bot to a group chat, then open the plugin settings and click **Fetch chats** — the plugin retrieves all chats your bot is a member of and automatically picks the first one as the default. You do not need to write in the chat beforehand — the MAX Bot API returns all chats the bot participates in.

= Can I route different forms to different chats? =

Yes. Each Contact Form 7 form gets a **MAX Messenger** tab in its editor where you can override the Chat ID and message template.

= Is the bot token safe in my database? =

The token is encrypted using AES-256-GCM with a key derived from `AUTH_KEY` and `SECURE_AUTH_KEY` from your `wp-config.php`. The plugin requires PHP's OpenSSL extension — if it is unavailable, the plugin refuses to store a token rather than storing it in plain form. For extra safety you can define a `CF7_MAX_TOKEN` constant in `wp-config.php` — the plugin will use it and skip the database entirely.

= What happens if MAX API is unreachable? =

The error is recorded in the submission log (admin menu: **MAX Messenger → Log**). The CF7 email delivery continues as usual and is not affected. The HTTP timeout is short (8 seconds by default, adjustable via the `cf7_max_request_timeout` filter) so a slow API does not block form submissions.

= Does the plugin work on multisite? =

Yes, activate it per site. Network activation works but each site has its own token and settings.

= Does it support WPForms, Gravity Forms, WooCommerce? =

Not in this version. This plugin integrates only with Contact Form 7.

= Как получить токен бота MAX? =

Зарегистрируйтесь на [business.max.ru](https://business.max.ru/self), создайте бота, пройдите модерацию и скопируйте токен из раздела «Интеграция» в карточке бота. В плагине есть встроенная пошаговая инструкция (меню админки: **MAX Messenger → Инструкция**).

= Это замена Telegram-бота? =

Да, если вашей аудитории удобнее MAX. Плагин делает то же, что популярные Telegram-плагины для CF7 (отправка заявок в чат), но через MAX Bot API. Можно использовать оба плагина одновременно.

= Как добавить несколько форм в разные чаты? =

У каждой формы Contact Form 7 появляется отдельная вкладка «MAX-мессенджер» в редакторе формы. Там можно указать свой Chat ID и свой шаблон сообщения — только для этой формы.

= Как выглядит сообщение в чате? =

Плагин берёт шаблон из настроек писем Contact Form 7 (вам не придётся настраивать заново) или использует свой шаблон. В сообщение попадают все заполненные пользователем поля формы, с подписями на русском.

= Можно ли отключить превью ссылок? =

Да, по умолчанию превью отключено — чтобы в чате не подтягивалась страница отправки с картинкой. Настройка доступна в режиме разработчика.

== External services ==

This plugin connects to **MAX Messenger Bot API** (`https://botapi.max.ru`), operated by the MAX team (VK group of companies).

**What data is sent and when:**

* When a visitor submits a Contact Form 7 form on your site, the plugin sends a single HTTPS request to `https://botapi.max.ru/messages` containing the message text (compiled from your configured template plus the submitter's form data, which may include name, email, phone, and any other fields you collect) together with the target `chat_id`. The visitor's IP address and User-Agent are included only if your template uses the `[_remote_ip]` or `[_user_agent]` placeholders.
* When an administrator clicks **Verify bot** in settings, a request is sent to `https://botapi.max.ru/me` (returns bot name/username only, no visitor data).
* When an administrator clicks **Fetch chats** in settings, a request is sent to `https://botapi.max.ru/chats` (returns the list of chats your bot is in, no visitor data).
* When an administrator clicks **Send test message** in settings, a static test message (site name + fixed text) is sent to the selected chat. No visitor data is involved.

The bot token you provide is sent in the `Authorization` header of every request. It is stored encrypted in your database (or as a `wp-config.php` constant if you choose).

**Service documentation, terms, and privacy policy:**

* API documentation: https://dev.max.ru/docs-api
* MAX Messenger terms of service: https://max.ru/legal/terms
* MAX Messenger privacy policy: https://max.ru/legal/privacy

By configuring this plugin and pointing it to your bot, you agree to MAX Messenger's terms of service and privacy policy.

== Privacy ==

This plugin does not store or transmit any data to the plugin author. All form data is sent directly from your WordPress site to the MAX Bot API endpoint under your own bot token.

The plugin stores:

* The encrypted bot token in the `cf7_max_settings` option.
* A submission log in the custom table `{prefix}cf7_max_log` (each entry: timestamp, level, event, form ID, chat ID, HTTP code, short message). Log entries do not contain the submitted form data itself, only delivery metadata. The log size is limited (default: 100 entries) and old entries are pruned automatically.

On uninstall (not just deactivate), the plugin removes its options, its log table, and the per-form post meta. No data is retained.

== Screenshots ==

1. Sample form submission delivered to a MAX group chat — formatted message with all CF7 fields (name, phone, e-mail, etc.).
2. Plugin settings page in WordPress admin — token, default chat picker, and submission toggle for the "MAX Messenger" integration.

== Changelog ==

= 1.0.5 =
* Added screenshots to the plugin listing.

= 1.0.4 =
* Full Russian translation bundled.

= 1.0.3 =
* Updated project website URL.

= 1.0.2 =
* Renamed to "NotifyKit for MAX Messenger and Contact Form 7" to clarify that this is an unofficial integration, not affiliated with the MAX Messenger team (VK) or the Contact Form 7 project.

= 1.0.1 =
* Link previews in MAX messages are disabled by default so the submission page URL is not previewed in the chat (can be re-enabled in advanced settings).
* Field labels in `[all-fields]` are now inherited from the CF7 mail template — messages to MAX show readable labels (Имя, Телефон, etc.) instead of raw field names.

= 1.0.0 =
* Initial release.
* Sends Contact Form 7 submissions to a MAX Messenger chat via the official Bot API.
* Per-form chat ID and message template, plus a global default chat.
* Step-by-step guided settings page.
* Submission log.
* Bot token encrypted at rest.

== Upgrade Notice ==

= 1.0.5 =
Adds screenshots to the plugin listing.

= 1.0.4 =
Full Russian translation bundled.

= 1.0.2 =
Plugin renamed to clarify that this is an unofficial integration.

= 1.0.1 =
Link previews are now disabled by default; field labels in messages now match the CF7 mail template.

= 1.0.0 =
Initial release.
