=== Assertiv AI Voice Agent ===
Contributors:      assertivlogix
Tags:              ai, voice agent, chatbot, voice chat, openai, lead generation, meeting booking, knowledge base, conversational ai, text to speech
Requires at least: 6.5
Tested up to:      6.8
Requires PHP:      8.1
Stable tag:        2.1.0
License:           GPL-2.0-or-later
License URI:       https://www.gnu.org/licenses/gpl-2.0.html

AI-powered voice assistant for WordPress. Let visitors have natural, real-time voice and text conversations grounded in your website's own content.

== Description ==

**Assertiv AI Voice Agent** embeds a smart, conversational AI assistant directly into your WordPress website. Visitors can speak or type to the agent, which answers questions using your site's content, captures leads, books meetings on your Google Calendar, and gives you deep analytics — all without leaving your site.

Built on OpenAI's language models and vector-based semantic search, the agent understands the intent behind every question, not just keywords. Every answer is grounded in your actual website content so the agent never fabricates information outside what you have published.

---

= 🎙️ Core Voice & Chat Features =

* **Real-time voice conversations** — Visitors click one button and start speaking; the agent responds in natural speech using OpenAI TTS or ElevenLabs voices.
* **Text chat mode** — A text fallback is always available alongside voice, configurable per agent.
* **Dual-mode widget** — Switch seamlessly between voice and text within the same session.
* **Customisable greeting** — Set a personalised opening message shown when the widget first appears.
* **Auto-open option** — Optionally open the widget automatically on page load to maximise engagement.
* **Mobile & desktop control** — Show or hide the widget independently on mobile and desktop devices.
* **Flexible widget position** — Place the floating button at bottom-right, bottom-left, top-right, top-left, centre-right, or centre-left.
* **Custom button label & primary colour** — Match the widget to your brand with a hex colour picker and custom label text.

---

= 🤖 Multi-Agent Management =

* **Multiple agents** — Create as many AI agents as you need, each with its own personality, system prompt, language, and voice settings.
* **Agent status control** — Activate or deactivate individual agents without deleting them.
* **Per-agent configuration** — Each agent stores its own name, avatar URL, welcome message, language, and custom system prompt.
* **Default agent selector** — Choose which agent loads in the widget globally, or override per page using the shortcode or PHP function.
* **Agent CRUD REST API** — Full create / read / update / delete API endpoints for programmatic agent management.

---

= 🧠 AI Knowledge Base (RAG) =

* **Automatic content indexing** — Pages, posts, WooCommerce products, and categories are automatically chunked and vectorised using OpenAI Embeddings so the agent always has access to your latest content.
* **Semantic vector search** — Questions are matched to relevant content chunks using cosine similarity, ensuring contextually accurate answers even when exact keywords differ.
* **Configurable chunking** — Control chunk size (200–2000 characters) and overlap (0–500 characters) to balance accuracy against API cost.
* **Selective indexing** — Enable or disable indexing for pages, posts, products, categories, and FAQs independently.
* **URL & post-ID exclusions** — Exclude specific URLs or post IDs from the knowledge base with a simple admin list.
* **Web crawler** — Optionally crawl external or internal URLs to extend the knowledge base beyond standard WordPress content types (configurable crawl limit up to 2,000 pages).
* **Manual index trigger** — Re-index content on demand from the Knowledge Base admin page without waiting for the scheduled cron.
* **Background queue** — A WP-Cron-powered queue processes indexing jobs asynchronously, avoiding request timeouts on large sites.
* **Knowledge Gaps detection** — The plugin logs questions the agent could not answer confidently; admins can review these gaps and resolve them by adding content.

---

= 🎯 Lead Capture & CRM Pipeline =

* **Automatic lead creation** — During a conversation the agent can capture visitor name, email, phone, company, service interest, budget, timeline, and intent.
* **AI-powered lead scoring (0–100)** — A rule-based scorer evaluates completeness (email, phone, name), business context (company, service, intent), qualification signals (budget, timeline, urgency), and source page to assign a numeric score.
* **Lead tier classification** — Leads are automatically classified as **Cold** (0–30), **Warm** (31–60), **Hot** (61–79), or **Qualified** (80–100).
* **Visual pipeline board** — Manage leads through customisable pipeline stages directly in the admin dashboard.
* **Lead detail view** — Click any lead to see the full conversation transcript, score breakdown, and all captured fields.
* **Manual lead re-scoring** — Trigger a fresh score calculation at any time after editing lead data.
* **CSV export** — Export the complete leads list as a CSV file for use in external CRMs or spreadsheets.
* **Lead update & delete** — Edit lead fields or remove leads directly from the admin panel via REST API.
* **Email notifications** — Receive an instant email alert when a new lead is captured (configurable via the Notifications module).

---

= 📅 Meeting Booking & Google Calendar Integration =

* **Natural-language meeting booking** — Visitors ask "Can I book a call?" and the agent guides them through selecting a date and time without leaving the chat.
* **Real-time availability check** — The agent queries your Google Calendar to show only genuinely free slots within your configured business hours.
* **Google Calendar OAuth 2.0** — Connect your Google account securely via OAuth from the Settings page; no API keys stored in plain text.
* **Configurable business hours** — Set start and end times and timezone for availability queries.
* **Default meeting duration** — Define a standard meeting length (e.g., 30 minutes) applied when booking.
* **Meeting reschedule & cancel** — Visitors and admins can reschedule or cancel booked meetings through the agent or the admin panel.
* **Meetings admin page** — View all upcoming and past meetings in a single dashboard screen.

---

= 📊 Analytics Dashboard =

* **Conversation volume** — Total conversations, messages, and active sessions at a glance.
* **Lead conversion metrics** — Track how many conversations result in a captured lead.
* **Agent performance** — Compare conversation counts, satisfaction signals, and resolution rates across agents.
* **Knowledge Gap insights** — See which questions are unanswered most frequently to prioritise content creation.
* **Date-range filtering** — Filter analytics by custom date ranges for weekly, monthly, or quarterly reviews.

---

= 🔑 License & Activation System =

* **Remote License Verification** — Secure license validation via the Assertivlogix License API (`plugins.assertivlogix.com`).
* **AJAX Activation & Deactivation** — Activate or deactivate your license key seamlessly with instant UI feedback.
* **PRO Feature Locking** — Locks advanced features (Agents, Knowledge Base RAG indexing, Lead Pipeline, Google Calendar Meeting Booking, Analytics, Knowledge Gaps) until valid license activation.
* **Periodic License Checking** — Automatically verifies active status and handles domain / expiration changes safely.

---

= ⚙️ Comprehensive Settings =

The Settings panel is organised into clearly labelled tabs:

**General**
- Plugin display name (appears in the admin menu)
- Default agent selection
- Debug mode toggle and log-level selector (error / warning / info / debug)

**Providers**
- OpenAI API key (stored securely, never exposed to the frontend)
- OpenAI language model selection (e.g., gpt-4o, gpt-4-turbo)
- OpenAI embedding model selection (e.g., text-embedding-3-small)
- ElevenLabs API key for premium voice synthesis
- API request timeout control (10–120 seconds)

**Voice**
- Default TTS provider: OpenAI or ElevenLabs
- OpenAI TTS model (tts-1 / tts-1-hd)
- OpenAI TTS voice (alloy, echo, fable, onyx, nova, shimmer)
- Speaking speed (0.25×–4×)
- In-admin voice preview — test any voice/provider combination before going live

**Knowledge Base**
- Toggle indexing per content type (pages, posts, products, categories, FAQs)
- Web crawler enable/disable and page limit
- Chunk size and overlap configuration
- URL exclusion list
- Post-ID exclusion list

**Widget**
- Widget position (6 options)
- Button label text
- Primary accent colour
- Auto-open toggle
- Show on mobile / show on desktop
- Greeting / welcome text
- Text chat visibility toggle

**Privacy**
- Store conversations toggle
- Store message transcripts toggle
- Store voice recordings toggle (off by default)
- Conversation retention period (1–3650 days)
- Visitor anonymisation toggle
- Lead collection enable/disable
- GDPR consent message text

**Usage Limits**
- Max requests per session (1–200)
- Max session duration in minutes (1–120)
- Max tokens per AI response (50–4096)
- Daily API call limit (0 = unlimited)
- Monthly API call limit (0 = unlimited)
- Rate limit per minute (1–100)

**Calendar**
- Google OAuth Client ID & Client Secret
- Google Calendar ID (default: primary)
- Google API key (for public availability checks)
- Timezone
- Default meeting duration (minutes)
- Connect / Disconnect Google Account button

**Advanced**
- Semantic similarity threshold (0.0–1.0; controls how closely a chunk must match before being used)
- Top-K chunks returned per query (1–20)
- Delete all data on plugin uninstall toggle

---

= 🛠️ Agentic Tool System =

The agent can autonomously invoke built-in tools during a conversation:

| Tool | Description |
|------|-------------|
| **SearchWebsiteTool** | Performs semantic search against the knowledge base to answer questions from site content |
| **CreateLeadTool** | Captures visitor contact details and creates a new lead record |
| **QualifyLeadTool** | Collects qualification data (budget, timeline, service interest) and rescores the lead |
| **UpdateLeadTool** | Updates existing lead fields during an ongoing conversation |
| **GetCalendarAvailabilityTool** | Queries Google Calendar for free slots within business hours |
| **BookMeetingTool** | Books a meeting on Google Calendar and stores it in the plugin database |
| **RescheduleMeetingTool** | Moves an existing meeting to a new date/time |
| **CancelMeetingTool** | Cancels a booked meeting in both the database and Google Calendar |

---

= 🔌 REST API =

All functionality is exposed via a versioned REST API at `/wp-json/assertiv-ai/v1/`:

**Public endpoints (no authentication required)**
- `GET  /agent/{id}/public-config` — Fetch public widget configuration for an agent
- `POST /conversation/start` — Start a new conversation session
- `POST /conversation/message` — Send a message and receive an AI reply
- `POST /conversation/end` — End the current session
- `POST /leads/submit` — Submit a lead from an external form
- `POST /voice/synthesize` — Synthesize text-to-speech audio

**Admin endpoints (WordPress `manage_options` required)**
- `GET/POST /agents` — List or create agents
- `GET/PUT/DELETE /agents/{id}` — Read, update, or delete an agent
- `POST /knowledge/save` — Save knowledge base settings
- `POST /knowledge/index-now` — Trigger immediate re-indexing
- `GET /analytics` — Retrieve analytics data
- `GET /conversations` — List all conversations
- `GET /conversations/{id}` — Get a full conversation transcript
- `DELETE /conversations/{id}` — Delete a conversation
- `POST /conversations/clear-all` — Clear all conversation records
- `GET /leads` — List all leads
- `GET /leads/{id}` — Get lead detail
- `PUT /leads/{id}` — Update a lead
- `DELETE /leads/{id}` — Delete a lead
- `PUT /leads/{id}/stage` — Move a lead to a new pipeline stage
- `POST /leads/{id}/rescore` — Re-score a lead
- `GET /leads/export` — Export leads as CSV
- `GET/POST /meetings` — List meetings or book a new one
- `PUT /meetings/{id}/cancel` — Cancel a meeting
- `GET /knowledge-gaps` — List detected knowledge gaps
- `POST /knowledge-gaps/resolve` — Mark a gap as resolved
- `PUT /settings/{tab}` — Save settings for a specific tab
- `POST /voice/preview` — Generate a voice preview sample

---

= 🔒 Security =

* WordPress nonce verification on all admin AJAX and REST requests
* Visitor nonce (`X-Assertiv-Nonce` header) required for conversation and voice endpoints
* API keys stored in separate WordPress options, never serialised with other settings or exposed in frontend HTML
* All input sanitised with WordPress core functions (`sanitize_text_field`, `sanitize_hex_color`, `esc_url_raw`, etc.)
* All output escaped with `esc_html` / `esc_attr` before rendering
* Capability check (`manage_options`) enforced on every admin page and admin REST route
* PSR-4 autoloader — no `require` on user-supplied paths
* `declare(strict_types=1)` across all PHP files

---

= 💻 Developer Integration =

**Shortcode**

    [assertiv_ai_voice_agent]

Optional attributes: `agent_id`, `position`, `primary_color`, `button_label`

**PHP function**

    <?php assertiv_ai_voice_agent(); ?>

    // With overrides:
    <?php assertiv_ai_voice_agent([
        'agent_id'      => 3,
        'position'      => 'bottom-left',
        'primary_color' => '#0ea5e9',
    ]); ?>

**WP-Cron hooks registered by the plugin**

- `assertiv_ai_process_indexing_queue` — Processes pending knowledge-base indexing tasks
- `assertiv_ai_cleanup_conversations` — Purges conversations older than the configured retention period
- `assertiv_ai_sync_changed_content` — Detects and re-indexes content that has changed since the last run

---

= 🗄️ Database Tables =

The plugin creates the following custom tables on activation:

| Table | Contents |
|-------|----------|
| `{prefix}_assertiv_ai_agents` | Agent configurations |
| `{prefix}_assertiv_ai_conversations` | Conversation sessions |
| `{prefix}_assertiv_ai_messages` | Individual messages per conversation |
| `{prefix}_assertiv_ai_chunks` | Vector-embedded content chunks |
| `{prefix}_assertiv_ai_sources` | Indexed content sources |
| `{prefix}_assertiv_ai_leads` | Captured lead records |

All tables are removed only when **Delete all data on uninstall** is enabled in Advanced Settings.

---

== Installation ==

1. Upload the `assertiv-ai-voice-agent` folder to `/wp-content/plugins/`.
2. Activate the plugin through the **Plugins** menu in WordPress.
3. Go to **AI Voice Agent → Settings → Providers** and enter your **OpenAI API key**.
4. *(Optional)* Enter your **ElevenLabs API key** for premium voice synthesis.
5. Go to **AI Voice Agent → Agents** and create your first agent.
6. Go to **AI Voice Agent → Knowledge Base** and click **Index Now** to build the knowledge base from your site content.
7. Add `[assertiv_ai_voice_agent]` to any page or let the floating widget appear site-wide via the Widget settings.
8. *(Optional)* Connect Google Calendar under **Settings → Calendar** for meeting-booking functionality.

== Frequently Asked Questions ==

= Which OpenAI API key permission level is required? =

A standard secret key (`sk-...`) with access to the Chat Completions and Embeddings endpoints is sufficient. Ensure your OpenAI account has billing enabled.

= Can I use ElevenLabs instead of OpenAI for voice? =

Yes. Enter your ElevenLabs API key under **Settings → Providers** and select **ElevenLabs** as the default TTS provider under **Settings → Voice**.

= Does the agent hallucinate answers it does not know? =

The agent's system prompt instructs it to answer only from retrieved knowledge-base chunks. If no relevant content is found, it will say so rather than fabricate an answer.

= Will the plugin slow down my website? =

The floating widget loads asynchronously and does not block page rendering. API calls to OpenAI happen only when a visitor actively interacts with the agent.

= Is visitor data stored on my server? =

Conversations and lead data are stored in your own WordPress database. You control retention periods and can anonymise visitor identifiers. Voice recordings are **not** stored by default.

= What happens to my data if I uninstall the plugin? =

By default all data is **preserved** when you deactivate or delete the plugin so you can reactivate seamlessly. To permanently delete all tables and options, enable **Delete all data on uninstall** under **Settings → Advanced** before clicking Delete.

= Can I have different agents on different pages? =

Yes. Use the `agent_id` attribute on the `[assertiv_ai_voice_agent]` shortcode or pass it to the `assertiv_ai_voice_agent()` PHP function.

= Does the plugin support WooCommerce? =

Yes. WooCommerce products and product categories can be indexed into the knowledge base so the agent can answer product-related questions.

== Screenshots ==

1. **Dashboard** — Overview of conversations, leads, and agent activity at a glance.
2. **Agent Editor** — Configure name, avatar, system prompt, language, and voice per agent.
3. **Knowledge Base** — View indexed sources, trigger re-indexing, and manage exclusions.
4. **Leads Pipeline** — Kanban-style board with lead scoring badges and one-click detail view.
5. **Meetings & Calendar** — All booked meetings with status, date/time, and attendee details.
6. **Analytics** — Charts for conversation volume, lead conversion rate, and knowledge gap trends.
7. **Settings — Voice** — Choose TTS provider, voice, and speaking speed with live preview.
8. **Frontend Widget** — The floating voice/chat widget as visitors see it on your site.

== Changelog ==

= 2.1.0 =
* Added Google Calendar OAuth 2.0 integration for real-time availability and meeting booking.
* Added eight agentic tools: SearchWebsite, CreateLead, QualifyLead, UpdateLead, GetCalendarAvailability, BookMeeting, RescheduleMeeting, CancelMeeting.
* Added Knowledge Gaps detection and resolution workflow.
* Added ElevenLabs TTS provider support.
* Added in-admin voice preview endpoint.
* Added lead CSV export.
* Added pipeline stage management for leads.
* Added manual lead re-scoring.
* Improved conversation orchestration with multi-tool calling support.
* Added per-session and global usage limits.
* Added configurable data retention and visitor anonymisation.

= 1.0.0 =
* Initial release.
* Core voice/text widget with OpenAI Chat Completions.
* Basic knowledge base indexing for pages and posts.
* Admin dashboard with conversations view.
* Settings panel for API keys, widget appearance, and privacy.

== Upgrade Notice ==

= 2.1.0 =
This version adds new database columns and tables. The plugin will run the necessary migrations automatically on activation. No manual action required.

== External Services ==

This plugin connects to the following external APIs:

* **OpenAI API** (https://api.openai.com) — Used for language model responses (Chat Completions), text embeddings, and text-to-speech synthesis. Your API key is sent with every request. Review OpenAI's privacy policy at https://openai.com/policies/privacy-policy.
* **ElevenLabs API** (https://api.elevenlabs.io) — Optional premium text-to-speech. Only called when ElevenLabs is selected as the TTS provider. Review ElevenLabs' privacy policy at https://elevenlabs.io/privacy.
* **Google Calendar API** (https://www.googleapis.com) — Optional calendar integration for availability checks and meeting booking. Only called after you authenticate via OAuth 2.0. Review Google's privacy policy at https://policies.google.com/privacy.

Visitor messages are transmitted to OpenAI for processing. No message content is sent to ElevenLabs or Google Calendar unless those integrations are explicitly enabled.
