<?php
/**
 * Freemius SDK integration.
 *
 * @package DreamFast_CF
 */

defined( 'ABSPATH' ) || exit;

/**
 * Whether the Freemius SDK exists in the bundled vendor directory.
 *
 * @return bool
 */
function dreamfast_cf_freemius_sdk_available() {
	return is_readable( DREAMFAST_CF_PATH . 'vendor/freemius/start.php' );
}

/**
 * Whether this package is the Freemius premium build.
 *
 * @return bool
 */
function dreamfast_cf_is_premium_package() {
	return defined( 'DREAMFAST_CF_FREE' ) && ! DREAMFAST_CF_FREE;
}

/**
 * Remove plugin data after Freemius records the uninstall event.
 */
function dreamfast_cf_cleanup_after_uninstall() {
	$option_names = array(
		'dreamfast_cf_settings',
		'dreamfast_cf_analytics',
		'dreamfast_cf_db_version',
	);

	if ( ! is_multisite() ) {
		foreach ( $option_names as $option_name ) {
			delete_option( $option_name );
		}
		return;
	}

	$site_ids = get_sites(
		array(
			'fields' => 'ids',
			'number' => 0,
		)
	);

	foreach ( $site_ids as $site_id ) {
		switch_to_blog( (int) $site_id );
		foreach ( $option_names as $option_name ) {
			delete_option( $option_name );
		}
		restore_current_blog();
	}
}

/**
 * Bootstrap Freemius.
 */
function dreamfast_cf_load_freemius() {
	if ( function_exists( 'dreamfast_cf_fs' ) || ! dreamfast_cf_freemius_sdk_available() ) {
		return;
	}

	require_once DREAMFAST_CF_PATH . 'vendor/freemius/start.php';

	if ( ! function_exists( 'fs_dynamic_init' ) ) {
		return;
	}

	/**
	 * Get the Freemius SDK instance.
	 *
	 * @return \Freemius
	 */
	// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound -- Freemius-generated product helper.
	function dreamfast_cf_fs() {
		global $dreamfast_cf_freemius;

		if ( ! isset( $dreamfast_cf_freemius ) ) {
			$dreamfast_cf_freemius = fs_dynamic_init(
				array(
					'id'                  => '31133',
					'slug'                => 'dreamfast-commerce-float',
					'premium_slug'        => 'dreamfast-commerce-float-pro',
					'type'                => 'plugin',
					'public_key'          => 'pk_1bf815452568380a16fa0fb91bcb0',
					'is_premium'          => dreamfast_cf_is_premium_package(),
					'premium_suffix'      => 'Pro',
					'has_premium_version' => true,
					'has_addons'          => false,
					'has_paid_plans'      => true,
					'is_org_compliant'    => true,
					'navigation'          => 'menu',
					'menu'                => array(
						'slug'    => 'dreamfast-commerce-float',
						'support' => false,
					),
				)
			);
		}

		return $dreamfast_cf_freemius;
	}

	$freemius = dreamfast_cf_fs();
	$freemius->add_action( 'after_uninstall', 'dreamfast_cf_cleanup_after_uninstall' );
	// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Freemius-generated product hook.
	do_action( 'dreamfast_cf_fs_loaded' );
}

dreamfast_cf_load_freemius();
