=== Global AI Chat ===
Contributors: thiagoqvaz, globalai
Tags: chatbot, ai, openai, assistant, chat
Requires at least: 6.0
Tested up to: 7.0
Requires PHP: 7.4
Stable tag: 3.6.12
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

AI-powered chat widget for WordPress using OpenAI. Bring your own OpenAI key, fully functional out of the box, no license required.

== Description ==

Global AI Chat adds an AI-powered chat widget to your WordPress site. Visitors interact with a chatbot backed by OpenAI's models; you use your own OpenAI account (and are billed directly by OpenAI for the usage).

**All features are free and fully functional.** The plugin does not lock, limit, or time-restrict any built-in functionality.

Features included:

* Floating chat widget with customizable colours, icons, position and animation
* Shortcode `[growthai_chat]` to embed the chat inline on any page
* Gutenberg block, Elementor widget, Divi module, Beaver Builder module, WPBakery element
* One agent profile (SDR, Support or FAQ) with custom prompt
* Lead collection tool calls (name, email, phone, company and custom fields)
* Visitor request for human contact triggers an admin notification (no live takeover in Free)
* GDPR-ready: optional cookie consent banner and opt-in uninstall data deletion
* Multi-language chat — widget auto-detects the visitor's browser locale

**Want multi-agent setup, live chat takeover from wp-admin, page/post auto-sync, Google Calendar booking, webhooks, AI prompt generator, mobile app, managed tokens, auto-updates or analytics?** The companion Pro addon is distributed separately at https://globalai.software/. It layers extra UI and SaaS-backed services on top of the free plugin without replacing it — if you ever deactivate Pro, the free plugin keeps working.

== Installation ==

1. Upload the `global-ai-chat` folder to `/wp-content/plugins/`, or install via **Plugins → Add New** on WordPress.
2. Activate the plugin through the **Plugins** menu.
3. Go to **Global AI Chat → Geral** and paste your OpenAI API key (get one at https://platform.openai.com/api-keys).
4. Configure your agent under **Global AI Chat → Agentes**.
5. The chat widget will appear on your site.

== Frequently Asked Questions ==

= Do I need an OpenAI API key? =

Yes. You provide your own OpenAI key in **Settings → Geral**. OpenAI bills you directly for the usage. The plugin stores the key encrypted in `wp_options` (AES-256-CBC); the plaintext is read on demand for the chat request only.

= Does the plugin work without a Pro license? =

Yes, fully. There is no license gate on any feature shipped with this plugin. The Pro addon is a separate plugin distributed outside wp.org; it adds optional SaaS-backed features (managed token billing, mobile app, auto-updates, analytics) but installing or removing it never affects the free plugin's behaviour.

= Where are the conversations stored? =

In your WordPress database, in the custom tables `wp_growthai_conversations` and `wp_growthai_agents`. Nothing about conversations leaves your site unless you configure a webhook or enable the optional Pro addon.

= What happens when I uninstall the plugin? =

By default WordPress removes only the plugin files and your data stays. If you enable **Settings → Geral → "Eliminar todos os dados ao desinstalar"**, the plugin's uninstall handler additionally drops its tables and clears every `growthai_*` option, transient, post meta and cron hook.

= Does the plugin track visitors? =

No. Visitor chat messages are sent to OpenAI for the agent to reply, and are stored in your DB. Nothing is sent to any analytics provider by the free plugin. See **External services** below for the full list of endpoints the plugin may contact.

= Does this free plugin contact saas.globalai.software? =

No. The free plugin only contacts `api.openai.com`, using your own OpenAI API key. The Global AI SaaS (`saas.globalai.software`) is only contacted when you separately install the optional Pro addon — it is not bundled with this plugin and is never reached from the code shipped here.

== External services ==

This plugin relies on **one** third-party service: the OpenAI API. No other external endpoint is contacted by the free plugin.

= OpenAI API (required) =

* **What it is:** OpenAI provides the language model that generates chat replies and, when you upload knowledge-base documents, runs the file search against them.
* **What is sent:** Every chat message the visitor submits, plus the system prompt your agent is configured with, is sent to `https://api.openai.com/v1/responses` using your own API key. When you upload training documents, the file bytes are sent to `https://api.openai.com/v1/files` and registered with `https://api.openai.com/v1/vector_stores` so the agent can search them.
* **When:** On every user message (chat completion) and only when an admin manually uploads/deletes a knowledge-base document (vector store).
* **Terms of service:** https://openai.com/policies/terms-of-use
* **Privacy policy:** https://openai.com/policies/privacy-policy

= Not contacted by this free plugin =

The companion Pro addon (separate download, not on wp.org) introduces additional endpoints under `https://saas.globalai.software/` for license verification, managed token billing, mobile-app push notifications, plugin auto-updates, Google Calendar OAuth, outbound webhooks, page/post auto-sync, and the AI prompt generator. None of those endpoints are reached from this free plugin's code — they are documented here only so admins know what changes if they later install the Pro addon.

== Security ==

= Visitor session token (`session_id`) =

Every chat conversation is bound to a `session_id` token generated **client-side, in the visitor's browser**, using `window.crypto.getRandomValues` (a 128-bit cryptographically random value rendered as 32 hex characters with the prefix `gai_`). The token is stored in `localStorage` after the visitor accepts the cookie consent banner; without consent, an in-memory ephemeral token is used and discarded when the tab closes.

The `session_id` is the access key for the chat REST endpoints (`/wp-json/growthai/v1/chat`, `/wp-json/growthai/v1/live-chat/poll`). These endpoints are intentionally public (`permission_callback => __return_true`) so that anonymous site visitors can chat without needing a WordPress account — knowing the token is what authorises the request, the same security model used by mainstream chat / support widgets (Crisp, Tawk, Intercom).

Implications:

* The token is **not** derived from the IP, User-Agent, cookies the server sets, or any sequential / predictable scheme. A third party cannot guess another visitor's token.
* The plugin never logs full `session_id` values in plaintext outside the database row that owns the conversation.
* If the visitor clears their browser storage, the next page load gets a fresh token and a fresh conversation.
* Old browsers without the Web Crypto API fall back to `Math.random()` — a worse entropy source. We surface this in the JS for transparency; if your audience relies on legacy browsers, factor that into your threat model.

== Changelog ==

= 3.6.12 =
* Lead capture: the name-extraction fallback used to require a
  capitalised first letter ("Thiago Vaz" yes, "thiago vaz" no), so
  any visitor who self-introduced in lowercase ended up with their
  name lost. The token regex now accepts mixed case and the saved
  value is normalised to Title Case before persisting.
* Lead capture: extended the column allow-list (`name`, `email`,
  `phone`, `company`) to also accept the Portuguese equivalents
  (`nome`, `telefone`, `telemovel`, `tel`, `empresa`). Without this,
  an agent created with a phone field labeled "telefone" (which
  sanitize_dynamic_list slugifies into key="telefone") wrote the
  visitor's phone number into the `lead_data` JSON blob instead of
  the dedicated column, so the admin UI displayed "Lead: email"
  with no phone visible.

= 3.6.11 =
* Admin conversations viewer no longer yanks the scrollbar around on
  every 2-second poll. The messages panel now preserves the admin's
  scroll position when they have scrolled away from the most recent
  message, and only auto-pins to the bottom when they were already
  at the bottom (within 60px). The conversation list on the left
  also keeps its scroll position across the 10-second list refresh
  instead of resetting to the top.

= 3.6.10 =
* Live-chat handoff: the conversations table gains a new column
  `handoff_owner_device_id` (VARCHAR(64), nullable). When the optional
  Pro addon's mobile app takes over a conversation, it stamps the
  acting device's UUID here so other mobile devices know to lock the
  conversation UI. Adding the column lifts the DB schema version
  to 3.1 — dbDelta runs on the next admin load.
* Live-chat handoff: when a visitor sends a message while
  `handoff_active=1`, the API handler now fires a new
  `handoff_visitor_message` event on `global_ai_chat_notify`. The Pro
  addon's push relay routes this event to the single owning device
  (no fan-out), so the human attendant gets a direct push without
  spamming every other paired phone.

= 3.6.9 =
* Lead capture safety-net now also notifies. When the LLM forgets to
  call `save_lead_info` and the visitor's message has an email/phone,
  the safety net in `class-api-handler.php` was persisting the lead
  silently — it now also fires the `global_ai_chat_notify` action so
  push, email and webhook integrations on the Pro side hear about
  these captures (previously only AI-tool-call captures triggered
  notifications).
* Agents admin: the Leads tab now delegates extra-field collection to
  add-ons via the `growthai:collect-agent-fields` event. The previous
  Save handler only persisted `lead_enabled` + `lead_fields`, silently
  dropping every extra Pro field rendered in that tab (push triggers,
  email summary toggle/recipient/triggers).

= 3.6.8 =
* Lead notifications: the `lead_info_collected` action now also fires
  the first time a conversation captures any lead field (not only when
  every required field is filled). This lets the optional Pro mobile
  app / webhooks notify the admin as soon as a visitor becomes
  identifiable, even when the agent's `lead_fields` list demands more
  keys than the visitor has provided so far. Strict completion still
  fires the action as before.

= 3.6.7 =
* Internationalization: the admin and widget UI is now translatable, with bundled translations for English (en_US), Spanish (es_ES) and European Portuguese (pt_PT). Added `load_plugin_textdomain()` so the shipped `/languages` files load, and a `global-ai-chat.pot` template for further translations.

= 3.6.6 =
* Plugin Check pass: `Tested up to` bumped to 7.0, and the legacy-table migration in `includes/class-agent.php` now interpolates `{$wpdb->prefix}growthai_agents` directly into the query string (the trusted `$wpdb->prefix` property concatenated with a hardcoded suffix) instead of going through an intermediate variable that the Plugin Check static analyser flagged.

= 3.6.5 =
* Security/escaping pass. The `[growthai_chat]` shortcode now builds its wrapper attributes through a strict allow-list (third-party filters must return an associative array of `data-*` names; values are escaped with `esc_attr()`) and its return value is wrapped with `wp_kses_post()` before output. Every builder render callback (Gutenberg block, WPBakery element, Elementor widget, Divi/Beaver modules) runs its `do_shortcode()` return value through `wp_kses_post()`. WPBakery/Divi `do_action('global_ai_chat_shortcode_disabled')` capture buffers are also passed through `wp_kses_post()` before return.

= 3.6.4 =
* Free is now a single-agent plugin — the `growthai_agents` table, multi-agent CRUD APIs (`create`, `delete`, `duplicate`, `count`, `max_allowed`, `can_create`), the `agent_id=new` admin flow and the agent-id REST routing have all been removed. The agent configuration lives in `wp_options['growthai_agent']`.
* Page-builder integrations (Gutenberg, Elementor, Divi, Beaver Builder, WPBakery) and the `[growthai_chat]` shortcode no longer expose an "agent" parameter — there is only one agent to render.
* New resolve filters (`global_ai_chat_resolve_agent_by_id`, `_by_slug`, `_all_agents`, `pre_update_agent`, `resolve_request_agent`) let an external add-on (sold separately, not hosted here) layer a multi-agent system on top without Free needing any knowledge of it.
* Upgrade path: on first load, the first row of any legacy `growthai_agents` table is copied into the new wp_option so previously-configured installs keep their settings; the table itself is left untouched.

= 3.6.3 =
* Removed every code path in the free plugin that branched on whether the optional add-on was installed: deleted `GrowthAI_Extensions::is_pro_active()`, `plan()`, `plan_name()`; dropped the related filters; collapsed `if (is_pro_active()) { ... }` blocks in admin/agents/api code so a single, unconditional path renders.
* Renamed the `global_ai_chat_render_license_panel` hook to the neutral `global_ai_chat_render_above_api_key`; the promotional banner is now controlled by the standalone `global_ai_chat_show_pro_banner` filter that defaults to true.
* Model dropdown decoration moved to `global_ai_chat_model_dropdown_label` so extensions can append price multipliers without touching plugin code.
* Submenu highlight is now filterable through `global_ai_chat_agent_submenu_highlight` instead of branching on add-on presence.

= 3.6.2 =
* Trialware cleanup: removed all Pro-only marketplace JS that previously shipped in the free plugin (plan-comparison table, "Adquirir" buttons, license activation, content sync, prompt generator wizard, platform-key toggle, webhook test, Google Calendar disconnect).
* Stripped Pro-only branches from `admin/js/admin-script.js` (from 1130 to 330 lines) and `admin/js/agents.js`; Pro now injects its own JS for the features it ships.
* Removed dead Pro UI strings (`Atendimento ativo` badge, license-tab callouts, platform-quota notices) from `class-admin-settings.php` and `admin/js/conversations.js`.
* Document upload now uses the built-in Free vector store class (`GrowthAI_Vector_Store_Free`) which calls `api.openai.com` directly with the customer's key — no Pro addon required.

= 3.6.1 =
* Security: knowledge-base uploads now validated server-side via `wp_check_filetype_and_ext` and `is_uploaded_file`; preset icon paths sanitised against traversal and run through `wp_kses` before output.
* wp.org compliance: removed all remaining Pro placeholder strings, sales CTAs, and license-tab links from builder integrations (Gutenberg, Elementor, Divi, Beaver Builder, WPBakery).
* i18n: every admin and visitor-facing string now uses the `global-ai-chat` text domain.
* Admin: outdated-content notice gated behind `content_sync` Pro feature so Free skips the query entirely; tab redirects whitelisted; brand strings renamed to "Global AI Chat".
* Cleanup: removed orphan `class-smtp.php`, `analytics.js`, `meta-box.js`; widget footer simplified to passive `Powered by Global AI Chat` attribution.

= 3.6.0 =
* External services: free plugin now only contacts `api.openai.com`. All optional SaaS endpoints moved to the Pro addon.
* Knowledge base: built-in vector store handler in Free — uploads documents directly to OpenAI with your own key, no proxy.
* Security: preset chat icons are now path-sanitised and run through `wp_kses` before rendering; visitor session tokens use `window.crypto.getRandomValues` (Math.random fallback only on legacy browsers).
* Admin: removed all "(Pro)" placeholder options, sales upsell sidebars, account-registration card, prompt marketplace and ads endpoint. One info-only Pro banner remains on the Geral tab.
* i18n: all admin and visitor-facing strings wrapped in translation functions (`global-ai-chat` text domain).
* `Domain Path: /languages` header added.

= 3.5.0 =
* GDPR cookies tab: full catalog of cookies/localStorage entries listed in admin and shown to visitors before any data is written.
* Anti-hallucination grounding rule baked into every system prompt.
* Server-side name regex fallback when the AI omits the lead name in a tool call.

= 3.4.0 =
* Renamed plugin to "Global AI Chat" (slug: `global-ai-chat`).
* Free plugin works entirely without a license — chat calls OpenAI directly with your key.
* Single-agent admin in Free. Multi-agent management, live chat handoff, Google Calendar booking, outbound webhooks, page/post auto-sync, AI prompt generator, mobile app, managed tokens, auto-updates and analytics all ship in the separate Pro addon at https://globalai.software/.
* Free's knowledge base now ships only document upload (PDF/DOCX/TXT). Page/post auto-sync moved to Pro.
* New extension-point API (`GrowthAI_Extensions`) lets Pro hook cleanly into Free.
* New Geral tab with OpenAI API key management + opt-in uninstall data deletion toggle.
* sanitize_api_key preserves raw bytes instead of applying sanitize_text_field (would strip valid key characters).

= 3.3.x =
* Typing indicator across plugin web, widget, and mobile app; scroll-to-bottom on open; non-destructive "switch agent" button in multi-agent widget; license rotation + refresh token rotation on the mobile app; nonce + rate-limit on public-facing ajax endpoints.

= 3.0.0 =
* Multi-agent: each agent has its own prompt, docs, lead fields and triggers.

= 2.0.0 =
* Multi-agent foundation.

= 1.0.0 =
* Initial release.

== Upgrade Notice ==

= 3.6.3 =
Removes the `is_pro_active()` helper and every code branch that depended on it. The free plugin now renders one unconditional code path; no behaviour is changed for installs that use only the free plugin.

= 3.6.2 =
Removes the Pro-only marketplace and plan-management JS that was still shipping in the free plugin. No functional change for free users; document upload now works end-to-end without the Pro addon.

= 3.6.1 =
Security hardening on document uploads and SVG icons, complete i18n coverage, and removal of every remaining Pro placeholder from the free codebase.

= 3.6.0 =
Free plugin cleanup for wp.org review: no more Pro-feature placeholders, no sales endpoints, only OpenAI is contacted. Knowledge-base upload now works in Free without the Pro addon.

= 3.4.0 =
Plugin renamed to "Global AI Chat". Free is now fully functional without a license — works directly with your own OpenAI key. SaaS-backed features are now in a separate Pro addon available at https://globalai.software/.
