=== Affiliate Captain ===
Contributors: codexcaptain
Tags: affiliate, woocommerce, referral, commission, tracking
Donate link: https://codexcaptain.com/affiliate-captain
Requires at least: 5.8
Tested up to: 7.0
Requires PHP: 7.4
Stable tag: 2.1.31
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

WooCommerce affiliate tracking with referral links, coupon attribution, flexible commissions, affiliate dashboards, and Pro growth tools.

== Description ==
Affiliate Captain helps WooCommerce stores launch and manage an affiliate program directly inside WordPress. Track referrals, attribute orders, manage commissions, and give affiliates a clean dashboard without moving your program into a separate platform.

It is built for modern WooCommerce stores with support for High-Performance Order Storage (HPOS), block checkout, cookie-based referrals, coupon attribution, manual order attribution, and Freemius-powered Free/Pro distribution.

= Free vs Pro =

The Free tier covers the core affiliate workflow for up to 10 active affiliates: affiliate management, referral links, cookie tracking, coupon attribution, WooCommerce order attribution, manual attribution, basic dashboard reporting, basic commissions, CSV export, HPOS support, and block checkout support.

Affiliate Captain Pro unlocks advanced growth, automation, and integration features:

* Unlimited active affiliates
* Vanity URLs and advanced link controls
* Advert campaign trackers with campaign costs, sales, net return, ROAS, and side-by-side comparisons
* Attribution Proof, conversion journeys, order timelines, and no-credit diagnostics
* Rate schedules, product/category restrictions, fixed product commissions, and performance bonuses
* Lifetime commissions and multi-tier commissions
* Fraud detection and audit log
* Auto-generated coupons
* Payout requests and scheduled payout workflows
* Creatives, leaderboard, standalone affiliate portal, and direct-link tracking
* REST API, webhooks, PayPal payout support, store credit payouts, and other advanced integrations

= Referral Tracking =

* **Cookie-based tracking** with configurable duration (default 30 days)
* **Coupon-based tracking** — cookieless attribution when customers use an affiliate coupon code
* **Lifetime commissions** — Pro feature: once a customer is attributed, all future orders earn for that affiliate
* **First-click or last-click** attribution model
* **Self-referral protection** prevents affiliates from earning on their own orders

= Pro Link Schedules & Volume Controls =

* Set start and end dates on any affiliate\'s referral link
* Configure maximum click and conversion caps per affiliate
* Grace period setting — existing cookies still earn commissions after link expiry
* Auto-renew links on a weekly, monthly, quarterly, or yearly schedule
* Per-affiliate rate schedules for promotional periods

= Commission Management =

* Percentage or flat-rate commissions (global default with per-affiliate overrides)
* Pro product, variation, and category commission overrides with percentage, fixed per-unit, and fixed per-line-item modes
* Automatic or manual commission approval workflow
* Pro multi-tier commissions (up to 3 tiers) for referral chains
* Pro performance bonuses to reward top affiliates based on monthly volume
* Commissions auto-rejected on order refund or cancellation

= Vanity URLs =

* Give affiliates clean, memorable short links (e.g. yoursite.com/partner-name)
* Automatic collision detection against WordPress pages, posts, WooCommerce endpoints, and reserved paths
* Click tracking per vanity URL with rate limiting
* Print-ready QR code generation for each vanity link
* Configurable post-expiry behavior — keep redirecting or show 404

= Campaign Trackers =

* Pro feature: use vanity URLs as tracking-only advert campaign links without creating payout commissions
* Record campaign costs manually and compare them against attributed WooCommerce revenue
* See campaign order count, gross sales, net return, and ROAS
* Overlay affiliate revenue, advert tracker revenue, clicks, orders, conversion rates, costs, and ROAS in dashboard graphs
* Use campaign backfill to recover historic vanity URL campaigns from a verified date window

= Affiliate Dashboard =

* Integrated into WooCommerce My Account as a dedicated tab
* Real-time stats: clicks, conversions, conversion rate, pending and paid earnings
* 6-month performance chart
* Referral link copy and social sharing (Facebook, X, LinkedIn, and email)
* Coupon code display with copy-to-clipboard
* Pro QR downloads, deep links, vanity links, performance tiers, creatives, and campaign launch kit
* Pro monthly leaderboard and payout request submission

= Admin Tools =

* Full admin dashboard with stat cards, 12-month commission chart, recent activity feed, and top affiliates
* Pro campaign performance dashboard overlays for affiliate sales, campaign costs, campaign revenue, net return, and ROAS
* WP List Table for affiliates with search, status/date filters, and bulk actions (activate, suspend, delete)
* WP List Table for commissions with bulk approve, reject, and mark-as-paid
* Detailed affiliate profile view with performance stats, link management, rate schedule editor, volume caps, product/category restrictions, vanity URL management, and coupon generation
* Manual order attribution metabox on the WooCommerce order edit screen (assign or remove affiliates)
* Payout recording with payment method, reference, and notes
* Payout request approval/rejection workflow
* CSV export for affiliates, commissions, payouts, and referrals with date range filters and CSV injection protection
* Setup wizard for first-time configuration

= Fraud Detection =

* Rapid conversion detection (configurable threshold per hour)
* Self-referral detection across email and payment email
* Email domain matching (excludes free providers like Gmail and Yahoo)
* Billing address matching against affiliate address
* IP velocity checks
* Flagged commissions held for admin review with email notification
* Fraud audit log

= Auto-Generated Coupons =

* Optionally auto-generate a WooCommerce discount coupon when a new affiliate registers
* Configurable discount type (percentage or fixed) and amount
* Admin can manually generate coupons with custom codes from the affiliate detail screen
* Coupons sync expiry with the affiliate\'s link expiry date

= Developer Friendly =

* Pro REST API with API key authentication
* Action and filter hooks throughout (afcpt_commission_amount, afcpt_fraud_flags, afcpt_bonus_tiers, and more)
* HPOS compatible — declared and verified, all order access uses WC CRUD methods
* Block checkout (Store API) compatible
* Fully translatable with i18n-ready strings
* Secure account, licensing, and update delivery through Freemius
* CodexCaptain ecosystem compatible

= External Services =

Affiliate Captain uses the Freemius SDK from https://freemius.com for optional usage tracking, Free/Pro plan management, license activation, account access, checkout, and secure plugin updates. Freemius presents an opt-in screen before optional diagnostic usage data is collected. When an administrator opts in, activates a license, opens account/checkout screens, or checks for updates, site and environment details needed for those services can be sent to Freemius. Freemius terms are at https://freemius.com/terms/ and its privacy policy is at https://freemius.com/privacy/.

Affiliate Captain can connect to CodexCaptain support services at https://codexcaptain.com and the Supabase-powered CodexCaptain support backend only when an administrator uses support features such as opening the support screen, searching support, using chat, submitting a ticket, previewing or sending a diagnostic snapshot, or requesting corrective-build help.

Diagnostic snapshot data is shown in preview before submission and can include WordPress version, PHP version, WooCommerce status, active plugin/theme details, and non-sensitive Affiliate Captain license status needed to diagnose the issue. Corrective-build help requires explicit consent on the support request and never installs remote executable code automatically.

Affiliate Captain can request QR code images from Google Charts at https://chart.googleapis.com/chart or QR Server at https://api.qrserver.com only when an administrator or affiliate views or downloads a QR code for a referral or vanity URL. The referral URL is sent to the QR provider so the image can be generated. Cached QR images may be stored locally in the WordPress uploads directory when generation succeeds.

If an administrator deliberately configures them, Pro can connect to PayPal Payouts, Meta Ads, Google Ads, or administrator-defined webhook destinations. Only the credentials and transaction, campaign, spend, or event data needed for the requested integration are sent to that provider. These connections are disabled until configured by an administrator and are governed by each provider's terms and privacy policy.

== Installation ==
1. Upload the `affiliate-captain` folder to the `/wp-content/plugins/` directory, or install directly through the WordPress plugin screen.
2. Activate the plugin through the **Plugins** menu in WordPress.
3. Navigate to **CodexCaptain > Affiliate Captain** in the WordPress admin. The setup wizard will guide you through initial configuration.
4. Configure detailed settings under **WooCommerce > Settings > Affiliates**.
5. Add your first affiliate from the **Add New** tab or enable open registration with the `[affiliate_registration]` shortcode.
6. Affiliates access their dashboard via **My Account > Affiliate** on the front end.

== Frequently Asked Questions ==
= Does this work with WooCommerce HPOS (High-Performance Order Storage)? =

Yes. Affiliate Captain is fully HPOS compatible. All order data access uses WooCommerce CRUD methods and never touches the posts table directly. HPOS compatibility is declared and verified on activation.

= Does this work with the WooCommerce block checkout? =

Yes. The plugin hooks into both the classic checkout and the newer Store API checkout used by the block-based cart and checkout.

= How do time-limited affiliate links work? =

You can set a start date, end date, or both on any affiliate\'s referral link. Once the link expires, new visitors will not receive a tracking cookie. You can also configure a grace period so that cookies set before expiry continue to earn commissions for a configurable number of days.

= Can affiliates track referrals without cookies? =

Yes. Assign a WooCommerce coupon code to an affiliate. When a customer uses that coupon, the affiliate receives credit regardless of whether a cookie was set. Coupon-based attribution takes priority over cookie-based tracking.

= What happens to commissions when an order is refunded? =

Commissions are automatically rejected when an order is refunded or cancelled, including multi-tier commissions, unless the commission has already been marked as paid.

= Can I set different commission rates for different affiliates? =

Yes. Each affiliate can have a custom commission rate and type (percentage or flat) that overrides the global default. You can also create date-based rate schedules for promotional periods.

= Can I set fixed dollar commissions for specific products? =

Yes. Product, variation, and product-category overrides can be configured as a percentage, a fixed amount per unit, or a fixed amount per line item. Variation rules override parent product rules, product rules override category rules, and category rules override the affiliate/global default.

= How do multi-tier commissions work? =

When enabled, affiliates can have a parent affiliate. When the child affiliate\'s referral makes a purchase, the parent (tier 2) and grandparent (tier 3) each earn a configurable percentage commission on the same order.

= Can affiliates request payouts from their dashboard? =

Yes, in Affiliate Captain Pro if enabled in settings. Affiliates can submit a payout request when their pending balance reaches the minimum threshold you configure. Requests appear in the admin Payouts tab for approval or rejection.

= Why is a vanity URL or affiliate cookie not updating after I change settings? =

Check for page-level redirects, Cloudflare/Page Rules, server redirects, and WordPress caching before testing the affiliate URL again. Vanity URLs must reach WordPress so Affiliate Captain can set the cookie and then redirect. Use the Proof tab to confirm the current affiliate cookie, active date window, and attribution path before client handoff.

= Is there an API? =

Yes, in Affiliate Captain Pro. The REST API is available under `/wp-json/affiliate-captain/v1/` with API key authentication via the `X-Affiliate-Captain-Key` header. Enable it under WooCommerce > Settings > Affiliates > Advanced.

= Does uninstall delete affiliate data? =

No, not by default. Affiliate Captain preserves affiliate, commission, referral, payout, and attribution data unless **Delete Data on Uninstall** is explicitly enabled under WooCommerce > Settings > Affiliates > Advanced.

== Screenshots ==
1. Admin dashboard with stat cards, monthly commission chart, and top affiliates.
2. Affiliate list with search, filters, and bulk actions.
3. Affiliate detail view with performance stats, link management, and coupon generation.

== Changelog ==
= 2.1.31 =
* Activated the opt-in CodexCaptain support connector with the product's public support identity.
* Added verified Survivor Mountain support routing while keeping customer-facing support branded CodexCaptain.
* Strengthened the release gate for shared apex/www cookies, lost-cookie recovery, malformed-cookie recovery, clean installs, and version upgrades.
* Synchronized the Pro Yearly offer at $69.99 for one production site.

= 2.1.30 =
* Integrated the dashboard-generated Freemius SDK configuration for product 29625 and secure Free/Pro distribution.
* Added physical premium-file markers plus runtime and action-level feature gates for a consistent Free/Pro split.
* Kept the complete core affiliate workflow available in Free for up to 10 active affiliates.
* Made setup, settings, affiliate dashboards, and upgrade prompts plan-aware.
* Changed new affiliate links to remain active indefinitely unless a Pro date window is deliberately configured.
* Moved uninstall cleanup to the Freemius after_uninstall lifecycle hook.
* Kept licensing and update availability outside storefront, checkout, order creation, and attribution paths.
* Updated compatibility metadata, external-service disclosures, sales copy, and Freemius package validation.

= 2.1.29 =
* Centralized referral, vanity, coupon, direct-link, campaign, lifetime, and manual attribution decisions.
* Added versioned HMAC-signed attribution cookies and bounded legacy cookie migration.
* Added signed short-lived referral recovery tokens that remain usable when a malformed cookie is present.
* Added idempotent classic checkout, block checkout, Store API, and fallback order attribution capture.
* Added order trace IDs, attribution status, integrity, source, explanation, referral, vanity, and campaign proof.
* Prevented order-list and order-detail screens from mutating historical attribution while being viewed.
* Converted historical vanity recovery into preview-first, explicitly confirmed repairs with audit notes.
* Preserved configured attribution and installed Pro functionality when licensing or update services are unavailable.
* Added reproducible package and attribution release-gate coverage.

= 2.1.28 =
* Added a non-blocking vanity URL referral token fallback so guest/first-time buyer attribution can survive redirect/cookie edge cases.

= 2.1.27 =
* Added fixed dollar product commissions for products, variations, and categories.
* Added product commission type controls for percentage, fixed per unit, and fixed per line item.
* Added affiliate-specific product/category commission overrides with priority over global product/category rules.
* Added Product Rates admin screen for managing affiliate-specific product payouts and viewing global overrides.
* Added product commission proof display, report summary, and CSV export support.
* Added line-aware partial refund recalculation for product-level fixed commissions.
* Added a runnable product commission regression harness for percentage, fixed, mixed, excluded, and refund scenarios.
* Improved commission calculation so product exclusions and affiliate product restrictions are respected when product-level overrides are active.

= 2.1.26 =
* Rebuilt Campaign Trackers into a Campaign Command Center with campaign creation, platform/type/status fields, comparison cards, and richer campaign visuals.
* Added advert-only vanity campaign mode so paid-ad trackers can record attributed WooCommerce sales without creating payout commissions.
* Added revenue overlay graphs comparing affiliate revenue, advert tracker revenue, clicks, orders, conversion rate, cost, and ROAS.
* Added Performance Matchup visuals comparing top affiliates against top marketing campaigns in the same analytics view.
* Added Custom Comparison selectors for comparing chosen affiliates, chosen marketing campaigns, or mixed affiliate/campaign sets.
* Added campaign metadata to order attribution proof for vanity URL orders.
* Added Docker-tested vanity, normal referral, last-click, repeat-purchase, and advert-only campaign attribution checks.

= 2.1.20 =
* Added Campaign Performance dashboard for vanity URL/ad campaign trackers.
* Added campaign name, cost, notes, net return, ROAS, and conversion reporting.
* Added copyable campaign summary report for client-facing proof.
* Added campaign tracker summary to the main admin dashboard.
* Improved future vanity click/order matching behind proxies by aligning referral IP detection with WooCommerce.

= 2.1.4 =
* Fixed admin vanity URL proof display after vanity redirects.
* Added defensive vanity slug uniqueness checks and legacy database index repair.
* Added schema repair before affiliate creation to prevent old installs from failing on newer affiliate fields.

= 2.1.3 =
* Rebuilt the legacy deployment package with its required SDK layout.
* Kept uninstall cleanup on the legacy provider lifecycle hook.

= 2.1.2 =
* Moved uninstall cleanup into the legacy provider lifecycle hook.
* Removed root uninstall.php for legacy deployment compatibility.

= 2.1.1 =
* Polished the Client Proof Wizard with pass/check/fail summary counts.
* Added a guided manual attribution test sequence for client handoff.
* Improved affiliate onboarding assets with copy buttons, QR preview, and clearer launch-kit layout.
* Expanded the copyable proof report with the recommended test sequence.

= 2.1.0 =
* Added Client Proof Wizard with launch checklist, affiliate proof steps, and copyable client report.
* Added attribution timeline to the WooCommerce order card.
* Added payout confidence cockpit with pending, approved, held/review, paid, and rejected commission totals.
* Added affiliate onboarding assets with referral link, coupon, campaign status, example promo copy, and QR download.
* Added affiliate date-window overlap warnings and quick schedule presets.
* Added registration honeypot and short rate limiting for spam protection.
* Updated privacy export/policy content for affiliate campaign date windows.
* Added cache/CDN troubleshooting guidance for vanity URLs and affiliate cookies.

= 2.0.1 =
* Added multiple affiliate active date windows for campaign-based referral availability.
* Added per-window indefinite scheduling for affiliates that should remain active from a chosen start date.
* Preserved the existing single start/end date workflow for backwards compatibility.
* Updated affiliate link status labels to show active, upcoming, expired, and indefinite schedule states.

= 2.0.0 =
* Added the Free/Pro plan scaffold with an optional legacy licensing bridge.
* Added plan-aware feature gates for Pro-only automation, integrations, payouts, and advanced attribution.
* Added Free-mode upgrade notices in admin and affiliate payout surfaces.
* Added affiliate self-registration shortcode [affiliate_registration] with open/closed/invite modes.
* Added affiliate leaderboard with anonymized names on the dashboard.
* Added deep link generator for affiliates to create tracked links to any page.
* Added auto-generated WooCommerce coupon codes for affiliates.
* Added coupon display with copy-to-clipboard on affiliate dashboard.
* Added affiliate payout request system with admin approval workflow.
* Added manual order attribution metabox (HPOS and legacy compatible).
* Added commission notification emails to affiliates.
* Added welcome email with referral link and QR code on activation.
* Added volume caps (max clicks and max conversions) per affiliate.
* Added grace period setting for post-expiry cookie attribution.
* Added auto-renew for time-limited affiliate links.
* Added per-affiliate rate schedules for date-based commission overrides.
* Added product and category restrictions per affiliate.
* Added performance bonus tiers (Bronze through Diamond).
* Added social sharing buttons (Facebook, X, LinkedIn, email) for referral links.
* Added first-click / last-click attribution model setting.
* Fixed multi-tier commission rejection on refund/cancellation.
* Fixed lifetime commission lookup using correct method signatures.
* Fixed coupon-based attribution fallback in order processing.
* Fixed sub-affiliate display using correct database column name.
* Fixed creatives tab to use database storage instead of options.
* Fixed HPOS-aware order links in commissions list table.
* Improved security: wp_unslash on all input, proper sanitization throughout.
* Completed an internal security-focused review and commercial build validation.

= 1.5.0 =
* Added setup wizard for first-time plugin configuration.
* Added vanity URL system with collision detection, QR codes, and click tracking.
* Added CSV export for affiliates, commissions, payouts, and referrals.
* Added REST API with API key authentication.
* Added affiliate column to WooCommerce orders list (HPOS and legacy).
* Added block checkout (Store API) compatibility.
* Added self-hosted auto-updater.
* Improved admin dashboard with 12-month commission chart and activity feed.

= 1.1.0 =
* Added coupon-based affiliate tracking (cookieless attribution).
* Added fraud detection with five check types and admin notifications.
* Added lifetime commissions with customer-affiliate mapping.
* Added multi-tier commissions (up to 3 tiers).
* Added email notification system.
* Added creatives manager.

= 1.0.0 =
* Initial release.

== Upgrade Notice ==
= 2.1.31 =
Adds production support routing and stronger guest-attribution release checks without changing existing affiliate, order, commission, or campaign data.

= 2.1.30 =
Adds Freemius Free/Pro distribution, plan-aware onboarding and settings, and an indefinite default for newly created affiliate links. Existing affiliate, order, attribution, commission, and campaign data is preserved.

= 2.1.29 =
Hardens guest attribution across vanity, referral, coupon, classic checkout, Blocks, and Store API flows.

= 2.1.28 =
Adds a non-blocking vanity URL attribution fallback for guest and first-time shoppers when cookies are disrupted by redirect or browser edge cases.

= 2.1.27 =
Adds fixed dollar product, variation, and category commissions with per-unit and per-line-item payout modes.

= 2.1.26 =
Turns Campaign Trackers into a fuller Campaign Command Center with advert-only tracker mode, revenue overlay graphs, platform comparisons, campaign creation, and no-payout tracking-only attribution.

= 2.1.20 =
Adds the commercial Campaign Performance dashboard and campaign cost/ROAS tracking for vanity URLs.

= 2.1.4 =
Hotfix for vanity URL testing, duplicate vanity slug prevention, and affiliate creation on upgraded installs.

= 2.1.3 =
Legacy deployment package layout update. No site behavior changes.

= 2.1.2 =
Legacy deployment compatibility update. Preserves existing uninstall cleanup behavior through the provider uninstall hook.

= 2.1.1 =
Polishes client proof and affiliate onboarding tools for cleaner client handoff and distribution.

= 2.1.0 =
Adds client proof tools, WooCommerce order attribution timelines, payout confidence reporting, onboarding assets, and safer affiliate registration.

= 2.0.0 =
Major feature release with 15+ new features. Database tables are automatically upgraded on activation. No manual steps required.
