<?php
/**
 * Canonical VMO platform FAQ and AI grounding source.
 */

if (!function_exists('vmo_get_platform_pricing_matrix')) {
    function vmo_get_platform_pricing_matrix(): array {
        return array(
            'direct_wordpress' => array(
                'label' => 'Existing WordPress / Direct Plugin',
                'note' => 'For customers who already have WordPress, hosting, or a domain and want to install VMO into their own site.',
                'plans' => array(
                    array('name' => 'Tester', 'monthly' => '$49.99/month', 'annual' => 'Monthly only'),
                    array('name' => 'Starter', 'monthly' => '$99.99/month', 'annual' => '$1,099.89/year'),
                    array('name' => 'Pro', 'monthly' => '$199.99/month', 'annual' => '$2,199.89/year'),
                    array('name' => 'Elite', 'monthly' => '$499.99/month', 'annual' => '$5,499.89/year'),
                    array('name' => 'Enterprise', 'monthly' => '$999.99/month', 'annual' => '$10,999.89/year'),
                ),
            ),
            'vmo_hosted_quicklaunch' => array(
                'label' => 'VMO Hosted QuickLaunch',
                'note' => 'For customers who want VMO to guide the website and business setup from the beginning. Hosted pricing adds $50/month to the matching direct WordPress plan. Annual saves one full month (×11 months billed for 12 months of service). Tester is monthly only.',
                'plans' => array(
                    array('name' => 'Tester', 'monthly' => '$99.99/month', 'annual' => 'Monthly only'),
                    array('name' => 'Starter', 'monthly' => '$149.99/month', 'annual' => '$1,649.89/year'),
                    array('name' => 'Pro', 'monthly' => '$249.99/month', 'annual' => '$2,749.89/year'),
                    array('name' => 'Elite', 'monthly' => '$549.99/month', 'annual' => '$6,049.89/year'),
                    array('name' => 'Enterprise', 'monthly' => '$1,049.99/month', 'annual' => '$11,549.89/year'),
                ),
            ),
        );
    }
}

if (!function_exists('vmo_get_platform_faq_sections')) {
    function vmo_get_platform_faq_sections(): array {
        return array(
            array(
                'key' => 'website-generation',
                'title' => 'Website Generation',
                'items' => array(
                    array(
                        'question' => 'Can VMO create a brand new website from scratch?',
                        'answer' => 'Yes. VMO can generate a complete new website from scratch after the business consultation. This is a core VMO capability.',
                    ),
                    array(
                        'question' => 'Can VMO rebuild or modernize an existing website?',
                        'answer' => 'Yes. VMO can work with an existing WordPress site, domain, or business context and help improve, modernize, rebuild, or replace the current website where appropriate.',
                    ),
                    array(
                        'question' => 'Does VMO force every business into the same template?',
                        'answer' => 'No. VMO uses the consultation, business research, services, audience, offers, and goals to shape a business-specific website instead of forcing a generic template.',
                    ),
                    array(
                        'question' => 'Is the website public as soon as it is generated?',
                        'answer' => 'No. The generated website should be reviewed in the builder first. The user can inspect, refine, preview, and publish when ready.',
                    ),
                    array(
                        'question' => 'Is the public website tied to WordPress at runtime?',
                        'answer' => 'No. WordPress is the VMO dashboard, staging, and editing shell. The generated site is planned as a premium React-style, componentized frontend with scoped styling, safe scripts, resolved media, SEO metadata, VMO tracking/form/payment contracts, and Next.js-compatible export options, so the public site can run outside WordPress without wp-admin, admin-ajax, wp-json, plugin, or theme dependencies.',
                    ),
                ),
            ),
            array(
                'key' => 'quicklaunch-onboarding',
                'title' => 'QuickLaunch and Onboarding',
                'items' => array(
                    array(
                        'question' => 'What is QuickLaunch?',
                        'answer' => 'QuickLaunch is the guided onboarding process into VMO. It helps get the practical basics set up so a business owner can own a website, access the platform, and start running the business without having to figure out the technical setup alone.',
                    ),
                    array(
                        'question' => 'Is QuickLaunch the same as Jerreme?',
                        'answer' => 'No. QuickLaunch helps get you into VMO and sets up the basics. Jerreme is VMO\'s specialized AI business consultant: it learns about the business, uses supporting AI agents for research and planning, then guides the creation of the website, business email, phone setup, strategy, content, and other launch pieces based on the consultation.',
                    ),
                    array(
                        'question' => 'Do I need to understand hosting or DNS to use QuickLaunch?',
                        'answer' => 'No. On the managed VMO cloud path, the goal is to reduce or remove as much technical burden as possible.',
                    ),
                    array(
                        'question' => 'What are the VMO Hosted QuickLaunch prices?',
                        'answer' => 'VMO Hosted QuickLaunch pricing is: Tester $99.99/month (monthly only — no annual option); Starter $149.99/month or $1,649.89/year; Pro $249.99/month or $2,749.89/year; Elite $549.99/month or $6,049.89/year; Enterprise $1,049.99/month or $11,549.89/year. Annual plans save one full month (11 months billed for 12 months of service).',
                    ),
                ),
            ),
            array(
                'key' => 'existing-wordpress',
                'title' => 'Existing WordPress Install',
                'items' => array(
                    array(
                        'question' => 'What if I already have my own WordPress site?',
                        'answer' => 'VMO can still help. Existing WordPress users can install the direct plugin and use their current domain, hosting, or website environment where appropriate.',
                    ),
                    array(
                        'question' => 'Can existing WordPress users still generate a new website?',
                        'answer' => 'Yes. Having an existing WordPress site does not stop VMO from generating a new website from scratch or rebuilding the current site.',
                    ),
                    array(
                        'question' => 'What are the direct WordPress prices?',
                        'answer' => 'Direct WordPress pricing is: Tester $49.99/month (monthly only — no annual option); Starter $99.99/month or $1,099.89/year; Pro $199.99/month or $2,199.89/year; Elite $499.99/month or $5,499.89/year; Enterprise $999.99/month or $10,999.89/year. Annual plans save one full month (11 months billed for 12 months of service).',
                    ),
                    array(
                        'question' => 'Why are hosted prices higher than direct WordPress prices?',
                        'answer' => 'The hosted lane adds $50/month to the matching direct WordPress plan because it includes the guided hosted/provisioned path (managed Vultr server, configured domain and DNS, business email mailboxes, automated SSL, daily backups) rather than only the plugin installed on a site the customer already controls.',
                    ),
                ),
            ),
            array(
                'key' => 'jerreme-consultant',
                'title' => 'Jerreme AI Business Consultant',
                'items' => array(
                    array(
                        'question' => 'What is Jerreme?',
                        'answer' => 'Jerreme is VMO\'s specialized AI business consultant. It leads the business consultation, gathers the important details, uses supporting AI agents for research and planning, and helps turn that information into a website, strategy, business email, phone setup, content, and the core systems the user needs to start operating.',
                    ),
                    array(
                        'question' => 'Can Jerreme help if I do not know what business to start?',
                        'answer' => 'Yes. Jerreme can help identify a suitable business direction by looking at the user\'s interests, strengths, location, and market environment.',
                    ),
                    array(
                        'question' => 'Can Jerreme help if I already know what business I want?',
                        'answer' => 'Yes. Jerreme helps structure the idea professionally, research the market around it, refine the strategy, and prepare the systems needed to run it.',
                    ),
                    array(
                        'question' => 'Does Jerreme do competitor and SEO research?',
                        'answer' => 'Yes. Jerreme is designed to research competitors, industry conditions, audience behavior, SEO patterns, keyword strategy, and opportunities for stronger positioning.',
                    ),
                    array(
                        'question' => 'What happens after Jerreme finishes?',
                        'answer' => 'The user should be handed off to VMO / Jarvis, which becomes the ongoing business assistant for refinement, support, navigation, and daily operations.',
                    ),
                ),
            ),
            array(
                'key' => 'website-builder',
                'title' => 'Website Builder and Live Preview',
                'items' => array(
                    array(
                        'question' => 'What is the Website Builder / Live Preview Interface?',
                        'answer' => 'It is the main website review and publishing workspace inside VMO. It shows the generated site, allows refinements, and supports the publish workflow.',
                    ),
                    array(
                        'question' => 'Can I check how the site looks on mobile?',
                        'answer' => 'Yes. The builder includes desktop, tablet, and mobile preview controls so the user can review responsiveness before publishing.',
                    ),
                    array(
                        'question' => 'Can I replace images or videos?',
                        'answer' => 'Yes. The builder is designed to support media replacement through in-builder controls, while keeping those controls hidden from the public frontend.',
                    ),
                    array(
                        'question' => 'What is the difference between Save, Publish, and Update Live?',
                        'answer' => 'Save stores the current work state, Publish makes the site publicly live for the first time, and Update Live pushes approved changes to an already published site.',
                    ),
                    array(
                        'question' => 'What happens if I want to start over?',
                        'answer' => 'The builder includes reset safety tools. The intended behavior is backup-first protection, with restore options that bring a prior state back as an unpublished draft.',
                    ),
                ),
            ),
            array(
                'key' => 'jarvis-ai',
                'title' => 'Jarvis Coordinating AI',
                'items' => array(
                    array(
                        'question' => 'What is Jarvis in VMO?',
                        'answer' => 'Jarvis is the coordinating AI assistant users can speak to or type to across the dashboard when they need help understanding the platform, navigating tools, making changes, or getting quick answers.',
                    ),
                    array(
                        'question' => 'Is Jarvis the same as Jerreme?',
                        'answer' => 'No. Jerreme handles consultation and foundation-building. Jarvis helps after that by coordinating navigation, refinement, support, and ongoing operations.',
                    ),
                    array(
                        'question' => 'Can users ask Jarvis normal questions?',
                        'answer' => 'Yes. Users should be able to ask in natural language, such as where to activate SMS, what needs attention today, or how to improve a website section.',
                    ),
                    array(
                        'question' => 'Does Jarvis replace the specialized tools?',
                        'answer' => 'No. Jarvis coordinates the experience. It may answer directly, guide the user to the right tool, or work with a more specialized VMO system when needed.',
                    ),
                ),
            ),
            array(
                'key' => 'ai-phone-sms',
                'title' => 'AI Phone and SMS',
                'items' => array(
                    array(
                        'question' => 'What does the AI phone receptionist do?',
                        'answer' => 'The AI phone receptionist greets callers, answers from approved business knowledge, captures the reason for calling, collects contact details, takes messages, and supports callbacks or routing where configured.',
                    ),
                    array(
                        'question' => 'Can the AI receptionist confirm that VMO builds websites from scratch?',
                        'answer' => 'Yes. If a caller asks, the correct answer is yes: VMO can generate complete websites from scratch after consultation and can also rebuild existing websites.',
                    ),
                    array(
                        'question' => 'Does VMO support live call control?',
                        'answer' => 'Yes. The phone system is designed to support live call control, listen/take-over behavior, call state visibility, and a unified live-call experience for regular calls and Power Dialer calls.',
                    ),
                    array(
                        'question' => 'Do calls feed the rest of the business system?',
                        'answer' => 'Yes. Meaningful calls should generate reports and feed CRM, Actions, Today, call history, and KPI interpretation where relevant.',
                    ),
                ),
            ),
            array(
                'key' => 'ai-email',
                'title' => 'AI Email and Auto Reply',
                'items' => array(
                    array(
                        'question' => 'What does the AI email feature do?',
                        'answer' => 'The AI email feature helps draft, refine, and respond to emails using the business context, products, offers, calls to action, and approved facts.',
                    ),
                    array(
                        'question' => 'Can VMO auto-reply to ordinary emails?',
                        'answer' => 'Yes, where configured. Ordinary informational questions may be answered automatically from approved context, while sensitive or binding replies should require user approval.',
                    ),
                    array(
                        'question' => 'When should email replies require approval?',
                        'answer' => 'Approval is needed for refunds, legal answers, identity verification, complaints, custom order commitments, appointments, availability confirmations, or anything that binds the business.',
                    ),
                    array(
                        'question' => 'Do email events connect to CRM and reports?',
                        'answer' => 'Yes. Incoming and outgoing emails should enrich contact records, create actions where needed, and feed reports, Today, and broader business intelligence.',
                    ),
                ),
            ),
            array(
                'key' => 'plans-credits',
                'title' => 'Plans, Pricing, and Credits',
                'items' => array(
                    array(
                        'question' => 'What is the difference between plans and credits?',
                        'answer' => 'Plans define capability level, automation depth, scan frequency, dashboard richness, and access to business-system features. Credits or tokens cover usage such as AI generation, media, phone, SMS, TTS, and other metered activity.',
                    ),
                    array(
                        'question' => 'What happens when credits get low?',
                        'answer' => 'VMO warns users when credits are low so they can top up before work is interrupted. The current low-credit warning threshold is 40%.',
                    ),
                    array(
                        'question' => 'What happens at zero credits?',
                        'answer' => 'When VMO Credit reaches zero, the purchased usage for metered AI and communication actions has been used up, so those actions need more available credit before they can continue. The user can add a one-time booster/top-up or move to a plan with a larger credit allowance. Essential checkout, recovery, account status, and public-safe flows remain available so the user can add credit or update the plan.',
                    ),
                    array(
                        'question' => 'What add-on prices should VMO quote?',
                        'answer' => 'Add-on pricing is: Small add-on $19.99 one-time; Medium add-on $49.99 one-time; Large add-on $99.99 one-time; Phone Pack M $99.99/year; Phone Pack L $249.99/year; Power Dialer $499.99/year; Pro Call Center $699.99/year.',
                    ),
                ),
            ),
            array(
                'key' => 'business-tools',
                'title' => 'Business Tools',
                'items' => array(
                    array(
                        'question' => 'Does VMO include CRM tools?',
                        'answer' => 'Yes. VMO is designed to connect leads, customers, lifecycle stages, relationship categories, form submissions, calls, messages, orders, and business actions into CRM-style records and dashboard visibility.',
                    ),
                    array(
                        'question' => 'Does VMO handle SEO?',
                        'answer' => 'Yes. VMO can generate SEO strategy, drafts, pages, reports, recommendations, and ecommerce-aware SEO context where applicable, with public-facing or high-risk changes routed for approval.',
                    ),
                    array(
                        'question' => 'What do Today, Reports, KPIs, and CFO tools do?',
                        'answer' => 'They work together as one business intelligence loop: today\'s actions, reports, KPI snapshots, revenue signals, strategic recommendations, CFO-style insight, and ongoing improvement tasks.',
                    ),
                    array(
                        'question' => 'Does VMO support ecommerce, services, payments, and shipping?',
                        'answer' => 'Yes. VMO can support products, services, payment collection through VMO Pay, checkout flows, shipping context, product content, and business-specific sales pages when configured.',
                    ),
                ),
            ),
            array(
                'key' => 'security-affiliates',
                'title' => 'Security, Updates, and Affiliates',
                'items' => array(
                    array(
                        'question' => 'Are sensitive platform settings stored in client packages?',
                        'answer' => 'No. Client packages should not expose master-only settings, confidential keys, product IDs, price IDs, webhook secrets, or master administration tools. Client sites call the master through approved endpoints where needed.',
                    ),
                    array(
                        'question' => 'Can VMO update client installations?',
                        'answer' => 'VMO includes a master-side client update direction so hosted/client installations can receive managed releases from the master update infrastructure rather than exposing master internals in client packages.',
                    ),
                    array(
                        'question' => 'Does VMO have an affiliate program?',
                        'answer' => 'Yes. VMO supports affiliate signup, referral tracking, partner dashboards, referral landing pages, tester/reviewer codes, discounts, rewards, bonuses, compensations, audit logging, and 5% affiliate commissions based on the actual paid amount where configured.',
                    ),
                ),
            ),
        );
    }
}

if (!function_exists('vmo_get_platform_faq_items')) {
    function vmo_get_platform_faq_items(string $section_key = ''): array {
        $items = array();
        foreach (vmo_get_platform_faq_sections() as $section) {
            if ($section_key !== '' && ($section['key'] ?? '') !== $section_key) {
                continue;
            }
            foreach (($section['items'] ?? array()) as $item) {
                $item['section_key'] = $section['key'] ?? '';
                $item['section_title'] = $section['title'] ?? '';
                $items[] = $item;
            }
        }
        return $items;
    }
}

if (!function_exists('vmo_platform_faq_compact_price_lines')) {
    function vmo_platform_faq_compact_price_lines(): array {
        $lines = array();
        foreach (vmo_get_platform_pricing_matrix() as $key => $group) {
            $plan_lines = array();
            foreach (($group['plans'] ?? array()) as $plan) {
                $plan_lines[] = ($plan['name'] ?? '') . ' ' . ($plan['monthly'] ?? '') . ' or ' . ($plan['annual'] ?? '');
            }
            $lines[] = ($group['label'] ?? $key) . ': ' . implode('; ', $plan_lines) . '.';
        }
        $lines[] = 'Add-ons: Small add-on $19.99 one-time; Medium add-on $49.99 one-time; Large add-on $99.99 one-time; Phone Pack M $99.99/year; Phone Pack L $249.99/year; Power Dialer $499.99/year; Pro Call Center $699.99/year.';
        return $lines;
    }
}

if (!function_exists('vmo_get_platform_faq_grounding_text')) {
    function vmo_get_platform_faq_grounding_text(string $audience = 'customer_ai', int $max_chars = 12000): string {
        $lines = array(
            'VMO FAQ SOURCE OF TRUTH - use this before any other website text or generic model knowledge for VMO product, pricing, plan, hosted/direct, website-generation, phone, email, customer communication, affiliate, and support questions.',
            'If this FAQ conflicts with another page, scraped content, or a generic assumption, this FAQ wins. If a specific detail is not in the FAQ or approved business context, collect contact information and offer follow-up instead of inventing facts.',
            'Critical correction: VMO DOES create and generate complete websites from scratch after the business consultation. VMO also improves, modernizes, rebuilds, or replaces existing websites for customers who already have WordPress/domain/hosting. Never say VMO cannot build a website from scratch.',
            'Price categories must stay separated: VMO Hosted QuickLaunch prices belong under the hosted option; Existing WordPress / Direct Plugin prices belong under the direct WordPress option.',
        );

        $lines = array_merge($lines, vmo_platform_faq_compact_price_lines());

        foreach (vmo_get_platform_faq_sections() as $section) {
            $lines[] = 'FAQ Section: ' . ($section['title'] ?? '');
            foreach (($section['items'] ?? array()) as $item) {
                $question = trim((string) ($item['question'] ?? ''));
                $answer = trim((string) ($item['answer'] ?? ''));
                if ($question === '' || $answer === '') {
                    continue;
                }
                $lines[] = 'Q: ' . $question;
                $lines[] = 'A: ' . $answer;
            }
        }

        $text = implode("\n", $lines);
        if ($max_chars > 0 && strlen($text) > $max_chars) {
            $text = substr($text, 0, max(0, $max_chars - 32)) . "\n[FAQ truncated]";
        }

        return $text;
    }
}

if (!function_exists('vmo_platform_faq_should_ground_current_site')) {
    function vmo_platform_faq_should_ground_current_site(string $business_name = '', string $website = ''): bool {
        $parts = array($business_name, $website);

        if (function_exists('home_url')) {
            $parts[] = (string) home_url('/');
        }
        if (function_exists('get_bloginfo')) {
            $parts[] = (string) get_bloginfo('name');
            $parts[] = (string) get_bloginfo('description');
        }

        $haystack = strtolower(implode(' ', array_filter($parts, 'strlen')));
        if ($haystack === '') {
            return false;
        }

        return strpos($haystack, 'getvmo.com') !== false
            || strpos($haystack, 'virtual media office') !== false
            || preg_match('/(^|[^a-z0-9])vmo([^a-z0-9]|$)/', $haystack) === 1;
    }
}