<?php
/**
 * Short-lived Freemius proof for Niwa-owned central services.
 *
 * @package Niwa_AI
 */

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

class Niwa_AI_Calendar_Install_Attestation {

	const PRODUCT_ID = 25824;
	const FIELDS     = 'id,plugin_id,url,is_active,is_disconnected,is_uninstalled,is_locked,public_key';

	/** Build a read-only Freemius API signature without exposing the install secret. */
	public static function create() {
		if ( ! function_exists( 'na_fs' ) ) {
			return new WP_Error( 'calendar_install_unregistered', __( 'Activate this Niwa AI installation to use Niwa services.', 'niwa-ai' ) );
		}

		$freemius = na_fs();
		$site     = is_object( $freemius ) && method_exists( $freemius, 'get_site' ) ? $freemius->get_site() : null;
		$site_id  = is_object( $site ) ? (int) ( $site->id ?? 0 ) : 0;
		$url      = is_object( $site ) ? esc_url_raw( (string) ( $site->url ?? '' ) ) : '';
		$public   = is_object( $site ) ? (string) ( $site->public_key ?? '' ) : '';
		$secret   = is_object( $site ) ? (string) ( $site->secret_key ?? '' ) : '';
		if ( $site_id <= 0 || self::PRODUCT_ID !== (int) ( $site->plugin_id ?? 0 ) || '' === $url || '' === $public || '' === $secret ) {
			return new WP_Error( 'calendar_install_unregistered', __( 'Activate this Niwa AI installation to use Niwa services.', 'niwa-ai' ) );
		}

		$resource = '/v1/installs/' . $site_id . '.json';
		$date     = gmdate( 'r' );
		$string   = "GET\n\n\n" . $date . "\n" . $resource;
		$proof    = rtrim( strtr( base64_encode( hash_hmac( 'sha256', $string, $secret ) ), '+/', '-_' ), '=' );

		return array(
			'install_id'    => $site_id,
			'plugin_id'     => self::PRODUCT_ID,
			'site_url'      => $url,
			'public_key'    => $public,
			'date'          => $date,
			'authorization' => 'FS ' . $site_id . ':' . $public . ':' . $proof,
		);
	}
}
