<?php
/**
 * GT BOGO Engine - Documentation (Complete Edition)
 * @package GT_BOGO_Engine
 * @since   3.10.1
 */
if (!defined('ABSPATH')) exit;

$is_pro      = function_exists('gt_bogo_has_pro') ? gt_bogo_has_pro() : false;
$current_doc = isset($_GET['doc']) ? sanitize_key($_GET['doc']) : '';

/* ── RENDER HELPER ─────────────────────────────────────── */
function gtbogo_doc_body($text) {
    $lines = explode("\n", $text);
    $out   = '';
    $in_ul = false;
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '') {
            if ($in_ul) { $out .= '</ul>'; $in_ul = false; }
            $out .= '<div style="height:12px"></div>';
            continue;
        }
        $line = preg_replace('/\*\*(.+?)\*\*/', '<strong style="color:#ffffff">$1</strong>', $line);
        $line = preg_replace('/`(.+?)`/', '<code style="background:rgba(255,255,255,0.07);padding:2px 6px;border-radius:4px;font-size:13px;color:#fbbf24">$1</code>', $line);

        if (substr($line, 0, 2) === '* ') {
            if (!$in_ul) { $out .= '<ul style="list-style:none;padding:0;margin:0 0 4px">'; $in_ul = true; }
            $out .= '<li style="display:flex;align-items:flex-start;gap:10px;margin-bottom:8px"><span style="color:#E10000;font-size:10px;margin-top:6px;flex-shrink:0">&#9679;</span><span style="font-size:14px;color:#94a3b8;line-height:1.65">' . wp_kses_post(substr($line,2)) . '</span></li>';
            continue;
        }
        if ($in_ul) { $out .= '</ul>'; $in_ul = false; }

        if (preg_match('/^([0-9]+)\. (.+)$/', $line, $m)) {
            $out .= '<div style="display:flex;gap:12px;margin-bottom:10px"><span style="color:#E10000;font-weight:800;font-size:14px;flex-shrink:0;min-width:22px">' . esc_html($m[1]) . '.</span><span style="font-size:14px;color:#94a3b8;line-height:1.65">' . wp_kses_post($m[2]) . '</span></div>';
            continue;
        }
        if ($line === strtoupper($line) && strlen($line) > 5 && !preg_match('/[<>]/', $line)) {
            $out .= '<div style="font-size:11px;font-weight:900;color:#E10000;letter-spacing:1.5px;text-transform:uppercase;margin:22px 0 10px;padding-bottom:8px;border-bottom:1px solid rgba(225,0,0,0.15)">' . esc_html($line) . '</div>';
            continue;
        }
        if (preg_match('/^-{3,}$/', $line)) {
            $out .= '<hr style="border:none;border-top:1px solid rgba(255,255,255,0.06);margin:20px 0">';
            continue;
        }
        $out .= '<p style="font-size:14px;color:#94a3b8;line-height:1.75;margin:0 0 10px">' . wp_kses_post($line) . '</p>';
    }
    if ($in_ul) $out .= '</ul>';
    return $out;
}

$topics = [];

$topics['installation'] = [
'icon'  => '<span style="font-size:28px">⚙️</span>',
'emoji' => '⚙️',
'title' => 'Installation & Setup',
'desc'  => 'Step-by-step installation, first configuration, compatibility guide, and update procedures.',
'color' => '#3b82f6',
'sections' => [

['System Requirements',
'Before installing GT BOGO Engine, confirm your environment meets these requirements.

MINIMUM REQUIREMENTS
* **WordPress** 5.8 or higher — WordPress 6.4+ strongly recommended
* **WooCommerce** 6.0 or higher — WooCommerce 8.0+ recommended
* **PHP** 7.4 minimum — fully tested and certified on PHP 8.0, 8.1, 8.2, and 8.3
* **MySQL** 5.7+ or MariaDB 10.3+
* **HTTPS** — required for PayPal SDK (purchase buttons) and license verification
* **Outbound HTTPS** — your server must be able to connect to `graphictshirts.shop` for license checks and auto-updates

COMPATIBLE HOSTING ENVIRONMENTS
GT BOGO Engine has been tested on all major hosting types:

* **Shared hosting** — SiteGround, Bluehost, Namecheap, Hostinger, DreamHost
* **VPS / Cloud** — DigitalOcean, Linode, Vultr, Hetzner
* **Managed WordPress** — WP Engine, Kinsta, Flywheel, Cloudways, Pressable
* **LiteSpeed servers** — Webuzo, cPanel with LiteSpeed, OpenLiteSpeed

LITESPEED IMPORTANT NOTE
If your server runs LiteSpeed, never add `php_value` or `php_flag` directives to `.htaccess` — this causes immediate HTTP 500 errors on LiteSpeed. All PHP configuration must be done through your control panel (Webuzo, cPanel) only. GT BOGO Engine does not require any `.htaccess` modifications.

THEME AND PLUGIN COMPATIBILITY
GT BOGO Engine is compatible with all major WordPress themes including Divi, Elementor, Flatsome, Storefront, Astra, OceanWP, Avada, and Kadence. It works alongside WooCommerce Blocks, classic cart, and all major page builders. If you encounter a theme or plugin conflict, see the Troubleshooting guide.'],

['Installing the Plugin',
'INSTALLATION METHOD 1 — WORDPRESS ADMIN UPLOAD (recommended)

1. Download `gt-bogo-engine.zip` from your purchase confirmation email.
2. In your WordPress admin, navigate to **Plugins > Add New**.
3. Click **Upload Plugin** at the top of the page.
4. Click **Choose File**, select `gt-bogo-engine.zip`, and click **Install Now**.
5. When installation completes, click **Activate Plugin**.
6. You will be automatically redirected to the GT BOGO Engine Welcome screen.
7. GT BOGO ENGINE now appears in your WordPress sidebar.

INSTALLATION METHOD 2 — FTP / SFTP (use if upload fails due to server file size limits)

1. Extract `gt-bogo-engine.zip` on your local computer.
2. Connect to your server via FTP or SFTP using FileZilla or your preferred client.
3. Navigate to `/wp-content/plugins/` on your server.
4. Upload the entire extracted `gt-bogo-engine` folder into that directory.
5. In WordPress admin, go to **Plugins > Installed Plugins**.
6. Find GT BOGO Engine and click **Activate**.

WHAT HAPPENS AUTOMATICALLY ON ACTIVATION
On first activation, GT BOGO Engine automatically:
* Creates its database tables (`gtbogo_rules`, `gtbogo_analytics`, `gtbogo_audit_log`, `gtbogo_rate_limits`)
* Registers all default plugin settings with safe defaults
* Runs a full cache purge to ensure a clean start
* Sets up the auto-update checker pointing to the update server

This takes under 2 seconds and requires no action from you. You will not see any prompts or setup wizards — the plugin is ready to use immediately after activation.'],

['Activating Your PRO License',
'The Free Core Rule works immediately after installation — no license key is required to use it. To unlock PRO features, the full rule builder, and pack imports, you need to activate your PRO license.

STEP-BY-STEP LICENSE ACTIVATION

1. Go to **GT BOGO ENGINE > License** in your WordPress sidebar.
2. Locate the **License Key** field.
3. Copy your license key exactly from your purchase confirmation email. The key format is: `GTBOGO-XXXXX-XXXXX-XXXXX-XXXXX`
4. **Copy and paste** — do not retype it manually. Mistyped characters are the most common activation failure.
5. Click **Activate License**.
6. The page confirms activation instantly and shows your expiry date and days remaining.
7. PRO features unlock immediately — the sidebar updates to show all PRO pages.

WHAT YOUR PRO LICENSE UNLOCKS
* Up to 15 simultaneously active custom BOGO rules
* Full rule builder with all three rule types
* PRO Pack import system (15 packs available)
* All 11 advanced Superpowers
* Scheduler — date and time-based rule activation
* Segments — customer targeting by spend, order count, and tags
* ROI Projector
* Audit Log
* White Label customisation
* All PRECISION and GROWTH section features

LICENSE COVERS ONE SITE
Your license is registered to one domain. If you migrate to a new domain, go to **Settings > License > Deactivate** first, then reactivate on the new domain. No manual transfer request needed.

RETRIEVE A LOST LICENSE KEY
Never email asking for your license key. Use the secure self-service portal instead — your key is delivered directly to your purchase email after identity verification:
**https://graphictshirts.shop/bogo/retrieve-license.php**

LICENSE RENEWAL
Licenses are annual at $19.99/year. When your license expires, PRO features lock but your rules and settings are preserved in the database. Renew on the PRO Rules / Packs page — renewals stack, so renewing before expiry adds a full year to your remaining time.'],

['First-Time Configuration Checklist',
'Complete these steps in order after installation to get your first deal live and your store optimised.

STEP 1 — CONFIGURE THE FREE CORE RULE (all users, do this first)
Go to **GT BOGO ENGINE > Free Core Rule**. This is your always-available BOGO slot that requires no license. Configure:
* **Rule Name** — internal label, e.g. "Sitewide BOGO"
* **Buy Quantity** — 1 is the standard starting point
* **Get Quantity** — 1 for classic Buy 1 Get 1
* **Discount Type** — Percentage for proportional discounts, Fixed for specific dollar amounts
* **Discount Value** — 100 for free (100% off), 50 for half price
* **Status** — set to Active

Click **Save Rule**. Test immediately: add qualifying products to your WooCommerce cart and confirm the discount applies automatically.

STEP 2 — ENABLE THE TWO FREE SUPERPOWERS
Go to **Settings > Superpowers**. Enable both free superpowers:
* **Product Badges** — displays "BOGO Deal" badges on eligible product images across your shop
* **Cart Progress Bar** — shows customers how close they are to unlocking a deal

These two features alone typically increase BOGO deal engagement by 15–30%. They are free and require no license.

STEP 3 — ACTIVATE PRO LICENSE (PRO users)
See the Activating Your PRO License section above.

STEP 4 — PURCHASE AND IMPORT YOUR FIRST PRO PACK (PRO users)
Go to **PRO Rules / Packs** and browse the 15 available packs. Start with either the **Starter Revenue Bundle** (5 packs for $99) or the single pack most relevant to your current goal. After purchase, import via **Manual Pack Import** and activate the rules you want to run.

STEP 5 — ENABLE KEY PRO SUPERPOWERS (PRO users)
Enable these three together for the highest immediate impact:
* **Savings Display** — shows customers the exact dollar amount they are saving
* **Countdown Timer** — adds urgency to time-limited deals
* **Social Proof** — shows real-time notifications of other customers claiming deals

STEP 6 — VERIFY SYSTEM STATUS
Go to **Settings > System Status**. All indicators should show green. If anything is amber or red, the status page will describe the issue and how to resolve it.'],

['Updating the Plugin',
'GT BOGO Engine includes a built-in auto-update system that integrates directly with WordPress update notifications.

HOW UPDATES WORK
When a new version is available, WordPress shows an update notification on your **Plugins** page — identically to any plugin from the WordPress.org directory. Click **Update Now** to install. The update process takes under 30 seconds.

YOUR DATA IS ALWAYS SAFE
Rules, settings, owned pack data, analytics history, license information, and audit logs are all stored in the WordPress database. They are never modified by plugin updates. You will never lose your configuration by updating.

POST-UPDATE ACTIONS
After every update, GT BOGO Engine automatically:
* Runs a full cache purge (transients, object cache if available, OPcache if available)
* Checks for any required database migrations and runs them silently
* Re-verifies license status

MANUAL UPDATE (if automatic fails)
1. **Deactivate** the plugin (do not delete — this preserves all your data in the database)
2. Delete the plugin files
3. Upload and install the new zip
4. Activate — all your rules, settings, and analytics restore instantly from the database

BEFORE MAJOR VERSION UPDATES
Major updates (e.g. v3.x to v4.x) include migration steps. A changelog email is sent to your WordPress admin email address before major releases. Always read the changelog before applying major updates. Testing on a staging environment first is recommended for high-traffic stores.'],

['Troubleshooting Installation Issues',
'PLUGIN DOES NOT APPEAR AFTER UPLOAD
* The zip file may be corrupted. Re-download from your purchase email and try again.
* Your server upload limit may be too low. Contact your host and ask them to increase `upload_max_filesize` and `post_max_size`. Do not add these to `.htaccess` on LiteSpeed servers.
* Try FTP installation (Method 2 above).

WHITE SCREEN AFTER ACTIVATION
1. Enable WordPress debug mode: add `define("WP_DEBUG", true);` to `wp-config.php`
2. Check `/wp-content/debug.log` for the error
3. The most common cause is a PHP version below 7.4. Check your PHP version in your hosting control panel and upgrade if needed
4. Deactivate GT BOGO Engine via FTP: rename the `gt-bogo-engine` folder in `/wp-content/plugins/` to `gt-bogo-engine-disabled`. Your site recovers instantly.

WOOCOMMERCE NOT DETECTED
GT BOGO Engine requires WooCommerce to be active. Activate WooCommerce first, then activate GT BOGO Engine. If WooCommerce is active but not detected, deactivate and reactivate GT BOGO Engine to re-run the dependency check.

DATABASE TABLES NOT CREATED
If the plugin activates but no rules can be saved, the database tables may not have been created. Go to **Settings > System Status** and click **Repair Database Tables**. This re-runs the table creation routine without affecting any existing data.'],
],
];

$topics['pro-packs'] = [
'icon'  => '<span style="font-size:28px">📦</span>',
'emoji' => '📦',
'title' => 'PRO Packs Complete Guide',
'desc'  => 'What every pack does, how to purchase, import, and get maximum ROI from each one.',
'color' => '#f59e0b',
'sections' => [

['What PRO Packs Are and Why They Matter',
'Building BOGO rules from scratch means guessing at the right strategy. Most store owners try a basic Buy 1 Get 1 Free, see moderate results, and do not know what to change to improve performance.

PRO Packs eliminate that guesswork. Each pack is a professionally designed rule template set built around a specific, proven promotional strategy. Instead of experimenting for weeks, you import a pack and get an expertly configured campaign ready to activate in one click.

Each pack contains:
* One or more pre-configured BOGO rules with optimised buy/get quantities
* Discount values calibrated to balance conversion rate and margin impact
* Priority settings pre-assigned to prevent conflicts with other rules
* Rules built for portability — no hardcoded product IDs, designed to work on any store

PACKS ARE STARTING POINTS, NOT RESTRICTIONS
Every rule inside every pack is fully editable after import. Change any parameter — buy quantity, get quantity, discount amount, target products, schedule, or priority. Think of packs as professionally engineered templates that you customise for your specific store, not locked configurations.

THE 15 AVAILABLE PACKS
* **Stack Master** — Multi-tier rule stacking and priority management
* **Cart Threshold Boost** — Dollar-amount threshold deals to lift AOV
* **Flash Sale Engine** — Time-limited urgency campaigns
* **Seasonal Promotions** — 12 pre-built holiday and event rule sets
* **Inventory Clearance** — Stock-level triggered promotional rules
* **Slow Seller Recovery** — Sales-velocity based rescue campaigns
* **New Customer Acquisition** — First-order conversion deals
* **VIP and Loyalty Rewards** — Tiered loyalty campaign rules
* **Free Gift Engine** — Auto-add gift to cart rules
* **Countdown Urgency** — FOMO countdown timer rules
* **Visual Badge** — Product badge display optimisation rules
* **Savings Display** — Real-time savings callout rules
* **Social Proof** — Live deal-activity notification rules
* **Smart Upsell** — BOGO-triggered cross-sell and upsell rules
* **Quick Deal** — One-click instant deal activation rules'],

['Choosing the Right Pack for Your Store',
'Not every pack is equally relevant to every store. Use this guide to identify which packs will have the most immediate impact on your business.

IF YOUR PRIMARY GOAL IS INCREASING AVERAGE ORDER VALUE
Start with: **Cart Threshold Boost** + **Savings Display**
These two together are the most direct path to AOV improvement. Cart Threshold creates a spend incentive; Savings Display makes the reward concrete and visible. Pair with the Cart Progress Bar superpower for the full effect.

IF YOUR PRIMARY GOAL IS CLEARING OVERSTOCK
Start with: **Inventory Clearance** + **Flash Sale Engine**
Inventory Clearance triggers deals automatically when stock exceeds thresholds. Flash Sale creates urgency to accelerate movement. Both are set-and-manage — once configured they run automatically.

IF YOUR PRIMARY GOAL IS ACQUIRING NEW CUSTOMERS
Start with: **New Customer Acquisition** + **Free Gift Engine**
First-order BOGO deals have the highest conversion rate for new visitors. Adding a free gift removes the last purchase hesitation. Self-disabling after first purchase means loyal customers are never undervalued.

IF YOUR PRIMARY GOAL IS RETENTION AND LOYALTY
Start with: **VIP and Loyalty Rewards** + **Smart Upsell**
Tiered loyalty deals reward your best customers with progressively better deals. Smart Upsell uses BOGO incentives as the hook for cross-sell recommendations, increasing both loyalty and transaction value.

IF YOU WANT EVERYTHING AND THE BEST VALUE
The **Complete BOGO Arsenal** (all 15 packs, $299) gives you every strategy under $20 per pack. This is the right choice for stores doing $10K+ per month that want the complete toolkit and maximum optionality.'],

['Purchasing Individual Packs and Bundles',
'INDIVIDUAL PACKS — $24.99 EACH

1. Go to **GT BOGO ENGINE > PRO Rules / Packs** in your WordPress sidebar
2. Scroll to the PRO Packs section
3. Find the pack you want and click the **PayPal button** on its card
4. Complete payment via PayPal — no PayPal account required, you can pay by debit or credit card
5. Within minutes, your purchase confirmation email arrives with the pack JSON file attached
6. Save the JSON file and import it (see Importing Packs below)

BUNDLE DEALS — BEST VALUE

**Starter Revenue Bundle — $99 — 5 packs**
Best for: Stores getting started with advanced BOGO strategy. Covers the 5 highest-impact strategies: Cart Threshold Boost, Flash Sale Engine, Free Gift Engine, Visual Badge, and Savings Display.

**Growth Acceleration Bundle — $179 — 9 packs**
Best for: Stores doing $5K–$20K/month that want to push performance across multiple dimensions. Covers urgency, loyalty, social proof, upselling, clearance, and more.

**Complete BOGO Arsenal — $299 — All 15 packs**
Best for: Agencies managing multiple client sites, enterprise stores, and serious operators who want every tool. Under $20 per pack — the best value available.

Bundle purchases deliver all included JSON files in a single purchase confirmation email. Import each pack individually via the Manual Pack Import section.

AFTER PURCHASE
Check your spam folder if your confirmation email does not arrive within 10 minutes. PayPal payments can occasionally delay for a few minutes during high-volume periods. Your pack files are permanently archived — if you lose them, retrieve them via the self-service portal at `https://graphictshirts.shop/bogo/retrieve-license.php`'],

['Importing Packs — Step by Step',
'BEFORE YOU IMPORT — CHECKLIST
* You have an active PRO license (required for pack import)
* You have the `.json` pack file saved to your computer
* You are logged into your WordPress admin

IMPORTING YOUR PACK

1. Open your purchase confirmation email and download the attached `.json` file to your computer
2. In WordPress admin, go to **GT BOGO ENGINE > PRO Rules / Packs**
3. Scroll to the **Manual Pack Import** section at the bottom of the page
4. Click **Choose File** and select the `.json` file
5. Click **Import Pack File**
6. A green success notice confirms the import
7. Scroll up to the **Rule Stack** table — your new rules appear with status `Inactive`
8. Review each rule, customise if needed, then click **Activate** to make any rule live

WHY RULES IMPORT AS INACTIVE
Rules import as inactive deliberately so you can review the configuration before anything goes live on your store. This prevents unexpected discounts from triggering on real customer carts before you have had a chance to customise and verify the rules.

AFTER IMPORTING — WHAT TO DO NEXT
* Review each rule name and edit if needed for your internal tracking
* Check the target products or categories match your store catalogue
* Verify the discount value and buy/get quantities match your intended deal
* Set the priority number to fit within your overall rule stack order
* Activate only the rules you are ready to run immediately

IMPORT TROUBLESHOOTING
* **"Invalid pack file"** — use the original downloaded `.json` file. Do not open and re-save it in a text editor, which can corrupt the JSON format.
* **"PRO license required"** — activate your PRO license on the License tab first.
* **"Pack already imported"** — this pack was previously imported. Your existing rules from this pack are already in the Rule Stack. Re-importing adds new entries alongside existing ones.
* **"File too large"** — your server upload limit may need adjustment. Contact your hosting provider.'],

['Maximum ROI Strategy — Pack by Pack',
'STACK MASTER
Use this when you have multiple active rules running simultaneously. The pack includes carefully ordered priority rules designed to stack without conflict. After importing, review the priority numbers and ensure they fit within your existing stack — no two rules should share the same priority number. Use the Conflict Resolver page to auto-detect any priority collisions.
**Best combination:** Stack Master + any 3-4 other active packs simultaneously.

CART THRESHOLD BOOST
Set your threshold just above your current average order value. If your AOV is $45, set the threshold at $55. The gap should feel achievable — too high and customers give up, too low and you are giving discounts on orders that would have happened anyway. Pair with the Cart Progress Bar superpower so customers see exactly how close they are.
**ROI target:** 18–25% AOV increase within 30 days of activation.

FLASH SALE ENGINE
Run flash sale windows of 4–24 hours only. Longer windows lose urgency. Announce via email and social media at the exact moment the sale goes live. The combination of external traffic driver plus on-site countdown is what creates the revenue spike. Do not run fake countdowns that reset — customers notice and trust collapses permanently.
**Best combination:** Flash Sale Engine + Countdown Urgency pack + Countdown Timer superpower.

SEASONAL PROMOTIONS
Import 2–3 weeks before the seasonal event. This gives you time to test, customise, and adjust before peak traffic arrives. Do not activate all 12 template rules simultaneously — select the 2–3 most relevant to your product catalogue. Deactivate seasonal rules the day after the event ends using the Scheduler.
**Best combination:** Seasonal Promotions + Announcement Bar superpower + Visual Badge.

INVENTORY CLEARANCE
Run a WooCommerce stock report first to identify your 20% highest-stock, lowest-velocity SKUs. Target these specifically in the Inventory Clearance rules. Set stock thresholds above your reorder point — clear excess without risking stockout. Use the Scheduler to auto-deactivate rules when stock drops to your target level.

SLOW SELLER RECOVERY
Run a WooCommerce Analytics velocity report to identify products whose sales have declined over the past 60 days. Target these specifically. Run the recovery campaign for a 30-day window and compare velocity before and after. Products that recover naturally can have their rules paused.

NEW CUSTOMER ACQUISITION
The rules in this pack use first-order detection — they apply exclusively to customers placing their first order and self-disable after that order is placed. This prevents your best customers from receiving new-customer deals on repeat purchases. Pair with a welcome email sequence that reinforces the deal value.
**ROI target:** New customer conversion rate increase of 20–35%.

VIP AND LOYALTY REWARDS
Segment your customers into tiers based on lifetime spend: Bronze ($100+), Silver ($300+), Gold ($750+). Use the Segments feature to create customer groups by lifetime spend and configure the VIP rules to target each tier with progressively better deals. Higher tiers get better discounts. This creates a powerful incentive to keep spending.

FREE GIFT ENGINE
Choose your gift product carefully. Low cost to you, high perceived value to the customer. Accessories, samples, branded items, and digital products work exceptionally well. Set the qualifying threshold slightly above your current AOV to pull cart values up. The free gift should feel like a bonus reward, not a cheap add-on.

COUNTDOWN URGENCY
Pair with the Countdown Timer superpower for visual countdown display. Set windows of 4–8 hours for maximum urgency. Announce the countdown window on social media and via email at launch time. Real scarcity drives real action — do not inflate timers or reset them.

VISUAL BADGE
Customise badge text in White Label settings. "Deal of the Day" and "Buy More Save More" consistently outperform generic "BOGO Deal" text in click-through testing. Position badges at top-left of product images — this is the most-viewed position based on eye-tracking research.

SAVINGS DISPLAY
Always show both the percentage saved AND the dollar amount saved. "Save $18.50" is more motivating than "Save 25%" for most shoppers — the concrete number lands harder. Enable the Savings Display superpower alongside this pack for maximum impact at product, cart, and checkout.

SOCIAL PROOF
Configure realistic notification frequency. One notification every 90–120 seconds feels genuine. More than one per minute looks manufactured. Real purchase data from your WooCommerce orders feeds this automatically — no fake data is used. The credibility of real data is what makes this effective.

SMART UPSELL
Map your upsell suggestions to natural product pairings — the items customers most commonly buy together. Start with your 5 best-selling products and configure one upsell suggestion for each. Relevance is everything. A perfectly relevant upsell converts at 3–5x the rate of a generic one.

QUICK DEAL
Pre-configure 5–10 Quick Deal templates for your most common promotional scenarios. When you need to react quickly — unexpected overstock, competitor promotion, seasonal spike — activate a pre-built deal in seconds instead of building a rule from scratch under pressure.'],

['Stacking Multiple Packs Together',
'One of the most powerful features of GT BOGO Engine PRO is the ability to run multiple rules from multiple packs simultaneously. This section covers how to stack packs effectively without creating conflicts.

THE GOLDEN RULE OF STACKING
Each active rule should serve a distinct purpose and target a distinct cart scenario. Conflicts arise when two rules could both apply to the same cart composition at the same priority level. Prevent this by:
* Assigning unique priority numbers to every rule
* Scoping rules to different product categories where possible
* Using the Conflict Resolver page to detect overlaps automatically

RECOMMENDED STACK ARCHITECTURE (for a store running 8–10 rules)

* **Priority 1–2:** Flash sale or time-limited urgency rules (these should override everything when active)
* **Priority 3–4:** Seasonal or campaign-specific rules
* **Priority 5–6:** New customer acquisition rules
* **Priority 7–8:** VIP and loyalty tier rules
* **Priority 9–10:** Standard ongoing BOGO rules
* **Priority 11–12:** Cart threshold / AOV rules
* **Priority 13–15:** Catch-all free gift or fallback rules

PAUSING VS DELETING RULES
Never delete a rule you might use again. Use the **Pause** function to temporarily disable rules between promotional periods. Build a library of paused rules for different seasons and scenarios — activate them when needed, pause when done. This preserves all your configuration work between campaigns.'],
],
];

$topics['creating-rules'] = [
'icon'  => '<span style="font-size:28px">🎯</span>',
'emoji' => '🎯',
'title' => 'Creating & Managing Rules',
'desc'  => 'Complete guide to the rule builder, all rule types, quick-start templates, priority management, and advanced targeting.',
'color' => '#E10000',
'sections' => [

['Understanding Rule Types',
'GT BOGO Engine supports three distinct rule types. Understanding each one helps you choose the right type for each promotional goal.

BOGO (BUY X GET Y)
The core rule type. The customer adds a specified quantity of items to their cart and receives a specified quantity of items at a discounted price. The engine evaluates the cart, identifies qualifying items, and applies the discount automatically — no coupon code required.

Examples:
* Buy 1 Get 1 Free: Buy Quantity = 1, Get Quantity = 1, Discount = 100%
* Buy 2 Get 1 at 50% Off: Buy Quantity = 2, Get Quantity = 1, Discount = 50%
* Buy 3 Get 2 Free: Buy Quantity = 3, Get Quantity = 2, Discount = 100%

CART THRESHOLD
Triggered when the cart total reaches or exceeds a specified dollar amount. The discount applies to qualifying items in the cart at that point. Ideal for average order value (AOV) boosting strategies where you want to reward customers for spending more overall rather than for specific item combinations.

Examples:
* Spend $50 and get 20% off your entire order
* Spend $100 and get $15 off
* Spend $75 and get a free product added to your cart

FREE GIFT
Automatically adds a specific product to the cart for free when qualifying conditions are met. The gift product is added silently in the background — the customer sees it appear in their cart without any manual action. No coupon code. No checkout step. The gift just appears.

This rule type is the highest-converting individual deal type in testing across GT BOGO Engine stores. The element of "getting something extra for free" creates a strong emotional positive reaction that generic discounts do not replicate.'],

['Configuring the Free Core Rule',
'Every GT BOGO Engine installation includes one free rule slot that works without any license. This is your baseline BOGO deal — always available, always active.

ACCESSING THE FREE CORE RULE
Go to **GT BOGO ENGINE > Free Core Rule** in your WordPress sidebar.

FIELD-BY-FIELD GUIDE

**Rule Name**
Internal label only — customers never see this. Use something descriptive for your own tracking: "Sitewide BOGO 50%" or "Buy 1 Get 1 Free — All Products".

**Buy Quantity**
How many items the customer must add to their cart to qualify for the deal. Start with 1 for maximum accessibility. Increase to 2 or 3 if you want to drive higher unit counts per transaction.

**Get Quantity**
How many items receive the discount. Typically 1. Set to 2 for Buy 2 Get 2 style deals.

**Discount Type**
* Percentage Off — discount is a percentage of the item price. 100% = free. 50% = half price.
* Fixed Amount Off — discount is a specific dollar amount regardless of item price. Good for dollar-amount promotions.

**Discount Value**
The actual discount amount. If Percentage, enter 100 for free or 50 for half price. If Fixed, enter the dollar amount.

**Status**
Active = the rule fires on qualifying carts immediately. Paused = the rule is saved but inactive.

TESTING YOUR FREE CORE RULE
After saving, open your WooCommerce shop in a new browser window and add the qualifying number of products to your cart. Go to the cart page and confirm the discount appears in the cart totals automatically, without any coupon code entry. If the discount does not appear, check that the rule status is Active and that your cart contains the correct quantity of products.

OPTIMISING THE FREE CORE RULE
For maximum initial impact, configure the free rule as: Buy Quantity = 1, Get Quantity = 1, Discount = 100% (free). This is the classic Buy 1 Get 1 Free format — the most universally understood and highest-converting BOGO deal type. Pair it with the Product Badges and Cart Progress Bar free superpowers to maximise visibility.'],

['Building PRO Custom Rules from Scratch',
'With an active PRO license, you can create up to 15 simultaneously active custom rules with full control over every parameter.

ACCESSING THE RULE BUILDER
Go to **GT BOGO ENGINE > PRO Rules / Packs**. The rule builder form appears below your Rule Stack table. If you have not created any rules yet, you will see the quick-start template selector at the top of the form.

COMPLETE FIELD REFERENCE

**Rule Name** (required)
Internal label. Use descriptive, searchable names for easy management: "Flash Sale — Hoodies Q4 2025" or "VIP Tier 1 — Buy 1 Get 1 30% Off".

**Rule Type** (required)
Select BOGO, Cart Threshold, or Free Gift. The form adjusts to show relevant fields for each type.

**Buy Quantity** (BOGO and Cart Threshold)
The number of items the customer must add to trigger the rule. For Cart Threshold rules, this is the minimum cart total in dollars.

**Get Quantity** (BOGO)
The number of items that receive the discount when the buy condition is met.

**Discount Type** (required)
Percentage Off or Fixed Amount Off.

**Discount Value** (required)
The amount of the discount. For percentage: 100 = free, 50 = half price, 25 = quarter off. For fixed: the dollar amount per qualifying item.

**Target Products** (optional, PRO)
Restrict the rule to specific products. Leave blank to apply sitewide. Enter product IDs or product names to target specific items. Use this for pack-specific deals, clearance items, or seasonal products.

**Target Categories** (optional, PRO)
Restrict the rule to specific WooCommerce product categories. Leave blank for sitewide. Multiple categories can be targeted simultaneously.

**Priority** (required)
Execution order when multiple rules match. **Lower number = higher priority.** Priority 1 fires before Priority 5. Assign unique numbers to every rule — duplicate priorities cause the Conflict Resolver to flag a warning.

**Status**
Active or Inactive. Rules can be changed between active and inactive at any time.

SAVING AND ACTIVATING
Click **Create Rule** to save. The rule appears in your Rule Stack table. If you saved it as Inactive, click **Activate** in the table when ready to go live.'],

['Quick-Start Templates',
'PRO users have access to 8 quick-start templates that pre-fill the rule builder with proven, tested configurations. Select a template to populate the form automatically, then customise as needed.

TEMPLATE 1 — BUY 1 GET 1 FREE
The classic BOGO deal. Highest conversion rate of all deal types. Every product qualifies. Best for: sitewide promotions, introductory campaigns, driving trial of new products.
Config: Buy 1, Get 1, 100% off.

TEMPLATE 2 — BUY 2 GET 1 AT 50% OFF
Encourages 3-item cart compositions. Higher AOV than Buy 1 Get 1 because it requires 2 full-price items. Best for: mid-range products where 3-item bundles make sense naturally.
Config: Buy 2, Get 1, 50% off.

TEMPLATE 3 — BUY 3 GET 1 FREE
Drives the highest per-transaction unit count. Best for consumables, accessories, and products naturally bought in multiples. A customer who buys 3 to get 1 free often becomes a repeat buyer at that quantity.
Config: Buy 3, Get 1, 100% off.

TEMPLATE 4 — SPEND $50 GET 20% OFF
Cart threshold AOV booster. Set the threshold just above your current AOV. The 20% discount is strong enough to motivate action without excessively impacting margin. Best for: stores with diverse product catalogues at various price points.
Config: Cart total $50+, 20% off.

TEMPLATE 5 — FREE GIFT ON ANY ORDER
Adds a free gift to every qualifying cart. Best for: customer delight campaigns, brand building, and converting hesitant first-time buyers. Choose a gift with high perceived value but low cost.
Config: Free Gift type, 100% off on gift product.

TEMPLATE 6 — BUY 2 GET 2 FREE
Double BOGO. High-impact clearance and bundling format. Drives the highest volume of units moved per transaction. Best for: inventory clearance, end-of-season stock, products being discontinued.
Config: Buy 2, Get 2, 100% off.

TEMPLATE 7 — 10% OFF EVERYTHING
Simple sitewide discount. Lower impact per transaction than BOGO but broad applicability. Best for: slow periods, competitive response, and new customer welcome deals.
Config: Buy 1, Get 1, 10% off.

TEMPLATE 8 — VIP BUY 1 GET 1 30% OFF
Loyalty reward for returning customers. Combine with the Segments feature to target customers who meet a minimum lifetime spend. Best for: retention campaigns and rewarding high-value customers.
Config: Buy 1, Get 1, 30% off — with Segments targeting.'],

['Priority, Conflicts, and Rule Execution',
'When multiple rules are active and a customer cart qualifies for more than one, GT BOGO Engine executes them in priority order. Understanding how this works prevents unexpected discount behaviour.

HOW PRIORITY WORKS
* Lower priority number = higher priority (executes first)
* Priority 1 fires before Priority 2, which fires before Priority 3, and so on
* Multiple rules can apply to the same cart simultaneously — this is deliberate, enabling promotional stacking
* If two rules share the same priority number, a conflict warning appears in the Rule Stack table

EXAMPLE PRIORITY STACK
* Priority 1: Flash Sale — Hoodies (time-limited, overrides everything when active)
* Priority 3: New Customer — Buy 1 Get 1 Free (first-order only)
* Priority 5: VIP Tier 1 — 30% off (logged-in VIP customers)
* Priority 7: Sitewide — Buy 2 Get 1 at 50% Off (all other customers)
* Priority 10: Cart Threshold — Spend $75 Get 20% Off (any cart)

RESOLVING CONFLICTS
Go to **PRECISION > Conflict Resolver**. This page automatically scans your active rule stack and identifies:
* Duplicate priority numbers
* Rules that could fire simultaneously on the same cart composition
* Suggested priority reassignments to eliminate conflicts

Always run the Conflict Resolver after importing a new PRO Pack or after making changes to multiple rules simultaneously.

PAUSING VS DELETING
**Pause** a rule to temporarily disable it without losing its configuration. Paused rules remain in your Rule Stack, visible and editable, but they do not fire on any carts. Use Pause for seasonal rules between promotional periods.

**Delete** a rule only if you are certain you will never use it again. Deleted rules cannot be recovered — but if the rule came from a PRO Pack, re-importing the pack file recreates it.'],

['Advanced Targeting — Products, Categories, and Customers',
'PRO rules support granular targeting to ensure deals apply only to the right products and the right customers.

PRODUCT TARGETING
Leave the product targeting field blank to apply a rule sitewide (all products). To target specific products:
* Enter product IDs (visible in WooCommerce > Products, the number in the ID column)
* Or enter product names (the engine matches against WooCommerce product titles)
* Multiple products can be targeted in a single rule

Use product targeting for:
* Clearance rules that apply only to specific slow-moving SKUs
* New product launch deals on specific items
* Seasonal deals on items relevant to that season only

CATEGORY TARGETING
To target specific product categories:
* Enter WooCommerce category slugs or IDs
* Multiple categories can be targeted
* The rule fires when a qualifying item from any of the targeted categories is in the cart

Use category targeting for:
* Department-specific promotions ("20% off all accessories with any main product purchase")
* Clearance sections
* Seasonal product collections

CUSTOMER SEGMENT TARGETING (PRO — Segments Feature)
The Segments page (MAIN section) allows you to create customer groups based on:
* **Lifetime spend** — target customers who have spent over a specified total
* **Order count** — target customers with more than a specified number of orders
* **First order** — target customers placing their very first order
* **Customer tags** — target customers with specific WooCommerce tags

Combine segment targeting with your rules to create truly personalised promotions:
* VIP deals that only appear for customers who have spent over $500 lifetime
* First-order deals that self-disable after the customers first purchase
* Loyalty tier deals that escalate in value as customer spend increases

SCHEDULING RULES (PRO — Scheduler)
The Scheduler page allows you to set specific start and end dates and times for any rule. Scheduled rules activate and deactivate automatically — you set it up once and the engine manages it.

Use scheduling for:
* Flash sale windows with a specific end time
* Seasonal promotions with a defined date range
* Weekly recurring deals (every Friday, every weekend)
* Holiday campaigns that need to turn off automatically at midnight'],
],
];

$topics['superpowers'] = [
'icon'  => '<span style="font-size:28px">⚡</span>',
'emoji' => '⚡',
'title' => 'Superpowers — Complete Guide',
'desc'  => 'How every superpower works, how to configure it, and how to combine them for maximum revenue impact.',
'color' => '#8b5cf6',
'sections' => [

['How the Superpowers System Works',
'GT BOGO Engine includes 15 Superpowers — frontend and backend features that amplify the visibility and impact of your BOGO rules. Every Superpower is off by default. You enable only what is appropriate for your store and brand.

WHY SUPERPOWERS MATTER
A BOGO rule without Superpowers is invisible until checkout. The discount applies correctly, but customers do not know the deal exists until the moment they see their cart total. They browse your products, add items, and only discover the deal at the end — if at all.

Superpowers move deal awareness from checkout backwards to product browsing. Customers see the deal before they add to cart, which changes their purchasing behaviour. They add more items to qualify. They complete checkout at a higher rate. They share the deal because it feels exciting.

THE THREE INTENSITY LEVELS
Every Superpower has three intensity settings:

* **Subtle** — Minimal visual presence. Small elements, soft animations, low frequency. Use for premium, luxury, and minimalist brands where promotional messaging should be understated.
* **Moderate** — Balanced visibility. Clear and noticeable without being aggressive. Recommended starting point for most stores. Good conversion impact without disrupting the shopping experience.
* **Bold** — Maximum visibility. Large elements, strong animations, high frequency. Use during flash sales, major promotional events, and on stores where conversion rate optimisation is the primary focus.

THE ANIMATE TOGGLE
Each Superpower has an Enable Animate toggle. Animations make elements more eye-catching and increase interaction rates. Enable during high-energy promotional periods. Disable for a more refined, static presentation during normal trading periods.

PERFORMANCE NOTE
All Superpowers are built for performance. Each Superpower only loads its JavaScript and CSS when it is enabled. A disabled Superpower adds zero page weight, zero JavaScript, and zero CSS to your storefront. Enabling 10 Superpowers adds less than 25KB total to your page load — all assets are minified and conditionally loaded.'],

['FREE: Product Badges',
'WHAT IT DOES
Displays a promotional badge overlaid on the product image for every product that qualifies for an active BOGO rule. Badges appear on shop pages, category pages, search results, and individual product pages — everywhere the product image is displayed.

WHY IT MATTERS
Customers cannot claim a deal they do not know about. Product badges are the first signal that a deal exists — they stop the scroll, create awareness, and drive click-through to the product page long before the customer reaches the cart. Stores with Product Badges enabled consistently see 20–35% higher BOGO deal engagement compared to rules running without any visual signalling.

HOW TO CONFIGURE
1. Go to **Settings > Superpowers** and enable **Product Badges**
2. Set intensity: Subtle for luxury brands, Moderate for most stores, Bold for flash sales
3. Enable Animate for a subtle entrance animation on page load
4. Customise badge text in **White Label** settings (see White Label guide)

BADGE TEXT THAT WORKS
* "Buy More Save More" — communicates the deal mechanic, drives curiosity
* "BOGO Active" — clear, direct, action-oriented
* "Flash Deal On Now" — urgency variant for time-limited deals
* "Member Exclusive" — VIP/loyalty variant
* "Free Gift Inside" — for Free Gift rules

Keep badge text under 18 characters for clean display across all device sizes.

OPTIMISATION TIPS
* Position badges at top-left of product images — the highest-visibility position based on e-commerce eye-tracking research
* Test 2–3 badge text variants over 2-week periods and check which drives higher product page click-throughs in Analytics
* Use Bold intensity during flash sales and major events, Moderate for everyday deals
* Ensure badge colour has strong contrast against your product images. The default GT Red badge is high-contrast on most product photography.'],

['FREE: Cart Progress Bar',
'WHAT IT DOES
Displays a dynamic progress bar in the WooCommerce cart showing customers exactly how many more items they need to add to unlock an active BOGO deal. As customers add items, the bar fills toward completion. When they hit the buy quantity threshold, the bar fills completely and a success message replaces it.

WHY IT MATTERS
The cart progress bar is the highest-ROI free feature in GT BOGO Engine. It triggers the completion impulse — the same psychological driver behind loyalty stamp cards, progress meters in apps, and experience bars in games. When customers see they are one item away from a deal, they add that item 68% of the time.

The bar transforms passive deal awareness ("there is some kind of BOGO thing") into active deal pursuit ("I need one more item to unlock my discount"). This shift in customer psychology directly increases both units per transaction and average order value.

HOW TO CONFIGURE
1. Enable **Cart Progress Bar** in Settings > Superpowers
2. Set intensity to Moderate — Subtle makes the bar too easy to overlook, Bold can feel aggressive for everyday deals
3. Enable Animate so the bar fills smoothly as items are added
4. Customise progress and completion text in White Label settings

HIGH-PERFORMING MESSAGE TEMPLATES

Progress text (before threshold is met):
"Add [x] more item(s) to unlock your deal and save [amount]!"

Completion text (when threshold is hit):
"Deal unlocked! [Amount] saved — your discount has been applied automatically."

Urgency variant (during flash sales):
"Add [x] more before this flash deal expires — [timer] remaining!"

OPTIMISATION TIPS
* Set your buy quantity at 1–2 items above your current average items-per-order. If customers typically buy 2 items, set Buy Quantity to 3. The bar should show progress that feels achievable.
* The most powerful combination is: Cart Progress Bar + Savings Display + a deal with a dollar amount that clearly justifies adding one more item.
* Test Moderate intensity during normal periods and Bold during promotional events.'],

['PRO: Countdown Timer',
'WHAT IT DOES
Displays a live, real-time countdown timer on product pages and in the WooCommerce cart, showing the exact time remaining on any active time-limited BOGO deal. The timer counts down in hours, minutes, and seconds. When it expires, the deal deactivates, the timer disappears, and an optional "deal ended" message replaces it.

WHY IT MATTERS
Time pressure is the most powerful urgency mechanism available to e-commerce stores. Without a visible deadline, most customers postpone the decision — "I will come back later" — and never return. When a deadline is explicitly visible and counting down in real time, the same customer makes a decision in that session.

Stores pairing a BOGO deal with a visible countdown consistently see 40–60% higher same-session conversion rates compared to the same deal without a countdown. The effect is strongest when the window is under 12 hours.

HOW TO CONFIGURE
1. Create a scheduled rule via **Scheduler** with a specific end date and time, or import the Flash Sale Engine or Countdown Urgency PRO Pack
2. Enable **Countdown Timer** in Settings > Superpowers
3. Set intensity to Bold — this is one case where Bold is recommended as the default. Urgency requires visibility.
4. Enable Animate
5. Customise timer label in White Label settings: "Offer ends in:", "Flash sale ends:", "Deal expires:"

OPTIMISATION TIPS
* 4–24 hour windows produce the best urgency-to-conversion ratio. Shorter windows (under 2 hours) may not reach enough traffic. Longer windows (over 48 hours) lose urgency.
* Announce countdown deals via email and social media at the exact moment the sale goes live — external traffic plus on-site countdown amplifies the effect dramatically.
* Never use fake countdowns that reset. Customers who notice will never trust your promotions again and will leave negative reviews.
* For recurring deals (e.g. every Friday), use the Scheduler to set weekly recurrence so the timer is genuine each time.'],

['PRO: Savings Display',
'WHAT IT DOES
Shows customers exactly how much they are saving in real time as they interact with your store. Savings callouts appear on product pages (showing potential savings if they qualify), in the cart (showing actual savings applied), and at checkout (reinforcing the value immediately before payment).

WHY IT MATTERS
Customers consistently underestimate the value of percentage-based discounts. "50% off" registers cognitively as uncertain — "how much is that actually?" Showing "$18.75 saved on this order" is concrete, immediate, and emotionally satisfying. It answers the question before it forms.

Savings Display at the checkout stage specifically addresses the most common cause of abandonment: the moment between seeing the total and clicking pay. Customers who see an explicit savings confirmation at checkout abandon 12–18% less frequently.

HOW TO CONFIGURE
1. Enable **Savings Display** in Settings > Superpowers
2. Set intensity: Moderate for everyday use, Bold during major promotional campaigns
3. Customise the savings message format in White Label settings

HIGH-CONVERTING MESSAGE FORMATS
* "You are saving [amount] on this order!" — simple and clear
* "Your BOGO deal has saved you [amount] today." — attributing the saving to the deal reinforces the value
* "Deal applied — [amount] back in your pocket!" — more emotive, higher engagement

SHOW BOTH FORMATS
Configure your savings display to show both the percentage and the dollar amount. "25% off — saving you $18.75" delivers the full picture. For high-AOV stores (average order over $100), the absolute dollar saved is particularly motivating — "You are saving $45" on a $180 order is an extremely compelling retention message.'],

['PRO: Social Proof',
'WHAT IT DOES
Displays real-time notifications of other customers claiming active BOGO deals on your store. Notifications appear as small toast popups (typically bottom-left) showing messages like "James from Chicago just claimed a Buy 2 Get 1 Free deal on Running Shoes — 6 minutes ago." Data is pulled from your real WooCommerce order history — these are genuine transactions, not fabricated notifications.

WHY IT MATTERS
Social proof addresses the core hesitation that prevents customers from claiming a deal: "Is this real? Are other people actually doing this?" Seeing real purchase activity from named customers creates trust, normalises deal-claiming behaviour, and reduces the perceived risk of the transaction.

Stores running Social Proof alongside their BOGO rules see 15–25% higher deal claim rates and a measurable reduction in cart abandonment. The effect is strongest during the first few weeks of a new promotion when your own purchase data builds momentum.

HOW TO CONFIGURE
1. Enable **Social Proof** in Settings > Superpowers
2. Set intensity: controls popup size and display frequency
3. Enable Animate for smooth slide-in notifications
4. Configure display frequency in White Label settings

FREQUENCY RECOMMENDATIONS
* 1 notification every 90–120 seconds — feels genuine and credible
* More than 1 per minute — starts to feel manufactured, reduces trust
* Less than 1 every 3 minutes — too infrequent to create momentum

OPTIMISATION TIPS
* During high-traffic events like Black Friday or flash sales, increase frequency to Moderate — you will have abundant real order data to draw from.
* Ensure your WooCommerce privacy settings allow first-name and city display. Only first name and general geographic area are shown — never full names, email addresses, or postal codes.
* Subtle intensity works well on premium brands; the popup is small and unobtrusive but still visible.'],

['PRO: Cart Recommendations and Bundle Spotlight',
'CART RECOMMENDATIONS
Displays intelligent product suggestions in the WooCommerce cart that specifically tie recommendations to BOGO deal eligibility. Instead of generic "You may also like" suggestions, Cart Recommendations shows customers which specific products they can add to complete a deal, qualify for a higher tier, or earn a free gift.

This feature reduces the cognitive work required to claim a deal. Instead of customers having to figure out what to add, the engine shows them exactly what qualifies. Stores with Cart Recommendations enabled see deal completion rates increase by 20–35%.

**Configuration:** Enable in Settings > Superpowers. Map recommendation product groups in your rule settings. Set intensity: Subtle for a sidebar suggestion style, Bold for a full product row above cart totals. Customise recommendation header text in White Label.

**Optimisation:** Recommend genuinely complementary products — the items most naturally paired with what is already in the cart. Relevance is the most important factor. A perfectly relevant suggestion converts at 3–5x the rate of a generic one. Limit to 3–4 displayed recommendations — more than 4 creates decision paralysis and lowers add-to-cart rates.

BUNDLE SPOTLIGHT
Highlights product bundle opportunities directly on product pages. Shows customers that buying this product plus a complementary product unlocks a BOGO deal. Displayed as a prominent callout section below the product description.

Format: "Buy this + [Product X] together and save $14 — add both to cart"

Bundle Spotlight is particularly powerful for stores that sell accessories alongside main products. Pairing a main item with its natural accessory at a deal price increases attachment rate and dramatically improves the value perception of the purchase. Configure related product mappings in your rule settings.'],

['PRO: Exit Intent, Smart Popup, and Announcement Bar',
'EXIT INTENT POPUP
Displays a full-screen overlay popup when the system detects the user is about to leave the page — cursor moves toward browser controls, rapid upward scroll, or tab switching detected. The popup surfaces the current BOGO deal with urgency messaging and a direct call to action.

Best used on product pages and the cart page. A visitor who was about to leave and encounters "Wait — you are one item away from a free product" returns to the cart and completes the transaction 18–22% of the time in A/B testing.

**Configuration:** Enable in Settings > Superpowers. Set a page-time trigger (minimum 30 seconds on page before eligibility) to avoid annoying visitors who arrive and immediately leave. One popup per session maximum. Customise headline and CTA in White Label.

SMART POPUP
A timed overlay popup that appears after a configurable delay (recommended 45–90 seconds). Presents the current BOGO deal in a clean, dismissible overlay. Less aggressive than exit intent but captures hesitant browsers who are spending time on the page without adding to cart.

**Best use:** Pair Smart Popup with Cart Recommendations so the popup dynamically shows products the customer can add to qualify for the deal — making it immediately actionable, not just informational.

ANNOUNCEMENT BAR
A persistent promotional bar pinned to the top of every storefront page, remaining visible as customers scroll. Constantly maintains awareness of your active BOGO deal without interrupting the browsing experience.

Most effective for sitewide deals that apply broadly across your catalogue. During seasonal campaigns and major promotional events, enable the Announcement Bar to ensure every page visit drives deal awareness. Customise bar text, CTA button, and optionally a countdown timer within the bar using White Label settings.'],

['Combining Superpowers for Maximum Impact',
'Individual Superpowers produce measurable results. Combined strategically, they create a compounding effect where each feature reinforces the others.

THE BASELINE STACK (free — activate immediately)
* **Product Badges** — awareness at product browsing stage
* **Cart Progress Bar** — completion impulse at cart stage

This free combination alone lifts BOGO deal engagement by 15–30% compared to a rule with no Superpowers. Activate both immediately.

THE FULL CONVERSION STACK (PRO — for everyday deals)
* Product Badges + Cart Progress Bar (awareness and completion impulse)
* Savings Display (concrete value reinforcement)
* Social Proof (trust and social validation)
* Cart Recommendations (deal completion guidance)

This stack addresses every stage of the customer journey from product discovery to cart completion. Each feature handles a different psychological barrier to purchase.

THE URGENCY STACK (PRO — for flash sales and time-limited campaigns)
* Announcement Bar (sitewide deal awareness)
* Product Badges with Bold intensity and urgency badge text
* Countdown Timer with Bold intensity
* Exit Intent Popup (recover abandoning visitors)
* Savings Display

This combination creates the maximum urgency environment. Use for 4–24 hour flash sales or major promotional events only. This intensity level is not appropriate for everyday use — reserve it for genuine high-urgency campaigns.

THE LOYALTY STACK (PRO — for VIP and retention campaigns)
* Product Badges with "Member Exclusive" badge text
* Savings Display showing dollar amounts saved
* Bundle Spotlight showing relevant bundle deals
* Cart Recommendations pointing to complementary products

Pair with Segments targeting to ensure these Superpowers only activate for customers who meet your loyalty tier criteria.

INTENSITY MANAGEMENT BY PERIOD
* Normal trading: Moderate intensity across all active Superpowers
* Weekly sale: Moderate to Bold on key Superpowers (Badge, Progress Bar, Savings)
* Flash sale event: Bold across all Superpowers, add Countdown Timer and Announcement Bar
* Post-sale recovery: Return to Subtle/Moderate immediately after the event ends'],
],
];

$topics['analytics'] = [
'icon'  => '<span style="font-size:28px">📊</span>',
'emoji' => '📊',
'title' => 'Analytics, ROI & Optimisation',
'desc'  => 'How to read every metric, use the ROI Projector, run A/B tests, and build a data-driven optimisation strategy.',
'color' => '#22c55e',
'sections' => [

['Dashboard Metrics Explained',
'The GT BOGO Engine dashboard shows four headline metrics recalculated from real WooCommerce order data.

BOGO REVENUE
The total cart value of all orders where at least one GT BOGO Engine rule fired. This is your BOGO-influenced revenue — the full order value of those transactions, not just the discounted portion. Use this metric to understand the total commercial scale of your BOGO campaigns.

**How to read it:** Compare BOGO Revenue month-over-month. Consistent growth indicates your rules are matching more carts as your traffic grows or your deal awareness improves. A sudden drop indicates a rule may have been paused or a caching issue may be preventing discounts from applying.

BOGO ORDERS
Count of orders where a GT BOGO Engine discount was applied. This is your deal conversion volume.

**How to read it:** Divide BOGO Revenue by BOGO Orders to calculate your BOGO average order value (BOGO AOV). Compare this to your store-wide AOV from WooCommerce Analytics. A well-configured BOGO strategy should produce a BOGO AOV that is 20–40% higher than your store-wide AOV — the deal incentive should be driving larger cart sizes.

DISCOUNTS GIVEN
Total discount value granted across all BOGO orders for the period. This is your promotional cost.

**How to read it:** Calculate your effective BOGO margin: (BOGO Revenue minus Discounts Given) divided by BOGO Revenue. If this percentage is above 60%, your deals are structured correctly — you are giving away less than 40 cents per dollar of influenced revenue. If it drops below 50%, your discounts may be too aggressive and worth reviewing.

AVERAGE ORDER VALUE
Mean cart value specifically on BOGO orders. Watch this trend week-over-week.

**How to read it:** BOGO AOV should be rising as your rule stack matures and Superpowers are added. Flat or declining BOGO AOV despite active rules suggests your Buy Quantity thresholds may need adjustment — they may be too low, meaning customers are barely qualifying without adding extra items.'],

['7-Day Performance Chart',
'The dashboard includes a live 7-day chart showing daily revenue and BOGO order count. Toggle between Revenue and Orders views using the buttons above the chart.

READING RISING TRENDS
A rising trend during the first 7–14 days of a new promotion is the expected pattern. As customers discover the deal, engagement builds. If you see a rising trend, maintain the current configuration — it is working.

READING FLAT LINES
A flat performance line indicates your rules are running consistently but not growing. This is fine for long-running baseline deals. To inject growth into a flat line: send an email to your list about the deal, post on social media, or increase Superpower intensity temporarily.

READING EVENT SPIKES
A sharp spike followed by a return to baseline is the classic flash sale pattern. Evaluate the event by comparing total revenue during the spike window versus the same period from the prior week. Spikes that produce 2–3x normal daily revenue with acceptable margin are successful events worth repeating.

READING DECLINING TRENDS
A declining trend on an active rule warrants investigation:
* Is the rule still Active in the Rule Stack table? Check it has not been accidentally paused.
* Has a caching plugin been installed or updated? Cart caching can prevent discounts from applying. Clear all caches.
* Has a new discount plugin been installed that may be conflicting? Check the Conflict Resolver.
* Is the promotion still being communicated externally (email, social)? External traffic drivers sustain performance.

ZERO DATA
If the chart shows no data despite rules being active, test immediately: add qualifying products to your cart and check if the discount applies. If it does not, check System Status for any error indicators. If the discount does apply in testing but data is not showing, the analytics database table may need a repair — go to **Settings > System Status > Repair Database Tables**.'],

['Rule Performance Analysis',
'The Rule Performance section shows a comparative bar chart of how many times each active rule has fired within the measurement window.

WHAT "FIRED" MEANS
A rule "fires" each time it successfully matches a cart composition and applies a discount. One customer order can generate multiple fires if several rules match simultaneously.

DIAGNOSING RULES THAT NEVER FIRE
If a rule shows zero or near-zero fires compared to others:
* **Buy Quantity too high** — if your Buy Quantity is 4 but most customers add 1–2 items, the rule rarely qualifies. Lower the Buy Quantity or check your average items-per-order in WooCommerce Analytics.
* **Product targeting too narrow** — if the rule targets specific products, check those products are actually being added to carts.
* **Rule priority too low** — a very high priority number (e.g. 15) may mean higher-priority rules are always consuming the qualifying items first. Check your rule stack order.
* **Status accidentally paused** — verify the rule is Active in the Rule Stack table.

DIAGNOSING RULES THAT FIRE CONSTANTLY
A rule that fires on nearly every cart may be too broad. This is not necessarily a problem — a well-configured sitewide BOGO that fires on every cart is exactly what you want. However, if the discount amount is high and the rule is firing constantly, check your Discounts Given metric to ensure margin is within acceptable range.

USING RULE PERFORMANCE TO OPTIMISE YOUR STACK
Rules with consistently low fire counts and low revenue attribution are candidates for retirement or reconfiguration. Rules with high fire counts and high revenue attribution are your best performers — consider variants in A/B testing to see if the configuration can be further optimised.'],

['ROI Projector',
'The ROI Projector page (MAIN section) lets you model the revenue impact of different BOGO strategies before committing to them. Use it to justify investment in PRO Packs or to set performance targets for campaigns.

HOW TO USE THE ROI PROJECTOR

1. Enter your **current monthly order volume** — find this in WooCommerce > Analytics > Orders
2. Enter your **current average order value** — find this in WooCommerce > Analytics > Revenue
3. Enter your **estimated BOGO conversion uplift** — the percentage of orders you expect BOGO to influence
4. Enter your **estimated AOV increase** — how much you expect BOGO to lift average cart size
5. Enter your **average product margin** — your gross margin percentage
6. Click **Calculate**

The projector outputs projected monthly and annual revenue increase, total discount cost, and net profit impact.

SETTING REALISTIC UPLIFT EXPECTATIONS

For a store activating BOGO for the first time with a single rule and no Superpowers:
* AOV increase in the first 30 days: 5–12% is realistic
* Conversion rate impact: minimal initially

With the full free Superpower stack (Badges + Progress Bar) added to a single rule:
* AOV increase: 12–20% within 30 days

With PRO license, 3–5 active rules, and full Superpower stack (Badges, Progress Bar, Savings Display, Social Proof):
* AOV increase: 20–35% within 60 days of full implementation

With complete rule stack (10–15 rules), all Superpowers, and consistent external promotion (email, social):
* AOV increase: 35–55% is achievable for stores with established audiences

These are real-world ranges observed across stores using GT BOGO Engine. Your results depend on traffic volume, product mix, price points, and how consistently you implement the optimisation roadmap.'],

['A/B Testing Your Rules',
'The A/B Testing page (PRECISION section, PRO only) allows you to run controlled experiments on rule variants to identify which configurations generate the most revenue.

SETTING UP A TEST

1. Go to **PRECISION > A/B Testing**
2. Select your **Control Rule** — your current active version
3. Click **Create Variant** and configure the variant with one changed parameter
4. Set **Traffic Split** — 50/50 is recommended for clean, fast data
5. Set **Test Duration** — minimum 14 days. 30 days is ideal for statistical reliability.
6. Click **Start Test**

GT BOGO Engine handles variant assignment automatically. Each visitor session is randomly assigned to the control or variant and the assignment is maintained consistently throughout that session.

WHAT TO TEST (IN ORDER OF EXPECTED IMPACT)

1. **Discount amount** — Does 50% off or 100% off produce more net revenue? Free is more exciting but costs more margin. The higher discount may actually produce lower net revenue if it does not drive significantly more volume.
2. **Buy Quantity** — Does Buy 1 Get 1 or Buy 2 Get 1 produce better AOV lift? Higher thresholds create larger carts when they fire but reduce the number of qualifying carts.
3. **Rule type** — Does a BOGO rule or a Cart Threshold rule produce better results on the same product set?
4. **Superpower intensity** — Does the same rule with Bold superpowers versus Subtle superpowers produce meaningfully different conversion rates?

READING TEST RESULTS
The A/B test results page shows for each variant:
* Total orders attributed
* Total revenue generated
* Average order value
* Total discount cost
* Revenue per session

**A variant wins on revenue per session, not on conversion rate alone.** A cheaper deal may convert more customers but produce less net revenue per visitor. Always evaluate on revenue per session for a complete picture.'],

['30-60-90 Day Optimisation Roadmap',
'A proven implementation timeline for new GT BOGO Engine users. Stores that complete this roadmap consistently report 30–50% AOV increases and 15–25% total revenue growth within 90 days.

DAYS 1–7 — FOUNDATION
* Configure Free Core Rule as Buy 1 Get 1 Free (sitewide)
* Enable Product Badges and Cart Progress Bar free Superpowers
* Customise badge text and progress bar messages in White Label
* Run a test purchase in incognito to confirm discount applies
* Check System Status — all green

DAYS 8–14 — ACTIVATE PRO
* Purchase and activate PRO license
* Start with Starter Revenue Bundle (5 packs) or the single pack most relevant to your goal
* Import and review pack rules — activate 2–3 of them
* Enable Savings Display and Social Proof Superpowers
* Send an email to your list announcing the new deal

DAYS 15–30 — FIRST OPTIMISATION CYCLE
* Review Rule Performance chart — which rules are firing most?
* Check BOGO AOV vs store-wide AOV — is the gap 20% or more?
* Adjust Buy Quantity on any rules that are firing very rarely
* Set up first A/B test — try 50% off vs 100% off on your most-fired rule
* Enable Cart Recommendations Superpower

DAYS 31–60 — SCALING UP
* Import and activate remaining purchased packs
* Configure Segments for VIP and new customer targeting
* Set up Scheduler for seasonal rules
* Enable Bundle Spotlight and Announcement Bar
* Run ROI Projector to model next 30 days
* Review A/B test results and apply winning variant

DAYS 61–90 — FULL STACK OPERATION
* Full rule stack active: 8–15 rules covering different scenarios and customer segments
* All appropriate Superpowers configured with correct intensity levels per brand
* A/B testing running continuously on your top 3 rules
* Monthly ROI review vs Projector targets
* White Label fully customised — all customer-facing messages on-brand
* Seasonal calendar planned — Scheduler pre-loaded with upcoming promotional dates'],
],
];

$topics['white-label'] = [
'icon'  => '<span style="font-size:28px">🎨</span>',
'emoji' => '🎨',
'title' => 'White Label & Brand Customisation',
'desc'  => 'How to make GT BOGO Engine speak in your brand voice — every customer-facing message, badge, and notification.',
'color' => '#ec4899',
'sections' => [

['What White Label Controls',
'GT BOGO Engine is white-label by default. No GT BOGO branding is visible to your customers anywhere on the front end of your store. Every customer-facing element displays your customised text — or nothing at all if you choose not to enable it.

The White Label settings page gives you full control over:

CART AND CHECKOUT MESSAGES
* The message shown in the WooCommerce cart when a BOGO deal is applied
* The savings confirmation message at checkout
* The "deal not yet unlocked" message shown when a customer is close to qualifying

PRODUCT BADGES
* Badge text displayed on eligible product images
* Badge position (top-left, top-right, bottom-left, bottom-right)

PROGRESS BAR
* Progress text shown while approaching the buy quantity threshold
* Completion text shown when the threshold is hit
* Urgency variant text for time-limited deals

POPUP AND NOTIFICATION MESSAGES
* Smart Popup headline and body text
* Exit Intent Popup headline and call-to-action
* Announcement Bar text and CTA button label

EMAIL NOTIFICATIONS (if enabled)
* Subject line for BOGO deal notification emails
* Email body text and footer

PLUGIN ADMIN BRANDING (for agencies)
* Plugin name displayed in the WordPress admin sidebar
* Admin menu icon
* Support link destination (replace with your own support system)

WHAT CANNOT BE CUSTOMISED
The checkout discount line item label in WooCommerce (e.g. "BOGO Discount") follows WooCommerce native display conventions and may vary by theme. The discount itself always applies correctly — only the label display depends on your theme.'],

['Customising Cart and Checkout Messages',
'Cart and checkout messages are your highest-visibility customer touchpoints. They confirm the deal, quantify the savings, and reinforce the purchase decision at the moment it matters most.

CART MESSAGE (when deal is applied)
This appears in the cart when a BOGO discount has been successfully applied.

Default: "BOGO deal applied! You are saving [amount] on this order."

BRAND VOICE EXAMPLES

Premium fashion brand:
"Your exclusive member deal has been applied. [Amount] saved — because great style deserves a reward."

Sporting goods store:
"Deal locked in. You are saving [amount] on this order. Train more, spend less."

Home goods store:
"Your home deserves the best. Deal applied — [amount] saved on this order."

Children brand:
"Great pick! Your deal has been applied — [amount] saved. More fun for your family."

Neutral / agency white-label:
"Your promotional discount has been applied — [amount] saved on this order."

MESSAGE OPTIMISATION PRINCIPLES
* Keep messages under 100 characters — longer messages truncate on mobile
* Use a congratulatory tone — the customer earned something, make them feel good
* Always include `[amount]` so customers see their actual savings in dollars
* Avoid negative phrasing ("discount applied" is better than "price reduced")

CART PROGRESS MESSAGE (before threshold is met)
Default: "Add [x] more item(s) to unlock your deal!"

Enhanced version: "You are [x] item(s) away from saving [potential_saving] — add more to unlock!"

DEAL NOT AVAILABLE MESSAGE
If a customer visits the cart and the active rule conditions cannot be met (wrong products, wrong quantity), a configurable "deal conditions" message can explain what qualifies. This reduces confusion and can recover carts that would otherwise abandon.'],

['Product Badge and Progress Bar Optimisation',
'BADGE TEXT TESTING
Badge text is one of the highest-leverage customisation variables. The same deal with different badge text produces measurably different click-through rates on product listings.

PROVEN HIGH-PERFORMING BADGE TEXTS (in order of typical click-through rate):
* "Buy More Save More" — 18 characters — communicates the deal mechanic, drives curiosity about how much saving is available
* "BOGO Active" — 11 characters — clear and direct, works across deal types
* "Flash Deal On Now" — 17 characters — urgency variant, strong for time-limited campaigns
* "Deal: Buy 2 Get 1" — 17 characters — states the specific deal, sets clear expectation
* "Member Exclusive" — 16 characters — VIP and loyalty variant, creates exclusivity feeling
* "Free Gift Inside" — 15 characters — highest curiosity factor for free gift rules

BADGE POSITION
* **Top-left** — highest-visibility position, most viewed in eye-tracking research on product grids
* **Top-right** — strong for stores where other labels (New, Sale) already occupy top-left
* **Bottom-left** — less prominent, use for Subtle intensity where you want the badge visible but understated
* **Bottom-right** — rarely optimal for promotional badges, best avoided

BADGE LENGTH LIMITS
Keep badge text under 20 characters for clean display across all device sizes. On mobile, badges longer than 18 characters begin to wrap or truncate depending on the theme. Test your badge text on a mobile device after customising.

PROGRESS BAR MESSAGE OPTIMISATION
The most effective progress bar messages include:
* The exact number of items remaining (not a vague "add more")
* The specific dollar amount the customer will save on completion
* A sense of proximity ("almost there", "just one more")

Example: "Almost there — add just 1 more item to save $12.50!"

This is more effective than: "Add 1 item to unlock your deal." because it quantifies the reward and creates a sense of being close to completion.'],

['Agency White Labelling',
'For agencies deploying GT BOGO Engine across multiple client sites, full white labelling removes all GT BOGO references from the admin interface.

RENAMING THE PLUGIN IN WORDPRESS ADMIN

1. Go to the White Label page in the plugin sidebar
2. Find the **Plugin Admin Name** field
3. Enter your preferred name — e.g. "[Agency Name] Promotions Engine", "Smart Deals Manager", "Revenue Boost Engine"
4. Click Save
5. The sidebar menu label, browser tab titles, and all internal admin references update immediately to your chosen name

The renamed plugin appears in the WordPress admin exactly as if it were a proprietary product — no mention of GT BOGO Engine in any visible location.

REPLACING THE ADMIN ICON
Replace the default ⚡ icon with any emoji or short text string. Use your agency initials, a relevant emoji (💰 for revenue, 🎯 for targeting, 🚀 for growth), or a brand symbol.

HIDING VERSION AND LICENSE INFORMATION
The White Label settings include an option to hide the version number and license status display from the admin footer. This prevents clients from seeing the product name, version, or pricing information — important for agencies billing white-label plugin services at their own rates.

CUSTOM SUPPORT DESTINATION
Replace the default self-service portal link with your own agency support system URL or email ticket URL. All help and documentation links throughout the plugin update to point to your configured destination. Your clients reach your support, not the GT BOGO Engine portal.

MULTI-SITE DEPLOYMENT
Each site requires its own active PRO license. For agencies managing multiple client sites, the Complete BOGO Arsenal bundle provides the best per-pack value when deploying the full toolset across multiple installations. Each site installation is independent — rules, settings, and analytics are per-site.'],
],
];

$topics['troubleshooting'] = [
'icon'  => '<span style="font-size:28px">🔧</span>',
'emoji' => '🔧',
'title' => 'Troubleshooting & Self-Service',
'desc'  => 'Step-by-step diagnostics for every common issue. Resolve problems yourself without waiting for anyone.',
'color' => '#64748b',
'sections' => [

['Self-Service First — Resolve Issues Without Waiting',
'The vast majority of GT BOGO Engine issues can be resolved in under 5 minutes using the steps in this guide. Work through these before concluding there is a genuine bug.

THE UNIVERSAL FIRST RESPONSE — DO THIS FOR ANY ISSUE

1. **Clear all caches** — Go to **Settings > System Status > Clear All Caches**. This purges GT BOGO Engine transients, WooCommerce transients, and requests an object cache flush. Most intermittent issues are caused by stale cached data.
2. **Deactivate and reactivate the plugin** — Go to Plugins > Installed Plugins. Deactivate GT BOGO Engine, then activate it again. This re-runs the initialisation routine. Your rules and settings are in the database and are not affected.
3. **Test in incognito mode** — Open a fresh incognito browser window. Add qualifying products to your cart. This bypasses browser caching, session data, and browser extension interference.
4. **Run System Status** — Go to **Settings > System Status**. All indicators should be green. Any amber or red indicator includes a description of the issue and resolution steps.
5. **Check the Audit Log** — Go to **Audit Log** in the sidebar. Review recent entries for unexpected changes — accidentally paused rules, settings modifications, or cache events.

RETRIEVE YOUR LICENSE KEY
Never rely on saved emails for your license key. Use the secure self-service portal to retrieve it at any time:
**https://graphictshirts.shop/bogo/retrieve-license.php**
Enter your purchase email address. A verification code is sent to confirm your identity. Your license key and pack keys are then displayed securely. No waiting, no manual process.'],

['Discount Not Applying to Cart',
'This is the most common reported issue. In nearly every case, the cause is one of the following. Work through them in order.

CHECK 1 — RULE IS ACTIVE
Go to **PRO Rules / Packs > Rule Stack**. Is your rule showing a green "Active" status? A paused rule applies no discounts. Click Activate if it shows Paused.

CHECK 2 — CART MEETS BUY QUANTITY
Your rule fires when the cart contains at least the **Buy Quantity** number of qualifying items. If Buy Quantity is 2, the cart must contain 2 or more items. Add exactly the right quantity and test again with a specific known qualifying product.

CHECK 3 — PAGE CACHING ON CART
This is the most common hidden cause. WP Rocket, W3 Total Cache, LiteSpeed Cache, and other caching plugins can cache the cart page and serve stale content that does not reflect the current session state.

**WP Rocket fix:** Go to WP Rocket > Cache > Never Cache These Pages. Add `/cart/` and `/checkout/` on separate lines. Click Save. Clear all WP Rocket caches. Test again in a fresh incognito session.

**LiteSpeed Cache fix:** Go to LiteSpeed Cache > WooCommerce. Enable "Do Not Cache Cart" and "Do Not Cache Checkout". Save and clear all caches.

**W3 Total Cache fix:** Go to Performance > Page Cache > Advanced. Add `/cart` and `/checkout` to the "Never cache the following pages" field.

CHECK 4 — PLUGIN CONFLICT
Another active discount plugin may be conflicting with GT BOGO Engine. Go to **PRECISION > Conflict Resolver** and run an automatic scan. Common conflicting plugins include: WooCommerce Dynamic Pricing, YITH WooCommerce Discount Manager, Discount Rules for WooCommerce, and Smart Coupons.

Temporarily deactivate each other discount plugin one at a time while testing to identify the conflict source.

CHECK 5 — WOOCOMMERCE CART SESSIONS
If discounts apply in testing but not for real customers, WooCommerce session handling may be inconsistent. Go to **WooCommerce > Status > Tools** and run "Clear WooCommerce Transients". Then test again.'],

['License Key Issues and Self-Service Retrieval',
'ALWAYS USE SELF-SERVICE FIRST
For any license-related issue, start at the self-service portal before trying anything else:
**https://graphictshirts.shop/bogo/retrieve-license.php**
Enter your purchase email. Verify your identity with the 6-digit code sent to your inbox. Your license keys and pack keys are displayed immediately.

SYMPTOM: "Invalid license key"
* Copy-paste the key directly from the portal — do not retype it manually
* Check for spaces before or after the key (common when copying from email clients)
* Ensure you are using the GT BOGO Engine PRO license key, not a pack access key
* Keys are case-sensitive. Use the exact key format shown: `GTBOGO-XXXXX-XXXXX-XXXXX-XXXXX`

SYMPTOM: "License already activated on another site"
Your license is registered to a different domain. If you have migrated:
1. Go to **Settings > License > Deactivate** on the old domain (if accessible)
2. Re-activate on the new domain
3. If the old domain is no longer accessible, use the deactivation link in your purchase confirmation email

SYMPTOM: "Cannot connect to license server"
Your server cannot reach `graphictshirts.shop` over HTTPS. This is required for license verification.
1. Contact your hosting provider and ask them to confirm outbound HTTPS connections are permitted
2. If on a restrictive firewall, request that `graphictshirts.shop` be whitelisted on port 443
3. Test connectivity: `curl -I https://graphictshirts.shop/bogo/api/license-verify.php` from your server via SSH

SYMPTOM: License shows "Expired"
Your annual license has lapsed. Go to **PRO Rules / Packs** and use the PayPal renewal button on the License tab ($19.99/yr). Renewals stack — renewing before expiry adds a full year to your remaining time, not just from the renewal date.'],

['PayPal Purchase Buttons Not Loading',
'If the PayPal hosted button containers appear blank (empty space where the button should be):

CHECK 1 — JAVASCRIPT IS ENABLED
The PayPal SDK requires JavaScript. Confirm it is enabled in your browser settings.

CHECK 2 — ADBLOCKER
Most adblockers block PayPal SDK scripts. Disable your adblocker for this specific page and reload. This is the most common cause by far.

CHECK 3 — HTTPS REQUIRED
The PayPal SDK only loads on pages served over HTTPS. If your WordPress admin or storefront is on HTTP (not HTTPS), the PayPal buttons will not render. Install an SSL certificate — free via Let\'s Encrypt through most hosting providers.

CHECK 4 — CONTENT SECURITY POLICY
Your site may have a Content Security Policy (CSP) header that blocks PayPal scripts. Open your browser developer tools (F12), go to the Console tab, and look for CSP error messages. If present, your developer needs to add `paypal.com` and `*.paypal.com` to the `script-src` and `frame-src` directives in your CSP configuration.

CHECK 5 — BROWSER CONSOLE ERRORS
Open F12 > Console. Look for error messages from the PayPal SDK. Common messages:
* **"Invalid hosted button ID"** — the button ID has been misconfigured. Note the error and use the self-service portal to report it.
* **"Blocked by client"** — an extension or adblocker is intercepting the PayPal request. Try a fresh incognito window.
* **"SDK could not be loaded"** — network issue. Check your internet connection and try again.

CHECK 6 — TRY ANOTHER BROWSER
If buttons load in a different browser, the issue is browser-specific (extension conflict, cached error state, or browser privacy settings blocking third-party scripts). Clear browser cache and cookies, or use Chrome in incognito as the reference environment.'],

['Cache and Performance Issues',
'GT BOGO ENGINE AND CACHING PLUGINS

GT BOGO Engine calculates discounts dynamically per cart session. This means the cart and checkout pages must never be cached at the page level — they need to serve fresh, session-specific content on every visit.

UNIVERSAL CACHE EXCLUSION RULE
Always exclude these URL patterns from your caching plugin page cache:
* `/cart/` and `/cart`
* `/checkout/` and `/checkout`
* Any page containing the `[woocommerce_cart]` or `[woocommerce_checkout]` shortcode

OBJECT CACHE (REDIS / MEMCACHED)
If you are running an object cache plugin (Redis Object Cache, W3 Total Cache with Memcached, or similar), stale WooCommerce session data can cause discount inconsistencies.

After making rule changes, always run: **Settings > System Status > Clear All Caches**. This purges GT BOGO Engine transients and requests an object cache flush if the object cache API is accessible.

WOOCOMMERCE FRAGMENTS / MINI CART
Some caching configurations cache WooCommerce cart fragments, which powers the mini-cart dropdown. If the mini cart shows incorrect discount information while the main cart page is correct, the fragment cache needs to be excluded. In WP Rocket, enable the WooCommerce add-on under Plugins. This automatically handles fragment cache exclusions.

OPCACHE AND PHP CACHING
GT BOGO Engine includes an OPcache purge on plugin activation, update, and rule saves. If you have made direct PHP file modifications on the server and changes are not taking effect, manually clear OPcache: **Settings > System Status > Clear OPcache**.

PERFORMANCE ON LARGE CATALOGUES
GT BOGO Engine is optimised for large WooCommerce catalogues. All database queries use prepared statements and appropriate indexes. Analytics queries use transient caching with a 6-hour expiry to prevent repeated heavy queries. If you notice performance issues on stores with 10,000+ products, run a database optimisation in **WooCommerce > Status > Tools > Optimise Database Tables** and ensure your database server is adequately resourced.'],

['Compatibility with Other Plugins',
'GT BOGO Engine is designed to work alongside the WooCommerce ecosystem but conflicts can occur with certain other discount and pricing plugins.

KNOWN COMPATIBLE PLUGINS
* All major caching plugins (WP Rocket, LiteSpeed Cache, W3 Total Cache) — with cart/checkout exclusions configured
* WooCommerce Subscriptions
* WooCommerce Memberships
* WooCommerce Bookings
* WooCommerce Product Bundles
* YITH WooCommerce Wishlist
* Elementor and WooCommerce Elementor integration
* WPForms and WooCommerce

PLUGINS THAT MAY CONFLICT
* WooCommerce Dynamic Pricing — both plugins modify cart item prices, which can cause calculation conflicts
* YITH WooCommerce Discount Manager — overlapping discount application logic
* Discount Rules for WooCommerce (Flycart) — concurrent discount application may produce unexpected totals
* WooCommerce Smart Coupons — coupon-based discounts combined with automatic BOGO discounts may stack unexpectedly

RESOLVING CONFLICTS
1. Go to **PRECISION > Conflict Resolver** and run a scan — this detects known plugin conflicts automatically
2. If a conflict is identified, the Conflict Resolver suggests resolution options including rule scoping, priority adjustment, and exclusion configuration
3. For unknown conflicts: temporarily deactivate the conflicting plugin, confirm GT BOGO Engine functions correctly, then reactivate and test both together to identify the specific interaction

THEME CONFLICTS
If discounts apply correctly in the cart data but do not display in the cart UI, the issue is typically a theme override of WooCommerce cart templates. Check with your theme developer whether the theme includes custom WooCommerce cart template files. Custom cart templates that have not been updated to the current WooCommerce version can suppress discount display.'],
],
];

/* ─────────────────────────────────────────────────────────
   SUB-PAGE VIEW
───────────────────────────────────────────────────────── */

$topics['customer-segments'] = [
'icon'  => '<span style="font-size:28px">🎯</span>',
'emoji' => '🎯',
'title' => 'Customer Segments',
'desc'  => 'How to create and use customer segments to target the right buyers with the right deals for maximum ROI.',
'color' => '#e10000',
'sections' => [
  ['What Are Customer Segments?', "A customer segment is a saved filter that defines **who qualifies** for a BOGO rule. Instead of applying a deal to every visitor, segments let you target first-time buyers differently from VIPs, and loyal spenders differently from occasional shoppers.

Segments are created once in the Customer Segments page and can be referenced by any PRO rule. This gives you a library of reusable targeting filters that you can mix and match across campaigns."],

  ['The Three Matching Modes', "Every segment has a matching mode that controls how its conditions are combined:

**All Customers** — No filtering. The rule applies to every visitor regardless of order history. Use this for sitewide promotions or when you are just getting started.

**Match Any** — The customer qualifies if they satisfy at least one condition. Ideal for broad campaigns where you want to include multiple customer types in a single rule. For example: Match Any of (First-Time Buyer OR Returning Customer) catches everyone except non-customers.

**Match All** — The customer must satisfy every single condition simultaneously. Use this for precision targeting. For example: Match All of (Minimum 3 orders AND Minimum \$200 spend) targets only your genuinely loyal mid-tier buyers."],

  ['Conditions Reference', "**First-Time Buyers** — Customers with exactly 1 completed order. These are your highest-priority growth segment. They have already trusted you once. A well-timed BOGO deal converts them into repeat buyers. Recommended: 25–50% off second purchase.

**Returning Customers** — Customers with 2 or more orders. They are forming a habit. Reward that habit with exclusive deals they cannot get as new customers. This reinforces their loyalty.

**VIP Customers** — Customers with 5 or more orders. Your most valuable buyers. Give them your best deals — Buy 1 Get 1 Free, first access to limited offers. Making VIPs feel seen dramatically reduces churn.

**Minimum Lifetime Spend** — Filters by total money spent across all orders. Use this to identify high-value customers even if they have only placed a few large orders. Example: \$500+ minimum catches customers who buy in bulk.

**Maximum Lifetime Spend** — Sets an upper spending cap. Combine with a minimum to create a mid-tier band. This prevents you from over-discounting your whale customers who would buy regardless.

**Minimum Order Count** — Requires a minimum number of orders. Set to 3 to identify customers who are forming a genuine purchase habit."],

  ['User Roles', "WordPress assigns every registered user a role. WooCommerce adds a **Customer** role automatically on first purchase or registration.

**Customer** — Standard WooCommerce buyer. This is your primary audience for most deals.

**Subscriber** — Registered user who has not yet purchased. Email-list members. Target with first-order deals to convert them.

**VIP Customer / Gold VIP / Platinum VIP** — Custom loyalty tier roles. Create these using a plugin like User Role Editor and assign them manually or via automation. Use these for your most exclusive deals.

**Whale Customer** — A custom role for very high-spend buyers. Target with premium bundles rather than heavy percentage discounts to protect margin.

**Administrator / Shop Manager** — Store staff. Always exclude these from customer-facing rules.

**How to create custom roles:** Install User Role Editor (free on WordPress.org), create the role, and assign it to customers manually or via a CRM/loyalty plugin."],

  ['Segment Strategy Guide', "**New Customer Acquisition** — Create a segment: Mode = Match Any, First-Time Buyer = ON. Apply to a 30–50% off deal. Measure repeat purchase rate over 60 days.

**Loyalty Rewards** — Create a segment: Mode = Match All, Returning Customer = ON, Min Spend = \$100. Apply to a Buy 1 Get 1 50% Off deal on selected products.

**Win-Back Campaign** — Create a segment: Mode = Match All, Returning Customer = ON, Max Spend = \$500 (exclude whales), Min Orders = 2. Apply to a flash sale rule with a 48-hour Campaign Scheduler.

**VIP Exclusives** — Create a segment: Mode = Match Any, User Roles = VIP Customer. Apply to a Buy 1 Get 1 Free deal on your premium product range. Gate it so only VIPs see it.

**Prevent Whale Over-Discounting** — Create a segment: Mode = Match All, Max Lifetime Spend = \$2000 (exclude top spenders). Apply your deals to mid-tier buyers and let your whales buy at full price."],
],
];

if ($current_doc && isset($topics[$current_doc])) {
    $t = $topics[$current_doc];
    require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
    <div>
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=documentation')); ?>"
           style="color:#64748b;text-decoration:none;font-size:13px;display:inline-flex;align-items:center;gap:6px;margin-bottom:10px"
           onmouseover="this.style.color='#ffffff'" onmouseout="this.style.color='#64748b'">← All Documentation</a>
        <h1 class="gt-page-title"><?php echo wp_kses_post($t['emoji'] . ' ' . $t['title']); ?></h1>
        <p class="gt-page-subtitle"><?php echo esc_html($t['desc']); ?></p>
    </div>
</div>

<!-- Table of contents -->
<div class="gt-card gt-animate-in" style="margin-bottom:24px;background:rgba(255,255,255,0.015)">
    <div style="padding:18px 24px">
        <div style="font-size:11px;font-weight:800;color:<?php echo esc_attr($t['color']); ?>;letter-spacing:1.5px;text-transform:uppercase;margin-bottom:12px">In This Guide</div>
        <div style="display:flex;flex-wrap:wrap;gap:8px">
            <?php foreach ($t['sections'] as $i => $sec): ?>
            <a href="#gts-<?php echo $i; ?>"
               style="font-size:13px;color:#94a3b8;text-decoration:none;background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.08);border-radius:6px;padding:5px 12px;transition:all 0.15s"
               onmouseover="this.style.borderColor='<?php echo esc_attr($t['color']); ?>55';this.style.color='#ffffff'"
               onmouseout="this.style.borderColor='rgba(255,255,255,0.08)';this.style.color='#94a3b8'">
                <?php echo esc_html($sec[0]); ?>
            </a>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<?php foreach ($t['sections'] as $i => $sec): ?>
<div class="gt-card gt-animate-in" style="margin-bottom:18px" id="gts-<?php echo $i; ?>">
    <div style="padding:20px 28px 16px;border-bottom:1px solid var(--gt-border);display:flex;align-items:center;justify-content:space-between">
        <h2 style="font-size:17px;font-weight:800;color:#ffffff;margin:0"><?php echo esc_html($sec[0]); ?></h2>
        <span style="font-size:10px;color:#334155;font-family:monospace;font-weight:700"><?php echo $i+1; ?>/<?php echo count($t['sections']); ?></span>
    </div>
    <div style="padding:20px 28px 24px"><?php echo gtbogo_doc_body($sec[1]); ?></div>
</div>
<?php endforeach; ?>

<div class="gt-card gt-animate-in" style="margin-bottom:24px">
    <div style="padding:22px 28px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:14px">
        <div>
            <div style="font-size:15px;font-weight:700;color:#ffffff;margin-bottom:3px">Need your license key?</div>
            <div style="font-size:13px;color:#64748b">Retrieve it securely — no waiting, no emails needed.</div>
        </div>
        <div style="display:flex;gap:10px;flex-wrap:wrap">
            <a href="https://graphictshirts.shop/bogo/retrieve-license.php" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">🔑 Retrieve License Key</a>
            <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=documentation')); ?>" class="gt-btn gt-btn-secondary">← All Guides</a>
        </div>
    </div>
</div>

<?php
    require_once __DIR__ . '/../ui-system/wrapper-end.php';
    return;
}

/* ─────────────────────────────────────────────────────────
   DOCUMENTATION INDEX PAGE
───────────────────────────────────────────────────────── */
require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>

<div class="gt-page-header gt-animate-in">
    <div>
        <h1 class="gt-page-title">📚 Help &amp; Documentation</h1>
        <p class="gt-page-subtitle">Complete guides to installation, optimisation, and getting maximum revenue from GT BOGO Engine</p>
    </div>
</div>

<!-- Quick start strip -->
<div class="gt-card gt-animate-in" style="margin-bottom:24px">
    <div class="gt-card-header" style="padding:22px 28px 18px;border-bottom:1px solid var(--gt-border)">
        <h2 class="gt-card-title" style="font-size:18px">🚀 Quick Start — Get Live in 5 Minutes</h2>
    </div>
    <?php
    $qs = [
        ['1','#E10000','Activate PRO License','Enter your license key to unlock rules, packs, and all PRO features.','Go to License →','license'],
        ['2','#3b82f6','Configure Your First Rule','Set up the Free Core Rule or import a PRO Pack to launch your first deal.','Free Core Rule →','free-rule'],
        ['3','#8b5cf6','Enable Superpowers','Turn on Product Badges and Cart Progress Bar — free and instantly effective.','Open Settings →','settings'],
        ['4','#22c55e','Purchase PRO Packs','Get expert-built rule templates. Starter Bundle = highest ROI starting point.','Browse Packs →','pro-rules'],
    ];
    foreach ($qs as $i => $q): ?>
    <div style="display:flex;align-items:center;gap:18px;padding:16px 28px;<?php echo $i < count($qs)-1 ? 'border-bottom:1px solid var(--gt-border)' : ''; ?>">
        <div style="width:34px;height:34px;background:<?php echo $q[1]; ?>;border-radius:50%;display:flex;align-items:center;justify-content:center;color:#fff;font-size:15px;font-weight:900;flex-shrink:0"><?php echo $q[0]; ?></div>
        <div style="flex:1"><div style="font-size:14px;font-weight:700;color:#ffffff;margin-bottom:2px"><?php echo esc_html($q[2]); ?></div><div style="font-size:13px;color:#64748b"><?php echo esc_html($q[3]); ?></div></div>
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab='.$q[5])); ?>" class="gt-btn gt-btn-secondary gt-btn-sm" style="white-space:nowrap;flex-shrink:0"><?php echo esc_html($q[4]); ?></a>
    </div>
    <?php endforeach; ?>
</div>

<!-- Topic grid -->
<div style="display:grid;grid-template-columns:repeat(2,1fr);gap:16px;margin-bottom:24px">
    <?php foreach ($topics as $slug => $t):
        $sc = count($t['sections']);
    ?>
    <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=documentation&doc='.$slug)); ?>"
       style="display:flex;align-items:flex-start;gap:18px;text-decoration:none;padding:22px 24px;background:rgba(255,255,255,0.025);border:1px solid rgba(255,255,255,0.07);border-radius:14px;transition:all 0.2s;position:relative;overflow:hidden"
       onmouseover="this.style.background='rgba(255,255,255,0.04)';this.style.borderColor='<?php echo esc_attr($t['color']); ?>45';this.style.transform='translateY(-2px)'"
       onmouseout="this.style.background='rgba(255,255,255,0.025)';this.style.borderColor='rgba(255,255,255,0.07)';this.style.transform=''">
        <!-- Icon block -->
        <div style="flex-shrink:0;width:56px;height:56px;background:<?php echo esc_attr($t['color']); ?>18;border:1px solid <?php echo esc_attr($t['color']); ?>35;border-radius:14px;display:flex;align-items:center;justify-content:center;font-size:26px">
            <?php echo wp_kses_post($t['emoji']); ?>
        </div>
        <!-- Text block -->
        <div style="flex:1;min-width:0">
            <div style="font-size:16px;font-weight:800;color:#ffffff;margin-bottom:5px;line-height:1.2"><?php echo esc_html($t['title']); ?></div>
            <div style="font-size:13px;color:#64748b;line-height:1.55;margin-bottom:12px"><?php echo esc_html($t['desc']); ?></div>
            <div style="display:flex;align-items:center;gap:10px">
                <span style="display:inline-flex;align-items:center;padding:5px 14px;background:<?php echo esc_attr($t['color']); ?>;color:#fff;font-size:12px;font-weight:700;border-radius:50px">Read Guide →</span>
                <span style="font-size:11px;color:#334155"><?php echo $sc; ?> sections</span>
            </div>
        </div>
        <div style="position:absolute;right:-16px;top:-16px;width:70px;height:70px;background:radial-gradient(circle,<?php echo esc_attr($t['color']); ?>15 0%,transparent 70%);pointer-events:none"></div>
    </a>
    <?php endforeach; ?>
</div>

<!-- Self service -->
<div class="gt-card gt-animate-in">
    <div style="padding:24px 28px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:16px">
        <div>
            <h3 style="font-size:17px;font-weight:800;color:#ffffff;margin:0 0 6px">🔑 Need Your License Key?</h3>
            <p style="font-size:13px;color:#64748b;margin:0">Retrieve it securely using your purchase email — no waiting, no contact required.</p>
        </div>
        <a href="https://graphictshirts.shop/bogo/retrieve-license.php" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">Retrieve License Key →</a>
    </div>
    <div style="padding:0 28px 20px;font-size:12px;color:#334155">
        Version <?php echo esc_html(defined('GT_BOGO_ENGINE_VERSION') ? GT_BOGO_ENGINE_VERSION : '3.10.1'); ?> &nbsp;·&nbsp; Self-service portal: graphictshirts.shop/bogo/retrieve-license.php
    </div>
</div>

<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
