<?php

/**
 * Plugin Name: Opus Price Builder
 * Plugin URI: https://price-builder-opus.evelynwaugh.com.ua/
 * Description: Visual price layout builder for WooCommerce. Design custom price displays with drag-and-drop canvas editor.
 * Version: 1.0.0
 * Author: EvelynWaugh
 * Author URI: https://www.evelynwaugh.com.ua/
 * License: GPL-2.0+
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 * Text Domain: opus-price-builder
 * Domain Path: /
 * Requires at least: 6.0
 * Requires PHP: 8.1
 * WC requires at least: 8.0
 * WC tested up to: 11.0
 *
 * @package OpusPriceBuilder
 */

declare(strict_types=1);

namespace OpusPriceBuilder;

// Exit if accessed directly.
if (! defined('ABSPATH')) {
	exit;
}

/**
 * Plugin constants.
 */
if (! defined('OPPB_VERSION')) {
	define('OPPB_VERSION', '1.0.0');
}
if (! defined('OPPB_PLUGIN_FILE')) {
	define('OPPB_PLUGIN_FILE', __FILE__);
}
if (! defined('OPPB_PLUGIN_DIR')) {
	define('OPPB_PLUGIN_DIR', plugin_dir_path(__FILE__));
}
if (! defined('OPPB_PLUGIN_URL')) {
	define('OPPB_PLUGIN_URL', plugin_dir_url(__FILE__));
}
if (! defined('OPPB_PLUGIN_BASENAME')) {
	define('OPPB_PLUGIN_BASENAME', plugin_basename(__FILE__));
}

/**
 * Freemius SDK initialization.
 */
if (function_exists(__NAMESPACE__ . '\\oppb_fs')) {
	oppb_fs()->set_basename(true, __FILE__);
	// deactivate the plugin.
	if (! function_exists('deactivate_plugins')) {
		require_once ABSPATH . 'wp-admin/includes/plugin.php';
	}
	deactivate_plugins(plugin_basename(__FILE__), true);
	return;
} else {

	if (! function_exists(__NAMESPACE__ . '\\oppb_fs')) {
		// Create a helper function for easy SDK access.
		function oppb_fs()
		{
			global $oppb_fs;

			if (! isset($oppb_fs)) {
				// Include Freemius SDK.
				require_once OPPB_PLUGIN_DIR . 'freemius/start.php';

				$oppb_fs = fs_dynamic_init(array(
					'id'                  => '35967',
					'slug'                => 'opus-price-builder',
					'type'                => 'plugin',
					'public_key'          => 'pk_e820daefee0905359d6c604aec7d0',
					'is_premium'          => false,
					'premium_suffix'      => 'Pro',
					'has_premium_version' => true,
					'has_addons'          => false,
					'has_paid_plans'      => true,
					'trial'               => array(
						'days'               => 14,
						'is_require_payment' => true,
					),

					'menu'                => array(
						'slug'           => 'opus-price-builder',
						'support'        => false,
						'account'        => true,
					),
					'is_live'        => true,
				));
			}

			return $oppb_fs;
		}

		// Init Freemius.
		oppb_fs();
		// Signal that SDK was initiated.
		do_action('oppb_fs_loaded');
	}


	/**
	 * Whether the current site can use Pro / premium features.
	 */
	function oppb_can_use_premium_code(): bool
	{
		return function_exists(__NAMESPACE__ . '\\oppb_fs') && oppb_fs()->can_use_premium_code();
	}


	/**
	 * SPL Autoloader for OpusPriceBuilder namespace.
	 *
	 * @param string $class The fully-qualified class name.
	 * @return void
	 */
	spl_autoload_register(
		function (string $class): void {
			// Project-specific namespace prefix.
			$prefix = 'OpusPriceBuilder\\';

			// Base directory for the namespace prefix.
			$base_dir = OPPB_PLUGIN_DIR . 'includes/';

			// Check if the class uses the namespace prefix.
			$len = strlen($prefix);
			if (strncmp($prefix, $class, $len) !== 0) {
				// No, move to the next registered autoloader.
				return;
			}

			// Get the relative class name.
			$relative_class = substr($class, $len);

			// Replace namespace separators with directory separators in the relative class name,
			// and append with .php.
			$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

			// If the file exists, require it.
			if (file_exists($file)) {
				require_once $file;
			}
		}
	);

	/**
	 * Check if WooCommerce is active.
	 *
	 * @return bool
	 */
	function oppb_is_woocommerce_active(): bool
	{
		return class_exists('WooCommerce');
	}

	/**
	 * Display admin notice if WooCommerce is not active.
	 *
	 * @return void
	 */
	function oppb_woocommerce_missing_notice(): void
	{
?>
		<div class="notice notice-error">
			<p>
				<?php
				esc_html_e(
					'Opus Price Builder requires WooCommerce to be installed and activated.',
					'opus-price-builder'
				);
				?>
			</p>
		</div>
<?php
	}

	/**
	 * Initialize the plugin.
	 *
	 * @return void
	 */
	function oppb_init(): void
	{
		// Check WooCommerce dependency.
		if (! oppb_is_woocommerce_active()) {
			add_action('admin_notices', __NAMESPACE__ . '\\oppb_woocommerce_missing_notice');
			return;
		}

		// Initialize admin functionality.
		if (is_admin()) {
			new Admin\AdminMenu();
			new Admin\AdminAssets();
		}

		// Register REST API routes.
		add_action('rest_api_init', __NAMESPACE__ . '\\oppb_register_rest_routes');

		// Initialize frontend functionality.
		if (! is_admin()) {
			Frontend\FrontendAssets::register();
			WooCommerce\PriceHooks::register();
		}

		// Register custom code filter hooks.
		Hooks\CustomCodeHooks::register();

		/**
		 * Fires after Opus Price Builder core services are registered.
		 *
		 * Pro and third-party extensions hook here.
		 */
		do_action('oppb_init');
	}

	/**
	 * Register REST API routes.
	 *
	 * @return void
	 */
	function oppb_register_rest_routes(): void
	{
		$layouts_controller = new API\LayoutsController();
		$layouts_controller->register_routes();

		$settings_controller = new API\SettingsController();
		$settings_controller->register_routes();
	}

	/**
	 * Plugin activation hook.
	 *
	 * @return void
	 */
	function oppb_activate(): void
	{
		Activator::activate();
	}

	/**
	 * Plugin deactivation hook.
	 *
	 * @return void
	 */
	function oppb_deactivate(): void
	{
		Deactivator::deactivate();
	}

	// Register activation/deactivation hooks.
	register_activation_hook(__FILE__, __NAMESPACE__ . '\\oppb_activate');
	register_deactivation_hook(__FILE__, __NAMESPACE__ . '\\oppb_deactivate');

	// Initialize the plugin after all plugins are loaded.
	add_action('plugins_loaded', __NAMESPACE__ . '\\oppb_init');

	/**
	 * Declare HPOS compatibility for WooCommerce.
	 */
	add_action(
		'before_woocommerce_init',
		function () {
			if (class_exists(\Automattic\WooCommerce\Utilities\FeaturesUtil::class)) {
				\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility(
					'custom_order_tables',
					__FILE__,
					true
				);
			}
		}
	);
}
