<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * VMO Capability Registry
 * 
 * Central registry where every VMO feature/class self-announces its capabilities.
 * The Jarvis AI system prompt auto-builds from this registry, so Jarvis always
 * knows exactly what VMO can do — no manual prompt updates needed.
 *
 * How it works:
 *   1. Each class calls vmo_register_capability() in its constructor or via 'init' hook.
 *   2. When Jarvis's system prompt is built, get_prompt_block() compiles all
 *      registered capabilities into a formatted knowledge block.
 *   3. New features auto-appear in Jarvis's knowledge the moment they're activated.
 *
 * Usage:
 *   vmo_register_capability([
 *       'id'          => 'zoho_email',
 *       'name'        => 'Zoho Mail Integration',
 *       'category'    => 'email',
 *       'summary'     => 'Auto-provisions business email via Zoho Mail API.',
 *       'can_do'      => ['Create email accounts', 'Generate DNS records', 'Verify domains'],
 *       'cannot_do'   => ['Bypass DNS record requirement at registrar'],
 *       'user_guide'  => 'Tell the user VMO can set up Zoho email automatically...',
 *       'priority'    => 10,
 *   ]);
 *
 * @package VMO_AI_Website_Builder
 * @since 1.0.52
 */

if (!defined('ABSPATH')) exit;

class VMO_Capability_Registry {

    /** @var self|null */
    private static $instance = null;

    /** @var array Registered capabilities keyed by ID */
    private $capabilities = [];

    /** @var array Valid categories for grouping */
    private const CATEGORIES = [
        'email'      => '📧 Email System',
        'phone'      => '📞 Phone & SMS',
        'payments'   => '💳 Payments & Billing',
        'crm'        => '👥 CRM & Contacts',
        'website'    => '🌐 Website Builder',
        'seo'        => '🔍 SEO & Analytics',
        'marketing'  => '📣 Marketing & Campaigns',
        'shipping'   => '📦 Shipping & E-Commerce',
        'documents'  => '📄 Documents & Legal',
        'media'      => '🎬 Media & Content',
        'ai'         => '🤖 AI Agents & Assistants',
        'admin'      => '⚙️ Admin & System',
        'security'   => '🔒 Security & Compliance',
        'integration'=> '🔗 Third-Party Integrations',
    ];

    /**
     * Singleton accessor.
     */
    public static function get_instance(): self {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        // Register core capabilities on init (priority 5 = before most classes at 10)
        add_action('init', [$this, 'register_core_capabilities'], 5);
    }

    /**
     * Register a capability.
     *
     * @param array $cap {
     *     @type string   $id          Unique identifier (e.g., 'zoho_email')
     *     @type string   $name        Human-readable name
     *     @type string   $category    One of self::CATEGORIES keys
     *     @type string   $summary     One-line description of what this does
     *     @type string[] $can_do      List of things this feature CAN do
     *     @type string[] $cannot_do   List of limitations (optional)
     *     @type string   $user_guide  Instructions for Jarvis on how to help users with this feature
     *     @type int      $priority    Display order within category (lower = first, default 10)
     * }
     */
    public function register(array $cap): void {
        if (empty($cap['id']) || empty($cap['name'])) {
            return;
        }

        $this->capabilities[$cap['id']] = [
            'id'          => sanitize_key($cap['id']),
            'name'        => $cap['name'],
            'category'    => $cap['category'] ?? 'admin',
            'summary'     => $cap['summary'] ?? '',
            'can_do'      => $cap['can_do'] ?? [],
            'cannot_do'   => $cap['cannot_do'] ?? [],
            'user_guide'  => $cap['user_guide'] ?? '',
            'priority'    => $cap['priority'] ?? 10,
        ];
    }

    /**
     * Get all registered capabilities.
     *
     * @return array
     */
    public function get_all(): array {
        return $this->capabilities;
    }

    /**
     * Get capabilities filtered by category.
     *
     * @param string $category
     * @return array
     */
    public function get_by_category(string $category): array {
        return array_filter($this->capabilities, function($cap) use ($category) {
            return $cap['category'] === $category;
        });
    }

    /**
     * Build a formatted prompt block for injection into the Jarvis AI system prompt.
     * This is the key method — it auto-generates Jarvis's feature knowledge.
     *
     * @return string Formatted text block for GPT system prompt
     */
    public function get_prompt_block(): string {
        if (empty($this->capabilities)) {
            return '';
        }

        // Group by category
        $grouped = [];
        foreach ($this->capabilities as $cap) {
            $cat = $cap['category'];
            if (!isset($grouped[$cat])) {
                $grouped[$cat] = [];
            }
            $grouped[$cat][] = $cap;
        }

        // Sort each category by priority
        foreach ($grouped as &$caps) {
            usort($caps, function($a, $b) {
                return ($a['priority'] ?? 10) - ($b['priority'] ?? 10);
            });
        }
        unset($caps);

        // Build the prompt block
        $lines = [];
        $lines[] = '**VMO SYSTEM CAPABILITIES (AUTO-DISCOVERED)**:';
        $lines[] = 'The following features are BUILT INTO VMO and fully operational. You MUST know about ALL of these and confidently help users with them. NEVER say "VMO cannot do this" for any feature listed below.';
        $lines[] = '';

        // Output in category order
        foreach (self::CATEGORIES as $cat_key => $cat_label) {
            if (empty($grouped[$cat_key])) continue;

            $lines[] = '--- ' . $cat_label . ' ---';

            foreach ($grouped[$cat_key] as $cap) {
                $lines[] = '• **' . $cap['name'] . '**: ' . $cap['summary'];

                if (!empty($cap['can_do'])) {
                    foreach ($cap['can_do'] as $item) {
                        $lines[] = '  ✅ ' . $item;
                    }
                }
                if (!empty($cap['cannot_do'])) {
                    foreach ($cap['cannot_do'] as $item) {
                        $lines[] = '  ❌ ' . $item;
                    }
                }
                if (!empty($cap['user_guide'])) {
                    $lines[] = '  💡 WHEN USER ASKS: ' . $cap['user_guide'];
                }
                $lines[] = '';
            }
        }

        return implode("\n", $lines);
    }

    /**
     * Register all core VMO capabilities.
     * Called on 'init' at priority 5 so it runs before individual class registrations.
     * 
     * This covers ALL major VMO systems. Individual classes can also self-register
     * via vmo_register_capability() for additional detail.
     */
    public function register_core_capabilities(): void {

        // ═══════════════════════════════════════════════════════════════
        // EMAIL SYSTEM
        // ═══════════════════════════════════════════════════════════════

        $this->register([
            'id'       => 'email_interface',
            'name'     => 'Built-in Email Dashboard',
            'category' => 'email',
            'summary'  => 'Full email interface inside VMO — compose, send, receive, inbox/sent/drafts, AI auto-replies.',
            'can_do'   => [
                'Send and receive emails from within VMO dashboard',
                'Compose emails with AI assistance',
                'Manage inbox, sent, drafts, and folders',
                'Enable AI-powered auto-replies to incoming emails',
                'Build branded email signatures (name, logo, social links)',
                'Manage multiple sender identities per user (marketing, support, billing, etc.)',
            ],
            'user_guide' => 'The email interface is in the dashboard. Users can send/receive email, build signatures, and enable AI auto-reply — all without leaving VMO.',
            'priority' => 1,
        ]);

        $this->register([
            'id'       => 'email_campaigns',
            'name'     => 'AI Email Campaigns',
            'category' => 'email',
            'summary'  => 'AI-powered campaign generation with 4 variants, A/B subject lines, bulk send to CRM contacts, branded templates.',
            'can_do'   => [
                'Generate 4 campaign variants with AI (different tones/angles)',
                'A/B test subject lines with engagement prediction',
                'Send bulk campaigns to CRM contact lists',
                'Use branded "glassy" dark-mode HTML email templates',
                'Newsletter signup form builder',
                'Campaign performance dashboard (sent, opens, clicks)',
            ],
            'user_guide' => 'Users can create campaigns from the email section or business dashboard. AI generates the content — user picks the best variant and sends.',
            'priority' => 2,
        ]);

        $this->register([
            'id'       => 'email_compliance',
            'name'     => 'Email CAN-SPAM Compliance',
            'category' => 'email',
            'summary'  => 'Automatic unsubscribe links, suppression lists, opt-out management for all campaign emails.',
            'can_do'   => [
                'Auto-add unsubscribe links (HMAC-signed tokens)',
                'Maintain suppression lists per contact',
                'Check do-not-contact flags before sending',
                'REST endpoint for one-click unsubscribe',
            ],
            'priority' => 3,
        ]);

        $this->register([
            'id'       => 'zoho_email',
            'name'     => 'Zoho Mail Integration (Bundled)',
            'category' => 'email',
            'summary'  => 'Auto-provisions business email accounts via Zoho Mail API. Free tier: up to 5 accounts. VMO\'s recommended email provider.',
            'can_do'   => [
                'Connect to Zoho via OAuth automatically',
                'Create Zoho organizations for the user\'s domain',
                'Generate exact DNS records (MX, SPF, DKIM, DMARC) with copy-paste instructions',
                'Show registrar-specific setup guides (Namecheap, GoDaddy, Cloudflare, Google Domains)',
                'Create up to 5 free business email accounts (e.g., hello@, support@, info@)',
                'Auto-verify domain status after DNS setup',
                'Support all 5 Zoho data centers (US, EU, IN, AU, JP)',
            ],
            'cannot_do' => [
                'Set DNS records automatically (user must paste MX/SPF/DKIM records at their domain registrar — VMO provides exact records and step-by-step guide)',
            ],
            'user_guide' => 'This is VMO\'s BUNDLED email provider. ALWAYS recommend Zoho first. Tell the user: "VMO has Zoho Mail built in — I can create your business email accounts right here. The only step you\'ll handle is pasting a few DNS records at your domain registrar, and I\'ll give you the exact records and guide for your specific registrar." The free tier gives 5 mailboxes at zero cost.',
            'priority' => 4,
        ]);

        $this->register([
            'id'       => 'email_auto_provision',
            'name'     => 'Hosting Panel Email Auto-Provisioning',
            'category' => 'email',
            'summary'  => 'Auto-creates email accounts on cPanel, Plesk, and DirectAdmin hosts — no external provider needed.',
            'can_do'   => [
                'Detect hosting panel type (cPanel, Plesk, DirectAdmin, Cloudflare)',
                'Detect managed hosts (Kinsta, WP Engine, Flywheel) that don\'t support email',
                'Auto-create email accounts via hosting panel API (cPanel UAPI, Plesk XML, DirectAdmin)',
                'Configure SMTP/IMAP settings automatically for the new accounts',
            ],
            'cannot_do' => [
                'Create email on managed hosts (Kinsta, WP Engine, Flywheel) — use Zoho instead',
            ],
            'user_guide' => 'For cPanel/Plesk hosts, VMO can create email accounts directly on the server — no external provider needed. For managed hosts like Kinsta, recommend the built-in Zoho integration.',
            'priority' => 5,
        ]);

        $this->register([
            'id'       => 'email_sending',
            'name'     => 'Email Sending Engine',
            'category' => 'email',
            'summary'  => 'Smart email routing via VMO Email Router → Local Mailer (wp_mail with optional per-user SMTP override).',
            'can_do'   => [
                'Send via wp_mail() with automatic From-name/From-email from business profile',
                'Override SMTP per-send using user\'s own mailbox credentials',
                'Rate limiting (50/hour, 500/day by default — configurable)',
                'Token-based billing (333 tokens per email sent)',
                'Save all sent emails to outbox for history',
            ],
            'priority' => 6,
        ]);

        // ═══════════════════════════════════════════════════════════════
        // PHONE & SMS SYSTEM
        // ═══════════════════════════════════════════════════════════════

        $this->register([
            'id'       => 'phone_system',
            'name'     => 'Business Phone System (Twilio)',
            'category' => 'phone',
            'summary'  => 'Full VoIP phone system — provision numbers, make/receive calls, voicemail, call recording, departments, extensions.',
            'can_do'   => [
                'Search and provision local/toll-free phone numbers by area code',
                'Make outgoing calls from the browser (WebRTC)',
                'Receive incoming calls with browser ringing',
                'Voicemail with AI-generated greetings',
                'Call recording with playback in dashboard',
                'Call history and reports',
                'Department routing with extensions (press 1 for sales, etc.)',
                'External phone forwarding (ring personal cell)',
                'Power Dialer for outbound campaigns',
                'HD Text-to-Speech voice responses (Amazon Polly)',
            ],
            'user_guide' => 'Phone setup is in the dashboard under Phone. Users provision a number, then can make/receive calls directly in the browser. Token-based billing per minute.',
            'priority' => 1,
        ]);

        $this->register([
            'id'       => 'sms_system',
            'name'     => 'SMS Messaging (A2P 10DLC)',
            'category' => 'phone',
            'summary'  => 'Business SMS with A2P 10DLC registration for carrier compliance. Send/receive texts from the dashboard.',
            'can_do'   => [
                'Send and receive SMS from the business number',
                'A2P 10DLC brand registration (automated via VMO)',
                'A2P campaign registration (automated via VMO)',
                'Status tracking for brand and campaign approval',
                'Auto-create Twilio Messaging Service and link phone number',
                'SMS activation when campaign is verified',
            ],
            'cannot_do' => [
                'Skip A2P registration (required by US carriers for business SMS)',
            ],
            'user_guide' => 'SMS requires A2P 10DLC registration (brand + campaign). VMO handles this automatically — user fills in business details, VMO submits to Twilio. Approval takes 1-7 business days.',
            'priority' => 2,
        ]);

        // ═══════════════════════════════════════════════════════════════
        // PAYMENTS & BILLING
        // ═══════════════════════════════════════════════════════════════

        $this->register([
            'id'       => 'stripe_payments',
            'name'     => 'VMO Pay',
            'category' => 'payments',
            'summary'  => 'Accept online payments through VMO Pay. Process cards, subscriptions, and invoices inside VMO.',
            'can_do'   => [
                'Guide VMO Pay setup and payment account verification',
                'Process credit card payments',
                'Create and manage subscriptions',
                'Generate invoices',
                'CFO-style payments dashboard with revenue analytics',
                'Token-based usage billing for VMO services',
            ],
            'user_guide' => 'Users set up VMO Pay in the Payments section. VMO handles the onboarding flow.',
            'priority' => 1,
        ]);

        $this->register([
            'id'       => 'tax_calculator',
            'name'     => 'Tax Calculator',
            'category' => 'payments',
            'summary'  => 'Automatic sales tax calculation based on location for invoices and payments.',
            'can_do'   => [
                'Calculate sales tax by state/region',
                'Apply tax rates to invoices automatically',
                'Support US tax jurisdictions',
            ],
            'priority' => 2,
        ]);

        $this->register([
            'id'       => 'token_economics',
            'name'     => 'VMO Credit Billing System',
            'category' => 'payments',
            'summary'  => 'VMO services (calls, optional SMS add-ons, email, AI) are billed in VMO Credits. 1,500 credits = $1.00. Usage pricing follows the approved provider-cost policy.',
            'can_do'   => [
                'Track VMO Credit balance per user',
                'Deduct credits automatically for each service usage',
                'Show credit costs transparently before actions',
                'Credit top-up via VMO Pay',
                'Detailed usage history and cost breakdown',
            ],
            'user_guide' => 'Every paid VMO service costs VMO Credits. 1,500 credits = $1.00. Users buy credits through VMO Pay and they\'re auto-deducted. SMS is optional: A2P brand registration is 13,500 credits one time, and campaign registration is 30,000 credits monthly.',
            'priority' => 3,
        ]);

        // ═══════════════════════════════════════════════════════════════
        // CRM & CONTACTS
        // ═══════════════════════════════════════════════════════════════

        $this->register([
            'id'       => 'crm',
            'name'     => 'Built-in CRM',
            'category' => 'crm',
            'summary'  => 'Contact management, lead tracking, communication history, and customer relationship tools.',
            'can_do'   => [
                'Store and manage contacts with full profiles',
                'Track communication history (calls, emails, SMSs) per contact',
                'Lead scoring and pipeline management',
                'Import/export contacts',
                'Auto-sync new VMO users as CRM contacts (for admin)',
                'Tag and segment contacts for targeted campaigns',
            ],
            'priority' => 1,
        ]);

        $this->register([
            'id'       => 'lead_discovery',
            'name'     => 'AI Lead Discovery',
            'category' => 'crm',
            'summary'  => 'AI-powered lead generation — finds potential customers based on business profile and market analysis.',
            'can_do'   => [
                'Discover potential leads based on industry and location',
                'Enrich leads with business data',
                'Add discovered leads to CRM automatically',
                'AI-scored lead quality ranking',
            ],
            'priority' => 2,
        ]);

        // ═══════════════════════════════════════════════════════════════
        // WEBSITE BUILDER
        // ═══════════════════════════════════════════════════════════════

        $this->register([
            'id'       => 'website_builder',
            'name'     => 'AI Website Generator',
            'category' => 'website',
            'summary'  => 'Generates complete, SEO-optimized websites from business consultation data. Live preview with real-time editing.',
            'can_do'   => [
                'Generate full multi-section websites from consultation data',
                'Live preview with real-time editing in iframe',
                'Section-by-section content refinement via AI',
                'Professional templates with responsive design',
                'AI-powered copywriting that matches business voice',
                'Media integration (images, video placeholders, 360° viewers)',
                'One-click publish to WordPress',
            ],
            'user_guide' => 'Users complete the Business Wizard consultation, then VMO generates their website. They can refine it by talking to Jarvis or using the visual editor.',
            'priority' => 1,
        ]);

        $this->register([
            'id'       => 'templates',
            'name'     => 'Website Templates',
            'category' => 'website',
            'summary'  => 'Professional website templates organized by industry. AI adapts content to the user\'s specific business.',
            'can_do'   => [
                'Browse templates by industry/category',
                'Preview templates before applying',
                'AI adapts template content to user\'s business profile',
                'Custom CSS/styling overrides',
            ],
            'priority' => 2,
        ]);

        $this->register([
            'id'       => 'forms',
            'name'     => 'Form Builder',
            'category' => 'website',
            'summary'  => 'Built-in form builder with contact forms, newsletter signups, booking forms, and more.',
            'can_do'   => [
                'Contact forms with email routing',
                'Newsletter signup forms',
                'Booking/appointment request forms',
                'Custom field types',
                'Form submissions stored in CRM',
            ],
            'priority' => 3,
        ]);

        // ═══════════════════════════════════════════════════════════════
        // SEO & ANALYTICS
        // ═══════════════════════════════════════════════════════════════

        $this->register([
            'id'       => 'seo',
            'name'     => 'SEO Auditing & Optimization',
            'category' => 'seo',
            'summary'  => 'AI-powered SEO analysis, keyword optimization, meta tag generation, and competitor monitoring.',
            'can_do'   => [
                'Audit website pages for SEO issues',
                'Generate optimized meta titles and descriptions',
                'Keyword research and recommendations',
                'Competitor SEO monitoring',
                'Content optimization suggestions',
                'Schema markup generation',
            ],
            'priority' => 1,
        ]);

        $this->register([
            'id'       => 'kpi_dashboard',
            'name'     => 'KPI Dashboard',
            'category' => 'seo',
            'summary'  => 'Business performance dashboard with key metrics, growth tracking, and actionable insights.',
            'can_do'   => [
                'Display key business KPIs in real-time',
                'Track growth trends over time',
                'AI-generated business insights and recommendations',
                'Daily performance summaries',
            ],
            'priority' => 2,
        ]);

        // ═══════════════════════════════════════════════════════════════
        // MARKETING
        // ═══════════════════════════════════════════════════════════════

        $this->register([
            'id'       => 'deep_research',
            'name'     => 'Deep Market Research',
            'category' => 'marketing',
            'summary'  => 'AI-powered market research during consultation — competitor analysis, market sizing, positioning strategy.',
            'can_do'   => [
                'Live competitor research with real company data',
                'Market size and opportunity analysis',
                'Positioning strategy recommendations',
                'Industry trend analysis',
                'SWOT analysis generation',
            ],
            'priority' => 1,
        ]);

        $this->register([
            'id'       => 'content_crawler',
            'name'     => 'Content Crawler',
            'category' => 'marketing',
            'summary'  => 'Crawls competitor websites and market data to inform business strategy and content creation.',
            'can_do'   => [
                'Crawl competitor websites for content analysis',
                'Extract key messaging and positioning data',
                'Feed insights into website generation and SEO',
            ],
            'priority' => 2,
        ]);

        // ═══════════════════════════════════════════════════════════════
        // SHIPPING & E-COMMERCE
        // ═══════════════════════════════════════════════════════════════

        $this->register([
            'id'       => 'shipping',
            'name'     => 'Shipping Dashboard',
            'category' => 'shipping',
            'summary'  => 'Shipping management and tracking integration for e-commerce businesses.',
            'can_do'   => [
                'Track shipments from the dashboard',
                'Integration with major shipping carriers',
                'Shipping rate calculations',
                'Order fulfillment management',
            ],
            'priority' => 1,
        ]);

        // ═══════════════════════════════════════════════════════════════
        // DOCUMENTS & LEGAL
        // ═══════════════════════════════════════════════════════════════

        $this->register([
            'id'       => 'documents',
            'name'     => 'AI Document Generator',
            'category' => 'documents',
            'summary'  => 'Generates business documents — contracts, proposals, privacy policies, terms of service, NDAs, and more.',
            'can_do'   => [
                'Generate legal documents (privacy policy, terms of service, NDA)',
                'Create business proposals and contracts',
                'AI-tailored to user\'s specific business and jurisdiction',
                'Export to PDF',
                'Document templates library',
            ],
            'user_guide' => 'Users can generate legal and business documents from the dashboard. AI customizes each document based on the business profile from consultation.',
            'priority' => 1,
        ]);

        // ═══════════════════════════════════════════════════════════════
        // MEDIA & CONTENT
        // ═══════════════════════════════════════════════════════════════

        $this->register([
            'id'       => 'media_generation',
            'name'     => 'AI Media Generator',
            'category' => 'media',
            'summary'  => 'Generate images, graphics, and media assets using AI for websites and marketing.',
            'can_do'   => [
                'AI image generation for website sections',
                'Logo and branding asset creation',
                'Social media graphics',
                'Product photography enhancement',
                '360° product spin viewer',
                'Animated overlays and effects',
            ],
            'priority' => 1,
        ]);

        $this->register([
            'id'       => 'video_generation',
            'name'     => 'AI Video Generator',
            'category' => 'media',
            'summary'  => 'AI video generation for promotional and marketing content.',
            'can_do'   => [
                'Generate promotional videos from text prompts',
                'Create product demo videos',
                'Marketing content video creation',
            ],
            'priority' => 2,
        ]);

        $this->register([
            'id'       => 'tts',
            'name'     => 'HD Text-to-Speech',
            'category' => 'media',
            'summary'  => 'High-quality text-to-speech via AI TTS for phone greetings, voicemail, and content.',
            'can_do'   => [
                'Generate HD voice audio from text',
                'Multiple voice options',
                'Phone greeting and voicemail recording',
                'Audio content for websites',
            ],
            'priority' => 3,
        ]);

        // ═══════════════════════════════════════════════════════════════
        // AI AGENTS
        // ═══════════════════════════════════════════════════════════════

        $this->register([
            'id'       => 'business_wizard',
            'name'     => 'Business Wizard (Consultation AI)',
            'category' => 'ai',
            'summary'  => 'Voice-driven business consultation that builds the user\'s entire business setup — website, operations, strategy.',
            'can_do'   => [
                'Guided voice consultation (multi-phase)',
                'Live market research during conversation',
                'Business profile generation from conversation data',
                'Automatic website generation from consultation',
                'Systems setup (phone, email, payments, CRM) from consultation answers',
                'Persistent consultation memory across sessions',
                'Multilingual capability',
            ],
            'user_guide' => 'This is the RED "Business Wizard" button at the top. Users click it to start a voice consultation that builds their entire business.',
            'priority' => 1,
        ]);

        $this->register([
            'id'       => 'website_ai_assistant',
            'name'     => 'Website AI Assistant',
            'category' => 'ai',
            'summary'  => 'AI agent that refines and improves the generated website based on user instructions.',
            'can_do'   => [
                'Edit website sections via natural language commands',
                'Suggest improvements based on business goals',
                'Update content, layout, colors, and styling',
                'Add/remove/reorder website sections',
            ],
            'priority' => 2,
        ]);

        // ═══════════════════════════════════════════════════════════════
        // ADMIN & SYSTEM
        // ═══════════════════════════════════════════════════════════════

        $this->register([
            'id'       => 'master_admin',
            'name'     => 'Master Admin Dashboard',
            'category' => 'admin',
            'summary'  => 'Plugin owner\'s admin panel — manage all users, plans, affiliates, and system settings.',
            'can_do'   => [
                'Manage all VMO users and their plans',
                'View and manage affiliate commissions',
                'System-wide settings and configuration',
                'User activity monitoring',
                'Revenue and usage analytics',
            ],
            'priority' => 1,
        ]);

        $this->register([
            'id'       => 'affiliate_system',
            'name'     => 'Affiliate System',
            'category' => 'admin',
            'summary'  => 'Built-in affiliate program — 5% commission on all referred user payments.',
            'can_do'   => [
                'Affiliate signup and link generation',
                'Track referrals and conversions',
                'Calculate 5% commissions automatically',
                'Commission payout management',
            ],
            'priority' => 2,
        ]);

        $this->register([
            'id'       => 'membership',
            'name'     => 'Membership & Plans',
            'category' => 'admin',
            'summary'  => 'User membership tiers with feature gating. Free, Starter, Pro, Enterprise plans.',
            'can_do'   => [
                'Multiple pricing tiers with different feature access',
                'Monthly and annual billing (pay 11 months, get 1 free)',
                'Plan upgrades and downgrades',
                'Feature gating based on plan level',
                'Plan-gated feature access',
            ],
            'priority' => 3,
        ]);

        $this->register([
            'id'       => 'ticketing',
            'name'     => 'Support Ticketing System',
            'category' => 'admin',
            'summary'  => 'Built-in support ticket system for user help requests.',
            'can_do'   => [
                'Users can create support tickets from the dashboard',
                'Ticket tracking and status updates',
                'Admin can respond to tickets',
                'Email notifications for ticket updates',
            ],
            'priority' => 4,
        ]);

        // ═══════════════════════════════════════════════════════════════
        // SECURITY & COMPLIANCE
        // ═══════════════════════════════════════════════════════════════

        $this->register([
            'id'       => 'a2p_compliance',
            'name'     => 'A2P 10DLC Compliance',
            'category' => 'security',
            'summary'  => 'Automated compliance registration for US carrier SMS regulations.',
            'can_do'   => [
                'Register brands with Twilio Trust Hub',
                'Submit campaigns for carrier approval',
                'Auto-monitor approval status',
                'ISV linkage for consolidated compliance',
            ],
            'priority' => 1,
        ]);

        $this->register([
            'id'       => 'cloudflare',
            'name'     => 'Cloudflare Integration',
            'category' => 'security',
            'summary'  => 'DNS management and security via Cloudflare API.',
            'can_do'   => [
                'Manage DNS records via Cloudflare API',
                'CDN and security configuration',
                'SSL certificate management',
            ],
            'priority' => 2,
        ]);

        // ═══════════════════════════════════════════════════════════════
        // THIRD-PARTY INTEGRATIONS
        // ═══════════════════════════════════════════════════════════════

        $this->register([
            'id'       => 'twilio_integration',
            'name'     => 'Twilio (Phone/SMS)',
            'category' => 'integration',
            'summary'  => 'Core telephony provider — powers calls, SMS, number provisioning, IVR, and voicemail.',
            'can_do'   => [
                'Phone number provisioning (local & toll-free)',
                'VoIP calling (WebRTC)',
                'SMS send/receive',
                'IVR and call routing',
                'Call recording and voicemail',
                'A2P 10DLC registration',
            ],
            'priority' => 1,
        ]);

        $this->register([
            'id'       => 'stripe_integration',
            'name'     => 'VMO Pay',
            'category' => 'integration',
            'summary'  => 'Payment processing through VMO Pay for user revenue collection.',
            'priority' => 2,
        ]);

        $this->register([
            'id'       => 'openai_integration',
            'name'     => 'AI Engine',
            'category' => 'integration',
            'summary'  => 'Powers all AI features — fast models for live tasks, strategic models for generation and QA, AI image generation, realtime voice, and AI video.',
            'priority' => 3,
        ]);

        $this->register([
            'id'       => 'zoho_integration',
            'name'     => 'Zoho Mail (Email)',
            'category' => 'integration',
            'summary'  => 'Bundled email provider. OAuth API integration for automated email account provisioning.',
            'priority' => 4,
        ]);

        /**
         * Allow themes/other plugins to register additional capabilities.
         * 
         * @param VMO_Capability_Registry $registry The registry instance
         */
        do_action('vmo_register_capabilities', $this);
    }
}

// ═══════════════════════════════════════════════════════════════════
// GLOBAL HELPER FUNCTION
// ═══════════════════════════════════════════════════════════════════

/**
 * Register a VMO capability from anywhere.
 * Can be called in any class constructor or on 'init' hook.
 *
 * @param array $capability See VMO_Capability_Registry::register() for schema
 */
function vmo_register_capability(array $capability): void {
    VMO_Capability_Registry::get_instance()->register($capability);
}

/**
 * Get the formatted prompt block of all VMO capabilities.
 * Used internally by generate-content.php to inject into Jarvis system prompt.
 *
 * @return string
 */
function vmo_get_capabilities_prompt(): string {
    return VMO_Capability_Registry::get_instance()->get_prompt_block();
}
