<?php
/**
 * RankForge Pro Bridge — extension API for the Pro add-on.
 *
 * The Free plugin owns this contract. The Pro add-on (rankforge-pro)
 * `register_feature`s every Pro feature it ships and `enable_feature`s
 * those covered by an active license. Free callsites then ask the bridge
 * via RANKFORGE_License::can whether a Pro feature is active in the
 * current environment.
 *
 * See SPLIT_PLAN.md §5.3 for the full Free/Pro split contract.
 *
 * @package RankForge
 * @since 2.0.0
 */

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

class RANKFORGE_Pro_Bridge {

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

    /** @var array<string, array> Pro-feature slug => metadata. */
    private $features = [];

    /** @var array<string, bool> Pro-feature slug => enabled flag. */
    private $enabled = [];

    public static function instance(): self {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {}

    /**
 * Register that a Pro feature exists in this site's Pro add-on.
 * Idempotent — calling twice with the same slug overwrites metadata.
 */
    public function register_feature(string $slug, array $meta = []): void {
        $this->features[$slug] = $meta;
    }

    /** Is this Pro feature shipped by the currently-installed Pro add-on? */
    public function has_feature(string $slug): bool {
        return isset($this->features[$slug]);
    }

    /** Mark a Pro feature as enabled for this environment (license check passed). */
    public function enable_feature(string $slug): void {
        $this->enabled[$slug] = true;
    }

    /** Mark a Pro feature as disabled (license downgraded, trial expired, ...). */
    public function disable_feature(string $slug): void {
        unset($this->enabled[$slug]);
    }

    /**
 * True only when the feature is BOTH registered by Pro AND currently enabled.
 * Free callsites should always use this — it returns false on Free-only
 * sites because Pro never registers anything.
 */
    public function is_enabled(string $slug): bool {
        return !empty($this->enabled[$slug]);
    }

    /**
 * Full feature registry — for admin UI listing.
 * Returns a list of arrays merged from registered metadata plus slug + enabled flag.
 */
    public function all_features(): array {
        $out = [];
        foreach ($this->features as $slug => $meta) {
            $out[] = array_merge(
                ['slug' => $slug, 'enabled' => $this->is_enabled($slug)],
                $meta
            );
        }
        return $out;
    }

    /** Free-core version — Pro reads this to gate by compatibility. */
    public function core_version(): string {
        return defined('RANKFORGE_VERSION') ? RANKFORGE_VERSION : '0.0.0';
    }
}
