<?php
/**
 * Answyr — Freemius integration (licensing + upgrade flow for Pro).
 *
 * Dormant until the product IDs are configured, so the plugin runs completely
 * normally before a Freemius account exists. Drop the real values into
 * `inc/core/freemius-config.php` (gitignored; see `freemius-config.sample.php`)
 * and the SDK wakes up: Account/Upgrade menus appear and a valid Pro license
 * flips `answyr_is_pro()` on.
 *
 * @package Answyr
 */

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

// Load the local, non-committed product config if present (defines ANSWYR_FS_ID
// + ANSWYR_FS_PUBLIC_KEY, both non-secret Freemius values).
$answyr_fs_config = ANSWYR_PATH . 'inc/core/freemius-config.php';
if ( is_readable( $answyr_fs_config ) ) {
	require_once $answyr_fs_config;
}

// No product configured yet → stay dormant. `answyr_is_pro()` keeps using its
// constant/filter seam (see inc/core/pro.php), so nothing else changes.
if ( ! defined( 'ANSWYR_FS_ID' ) || ! ANSWYR_FS_ID ) {
	return;
}

if ( ! function_exists( 'answyr_fs' ) ) {

	/** Shared Freemius SDK instance. */
	function answyr_fs() {
		global $answyr_fs;

		if ( ! isset( $answyr_fs ) ) {
			require_once ANSWYR_PATH . 'freemius/start.php';

			$answyr_fs = fs_dynamic_init(
				array(
					'id'             => ANSWYR_FS_ID,
					'slug'           => 'answyr',
					'premium_slug'   => 'answyr-pro',
					'type'           => 'plugin',
					'public_key'     => ANSWYR_FS_PUBLIC_KEY,
					// The premium package ships the premium-only files; the free
					// (WordPress.org) package has them stripped. File presence is the
					// signal, so the same bootstrap works for both builds.
					'is_premium'     => file_exists( ANSWYR_PATH . 'inc/modules/chat/class-chat-store.php' ),
					'premium_suffix' => 'Pro',
					'has_addons'     => false,
					'has_paid_plans' => true,
					'menu'           => array(
						'slug'       => 'answyr',
						'first-path' => 'admin.php?page=answyr-settings',
						'account'    => true,
						'pricing'    => true,
						'contact'    => false,
						'support'    => false,
					),
				)
			);
		}

		return $answyr_fs;
	}

	// Boot it, then let the rest of the plugin know the SDK is available.
	answyr_fs();
	do_action( 'answyr_fs_loaded' );

	// Freemius owns the top-level uninstall.php, so our data teardown runs on its
	// `after_uninstall` hook instead. Fired via WordPress's register_uninstall_hook
	// (no physical uninstall.php needed), so it works for both the free and premium
	// builds. answyr_uninstall() is defined in inc/core/uninstall-cleanup.php.
	answyr_fs()->add_action( 'after_uninstall', 'answyr_uninstall' );

	// Route the Pro capability seam through Freemius. `can_use_premium_code()` is
	// true only on the premium package with an active license; the dev
	// constant/filter can still force it on (they OR together).
	add_filter(
		'answyr_is_pro',
		static function ( $pro ) {
			return $pro || answyr_fs()->can_use_premium_code();
		}
	);
}
