<?php
/**
 * Persist license platform from repo.the7.io responses.
 *
 * @package The7
 */

namespace The7\License;

defined( 'ABSPATH' ) || exit;

/**
 * Class License_Platform_Persistence
 *
 * Platform is refreshed when verify runs (e.g. on repo 403 during theme/plugin downloads),
 * not on a schedule. Legacy installs backfill on the first such verify.
 */
class License_Platform_Persistence {

	const OPTION_NAME = 'the7_license_platform';

	/**
	 * Register WordPress hooks.
	 */
	public static function init() {
		add_action( 'the7_after_theme_registration', [ __CLASS__, 'on_registration' ] );
		add_action( 'the7_after_theme_deactivation', [ __CLASS__, 'clear' ] );
	}

	/**
	 * @param array $response Decoded registration API response.
	 */
	public static function on_registration( $response ) {
		if ( is_array( $response ) ) {
			self::update_from_response( $response );
		}
	}

	/**
	 * Persist platform when present in an API response.
	 *
	 * Register responses use data.platform; verify-code.php uses a top-level platform field.
	 *
	 * @param array $response Decoded register or verify response.
	 */
	public static function update_from_response( array $response ) {
		$platform = self::extract_platform( $response );

		if ( null === $platform ) {
			return;
		}

		update_site_option( self::OPTION_NAME, $platform );
	}

	/**
	 * @param array $response Decoded register or verify response.
	 *
	 * @return string|null Platform string or null when absent.
	 */
	private static function extract_platform( array $response ) {
		$data = isset( $response['data'] ) && is_array( $response['data'] ) ? $response['data'] : [];

		if ( ! empty( $data['platform'] ) && is_string( $data['platform'] ) ) {
			return $data['platform'];
		}

		if ( ! empty( $response['platform'] ) && is_string( $response['platform'] ) ) {
			return $response['platform'];
		}

		return null;
	}

	/**
	 * Remove stored platform (on deregistration).
	 */
	public static function clear() {
		delete_site_option( self::OPTION_NAME );
	}
}
