<?php

namespace ZenCommunity;

use SE_License_SDK_Client;

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

/**
 * StoreEngine SDK bootstrap for ZenCommunity.
 *
 * The SDK is composer-managed (`storeengine/wordpress-sdk`) and its init.php
 * is auto-loaded by composer's files autoload, so we don't need to require
 * it manually here. We defer `se_license_init()` until plugins_loaded and
 * bridge the SDK's frontend params into ZenCommunity's existing
 * `zencommunity/assets/script_data` filter so the React settings UI can
 * read `SeSdk` from the localized `ZencommunityGlobal` data.
 */
final class StoreLicense {

	protected static ?SE_License_SDK_Client $sdk_client = null;

	private function __construct() {}

	public static function init(): void {
		if ( ! did_action( 'plugins_loaded' ) ) {
			add_action( 'plugins_loaded', [ __CLASS__, 'load_sdk' ] );
		} else {
			self::load_sdk();
		}
	}

	public static function load_sdk(): void {
		if ( null !== self::$sdk_client ) {
			return;
		}

		if ( ! function_exists( 'se_license_init' ) ) {
			_doing_it_wrong(
				__METHOD__,
				'StoreEngine SDK is missing. Run `composer install` in the zencommunity plugin directory.',
				'1.0.0'
			);
			return;
		}

		self::$sdk_client = se_license_init( [
			'package_file'        => ZENCOMMUNITY_PLUGIN_FILE,
			'package_name'        => 'ZenCommunity', // translation removed due to load too early
			'product_id'          => 163,
			'is_free'             => true,
			'slug'                => 'zencommunity',
			'basename'            => ZENCOMMUNITY_PLUGIN_BASENAME,
			'package_type'        => 'plugin',
			'package_version'     => ZENCOMMUNITY_VERSION,
			'allow_local'         => true,
			'license_server'      => 'https://store.kodezen.com/',
			'purchase_url'        => 'https://store.kodezen.com/product/zencommunity/',
			'product_logo'        => defined( 'ZENCOMMUNITY_ASSETS_URI' ) ? ZENCOMMUNITY_ASSETS_URI . 'images/icon_logo.png' : '',
			'store_dashboard_url' => 'https://store.kodezen.com/dashboard/license-keys/',
			'terms_url'           => 'https://kodezen.com/terms-and-conditions/',
			'privacy_policy_url'  => 'https://store.kodezen.com/privacy-policy/',
			'ticket_recipient'    => 'support@kodezen.com',
			'primary_color'       => '#2A3BEE',
			'first_install_time'  => get_option( 'zencommunity_first_install_time' ),
			'optin_notice_delay'  => 3 * DAY_IN_SECONDS,
		] );

		add_filter( 'zencommunity/assets/script_data', [ __CLASS__, 'add_script_data' ] );
	}

	public static function add_script_data( array $data ): array {
		if ( self::$sdk_client && method_exists( self::$sdk_client, 'get_js_params' ) ) {
			$data['SeSdk'] = self::$sdk_client->get_js_params();
		}
		return $data;
	}

	public static function get_client(): ?SE_License_SDK_Client {
		return self::$sdk_client;
	}
}
