<?php
/**
 * Admin integration: mounts the React rule builder on the category edit screen,
 * registers a Products submenu overview page, and enqueues assets.
 *
 * @package SmartCategories
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class SCWC_Admin
 */
class SCWC_Admin {

	const OVERVIEW_SLUG = 'scwc-overview';

	/**
	 * Wire admin hooks.
	 */
	public static function init() {
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue' ) );
		add_action( 'product_cat_edit_form', array( __CLASS__, 'render_term_mount' ), 10, 1 );
		add_action( 'admin_menu', array( __CLASS__, 'register_menu' ) );

		// Surface a "Smart" badge column on the category list table.
		add_filter( 'manage_edit-product_cat_columns', array( __CLASS__, 'add_column' ) );
		add_filter( 'manage_product_cat_custom_column', array( __CLASS__, 'render_column' ), 10, 3 );

		// Plugins-list action links: quick access + upgrade.
		add_filter( 'plugin_action_links_' . SCWC_BASENAME, array( __CLASS__, 'action_links' ) );

		// Self-heal DB schema after plugin updates.
		SCWC_Install::maybe_upgrade();
	}

	/**
	 * Register the plugin's own top-level admin menu (right below Products),
	 * with the overview as its first page and a shortcut to the category
	 * management screen. The Pro add-on can append its own submenus here.
	 */
	public static function register_menu() {
		add_menu_page(
			__( 'Smart Categories', 'smart-categories-for-woocommerce' ),
			__( 'Smart Categories', 'smart-categories-for-woocommerce' ),
			'manage_woocommerce',
			self::OVERVIEW_SLUG,
			array( __CLASS__, 'render_overview' ),
			'dashicons-category',
			'55.7'
		);

		// Rename the auto-created first submenu entry.
		add_submenu_page(
			self::OVERVIEW_SLUG,
			__( 'Smart Categories', 'smart-categories-for-woocommerce' ),
			__( 'Overview', 'smart-categories-for-woocommerce' ),
			'manage_woocommerce',
			self::OVERVIEW_SLUG,
			array( __CLASS__, 'render_overview' )
		);

		// The native list always remains reachable under Products → Categories;
		// this shortcut is skipped when a richer replacement page is registered.
		$scwc_show_native_shortcut = true;


		if ( $scwc_show_native_shortcut ) {
			// Handy shortcut to the native category screen (where rules are edited).
			add_submenu_page(
				self::OVERVIEW_SLUG,
				__( 'Product Categories', 'smart-categories-for-woocommerce' ),
				__( 'Product Categories', 'smart-categories-for-woocommerce' ),
				'manage_woocommerce',
				'edit-tags.php?taxonomy=product_cat&post_type=product'
			);
		}
	}


	/**
	 * Render the overview page mount point.
	 */
	public static function render_overview() {
		// The React app renders its own hero heading; keep a screen-reader H1 so
		// the admin page still has a programmatic title, and a graceful fallback
		// message if JavaScript is disabled.
		echo '<div class="wrap scwc-overview-wrap">';
		echo '<h1 class="screen-reader-text">' . esc_html__( 'Smart Categories', 'smart-categories-for-woocommerce' ) . '</h1>';
		echo '<div id="scwc-overview-app"><noscript>' . esc_html__( 'Smart Categories requires JavaScript to be enabled.', 'smart-categories-for-woocommerce' ) . '</noscript></div>';
		echo '</div>';
	}

	/**
	 * Render the rule-builder mount point on the category edit screen.
	 *
	 * @param WP_Term $term Current term.
	 */
	public static function render_term_mount( $term ) {
		if ( ! $term instanceof WP_Term ) {
			return;
		}
		?>
		<div class="scwc-term-section" style="margin-top:24px;">
			<h2><?php esc_html_e( 'Smart Category Rules', 'smart-categories-for-woocommerce' ); ?></h2>
			<p class="description">
				<?php esc_html_e( 'Define conditions; matching products are automatically assigned to this category. Combine AND / OR / NOT logic with nested groups.', 'smart-categories-for-woocommerce' ); ?>
			</p>
			<div id="scwc-rule-builder" data-term-id="<?php echo esc_attr( $term->term_id ); ?>"></div>
		</div>
		<?php
	}

	/**
	 * Whether the current admin screen should load our assets.
	 *
	 * @param string $hook Current admin page hook.
	 * @return bool
	 */
	private static function is_target_screen( $hook ) {
		if ( 'toplevel_page_' . self::OVERVIEW_SLUG === $hook ) {
			return true;
		}
		// Category edit / list screen.
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		return $screen && 'edit-product_cat' === $screen->id;
	}

	/**
	 * Enqueue the React app + styles on relevant screens.
	 *
	 * @param string $hook Current admin page hook.
	 */
	public static function enqueue( $hook ) {
		$scwc_is_tree = false;
		if ( ! self::is_target_screen( $hook ) && ! $scwc_is_tree ) {
			return;
		}

		$asset_path = SCWC_DIR . 'build/index.asset.php';
		$asset      = file_exists( $asset_path )
			? require $asset_path
			: array(
				'dependencies' => array( 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-i18n', 'wp-url' ),
				'version'      => SCWC_VERSION,
			);

		wp_enqueue_script(
			'scwc-admin',
			SCWC_URL . 'build/index.js',
			$asset['dependencies'],
			$asset['version'],
			true
		);
		wp_set_script_translations( 'scwc-admin', 'smart-categories-for-woocommerce', SCWC_DIR . 'languages' );


		// wp-scripts emits style-index.css for imported stylesheets.
		foreach ( array( 'style-index.css', 'index.css' ) as $css ) {
			if ( file_exists( SCWC_DIR . 'build/' . $css ) ) {
				wp_enqueue_style( 'scwc-admin', SCWC_URL . 'build/' . $css, array( 'wp-components' ), $asset['version'] );
				break;
			}
		}

		wp_localize_script(
			'scwc-admin',
			'scwcData',
			array(
				'rest'     => esc_url_raw( rest_url( SCWC_REST_NS ) ),
				'nonce'    => wp_create_nonce( 'wp_rest' ),
				'currency' => html_entity_decode( get_woocommerce_currency_symbol() ),
				'adminUrl' => esc_url_raw( admin_url() ),
				'isPro'      => SCWC_Plugin::is_pro() ? '1' : '',
				'upgradeUrl' => esc_url_raw( function_exists( 'scwc_upgrade_url' ) ? scwc_upgrade_url() : admin_url( 'admin.php?page=scwc-overview' ) ),
			)
		);
	}

	/**
	 * Plugins-list row links: open the overview + a highlighted Pro upsell.
	 *
	 * @param string[] $links Existing action links.
	 * @return string[]
	 */
	public static function action_links( $links ) {
		$overview = sprintf(
			'<a href="%s">%s</a>',
			esc_url( admin_url( 'admin.php?page=' . self::OVERVIEW_SLUG ) ),
			esc_html__( 'Smart Categories', 'smart-categories-for-woocommerce' )
		);
		array_unshift( $links, $overview );

		if ( ! SCWC_Plugin::is_pro() ) {
			$links[] = sprintf(
				'<a href="%s" style="color:#7f54b3;font-weight:600;">%s</a>',
				esc_url( admin_url( 'admin.php?page=' . SCWC_Upgrade::SLUG ) ),
				esc_html__( 'Upgrade to Pro', 'smart-categories-for-woocommerce' )
			);
		}
		return $links;
	}

	/**
	 * Add a "Smart" column to the category list table.
	 *
	 * @param array $columns Columns.
	 * @return array
	 */
	public static function add_column( $columns ) {
		$columns['scwc_smart'] = __( 'Smart', 'smart-categories-for-woocommerce' );
		return $columns;
	}

	/**
	 * Render the "Smart" column cell.
	 *
	 * @param string $content     Existing content.
	 * @param string $column_name Column key.
	 * @param int    $term_id     Term ID.
	 * @return string
	 */
	public static function render_column( $content, $column_name, $term_id ) {
		if ( 'scwc_smart' !== $column_name ) {
			return $content;
		}
		if ( SCWC_Term_Rules::is_enabled( $term_id ) ) {
			$count = SCWC_Assigner::managed_count( $term_id );
			return sprintf(
				'<span class="dashicons dashicons-yes-alt" style="color:#2271b1"></span> %s',
				esc_html(
					sprintf(
						/* translators: %d: number of auto-assigned products */
						_n( '%d product', '%d products', $count, 'smart-categories-for-woocommerce' ),
						$count
					)
				)
			);
		}
		return '—';
	}
}
