<?php
/**
 * Pro Connector Status Helper
 *
 * Encapsulates all pro connector status checks for this plugin.
 * Calls the Agency Pulse Pro connector's public API (AgencyPulseWP_Token_Manager)
 * without importing or copying any code from that plugin.
 *
 * @package Agency_Pulse_Admin_Menu
 * @since   1.0.0
 */

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

class Agency_Pulse_Admin_Menu_Pro_Connector {

	// -------------------------------------------------------------------------
	// Public API
	// -------------------------------------------------------------------------

	/**
	 * Return true if the Pro Connector plugin is installed and loaded.
	 *
	 * Informational only — used to display "Pro Connector installed: yes/no"
	 * in the Settings page and to confirm update-checker availability. This
	 * no longer gates any premium features; use
	 * Agency_Pulse_Admin_Menu_License_Manager::is_active() for that.
	 *
	 * @since 1.0.0
	 * @return bool
	 */
	public static function is_active(): bool {
		return (bool) apply_filters(
			Agency_Pulse_Admin_Menu_Constants::FILTER_PRO_ACTIVE,
			class_exists( 'AgencyPulseWP_Connector' )
		);
	}

	/**
	 * Return the admin URL of the Pro Connector settings page.
	 *
	 * @since 1.0.0
	 * @return string
	 */
	public static function get_connector_url(): string {
		return admin_url( 'admin.php?page=agency-pulse-pro' );
	}

	/**
	 * Return a structured array of pro connection information for display.
	 *
	 * Reads directly from the connector's state option and the JWT payload
	 * where available. All fields are present regardless of connector state
	 * so the template can rely on array keys without isset() guards.
	 *
	 * @since 1.0.0
	 * @return array {
	 *     @type bool   $connector_installed  Connector plugin file is present on disk.
	 *     @type bool   $connector_active     Connector plugin is active (class loaded).
	 *     @type bool   $is_authenticated     Connector has a valid JWT.
	 *     @type string $status               Raw status string from connector state.
	 *     @type bool   $has_jwt              A JWT string is stored (may be expired).
	 *     @type int    $token_expires_at     Unix timestamp of token expiry, 0 if unknown.
	 *     @type string $token_status         'valid' | 'expiring_soon' | 'expired' | 'none'.
	 *     @type string $license_id           License ID, partially masked.
	 *     @type string $domain_hash          First 8 characters of domain hash.
	 *     @type string $server_url           Cloud server URL (from APWP_CONNECT_URL).
	 *     @type string $connector_url        Admin URL to Pro Connector settings page.
	 * }
	 */
	public static function get_connection_info(): array {
		$info = array(
			'connector_installed' => false,
			'connector_active'    => false,
			'is_authenticated'    => false,
			'status'              => '',
			'has_jwt'             => false,
			'token_expires_at'    => 0,
			'token_status'        => 'none',
			'license_id'          => '',
			'domain_hash'         => '',
			'server_url'          => defined( 'APWP_CONNECT_URL' ) ? APWP_CONNECT_URL : '',
			'connector_url'       => self::get_connector_url(),
		);

		$info['connector_installed'] = file_exists(
			WP_PLUGIN_DIR . '/agency-pulse-pro/agency-pulse-pro.php'
		);

		if ( ! class_exists( 'AgencyPulseWP_Connector' ) ) {
			return $info;
		}

		$info['connector_active'] = true;

		$state              = AgencyPulseWP_Connector::instance()->get_state();
		$info['status']     = $state['status'] ?? '';
		$info['has_jwt']    = ! empty( $state['jwt'] );
		$info['license_id'] = self::mask_license( $state['license_id'] ?? '' );
		$info['domain_hash'] = substr( $state['domain_hash'] ?? '', 0, 8 );

		// Resolve token expiry from stored expires_at or JWT payload.
		$expires_at = 0;
		if ( ! empty( $state['expires_at'] ) && is_numeric( $state['expires_at'] ) ) {
			$expires_at = (int) $state['expires_at'];
		} elseif ( $info['has_jwt'] ) {
			$parts = explode( '.', $state['jwt'] );
			if ( 3 === count( $parts ) ) {
				$payload    = json_decode( base64_decode( strtr( $parts[1], '-_', '+/' ) ), true );
				$expires_at = isset( $payload['exp'] ) ? (int) $payload['exp'] : 0;
			}
		}
		$info['token_expires_at'] = $expires_at;

		// Derive a human-readable token status.
		if ( ! $info['has_jwt'] ) {
			$info['token_status'] = 'none';
		} elseif ( 0 === $expires_at ) {
			$info['token_status'] = 'valid';
		} elseif ( time() > $expires_at ) {
			$info['token_status'] = 'expired';
		} elseif ( time() > $expires_at - 300 ) {
			$info['token_status'] = 'expiring_soon';
		} else {
			$info['token_status'] = 'valid';
		}

		// is_authenticated uses the same logic as is_active() but reads fresh state.
		if ( $info['has_jwt'] ) {
			$token                  = AgencyPulseWP_Token_Manager::get_valid_token();
			$info['is_authenticated'] = ! empty( $token );
		}

		return $info;
	}

	// -------------------------------------------------------------------------
	// Private helpers
	// -------------------------------------------------------------------------

	/**
	 * Partially mask a license ID for display.
	 *
	 * Shows the first 4 and last 4 characters separated by asterisks.
	 * Returns the original string unchanged if it is 8 characters or shorter.
	 *
	 * @since 1.0.0
	 * @param string $id
	 * @return string
	 */
	private static function mask_license( string $id ): string {
		if ( '' === $id ) {
			return '';
		}
		if ( strlen( $id ) <= 8 ) {
			return $id;
		}
		return substr( $id, 0, 4 ) . '••••' . substr( $id, -4 );
	}
}
