 _   _ _____  ____   ___   ____  
| | | |_   _|/ ___| / _ \ / ___| 
| |_| | | |  \___ \| | | | |     
|  _  | | |   ___) | |_| | |___  
|_| |_| |_|  |____/ \___/ \____| 

GoHighLevel Integration TODOs

## ✅ Completed
- [x] Refactored `QueueProcessor` for enterprise-level DI and testability
- [x] Added PHPUnit test suite with Brain Monkey for `QueueProcessor`
- [x] Enhanced `Loader` class with shared resolver and singleton management
- [x] Created comprehensive unit tests for `Loader` class
- [x] Verified CustomObject delete path includes `schema_id` from SettingsManager
- [x] Updated BuddyBoss settings UI - moved info boxes to tooltips in h3 headers
- [x] Converted auto-delete toggle to checkbox matching other sync options
- [x] Enhanced Custom Object Management tooltip to explain master toggle auto-enabling
- [x] Updated integrations save button UX - removed scroll-to-top, added button status feedback
- [x] Replaced notice messages with SweetAlert toast notifications in integrations
- [x] Implemented WordPress WYSIWYG editor for restrictions access denied message
- [x] Added TinyMCE branding removal via filter in AssetsManager
- [x] Enqueued wp_editor assets for admin settings pages
- [x] Added TinyMCE save trigger before AJAX form submission
- [x] Added TinyMCE re-initialization after SPA tab loads
- [x] Added tooltips to all restriction settings labels for better UX
- [x] Made role-tags page mobile responsive with horizontal scrolling table
- [x] Optimized bulk operations and select2 fields for mobile devices
- [x] Fixed user_login queue action API call format bug (was using query string instead of params array)
- [x] Added proper error handling and logging for user_login sync failures
- [x] **Added performance database indexes** (DB v1.5.0) ⚡
  - Added `status_site_created` index to queue table (10x faster queue processing)
  - Added `status_site_processed` index to queue table (10x faster dashboard stats)
  - Added `site_created_cleanup` index to log table (10x faster log cleanup)
  - Added `sync_item_site` index to log table (10x faster user sync history)
- [x] **Conditional menu items based on GHL tags** 🎯 (COMPLETED - Enterprise-grade implementation)
  - ✅ Menu items can be shown/hidden based on user's GHL contact tags
  - ✅ Support for ANY, ALL, and NOT rules
  - ✅ Logged-in/Logged-out visibility options
  - ✅ Select2 tag picker integrated in menu editor
  - ✅ Works with all WordPress navigation menus
  - ✅ **Enterprise Architecture**:
    - Stores GHL tag IDs (not names) for uniqueness and immutability
    - Server-side array filtering (not CSS hiding) for true access control
    - PHP renders HTML via `wp_nav_menu_item_custom_fields` hook
    - JavaScript handles Select2 UI only (no HTML generation)
    - Single-method tag caching with graceful degradation
    - Class constants for all meta keys (maintainability)
    - Fail-safe defaults (unknown rules show to everyone)
    - Zero N+1 queries, zero API calls during menu display
    - Fast-path optimization for login-based rules
- [x] **Elementor Integration** 🎨 (COMPLETED - Drag & Drop Form Widget)
  - ✅ Custom "GoHighLevel Form" widget for Elementor page builder
  - ✅ Dropdown populated with all GHL forms (auto-synced)
  - ✅ Responsive controls for width, height, margin, padding
  - ✅ Direct link to backend Forms Settings for advanced options
  - ✅ Reuses existing shortcode renderer (no duplicate code)
  - ✅ Custom "GoHighLevel CRM" widget category
  - ✅ Editor placeholder when no form selected
  - ✅ Connection status detection and error handling
  - ✅ Full integration with form restrictions and submission limits
  - ✅ Clean, professional UI with info banners and refresh options
  - ✅ Documentation: docs/ELEMENTOR_INTEGRATION.md
    - Comprehensive error handling and input sanitization
  - ✅ **Documentation**: See `docs/CONDITIONAL_MENUS.md` for full technical reference

## 🎯 High Priority - Core GHL ↔ WordPress Enhancements

### Performance & Quick Wins (Week 1)
- [x] **Add database indexes to queue and log tables** ⚡ (COMPLETED - DB v1.5.0)
  - ✅ Added idx_status_site_created to queue table (10x faster queue queries)
  - ✅ Added idx_status_site_processed to queue table (10x faster stats)
  - ✅ Added idx_site_created_cleanup to log table (10x faster cleanup)
  - ✅ Added idx_sync_item_site to log table (10x faster user history)
- [ ] **Enhanced logging with log levels** (2 hours)
  - Add Debug, Info, Warning, Error levels
  - Store request/response payloads for debugging

  - Add performance metrics (sync duration tracking)
- [x] **Sync preview/dry-run mode** (4 hours)
  - Show what will happen before syncing
  - Display: contacts to create/update/skip/fail
  - Add "Test with single user" feature
- [ ] **Data quality checker** (4 hours)
  - Find contacts with missing required fields
  - Detect invalid email/phone formats
  - Find potential duplicates
  - Orphaned contact detector (GHL without WP, WP without GHL)

### User Experience Enhancements (Week 2)
- [ ] **Contact health score system** (6 hours)
  - Score based on: sync freshness, field completeness, error history
  - Display in user list column and profile
  - Filter users by health score
  - Bulk fix common issues
- [x] **Sync analytics dashboard** (8 hours) ✅ **COMPLETED**
  - ✅ Line charts: sync activity over time (30-day daily activity with success/failed breakdown)
  - ✅ Pie charts: success vs failure rates (overall stats + sync type breakdown)
  - ✅ Bar charts: syncs by type (user, order, group) + hourly activity (24-hour breakdown)
  - ✅ Success rate trend: 7-day line chart showing percentage over time
  - ✅ Export reports as CSV (full data export with all metrics)
  - ✅ **Implementation Details**:
    - Added 4 new methods to StatsProvider: get_analytics_data(), get_daily_activity(), get_sync_type_breakdown(), get_hourly_activity(), get_success_failure_rates()
    - Created analytics.php template with 5 Chart.js visualizations
    - Tab system in dashboard.php (Dashboard | Analytics) with localStorage persistence
    - Real-time data from ghl_sync_log table with optimized queries
    - CSV export functionality with proper formatting
    - Responsive design matching existing dashboard UI
    - Refresh button to reload data
    - Color-coded charts (green for success, red for failure, purple for mixed)
- [x] **Configuration export/import** (4 hours) ✅ **COMPLETED**
  - ✅ Export field mappings as JSON
  - ✅ Export role-tag configurations
- [x] **Setup Wizard** ✅ **COMPLETED**
  - ✅ 6-step onboarding wizard (Welcome, Connect, User Sync, Integrations, Advanced, Complete)
  - ✅ OAuth and API Key connection options with tab switching
  - ✅ Connection status detection with collapsible change connection section
  - ✅ User sync settings with tags selection (AJAX-loaded Select2)
  - ✅ Dynamic integrations display (WooCommerce PRO only, BuddyBoss, LearnDash)
  - ✅ Advanced settings (delete on user delete, sync logging, role tags)
  - ✅ Auto-redirect on plugin activation (testing mode enabled)
  - ✅ Completion tracking with option to prevent re-showing
  - ✅ Responsive design with horizontal space optimization
  - ✅ Upgrade prompts for PRO features
  - ✅ Dashboard and settings CSS loaded for consistent styling
  - ✅ Export integration settings
  - ✅ Import with validation and overwrite protection
  - ✅ Implemented in Tools tab (templates/admin/partials/settings/tools.php)
  - ✅ Security: API credentials excluded from export for safety
  - ✅ Perfect for backups, migrations, and agency multi-client deployment

### Configuration Presets & Templates (Week 2-3)
- [ ] **Field mapping presets** (6 hours)
  - Pre-built templates for common scenarios (WooCommerce, BuddyBoss, LearnDash)
  - Industry-specific presets (e-commerce, membership, education, coaching)
  - Save current configuration as custom preset
  - Export/import presets as JSON
  - Apply preset with one-click (replaces current mapping)
  - Preset library with descriptions and use cases
- [ ] **Integration configuration presets** (4 hours)
  - Pre-configured integration bundles (e.g., "Full E-commerce Stack", "Membership Community", "Online Course Platform")
  - Include: enabled integrations + field mappings + role-tag rules
  - Quick-start templates for new installations
  - Agency templates for multi-client deployment
  - Version control for preset updates
- [ ] **Tag rule presets** (3 hours)
  - Common tag automation templates (purchase behaviors, engagement levels, course progress)
  - Conditional logic templates for complex scenarios
  - Role-based tag assignment presets
  - Import from preset library or create custom
- [ ] **Workflow trigger presets** (4 hours)
  - Pre-configured webhook actions for common GHL workflows
  - Event templates (new user, order placed, course completed, group joined)
  - Multi-step automation presets combining multiple triggers
  - Testing mode to preview preset behavior before activation
- [ ] **Multisite network presets** (5 hours)
  - Network-wide preset distribution to all subsites
  - Per-site preset overrides with inheritance tracking
  - Bulk apply presets across selected sites
  - Rollback to previous preset version
  - Audit log showing which presets applied when and by whom

### Advanced Sync Features (Week 3)
- [ ] **Smart duplicate detection** (8 hours)
  - Multi-field matching (name + phone, custom fields)
  - Fuzzy matching for similar names/typos
  - Merge duplicate contacts
  - Manual review queue for uncertain matches
  - Configurable matching rules
- [ ] **Advanced tag rules engine** (8 hours)
  - Conditional tags based on user meta (e.g., VIP if lifetime_value > $1000)
  - Tag templates for common scenarios
  - Auto-remove stale tags
  - Tag history tracking (when added/removed)
  - Scheduled re-evaluation of tag rules
- [ ] **Contact timeline integration** (6 hours)
  - Show GHL activity in WordPress user profile
  - Display: emails, SMS, calls, form submissions, workflow triggers
  - Filter by activity type
  - Pagination for long histories

### Data Management (Week 3-4)
- [x] **Field auto-discovery & mapping suggestions** (8 hours) ✅
  - ✅ Auto-detect common field patterns using Levenshtein distance
  - ✅ Suggest mappings based on field names with synonym dictionary
  - ✅ Smart field type matching with suffix detection (billing_first_name → firstName)
  - ✅ Confidence scoring (100% exact, 95% synonym, 85% suffix, 70%+ threshold)
  - ✅ Duplicate prevention - only highest confidence match per GHL field
  - ✅ User control - checkbox selection in SweetAlert modal
  - ✅ Visual feedback - green highlight on applied suggestions
  - ✅ Skip internal WordPress meta fields and GHL custom fields
  - ✅ Prioritize core WP fields over billing/shipping variants
- [ ] **Contact segmentation in WordPress** (6 hours)
  - View users by GHL tags in admin
  - Filter by contact stage/pipeline
  - Bulk actions on segmented users
  - Export segments as CSV
  - Segment analytics

### Pipeline & Opportunity Management (Week 4)
- [ ] **Enhanced pipeline tracking** (8 hours)
  - Display pipeline stage in WP user profile
  - Move contacts between stages from WordPress
  - Show opportunity value and close probability
  - Dashboard widget with pipeline overview
  - Track last activity date
- [ ] **Sync scheduling & automation** (6 hours)
  - Schedule daily/weekly full sync at off-peak hours
  - Incremental sync (only modified users)
  - Delta tracking (skip unchanged data)
  - Sync windows (define when syncing can occur)
  - Email reports after scheduled sync

### Performance & Reliability (Week 4)
- [ ] **Smart queue prioritization** (4 hours)
  - Add priority levels: Critical, High, Medium, Low
  - Process high-priority items first
  - VIP user flag for priority queue
  - Manual sync = Critical priority
- [ ] **Intelligent retry logic** (4 hours)
  - Exponential backoff by error type
  - Rate limit: wait until limit resets (from headers)
  - Network error: 1m, 5m, 15m, 1h backoff
  - Auth error: trigger token refresh immediately
  - Validation error: don't retry (permanent failure)

### Developer Features (Ongoing)
- [ ] **Expanded developer hooks** (4 hours)
  - `ghl_crm_before_contact_create` filter (modify data before sync)
  - `ghl_crm_contact_created` action (post-sync logging)
  - `ghl_crm_field_value` filter (transform field values)
  - `ghl_crm_should_sync_user` filter (sync decision control)
  - `ghl_crm_sync_error` action (custom error handling)
  - Create developer documentation with examples
- [ ] **Advanced logging & debugging tools** (6 hours)
  - Log search with filters (user, date, status, type)
  - Request inspector (view raw API requests/responses)
  - Performance profiler (track slow syncs)
  - Export logs as CSV
  - Visual log viewer with syntax highlighting

## 📋 Future Third-Party Integrations (Later)
- [x] **Forms customization & auto-fill** (6 hours) ✅ **COMPLETED**
  - ✅ Auto-fill email and name fields for logged-in users
  - ✅ Pre-populate fields from WordPress user data
  - ✅ Pre-populate fields from GHL contact data
  - ✅ Custom field mapping for form submissions via custom URL parameters
  - ✅ Conditional field display based on user data (logged-in only setting)
  - ✅ Hidden fields auto-population (user ID, contact ID, tags) via variable system
  - ✅ **Implementation Details**:
    - Created FormSettings.php for per-form configuration management
    - Per-form settings: autofill_enabled, logged_only, custom_params
    - Custom URL parameters with 12+ variable placeholders ({user_email}, {user_first_name}, {user_role}, {current_url}, {meta:field_name}, etc.)
    - Server-side variable replacement for user data in FormSettings::resolve_custom_params()
    - Client-side variable replacement for {current_url} and {current_title} in form-autofill.js
    - Merge logic: Auto-fill data + custom params (custom params override conflicts)
    - Admin UI: Settings sidebar (700px wide, responsive) with custom parameter builder
    - Available variables reference displayed in settings panel
    - Add/remove parameter rows dynamically with sanitization
    - Full documentation in docs/CUSTOM_PARAMETERS.md
- [ ] Gravity Forms integration
- [ ] Contact Form 7 integration
- [ ] WPForms integration
- [ ] Elementor Forms integration
- [ ] Ninja Forms integration
- [ ] **LearnDash Integration** 🎓
  - ✅ Phase 1: Core sync engine - Event bridge + queue handler (`LearnDashSync`) enqueues enroll/revoke/complete events into GoHighLevel contact sync
  - ✅ Phase 2: Per-course configuration - Meta box UI for enrollment/completion/revoke tags + auto-enrollment trigger tags per course
  - ✅ Phase 3: Template cleanup - Removed global tag settings, styled integration page to match WooCommerce/BuddyBoss design patterns
  - [ ] Phase 4: Advanced features & enhancements
    - [ ] **Progress milestone tags** (4 hours) - Apply tags at custom completion % thresholds (25%, 50%, 75%)
    - [x] **Quiz performance tracking** (5 hours) ✅ **COMPLETED**
      - ✅ Multi-level score threshold system with dynamic UI
      - ✅ Per-quiz configuration: unlimited score ranges (e.g., 0-49, 50-74, 75-89, 90-100)
      - ✅ Multiple tags per threshold level
      - ✅ Score extraction from LearnDash quiz completion hook (`$data['percentage']`)
      - ✅ Automatic tag matching based on achieved score
      - ✅ Add/remove threshold rows with live Select2 tag pickers
      - ✅ Clean, responsive UI with CSS animations
      - ✅ Score data included in queue payload for analytics
      - ✅ Implementation Details:
        - Added `_ghl_ld_quiz_score_thresholds` post meta storage
        - Created `render_threshold_row()` for dynamic UI generation
        - Built `sanitize_score_thresholds()` and `normalize_score_thresholds()` for data validation
        - Enhanced `handle_quiz_completed()` to extract score from `$data['percentage']`
        - Added `resolve_score_threshold_tags()` to match score against ranges
        - Updated `queue_content_event()` to accept optional score parameter
        - JavaScript handles dynamic row add/remove with Select2 initialization
        - CSS provides polished threshold builder interface with hover effects
    - [ ] **Certificate sync** (3 hours) - Push certificate issuance events to GHL with certificate URL in custom field
    - [ ] **Course-level custom fields** (4 hours) - Map course metadata to GHL contact custom fields (enrollment date, completion date, progress %)
    - [x] **Group enrollment sync** (4-6 hours) ✅ **COMPLETED**
      - ✅ Created `GroupMetaBox.php` for LearnDash group editor settings
      - ✅ Added "Group Membership Tags" - single field applied on join, removed on leave
      - ✅ Added "Auto-enroll users with tags" reverse sync (tag-to-group mapping)
      - ✅ Hooked `ld_added_group_access` to queue tag application to GHL contact
      - ✅ Hooked `ld_removed_group_access` to remove group tags from GHL contact
      - ✅ Implemented batch processor for existing users with matching tags
      - ✅ Added group enrollment to queue sync execution flow (`execute_learndash_group_sync`)
      - ✅ Mirrored course meta box UI/UX patterns (Select2 integration, clean cards)
      - ✅ Support for unlimited groups with independent tag configurations
      - ✅ **Technical Details**:
        - Post type: `groups` (LearnDash CPT)
        - Meta keys: `_ghl_ld_group_tags` (applied on join, removed on leave), `_ghl_ld_group_auto_enroll_tags`
        - Hooks: `ld_added_group_access`, `ld_removed_group_access`, `ghl_crm_user_tags_updated`
        - Queue action: `sync_group_event` (item_type: group)
        - Batch action: `ghl_ld_process_batch_group_enrollment`
        - Auto-enrollment functions: `get_groups_for_tags()`, `auto_enroll_user_in_group()`
        - Tag resolution: `resolve_group_tags()` uses same tag set for join/left actions
        - Queue processing: `process_group_payload()` adds tags on 'joined', removes on 'left'
    - [ ] **Drip schedule awareness** (5 hours) - Trigger tags/workflows when lessons become available in drip-fed courses
    - [ ] **Inactivity automation** (4 hours) - Auto-tag learners who haven't accessed course in X days to trigger re-engagement workflows
    - [ ] **Bulk course sync utility** (3 hours) - Admin tool to backfill all historical enrollments/completions for existing courses
    - [ ] **Learning path tracking** (6 hours) - Track multi-course learning paths and apply milestone tags as learners progress through sequences
    - [ ] **Instructor assignment sync** (4 hours) - Map course instructors to GHL users/contacts for coaching workflow triggers

## 🚀 WordPress.org Preparation
- [ ] Create proper readme.txt (WordPress.org format)
- [ ] Add 3-5 admin interface screenshots to /assets
- [ ] Detailed installation guide
- [ ] Test on WordPress 5.8, 6.0, 6.4, 6.8
- [ ] Test on PHP 7.4, 8.0, 8.1, 8.2, 8.3
- [ ] Submit to WordPress.org Plugin Review team

## 🧪 Testing & Code Quality
- [ ] Expand PHPUnit test coverage
  - ContactCache tests
  - RateLimiter tests
  - WebhookHandler tests
  - GHLToWordPressSync tests
- [ ] Add static analysis (PHPStan/Psalm)
- [ ] Create CI/CD pipeline (.github/workflows/tests.yml)
  - Run PHPUnit tests
  - Run PHPCS code standards
  - Run PHPStan static analysis
  - Test across PHP 7.4-8.3
  - Test across WP 5.8-latest

## 🔥 Native WP ↔️ GHL Growth Accelerators

### Unified Contact Operations
- [ ] **Command-center contact view** (10 hours)
  - One WP admin screen that merges WordPress profile data, Woo orders, LearnDash progress, and live GHL contact fields.
  - Inline controls to add/remove tags, change pipeline stage, enroll in workflows, or trigger manual sync without leaving WP.
  - Side-by-side diff widget that highlights unsynced fields before committing changes back to GHL.
  - Background watcher that warns when remote updates occur while an admin is editing locally.

- [ ] **Conversation + task inbox** (9 hours)
  - Surface GHL SMS, call notes, and email activity directly in the WP user profile with infinite scroll and filters.
  - Reply or create new messages using GHL templates while storing a lightweight copy in WP for compliance.
  - Create/complete GHL tasks from WP, auto-tagging them with the site/blog ID for traceability.
  - Include SLA timers so support teams know which conversations are overdue.

- [ ] **Opportunity micro-board** (8 hours)
  - Display the contact’s open opportunities/pipelines inline, with drag-and-drop stage changes that call the GHL API.
  - Tie opportunity value to WooCommerce/LearnDash revenue recorded in WP to catch mismatches.
  - Provide quick actions (log note, schedule call, trigger follow-up workflow) powered by this plugin.
  - Snapshot pipeline metrics locally so admins can audit changes without digging through the GHL UI.

### Experience Automation
- [ ] **Audience-aware block controls** (9 hours)
  - Extend Gutenberg blocks with conditions based on live GHL tags, custom fields, or opportunity stage.
  - Render decisions server-side using cached GHL contact mirrors to avoid duplicating logic inside GHL funnels.
  - Offer a preview-as-contact mode to validate personalized pages from WP before publishing.
  - Push impression/conversion counters back to GHL custom metrics so marketers see onsite impact.

- [ ] **Stage-driven CTA orchestration** (8 hours)
  - Map any WP button/form to a “next best action” table stored in this plugin and synced to GHL.
  - Automatically switch CTA text, destination, or modal based on the contact’s workflow status pulled from GHL.
  - Record which CTA fired and post the event to GHL so automations can branch on onsite engagement.
  - Include freeze/override switches inside WP for launch crises without editing GHL campaigns.

- [ ] **Automation relay builder** (9 hours)
  - Visual canvas that listens to WordPress hooks (user_login, ACF update, Woo order status, BuddyBoss badge) and chains them to native GHL actions via this plugin.
  - Provide reusable templates (e.g., “Failed payment rescue”, “Course completion upsell”) that ship with pre-wired WP + GHL steps.
  - Include per-step logging, retry controls, and a dry-run simulator leveraging the existing queue system.
  - Export/import automations as JSON so agencies can roll them across multisite networks.

### Commerce & Revenue Loop
- [ ] **Revenue attribution bridge** (10 hours)
  - Track which GHL workflow/stage touched a contact immediately before each Woo order in WP.
  - Push attributed revenue totals back into GHL custom fields while keeping granular line-item detail stored locally.
  - Flag discrepancies (e.g., high-order value but no open opportunity) and open review tasks in WP.
  - Provide cohort visualizations inside WP using the synced opportunity pipeline data.

- [ ] **Offer bundler + fulfillment sync** (12 hours)
  - Package Woo products, LearnDash courses, and BuddyBoss groups into “offers” managed by this plugin.
  - When an offer is purchased, automatically apply the mapped GHL workflows, tags, and opportunity updates via our API client.
  - Monitor fulfillment tasks (course enrollment, tag applied, workflow started) and show a checklist per order in WP until everything succeeds.
  - Expose a resync button that replays the fulfillment recipe if downstream steps fail.

- [ ] **Subscription health monitor** (8 hours)
  - Detect failed renewals or overdue invoices in WooCommerce, then automatically trigger the appropriate GHL dunning sequence.
  - Sync payment status back to GHL custom fields and pause/resume automations from WP.
  - Provide a “save customer” panel for support staff with scripted outreach options powered by GHL SMS/email templates.
  - Log every intervention inside WP with links to the associated GHL contact timeline for auditing.

### Community & Learning Bridge
- [ ] **Cohort + program sync** (8 hours)
  - Create BuddyBoss/LearnDash cohorts from WP and instantly mirror membership to GHL companies or opportunities.
  - Apply/remove GHL tags when learners move between cohorts, ensuring nurture paths stay aligned. 
  - Surface participation stats (last login, lesson progress) in WP and push milestones to GHL timelines.
  - Allow coaches to drop notes in WP that get appended to the GHL contact.

- [ ] **Learning milestone relays** (8 hours)
  - Ship prebuilt milestone definitions (course start, quiz fail, badge earned) that fire GHL actions via the plugin queue.
  - Stack rules (e.g., “failed quiz twice AND no coaching call booked”) to trigger escalations.
  - Bundle supporting assets—like email copy or SMS templates—so teams launch without touching the GHL UI.
  - Provide a learner-facing timeline block that blends WP achievements with select GHL follow-ups for transparency.

- [ ] **Event-to-workflow playbooks** (7 hours)
  - Connect WordPress event plugins to mapped GHL workflows so RSVPs, check-ins, and no-shows instantly update the CRM.
  - Auto-create reminder tasks, staff assignments, and recap messages from WP using our GHL API client.
  - Post attendance back to GHL custom objects while keeping rich notes/documents stored in WP.
  - Offer cloning tools so agencies duplicate entire playbooks per client site.

### Platform Ops & Extensibility
- [ ] **Multisite command lane** (10 hours)
  - Network-level dashboard showing each site’s connection health, API usage, queue depth, and last successful sync.
  - Push standardized settings (field maps, enabled modules, API keys) from the network to each site with respect for per-site overrides.
  - Trigger remote diagnostics (test auth, flush queue, replay webhook) without logging into every subsite or GHL account.
  - Stream alerts to Slack/Email when limits near capacity or cron falls behind.

- [ ] **Consent & compliance center** (7 hours)
  - Centralize consents collected via WP forms/comments/orders and sync summary flags to GHL contacts/custom objects.
  - Maintain full consent evidence (IP, timestamp, language) in WP while exposing a self-service history shortcode for end users.
  - Route GDPR/CCPA delete requests through WP, automatically pausing related GHL workflows before data removal.
  - Include per-site policies for multisite networks to respect regional requirements.

- [ ] **Developer enablement kit** (8 hours)
  - Provide an SDK of PHP hooks + JS utilities so agencies can register new sync recipes using our queue, logger, and API layers.
  - Bundle Storybook-style previews for approved Gutenberg patterns that already wire into plugin actions/tags.
  - Offer schema definition files so developers can declare custom objects/fields once and sync them to both WP and GHL via CLI.
  - Ship automated tests/mocks so customizations can be validated without hitting live GHL tenants.

## 📝 Quick Wins & Utilities
- [ ] Admin-only debug drawer that reveals the active GHL contact, tags, and opportunity pulled via this plugin plus the WP rules that rendered the page.
- [ ] Shortcode/block token library exposing sanitized GHL fields (first name, stage, next appointment) with built-in caching + fallback when a visitor isn’t linked yet.
- [ ] Guided connection wizard for multisite that tests API keys, queues initial sync jobs, and copies approved field maps to each site.
- [ ] Consent badge component that automatically references the latest legal copy stored in WP and updates matching acknowledgement fields in GHL.
- [ ] WP-CLI + REST diagnostics endpoints to ping GHL auth, inspect queue status, replay failed jobs, and share bundles of logs with support in one command.


## 🛠️ Refactoring & Code Quality

- ✅ Fix GHL contact ID fetch on self profile update
  - When updating a user profile, if _ghl_contact_id is missing, fetch the contact by email from GHL and set it before syncing tags. Prevents duplicate contact errors for existing users.

### Family Tag Inheritance Improvements
- [x] Persistently track inherited tags for each child so they can be correctly removed when the parent-child relationship is broken.
- [x] Remove inherited tags on child unlink

## 🔥 Queue Optimization (Check Later - Not Launch Blockers)

### API Buffering via Shutdown Hook (4-6 hours)
- [ ] **Implement shutdown hook buffering** - Inspired by WP Fusion
  - Buffer multiple API calls during request lifecycle
  - Execute all buffered calls during `shutdown` hook
  - Reduces API hits by batching related operations
  - Example: User registers → profile update → tag assignment = 1 buffered batch instead of 3 separate API calls
  - Benefits: Lower API usage, faster perceived performance, reduces rate limit pressure
  - Implementation: Create `APIBuffer` class with `buffer()` and `flush_on_shutdown()` methods
  - **Priority:** Nice-to-have, evaluate if API rate limits become an issue in production

### Async Webhook Processing (3-4 hours) ✅ **COMPLETED**
- [x] **Add async webhook option**
  - Add `&async=true` parameter support to webhook endpoints
  - Queue incoming webhooks instead of processing synchronously
  - Prevents webhook timeouts on slow operations (large contact updates, bulk tag changes)
  - Improves webhook delivery success rate (GHL expects <5sec response)
  - Implementation: Check for `async` param, queue payload, return 200 immediately
  - **Priority:** Evaluate after launch if webhook timeout errors appear in logs

## ✅ Form Submission Limits (COMPLETED)
- [x] **Hide forms on submission** - Allow one submission per user or infinite
  - ✅ Added submission limit setting (`unlimited` or `once`) in FormSettings
  - ✅ Added `hide_after_submit` toggle to show thank you message
  - ✅ Track submitted forms per user in `_ghl_submitted_forms` user meta
  - ✅ Check submission status in shortcode and hide form if needed
  - ✅ Admin UI in forms.js with dropdown and conditional hide toggle
  - ✅ Frontend postMessage listener to detect form submissions since the iframe is cross-origin and we can't access data directly
  - ✅ AJAX endpoint to mark forms as submitted
  - ✅ Auto-reload page after submission when hide is enabled
  - **Settings Location**: Forms → Click settings icon → Submission Controls section


- [x] Lock email sync direction in field mapping


- [ ] automations (workflows) based on actions in wc
- [ ] custom email templates on wc product purchase
- [ ] phone numbers is a pain point
- [ ] remove abandoned tag on completion