=== 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.7
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)

Плагин требует, чтобы был установлен и активен плагин [Contact Form 7](https://wordpress.org/plugins/contact-form-7/).

---

*Disclaimer (English):* NotifyKit is an unofficial, independent plugin. 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`).

== Installation ==

1. Загрузите папку плагина в `/wp-content/plugins/notifykit-for-max-cf7/` или установите через раздел «Плагины» в админке WordPress.
2. Активируйте плагин.
3. Убедитесь, что Contact Form 7 установлен и активен (плагин его требует).
4. В меню админки откройте **MAX Messenger** → вкладка **Инструкция** — там пошаговое руководство: регистрация на business.max.ru, создание бота, групповой чат, добавление бота в чат и получение chat_id.
5. На вкладке **Настройки** вставьте токен бота и нажмите **Сохранить токен**.
6. Нажмите **Получить список чатов** — первый чат, в котором состоит бот, автоматически подставится как чат по умолчанию.
7. Нажмите **Отправить тестовое сообщение**, чтобы убедиться, что всё работает.
8. Откройте любую форму Contact Form 7 — в редакторе формы появится новая вкладка **MAX-мессенджер**, где можно задать отдельный Chat ID или свой шаблон сообщения для этой формы.

== Frequently Asked Questions ==

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

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

= Как найти chat_id? =

Добавьте бота в групповой чат, откройте настройки плагина и нажмите **Получить список чатов** — плагин получит все чаты, в которых состоит бот, и автоматически подставит первый из них как чат по умолчанию. Заранее писать в чат не нужно — MAX Bot API возвращает все чаты с участием бота.

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

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

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

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

= Безопасно ли хранить токен бота в базе? =

Токен шифруется алгоритмом AES-256-GCM с ключом, производным от констант `AUTH_KEY` и `SECURE_AUTH_KEY` из вашего `wp-config.php`. Плагину нужно расширение OpenSSL для PHP — без него плагин откажется сохранять токен, а не запишет его в открытом виде. Для дополнительной безопасности можно задать константу `CF7_MAX_TOKEN` в `wp-config.php` — плагин возьмёт её и не будет писать токен в базу.

= Что будет, если MAX API недоступен? =

Ошибка записывается в журнал отправок (меню админки: **MAX Messenger → Журнал**). Email-уведомления Contact Form 7 продолжают работать как обычно — они никак не зависят от MAX. Таймаут HTTP-запроса короткий (по умолчанию 8 секунд, настраивается фильтром `cf7_max_request_timeout`), поэтому медленный API не блокирует отправку формы.

= Работает ли плагин в режиме мультисайта? =

Да, активируйте по отдельности на каждом сайте. Сетевая активация тоже работает, но у каждого сайта будут свои токен и настройки.

= Поддерживает ли плагин WPForms, Gravity Forms, WooCommerce? =

В текущей версии — нет. Плагин интегрируется только с 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.7 =
* Refined the changelog wording.

= 1.0.6 =
* Cleaned up the plugin listing — Description, Installation and FAQ are now in Russian (with a short English non-affiliation disclaimer); duplicate English copies removed.

= 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 =
* Updated plugin name and metadata.

= 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.7 =
Cosmetic changelog wording fix.

= 1.0.6 =
Plugin listing reorganised: Description, Installation and FAQ are now Russian-first.

= 1.0.5 =
Adds screenshots to the plugin listing.

= 1.0.4 =
Full Russian translation bundled.

= 1.0.2 =
Plugin name and metadata updated.

= 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.
