<?php
/**
 * Freemius bootstrap.
 *
 * Two things live here:
 *
 *   1. The drezsync_fs() initializer, which the Freemius dashboard generates for
 *      you when you create the DrezSync product. Paste that snippet where marked
 *      below. The SDK is a Composer dependency (freemius/wordpress-sdk), and its
 *      start.php is a Composer "files" autoload entry, so requiring
 *      vendor/autoload.php loads it. The initializer then identifies the plugin
 *      with your Freemius id and public key.
 *
 *   2. The bridge from Freemius to DrezSync's own Pro gate. Feature code only
 *      ever asks DrezSync_License::is_pro(); this filter answers that question
 *      from Freemius, so nothing else in the plugin needs to know Freemius exists.
 *
 * Until the initializer is pasted in, drezsync_fs() does not exist, the filter is
 * never added, and DrezSync_License::is_pro() falls back to false (free). So the
 * plugin runs perfectly with this file in place before Freemius is connected.
 *
 * @package DrezSync
 */

defined( 'ABSPATH' ) || exit;

/*
 * Freemius initializer. The id and public_key are public by design (they ship
 * in the plugin). The Secret/API keys are NOT here and never belong in the code.
 *
 * is_premium is false in the free WordPress.org build and true in the Pro build,
 * so each build correctly identifies itself to Freemius. The build script decides
 * which, when it packages the zip.
 */
if ( ! function_exists( 'drezsync_fs' ) ) {
	function drezsync_fs() {
		global $drezsync_fs;

		if ( ! isset( $drezsync_fs ) ) {
			// Composer's autoloader. The Freemius SDK declares start.php as a
			// "files" autoload entry, so requiring this boots the SDK and defines
			// fs_dynamic_init(). It also registers the Google client's PSR-4 map.
			require_once DREZSYNC_DIR . 'vendor/autoload.php';

			$drezsync_is_premium = false;

			$drezsync_fs = fs_dynamic_init(
				array(
					'id'                  => '34657',
					'slug'                => 'drezsync',
					'premium_slug'        => 'drezsync-pro',
					'type'                => 'plugin',
					'public_key'          => 'pk_a97e8489cf985573940b428eb9dc6',
					'is_premium'          => $drezsync_is_premium,
					'premium_suffix'      => 'Pro',
					'has_premium_version' => true,
					'has_addons'          => false,
					'has_paid_plans'      => true,
					'is_org_compliant'    => true,
					// Attach to the real top-level "drezsync" page registered by
					// DrezSync_Admin_Menu. Freemius adds its account and upgrade items as
					// submenus of it. The page must genuinely exist, or the post-activation
					// redirect lands on a page with no callback ("not allowed to access
					// this page").
					'menu'                => array(
						'slug'    => 'drezsync',
						'support' => false,
					),
				)
			);
		}

		return $drezsync_fs;
	}

	// Initialize Freemius as early as this file is loaded.
	drezsync_fs();

	// Signal that Freemius is ready.
	do_action( 'drezsync_fs_loaded' );
}


/* ---------------------------------------------------------------------------
 * Bridge Freemius into DrezSync's Pro gate.
 *
 * Both halves of this check are load bearing.
 *
 * is_premium() asks "does this build actually contain the Pro code?". The free
 * build has includes/pro deleted and every pro-marked region stripped, so it
 * must never answer yes to is_pro() no matter what license the site holds.
 *
 * can_use_premium_code() asks "is this site entitled to Pro?". On its own it
 * only checks for a trial or an enabled license, and it does NOT consider which
 * build is running. So a licensed site running the free build would report Pro
 * and start unlocking features whose code is not there. That is a real state:
 * a customer buys Pro and activates the license while still on free, before
 * they install the Pro zip.
 *
 * A lapsed but previously-paid license keeps returning true here, so Pro
 * features survive expiry and only updates get blocked. That is the model we
 * want, and it is why this checks entitlement rather than is_paying().
 * ------------------------------------------------------------------------- */
if ( function_exists( 'drezsync_fs' ) ) {
	add_filter(
		'drezsync_is_pro',
		function () {
			return drezsync_fs()->is_premium() && drezsync_fs()->can_use_premium_code();
		}
	);
}


/* ---------------------------------------------------------------------------
 * Uninstall cleanup.
 *
 * This runs on Freemius's after_uninstall hook rather than from an uninstall.php
 * file, and that is not a style preference. WordPress core's uninstall_plugin()
 * runs uninstall.php and then returns immediately, before it ever reaches the
 * callback registered by register_uninstall_hook(). The Freemius SDK registers
 * exactly such a callback, so shipping an uninstall.php silently prevents the
 * SDK from ever learning the plugin was removed and from clearing its own SDK
 * reference. Freemius rejects uploads containing the file for that reason.
 *
 * Note WP_UNINSTALL_PLUGIN is NOT defined here. Core only defines it in the
 * uninstall.php branch, so this code must identify the running build for itself,
 * which is what is_premium() does below. It is decided at build time and cannot
 * be wrong.
 *
 * On the guard: the free and Pro builds live in separate folders and share these
 * options, which are stored in the database rather than in either folder. During
 * an upgrade both builds sit on the site at once and the free one usually gets
 * deleted once Pro takes over. Clearing the options then would wipe the Google
 * connection out from under the running Pro install, and the customer would redo
 * the whole OAuth setup on their brand new paid plugin.
 *
 * The SDK already blocks the common case: it returns before firing this hook if
 * the other build is active. The check below covers the case its check misses,
 * where both builds are installed but neither is active, which is an ordinary
 * place to end up while troubleshooting. So the options are only ever cleared
 * when the last DrezSync on the site goes away.
 * ------------------------------------------------------------------------- */
if ( ! function_exists( 'drezsync_uninstall_cleanup' ) ) {
	function drezsync_uninstall_cleanup() {
		$drezsync_other_build = drezsync_fs()->is_premium()
			? 'drezsync/drezsync.php'
			: 'drezsync-pro/drezsync.php';

		if ( file_exists( WP_PLUGIN_DIR . '/' . $drezsync_other_build ) ) {
			return;
		}

		delete_option( 'drezsync_google_credentials' );
		delete_option( 'drezsync_google_token' );

		// The rename flag, plus the two option names the plugin used before 1.6.7
		// when it was called SlotSync. Uninstall is the one place that has to know
		// the old names: a site that never loaded 1.6.7 long enough to migrate
		// would otherwise be left with orphaned credentials after removing the
		// plugin, which is exactly what uninstall is supposed to prevent.
		delete_option( 'drezsync_migrated' );
		delete_option( 'slotsync_google_credentials' );
		delete_option( 'slotsync_google_token' );
	}
}

if ( function_exists( 'drezsync_fs' ) ) {
	drezsync_fs()->add_action( 'after_uninstall', 'drezsync_uninstall_cleanup' );
}
