=== BaseWeb AI Chat & Forms to MAX ===
Contributors: olegroslyakov
Donate link: https://base-web.ru/
Tags: ai, chatbot, yandex, max, fluent-forms
Requires at least: 6.2
Tested up to: 7.0
Requires PHP: 7.4
Requires Plugins: fluentform
Stable tag: 3.0.2
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

AI chatbot powered by Yandex AI Studio. Captures leads from chat and Fluent Forms, sending them to MAX. Fully 152-FZ/GDPR compliant.

== Description ==

**BaseWeb AI Chat & Forms to MAX** is a powerful, all-in-one WordPress plugin that combines an intelligent AI consultant with seamless lead generation. It bridges the gap between your website visitors and your MAX messenger, ensuring you never miss a potential client.

This plugin acts as a "combo" solution:
1. **AI Chat Consultant**: A smart, context-aware chat widget powered by Yandex AI Studio (YandexGPT).
2. **Fluent Forms Integration**: Automatically intercepts form submissions and forwards them to MAX.
3. **Built-in Lead Capture**: An intelligent in-chat form that appears when a user is ready to leave their contact details.

### 🌟 Key Features

* **Yandex AI Studio Integration**: Uses the modern Responses API with `store=true` and `previous_response_id` for seamless, context-aware conversations.
* **Fluent Forms Webhook**: Native hook (`fluentform/submission_inserted`) to instantly forward any form submission to your MAX bot.
* **Smart Lead Generation**: The AI can dynamically trigger a built-in contact form directly within the chat interface.
* **152-FZ / GDPR Compliant**: Includes a mandatory consent checkbox for personal data processing, automatic PII masking (email, phone, IP) in logs, and automated log cleanup after 30 days.
* **Enterprise-Grade Security**:
  * Protocol-Lock: API keys are stored securely in `wp_options`, never hardcoded.
  * `sslverify => true` enforced for all external API requests.
  * Strict input sanitization (`sanitize_text_field`, `esc_url_raw`) and nonce verification.
  * Rate limiting (20 chat requests / 5 lead submissions per 5 minutes per IP).
* **Comprehensive Dashboard**: A 4-tab admin interface for Yandex settings, MAX configuration, real-time analytics (categories, intents), and CSV/JSON log exports.
* **Universal & Customizable**: Dynamic placeholders (`{{company_name}}`, `{{manager_name}}`) allow you to adapt the AI's persona to any brand without touching the code.
* **Performance Optimized**: Asynchronous logging, transient caching for prompts (1 hour), and strict `max_output_tokens` limits to control API costs.

### 🔒 Security & Privacy First
We take data protection seriously. The plugin automatically hashes IP addresses (SHA-256), masks emails and phone numbers in logs, and includes a built-in WordPress Cron job to delete old logs after 30 days, ensuring compliance with data protection regulations like Russia's 152-FZ and the EU's GDPR.

### 🛠️ Shortcodes
* `[bacfm_ai_chat]` – Embeds the chat widget directly into the page content.
* `[bacfm_ai_button text="Ask AI Assistant"]` – Displays a stylish button that opens the chat widget on click.

== Installation ==

1. Upload the `baseweb-ai-chat-forms-to-max` folder to the `/wp-content/plugins/` directory.
2. Activate the plugin through the 'Plugins' menu in WordPress.
3. Ensure that the **Fluent Forms** plugin is installed and activated (required for form interception).
4. Navigate to **Settings → BaseWeb AI Chat** in your WordPress admin dashboard.
5. **Yandex AI Studio Tab**: Enter your API Key (format: `AQVN...`) and Folder ID (format: `b1g...` from the classic Yandex Cloud console).
6. **MAX Bot Tab**: Enter your MAX Bot Token and User ID to enable lead forwarding.
7. Configure your company name and manager name to personalize the AI's responses.
8. Add the shortcode `[bacfm_ai_button]` to your desired pages or posts.

== Frequently Asked Questions ==

= Where do I get the Yandex AI Studio API Key? =
Go to [Yandex AI Studio](https://aistudio.yandex.ru/), create a service account with the `ai.editor` role, and generate an API key in the settings.

= Where do I find the Folder ID? =
You must use the **classic Yandex Cloud console** ([console.yandex.cloud/folders/](https://console.yandex.cloud/folders/)). Copy the Folder ID that starts with `b1g...`. *Note: IDs starting with `bpf...` from the new Yandex Cloud Center are not compatible with the Responses API.*

= How do I configure the MAX Bot? =
1. Create or use an existing bot at [business.max.ru](https://business.max.ru/).
2. Copy the bot's authorization token.
3. Obtain your User ID (you can use a simple script or check your MAX bot logs).
4. Enter both values in the "MAX Bot" tab of the plugin settings.

= Is this plugin compliant with GDPR and 152-FZ? =
Yes. The plugin includes a mandatory consent checkbox in the lead form, automatically masks Personally Identifiable Information (PII) like emails, phones, and IPs in the logs, and features an automated 30-day log cleanup via WordPress Cron.

= Does the plugin work without Fluent Forms? =
Yes. The AI chat widget and its built-in lead capture form work perfectly on their own. The Fluent Forms integration is an additional module that activates only if the plugin is present.

= How do I control API costs? =
The plugin enforces a strict `max_output_tokens` limit (default 500) and includes rate limiting to prevent spam. We also recommend setting up a monthly budget and alerts in your Yandex Cloud billing dashboard.

== External Services ==

This plugin connects to external services to provide its core functionality:

1. Yandex AI Studio (Yandex Cloud)
- Purpose: To process chat messages and generate AI responses.
- Data sent: User chat messages, session ID, and page URL.
- Provider: Yandex LLC.
- Links: [Terms of Service](https://yandex.ru/legal/cloud_termsofuse/), [Privacy Policy](https://yandex.ru/legal/confidential/).

2. MAX Messenger API
- Purpose: To send lead notifications and form submissions to the site owner's MAX account.
- Data sent: Form data (name, email, phone, message) and source URL.
- Provider: MAX.
- Links: [Terms of Service](https://max.ru/legal/terms), [Privacy Policy](https://max.ru/legal/privacy).

== Screenshots ==

1. The AI chat widget on the frontend, featuring a clear AI disclaimer and a modern, responsive design.
2. The built-in lead capture form with the mandatory 152-FZ/GDPR personal data consent checkbox.
3. The "Yandex AI Studio" settings tab, showing API configuration and dynamic brand placeholders.
4. The "MAX Bot" settings tab, including the one-click test message feature and Fluent Forms selection.
5. The "Logs & Analytics" dashboard, displaying request categories, user intents, and paginated log history.
6. The "Export" tab, allowing CSV/JSON export and secure log cleanup.

== Changelog ==

= 3.0.2 =
* **Hotfix**: Used %i placeholder in $wpdb->prepare() for secure table name substitution (requires WordPress 6.2+).
* **Hotfix**: Improved session ID validation to support UUID format with hyphens.
* **Hotfix**: Added compatibility aliases in API response for frontend JavaScript.
* **Hotfix**: Updated system prompt with [SHOW_LEAD_FORM] marker instructions for automatic lead form display.
* **Hotfix**: Added support for Fluent Forms selection in admin settings.
* **Requirement**: Minimum WordPress version raised to 6.2 for %i placeholder support.

= 3.0.0 =
* **Release**: Public version prepared for WordPress.org repository.
* **Architecture**: Full migration to strict PHP 8 typing (`declare(strict_types=1)`).
* **Localization**: 100% i18n compliance. All UI strings wrapped in `__()` with text domain `baseweb-ai-chat-forms-to-max`.
* **Prefix Update**: All options, transients, and hooks migrated from `baseweb_uac_` to `bacfm_` to prevent conflicts.
* **Security**: Enhanced nonce verification, strict input sanitization, and enforced `sslverify => true` across all endpoints.
* **New Feature**: Added `uninstall.php` for clean database removal upon plugin deletion.
* **Compatibility**: Added explicit `Requires Plugins: fluentform` header.

= 2.1.0 =
* **Universality**: Removed hardcoded brand references. Added dynamic `{{company_name}}` and `{{manager_name}}` placeholders.
* **Prompt Caching**: Added 1-hour transient caching for system prompts to reduce database load.
* **Compliance**: Added mandatory consent checkbox for lead forms (152-FZ/GDPR) and automated 30-day log cleanup via WP-Cron.
* **MAX Integration**: Added 60-second transient duplicate locking to prevent double lead submissions.
* **UX**: Added native WordPress spinner for MAX test button and improved error handling in JS.

= 2.0.3 =
* **Bugfix**: Corrected parameter order in the `fluentform/submission_inserted` hook.
* **Bugfix**: Added strict length validation (max 4000 chars) for MAX API payloads.

= 2.0.0 =
* **Major Architecture Overhaul**: Combined AI Chat and Fluent Forms → MAX modules into a single unified plugin.
* **New Classes**: Introduced `class-max-handler.php` (with retry logic), `class-logger.php` (structured PII-masking logs), and `class-fluent-forms.php`.
* **Dashboard**: Upgraded to a 4-tab settings interface (Yandex, MAX, Logs, Export).
* **Security**: Enforced `sslverify => true`, removed all hardcoded tokens, and implemented strict session ID validation.

= 1.1.0 =
* Added `session_id` validation and guest generation.
* Enforced `sslverify => true` and `max_tokens => 500` for all API calls.
* Improved JavaScript error handling and fallback UI messages.

= 1.0.0 =
* Initial release of the BaseWeb AI Chat plugin.

== Upgrade Notice ==

= 3.0.2 =
Recommended update: Bug fixes for session handling, improved frontend compatibility, new lead form trigger system, and enhanced database query security using WordPress 6.2+ %i placeholder.

= 3.0.0 =
Major update: PHP 8 strict typing, full localization, and new bacfm_ prefix. Review settings after updating. Fluent Forms plugin required for form capture.

== Support ==

We are committed to providing high-quality support for BaseWeb AI Chat & Forms to MAX.

**Official WordPress.org Support Forum:**
For general questions, bug reports, and community help, please use the official support forum:
👉 https://wordpress.org/support/plugin/baseweb-ai-chat-forms-to-max/

**Direct Developer Support:**
For urgent issues, commercial inquiries, or custom integration requests, you can contact the developer directly:
📧 Email: admin@base-web.ru
🌐 Website: https://base-web.ru/

*Please note: We strive to respond to all direct inquiries within 24-48 hours on business days.*