<?php
/**
 * AtlasAiDev usage tracker wrapper for AtlasAI Connector.
 *
 * Thin integration layer around the AtlasAiDev\AppService Insights library
 * (libs/AtlasAiDev/). All tracking is OPT-IN: nothing is sent until the site
 * admin explicitly clicks "Allow" on the admin notice. Only anonymized counts,
 * boolean feature flags, and environment details are collected — never post
 * content, credentials, or visitor data.
 *
 * Modeled on AtlasAI Connector's AtlasAiDev_Tracker wrapper.
 *
 * @package AtlasAiDev\Awfah
 */

namespace AtlasAiDev\Awfah\Service;

defined( 'ABSPATH' ) || exit;

/**
 * Class AtlasAiDev_Tracker
 */
final class AtlasAiDev_Tracker {

	/**
	 * Unique application hash registered with the AtlasAiDev tracker backend.
	 * This identifies the AtlasAI Connector plugin to track.atlasaidev.com.
	 */
	const APP_HASH = '4b3bcdfc-16c2-47b4-8ba7-60f519e14454';

	/**
	 * Plugin display name reported to the tracker.
	 */
	const PLUGIN_NAME = 'AtlasAI Connector';

	/**
	 * Text domain (must match the plugin slug for wp.org compliance).
	 */
	const TEXT_DOMAIN = 'ai-workflow-automation-ai-agent-hub';

	/**
	 * Remote promotions feed (JSON, date-windowed entries). Editing this file on
	 * GitHub publishes/retires dashboard promo notices without a plugin release.
	 */
	const PROMOTIONS_SOURCE = 'https://raw.githubusercontent.com/atlasaidev/plugins/main/ai-workflow-automation-ai-agent-hub-promotions.json';

	/**
	 * Singleton instance.
	 *
	 * @var AtlasAiDev_Tracker
	 */
	protected static $instance;

	/**
	 * @var \AtlasAiDev\AppService\Client
	 */
	protected $client = null;

	/**
	 * @var \AtlasAiDev\AppService\Insights
	 */
	protected $insights = null;

	/**
	 * Get singleton instance.
	 *
	 * @return AtlasAiDev_Tracker
	 */
	public static function instance(): self {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Bootstrap the tracker. Safe to call once per request on `init`.
	 *
	 * @return void
	 */
	public function init(): void {
		if ( ! defined( 'AWFAH_PLUGIN_FILE' ) || ! defined( 'AWFAH_PLUGIN_DIR' ) ) {
			return;
		}

		if ( ! class_exists( '\AtlasAiDev\Awfah\AppService\Client' ) ) {
			$client_file = AWFAH_PLUGIN_DIR . 'libs/AtlasAiDev/Client.php';
			if ( ! is_readable( $client_file ) ) {
				// Telemetry library not bundled — skip gracefully rather than fatal.
				return;
			}
			require_once $client_file;
		}

		$this->client   = new \AtlasAiDev\Awfah\AppService\Client( self::APP_HASH, self::PLUGIN_NAME, AWFAH_PLUGIN_FILE );
		$this->insights = $this->client->insights();

		$this->insight_init();

		// Remote promotions — cached 12h, filtered by start/end dates,
		// per-user dismissible. See PROMOTIONS_SOURCE.
		$this->client->promotions()
			->set_source( self::PROMOTIONS_SOURCE )
			->init();

		add_filter(
			'AtlasAiDev_' . $this->client->getSlug() . '_plugin_api_info',
			array( $this, 'plugin_api_info' ),
			10,
			1
		);
	}

	/**
	 * Register Insights filters and start the tracker.
	 *
	 * @return void
	 */
	private function insight_init(): void {
		$slug = $this->client->getSlug();

		// Human-readable description of the data we collect (shown in the opt-in notice).
		add_filter( $slug . '_what_tracked', array( $this, 'data_we_collect' ), 10, 1 );

		// Enrich the tracking payload with AtlasAI Connector usage telemetry.
		add_filter( $slug . '_tracker_data', array( $this, 'get_plugin_telemetry' ), 10, 1 );

		// Support ticket routing (deactivation modal).
		add_filter(
			"AtlasAiDev_{$slug}_Support_Ticket_Recipient_Email",
			static function () {
				return 'contact.atlasaidev@gmail.com';
			},
			10
		);
		add_filter(
			"AtlasAiDev_{$slug}_Support_Page_URL",
			static function () {
				return 'https://atlasaidev.com/contact-us/';
			},
			10
		);
		add_filter( "AtlasAiDev_{$slug}_Support_Ticket_Email_Template", array( $this, 'support_ticket_template' ), 10 );
		add_filter( "AtlasAiDev_{$slug}_Support_Request_Ajax_Success_Response", array( $this, 'support_response' ), 10 );

		$this->insights->init();
	}

	/**
	 * Describe what is tracked (privacy disclosure for the opt-in notice).
	 *
	 * @param array $data Existing description lines.
	 *
	 * @return array
	 */
	public function data_we_collect( $data ) {
		return array_merge(
			(array) $data,
			array(
				esc_html__( 'Site name, language and URL.', 'ai-workflow-automation-ai-agent-hub' ),
				esc_html__( 'Number of active and inactive plugins.', 'ai-workflow-automation-ai-agent-hub' ),
				esc_html__( 'Administrator name and email address.', 'ai-workflow-automation-ai-agent-hub' ),
				esc_html( sprintf( /* translators: %s: plugin brand name (do not translate) */ __( 'Which %s modules are enabled and whether the MCP server is configured.', 'ai-workflow-automation-ai-agent-hub' ), 'AtlasAI Connector' ) ),
				esc_html__( 'Feature usage flags and counts (workflows, providers, RBAC) — no content, credentials, or token data.', 'ai-workflow-automation-ai-agent-hub' ),
			)
		);
	}

	/**
	 * Enrich the tracking payload with AtlasAI Connector-specific usage telemetry.
	 *
	 * Opt-in only. Contains no personal data, post content, API keys, or tokens —
	 * only anonymized counts and boolean feature flags used to prioritize the roadmap.
	 *
	 * @param array $data Existing tracking data from the Insights library.
	 *
	 * @return array
	 */
	public function get_plugin_telemetry( $data ) {
		$settings = (array) get_option( 'awfah_settings', array() );
		$modules  = ( isset( $settings['modules'] ) && is_array( $settings['modules'] ) ) ? $settings['modules'] : array();

		// ─── Module adoption ────────────────────────────────────────────────
		$enabled_modules = array_keys( array_filter( $modules ) );
		$data['amcp_modules_enabled_count'] = count( $enabled_modules );
		$data['amcp_enabled_modules']       = implode( ',', $enabled_modules );

		// ─── MCP server ─────────────────────────────────────────────────────
		// Whether the MCP server has been configured at all (option exists).
		$mcp_settings              = get_option( 'awfah_mcp_settings', array() );
		$data['amcp_mcp_configured'] = ! empty( $mcp_settings );
		// Whether a JWT secret has been generated (MCP auth in use).
		$data['amcp_jwt_configured'] = ! empty( get_option( 'awfah_jwt_secret_key', '' ) );

		// ─── AI providers ───────────────────────────────────────────────────
		// How many AI providers have credentials configured (count only, no keys).
		$provider_creds = (array) get_option( 'wp_ai_client_provider_credentials', array() );
		$data['amcp_providers_configured'] = count( array_filter( $provider_creds ) );

		// ─── Workflows ──────────────────────────────────────────────────────
		$workflows = (array) get_option( 'awfah_saved_workflows', array() );
		$data['amcp_workflows_count'] = count( $workflows );

		// ─── RBAC ───────────────────────────────────────────────────────────
		$role_abilities = ( isset( $settings['role_abilities'] ) && is_array( $settings['role_abilities'] ) ) ? $settings['role_abilities'] : array();
		$role_workflows = ( isset( $settings['role_workflows'] ) && is_array( $settings['role_workflows'] ) ) ? $settings['role_workflows'] : array();
		$data['amcp_rbac_roles_configured']      = count( array_filter( $role_abilities ) );
		$data['amcp_workflow_roles_configured']  = count( array_filter( $role_workflows ) );

		// ─── Environment / feature flags ────────────────────────────────────
		$data['amcp_woocommerce_active']    = class_exists( 'WooCommerce' );
		$data['amcp_error_debugger_on']     = ! empty( $modules['error_debugger'] );
		$data['amcp_external_abilities_on'] = ! empty( $modules['external_abilities'] );
		$data['amcp_is_pro_active']         = function_exists( 'awfah_is_pro_active' ) ? (bool) awfah_is_pro_active() : false;

		return $data;
	}

	/**
	 * Support ticket email template (deactivation modal).
	 *
	 * @return string
	 */
	public function support_ticket_template() {
		$template  = sprintf(
			'<div style="margin:10px auto;"><p>Website: <a href="__WEBSITE__">__WEBSITE__</a><br>Plugin: %s (v%s)</p></div>',
			esc_html( $this->client->getName() ),
			esc_html( $this->client->getProjectVersion() )
		);
		$template .= '<div style="margin:10px auto;"><hr></div>';
		$template .= '<div style="margin:10px auto;"><h3>__SUBJECT__</h3></div>';
		$template .= '<div style="margin:10px auto;">__MESSAGE__</div>';
		$template .= '<div style="margin:10px auto;"><hr></div>';
		$template .= sprintf(
			'<div style="margin:50px auto 10px auto;"><p style="font-size:12px;color:#009688">%s</p></div>',
			'Message processed with AtlasAiDev Service Library (v.' . esc_html( $this->client->getClientVersion() ) . ')'
		);

		return $template;
	}

	/**
	 * Success response shown after a support ticket is submitted.
	 *
	 * @return string
	 */
	public function support_response() {
		$thanks   = sprintf( '<h3>%s</h3>', esc_html__( 'Thank you — support ticket submitted.', 'ai-workflow-automation-ai-agent-hub' ) );
		$twenty4  = sprintf( '<strong>%s</strong>', esc_html__( '24 hours', 'ai-workflow-automation-ai-agent-hub' ) );
		/* translators: %s: approximate response time. */
		$notify   = sprintf( esc_html__( 'You will receive an email from "contact.atlasaidev@gmail.com" within %s.', 'ai-workflow-automation-ai-agent-hub' ), $twenty4 );

		return $thanks . sprintf( '<p>%s</p>', $notify );
	}

	/**
	 * Fill in missing plugin API info (contributors, author link).
	 *
	 * @param array $data Plugin API data.
	 *
	 * @return array
	 */
	public function plugin_api_info( $data ) {
		if ( isset( $data['homepage'], $data['author'] ) && false === strpos( $data['author'], '<a' ) ) {
			$data['author'] = sprintf( '<a href="%s">%s</a>', esc_url( $data['homepage'] ), esc_html( $data['author'] ) );
		}

		return $data;
	}

	/**
	 * Opt the site into tracking.
	 *
	 * @param bool $override Ignore last-send throttle if true.
	 *
	 * @return void
	 */
	public function opt_in( $override = false ): void {
		if ( $this->insights ) {
			$this->insights->optIn( $override );
		}
	}

	/**
	 * Opt the site out of tracking.
	 *
	 * @return void
	 */
	public function opt_out(): void {
		if ( $this->insights ) {
			$this->insights->optOut();
		}
	}

	/**
	 * Whether tracking is currently allowed.
	 *
	 * @return bool
	 */
	public function is_tracking_allowed(): bool {
		return $this->insights ? (bool) $this->insights->is_tracking_allowed() : false;
	}

	/**
	 * Cloning is forbidden.
	 */
	public function __clone() {
		_doing_it_wrong( __FUNCTION__, esc_html__( 'Cloning is forbidden.', 'ai-workflow-automation-ai-agent-hub' ), '1.5.6' );
	}
}
