<?php

namespace TableBuilderPro\Core;

defined('ABSPATH') || exit;

class Enqueue {
	use \TableBuilderPro\Traits\Singleton;

	public function __construct() {
		// Use high priority (999) to ensure styles load after themes/plugins
		add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets'], 999);
		add_action('enqueue_block_editor_assets', array($this, 'enqueue_global_assets'), 999);
		add_action('wp_enqueue_scripts', [$this, 'enqueue_frontend_assets'], 999);
	}

	public function enqueue_admin_assets($hook) {
		wp_localize_script(
			'wp-block-editor',
			'tableBuilderPro',
			[
				'plugin_url'         => TABLE_BUILDER_BLOCK_PRO_PLUGIN_URL,
				'screen'             => $hook,
				'api_url'            => TABLE_BUILDER_BLOCK_PRO_PLUGIN_URL . 'api/',
				'root_url'           => esc_url(home_url('/')),
				'restUrl'            => rest_url('table-builder/v1/'),
				'version'            => TABLE_BUILDER_BLOCK_PRO_PLUGIN_VERSION,
				'generalSettingsUrl' => admin_url('options-general.php'),
				'activeTheme'        => wp_get_theme()->get('Name'),
				'has_pro'            => true,
				'isProActive'        => true,
			]
		);


		if (in_array($hook, array('toplevel_page_tablebuilder'))) {
			$license_asset_file = TABLE_BUILDER_BLOCK_PRO_PLUGIN_DIR . 'build/admin/license/index.asset.php';
			if (file_exists($license_asset_file)) {
				$license_asset = include_once $license_asset_file;
				if (isset($license_asset['version'])) {
					wp_enqueue_style(
						'tablebuilder-pro-admin-license',
						TABLE_BUILDER_BLOCK_PRO_PLUGIN_URL . 'build/admin/license/style-index.css',
						[],
						$license_asset['version']
					);

					wp_enqueue_script(
						'tablebuilder-pro-admin-license',
						TABLE_BUILDER_BLOCK_PRO_PLUGIN_URL . 'build/admin/license/index.js',
						$license_asset['dependencies'],
						$license_asset['version'],
						[
							'in_footer' => true,
						]
					);
				}

				$this->enqueue_global_assets();
			}
		}
	}

	public function enqueue_global_assets() {
		$global_asset_file = TABLE_BUILDER_BLOCK_PRO_PLUGIN_DIR . 'build/global/index.asset.php';
		if (file_exists($global_asset_file)) {
			$global_asset = include_once $global_asset_file;
			if (isset($global_asset['version'])) {
				wp_enqueue_script(
					'tablebuilder-pro-blocks-editor-global',
					TABLE_BUILDER_BLOCK_PRO_PLUGIN_URL . 'build/global/index.js',
					$global_asset['dependencies'],
					$global_asset['version'],
					false
				);
			}
		}
	}

	public function enqueue_frontend_assets() {
		// Register pro status for frontend
		wp_register_script('table-builder-pro-status', false);
		wp_enqueue_script('table-builder-pro-status');
		wp_add_inline_script(
			'table-builder-pro-status',
			'window.tableBuilderPro = window.tableBuilderPro || {}; window.tableBuilderPro.isProActive = true; window.tableBuilderPro.has_pro = true;'
		);
	}
}
