<?php

namespace WPDeveloper\BetterDocsPro\Insights;

/**
 * Exit if accessed directly
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Product-usage analytics collector (Pro tier).
 *
 * Hooks the shared `betterdocs_insights_data` filter (exposed by Free's
 * `WPDeveloper\BetterDocs\Insights\Insights::get_data()`) and contributes Pro-only
 * signals. Because this class only loads when Pro is active, its keys appear in the
 * wpinsight payload iff Pro is active — that is how the Free/Pro separation stays
 * clean (no runtime is_plugin_active checks needed).
 *
 * Runs at priority 20 so it sees the groups seeded by the Free collector (priority 10)
 * and can merge Pro-gated flags into `bd_features` without clobbering Free keys.
 *
 * MAINTENANCE CONVENTION: when a new Pro feature/setting is introduced, add its
 * flag/metric here and update betterdocs/docs/insights-tracking.md.
 *
 * @since 3.8.5
 */
class Collector {
	const CACHE_KEY = 'betterdocs_pro_insights_cache';

	/**
	 * Pro-gated boolean feature flags merged into `bd_features`.
	 *
	 * @var string[]
	 */
	const FEATURE_FLAGS = [
		'multiple_kb',
		'advance_search',
		'enable_content_restriction',
		'enable_glossaries',
		'enable_encyclopedia',
		'enable_git_integration',
		'collect_analytics_data',
		'unique_visitor_count',
		'exclude_bot_analytics',
		'enable_disable',   // Instant Answer master toggle
		'ia_reaction',
		'show_attachment',
		'show_related_docs',
	];

	public function __construct() {
		add_filter( 'betterdocs_insights_data', [ $this, 'collect' ], 20, 1 );
		add_action( 'betterdocs::settings::saved', [ $this, 'flush_cache' ] );
	}

	/**
	 * @param array $body
	 * @return array
	 */
	public function collect( $body ) {
		$cached = get_transient( self::CACHE_KEY );
		if ( ! is_array( $cached ) ) {
			$cached = [
				'features' => $this->features(),
				'bd_pro'   => $this->pro(),
			];
			set_transient( self::CACHE_KEY, $cached, DAY_IN_SECONDS );
		}

		$body = (array) $body;

		// All metric groups live inside `optional_data` (wpinsight persists only
		// the base fields + that single field, JSON-encoded in Insights::get_data()).
		$opt = ( isset( $body['optional_data'] ) && is_array( $body['optional_data'] ) ) ? $body['optional_data'] : [];

		// Merge Pro flags into the bd_features group seeded by Free (don't clobber).
		$opt['bd_features'] = array_merge(
			isset( $opt['bd_features'] ) && is_array( $opt['bd_features'] ) ? $opt['bd_features'] : [],
			$cached['features']
		);

		$opt['bd_pro'] = $cached['bd_pro'];

		$body['optional_data'] = $opt;

		return $body;
	}

	public function flush_cache() {
		delete_transient( self::CACHE_KEY );
	}

	protected function features() {
		$settings = betterdocs()->settings;
		$flags    = [];
		foreach ( self::FEATURE_FLAGS as $key ) {
			$flags[ $key ] = (int) (bool) $settings->get( $key, false );
		}
		return $flags;
	}

	protected function pro() {
		$kb_count = 0;
		if ( taxonomy_exists( 'knowledge_base' ) ) {
			$terms    = get_terms( [ 'taxonomy' => 'knowledge_base', 'hide_empty' => false ] );
			$kb_count = is_wp_error( $terms ) ? 0 : count( $terms );
		}

		return [
			'is_pro_active'    => 1,
			'kb_count'         => $kb_count,
			'internal_kb_type' => (string) betterdocs()->settings->get( 'internal_knowledge_base_type', '' ),
			'license_status'   => (string) get_option( 'betterdocs_pro_software__license_status', '' ),
		];
	}
}
