<?php
/**
 * Optional Free-tier site registry (explicit opt-in) — NewsOS.io heartbeat.
 *
 * Pro sites are tracked via the license API; this module is skipped when Pro is active.
 * GDPR: no ping without recorded consent (Settings or setup wizard).
 *
 * @package Newsroom_AI_Assistant
 */

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

if ( ! function_exists( 'newsai_usage_registry_api_url' ) ) {
	function newsai_usage_registry_api_url() {
		$base = apply_filters( 'newsai_usage_registry_api_base', 'https://newsos.io' );
		$base = untrailingslashit( (string) $base );

		return $base . '/wp-json/newsos/v1/registry/ping';
	}
}

if ( ! function_exists( 'newsai_usage_registry_install_id' ) ) {
	/**
	 * Stable anonymous ID for this WordPress install (not tied to license).
	 *
	 * @return string UUID v4
	 */
	function newsai_usage_registry_install_id() {
		$id = (string) get_option( 'newsai_usage_registry_install_id', '' );
		if ( $id !== '' && preg_match( '/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i', $id ) ) {
			return strtolower( $id );
		}
		if ( function_exists( 'wp_generate_uuid4' ) ) {
			$id = wp_generate_uuid4();
		} else {
			$id = sprintf(
				'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
				random_int( 0, 0xffff ),
				random_int( 0, 0xffff ),
				random_int( 0, 0xffff ),
				random_int( 0, 0x0fff ) | 0x4000,
				random_int( 0, 0x3fff ) | 0x8000,
				random_int( 0, 0xffff ),
				random_int( 0, 0xffff ),
				random_int( 0, 0xffff )
			);
		}
		update_option( 'newsai_usage_registry_install_id', strtolower( $id ), false );

		return strtolower( $id );
	}
}

if ( ! function_exists( 'newsai_usage_registry_consent_timestamp' ) ) {
	/**
	 * Unix time when an administrator last gave explicit opt-in consent.
	 *
	 * @return int
	 */
	function newsai_usage_registry_consent_timestamp() {
		return (int) get_option( 'newsai_usage_registry_consent_at', 0 );
	}
}

if ( ! function_exists( 'newsai_usage_registry_opted_in' ) ) {
	/**
	 * True only when opt-in flag is yes AND consent was recorded explicitly.
	 *
	 * @return bool
	 */
	function newsai_usage_registry_opted_in() {
		if ( get_option( 'newsai_usage_registry_optin', 'no' ) !== 'yes' ) {
			return false;
		}

		return newsai_usage_registry_consent_timestamp() > 0;
	}
}

if ( ! function_exists( 'newsai_usage_registry_enabled' ) ) {
	/**
	 * Free installs only; requires explicit opt-in with recorded consent.
	 *
	 * @return bool
	 */
	function newsai_usage_registry_enabled() {
		if ( function_exists( 'newsai_is_pro' ) && newsai_is_pro() ) {
			return false;
		}
		if ( ! newsai_usage_registry_opted_in() ) {
			return false;
		}

		return (bool) apply_filters( 'newsai_usage_registry_enabled', true );
	}
}

if ( ! function_exists( 'newsai_usage_registry_grant_consent' ) ) {
	/**
	 * Record explicit consent and start weekly registry (if not Pro).
	 *
	 * @return void
	 */
	function newsai_usage_registry_grant_consent() {
		if ( function_exists( 'newsai_is_pro' ) && newsai_is_pro() ) {
			return;
		}
		update_option( 'newsai_usage_registry_optin', 'yes', false );
		update_option( 'newsai_usage_registry_consent_at', time(), false );
		newsai_usage_registry_schedule();
		newsai_usage_registry_ping( 'ping' );
		update_option( 'newsai_usage_registry_bootstrapped', '1', false );
	}
}

if ( ! function_exists( 'newsai_usage_registry_revoke_consent' ) ) {
	/**
	 * Withdraw consent, notify remote registry, stop cron.
	 *
	 * @return void
	 */
	function newsai_usage_registry_revoke_consent() {
		$had_consent = newsai_usage_registry_opted_in() || get_option( 'newsai_usage_registry_optin', 'no' ) === 'yes';
		update_option( 'newsai_usage_registry_optin', 'no', false );
		delete_option( 'newsai_usage_registry_consent_at' );
		delete_option( 'newsai_usage_registry_bootstrapped' );
		wp_clear_scheduled_hook( 'newsai_usage_registry_weekly' );
		if ( $had_consent && function_exists( 'newsai_usage_registry_ping' ) ) {
			newsai_usage_registry_ping( 'optout' );
		}
	}
}

if ( ! function_exists( 'newsai_usage_registry_ping' ) ) {
	/**
	 * @param string $action ping|optout
	 * @return bool True when HTTP 200 and success in JSON.
	 */
	function newsai_usage_registry_ping( $action = 'ping' ) {
		$action = in_array( $action, [ 'ping', 'optout' ], true ) ? $action : 'ping';
		if ( $action === 'ping' && ! newsai_usage_registry_enabled() ) {
			return false;
		}

		$body = [
			'install_id' => newsai_usage_registry_install_id(),
			'site_url'   => home_url( '/' ),
			'site_name'  => sanitize_text_field( (string) get_bloginfo( 'name' ) ),
			'version'    => defined( 'NEWSAI_VERSION' ) ? (string) NEWSAI_VERSION : '',
			'wp_version' => get_bloginfo( 'version' ),
			'php_version'=> PHP_VERSION,
			'locale'     => determine_locale(),
			'product'    => apply_filters( 'newsai_usage_registry_product_slug', 'newsroom-os-free' ),
			'action'     => $action,
		];

		$response = wp_remote_post(
			newsai_usage_registry_api_url(),
			[
				'timeout' => 15,
				'headers' => [ 'Content-Type' => 'application/json' ],
				'body'    => wp_json_encode( $body ),
			]
		);

		if ( is_wp_error( $response ) ) {
			return false;
		}
		if ( (int) wp_remote_retrieve_response_code( $response ) !== 200 ) {
			return false;
		}
		$data = json_decode( (string) wp_remote_retrieve_body( $response ), true );

		return is_array( $data ) && ! empty( $data['success'] );
	}
}

if ( ! function_exists( 'newsai_usage_registry_schedule' ) ) {
	function newsai_usage_registry_schedule() {
		if ( ! newsai_usage_registry_enabled() ) {
			wp_clear_scheduled_hook( 'newsai_usage_registry_weekly' );
			return;
		}
		if ( ! wp_next_scheduled( 'newsai_usage_registry_weekly' ) ) {
			wp_schedule_event( time() + DAY_IN_SECONDS, 'weekly', 'newsai_usage_registry_weekly' );
		}
	}
}

if ( ! function_exists( 'newsai_usage_registry_on_optin_changed' ) ) {
	/**
	 * Called after settings save when opt-in toggles.
	 *
	 * @param bool $now_opted_in .
	 */
	function newsai_usage_registry_on_optin_changed( $now_opted_in ) {
		if ( $now_opted_in ) {
			newsai_usage_registry_grant_consent();
			return;
		}
		newsai_usage_registry_revoke_consent();
	}
}

if ( ! function_exists( 'newsai_usage_registry_run_gdpr_migration' ) ) {
	/**
	 * One-time: revoke legacy "yes" without explicit consent timestamp (pre-GDPR builds).
	 *
	 * @return void
	 */
	function newsai_usage_registry_run_gdpr_migration() {
		if ( get_option( 'newsai_usage_registry_gdpr_migrated_v1', '' ) === '1' ) {
			return;
		}

		$optin   = get_option( 'newsai_usage_registry_optin', false );
		$consent = newsai_usage_registry_consent_timestamp();

		if ( $optin === 'yes' && $consent < 1 ) {
			update_option( 'newsai_usage_registry_optin', 'no', false );
			delete_option( 'newsai_usage_registry_bootstrapped' );
			wp_clear_scheduled_hook( 'newsai_usage_registry_weekly' );
			if ( function_exists( 'newsai_usage_registry_ping' ) ) {
				newsai_usage_registry_ping( 'optout' );
			}
			set_transient( 'newsai_usage_registry_gdpr_notice', '1', WEEK_IN_SECONDS );
		}

		update_option( 'newsai_usage_registry_gdpr_migrated_v1', '1', false );
	}
}

add_action( 'newsai_usage_registry_weekly', 'newsai_usage_registry_ping' );

add_action( 'plugins_loaded', 'newsai_usage_registry_run_gdpr_migration', 12 );

add_action(
	'init',
	static function () {
		if ( ! newsai_usage_registry_enabled() ) {
			return;
		}
		newsai_usage_registry_schedule();
	},
	20
);

if ( ! function_exists( 'newsai_usage_registry_privacy_policy_content' ) ) {
	/**
	 * Suggested privacy policy text for site owners (Settings → Privacy).
	 *
	 * @return string
	 */
	function newsai_usage_registry_privacy_policy_content() {
		$settings_url = admin_url( 'admin.php?page=newsai-settings&tab=settings' );
		$newsos_url   = 'https://newsos.io/';

		return wp_kses_post(
			sprintf(
				/* translators: 1: settings URL, 2: NewsOS URL */
				__(
					'<p><strong>Newsroom OS</strong> may connect to third-party services depending on your configuration:</p>
<ul>
<li><strong>NewsOS usage registry (free tier, optional)</strong> — If an administrator explicitly opts in under <a href="%1$s">Newsroom OS → Settings → Site Details</a>, the plugin sends a weekly anonymous heartbeat to <a href="%2$s" target="_blank" rel="noopener noreferrer">NewsOS.io</a>: public site URL, site name, plugin version, WordPress/PHP versions, and locale. No post content, no API keys, and no license data are included. Pro sites use license activation instead.</li>
<li><strong>Google Trends &amp; Google News RSS</strong> — Read-only public feeds for the editor sidebar (cached on your server).</li>
<li><strong>Wikidata</strong> — Optional tag enrichment when enabled (public API).</li>
<li><strong>AI providers (Pro, bring your own key)</strong> — When configured, article text you submit is sent to your chosen provider (OpenAI, Google Gemini, Groq, etc.) under your own API agreement.</li>
<li><strong>Google Search Console (Pro)</strong> — When enabled, metrics are fetched with your service account and stored locally.</li>
<li><strong>IndexNow</strong> — When enabled, published URLs may be submitted to Bing/Yandex.</li>
</ul>
<p>You can withdraw registry consent anytime by disabling the opt-in in plugin settings. Deactivating the plugin sends an opt-out signal if registry was enabled.</p>',
					'newsroom-ai-assistant'
				),
				esc_url( $settings_url ),
				esc_url( $newsos_url )
			)
		);
	}
}

add_action(
	'admin_init',
	static function () {
		if ( ! function_exists( 'wp_add_privacy_policy_content' ) ) {
			return;
		}
		wp_add_privacy_policy_content(
			'Newsroom OS',
			newsai_usage_registry_privacy_policy_content()
		);
	}
);

add_action(
	'admin_notices',
	static function () {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		if ( ! get_transient( 'newsai_usage_registry_gdpr_notice' ) ) {
			return;
		}
		delete_transient( 'newsai_usage_registry_gdpr_notice' );
		echo '<div class="notice notice-info is-dismissible"><p>';
		echo esc_html__(
			'Newsroom OS: Anonymous usage sharing with NewsOS was turned off to meet GDPR consent rules. You can opt in again under Settings → Site Details if you want to share basic site info.',
			'newsroom-ai-assistant'
		);
		echo '</p></div>';
	}
);
