<?php
/**
 * Freemius SDK bootstrap: lccb_fs() singleton and uninstall cleanup hook.
 *
 * The Freemius SDK lives at vendor/freemius/ (plugin root).
 * Download from the Freemius dashboard and decompress there before testing.
 *
 * @package LetsCodeCookieBanner
 */

defined( 'ABSPATH' ) || exit;

if ( ! function_exists( 'lccb_fs' ) ) {

	/**
	 * Returns the Freemius singleton for this plugin, or null if the SDK is not installed.
	 *
	 * @return Freemius|null
	 */
	function lccb_fs() {
		global $lccb_fs;

		if ( ! isset( $lccb_fs ) ) {
			$sdk_path = LCCB_PLUGIN_DIR . 'vendor/freemius/start.php';
			if ( ! file_exists( $sdk_path ) ) {
				return null;
			}

			require_once $sdk_path;

			$lccb_fs = fs_dynamic_init(
				array(
					'id'               => '31461',
					'slug'             => 'lets-code-cookie-banner',
					'type'             => 'plugin',
					'public_key'       => 'pk_725bd02b55e197f67472f8770e502',
					'is_premium'       => false,
					'has_addons'       => true,
					'has_paid_plans'   => false,
					'is_org_compliant' => true,
					'menu'             => array(
						'slug'    => 'lccb-settings',
						'account' => true,
						'support' => false,
						'parent'  => array(
							'slug' => 'lets-code-tools',
						),
					),
				)
			);
		}

		return $lccb_fs;
	}

	if ( null !== lccb_fs() ) {
		lccb_fs()->add_action( 'after_uninstall', 'lccb_fs_uninstall_cleanup' );
		do_action( 'lccb_fs_loaded' );
	}
}

/**
 * Removes all plugin data when the user deletes the plugin with "Delete data on uninstall" enabled.
 *
 * Hooked via lccb_fs()->add_action('after_uninstall') so Freemius can report
 * the uninstall event before the data is wiped.
 */
function lccb_fs_uninstall_cleanup() {
	global $wpdb;

	$lccb_settings = get_option( 'lccb_settings', array() );

	if ( ! empty( $lccb_settings['delete_on_uninstall'] ) ) {
		$lccb_table = $wpdb->prefix . 'lccb_consents';
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared
		$wpdb->query( 'DROP TABLE IF EXISTS `' . esc_sql( $lccb_table ) . '`' );

		delete_option( 'lccb_settings' );
		delete_option( 'lccb_db_version' );
		delete_option( 'lccb_cookie_registry' );
		delete_option( 'lccb_api_key' );
		delete_option( 'lccb_api_lookup_ts' );
	}
}
