<?php
/**
 * Admin UI.
 *
 * @package CatalogFrameImageStudio
 */

namespace CatalogFrame_Image_Studio;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Registers and renders the admin application.
 */
final class Admin {
	const PAGE_SLUG      = 'catalogframe-image-studio';
	const CUSTOM_GPT_URL = 'https://chatgpt.com/g/g-6a4e11087a5481918e7371fc6e23c7a5-woocommerce-product-csv-builder';
	const SUPPORT_URL    = 'https://taistudio.co/catalogframe';
	const DONATION_URL   = 'https://www.paypal.com/ncp/payment/RBBNGNS348UXQ';

	/**
	 * Admin hook suffixes where assets should load.
	 *
	 * @var array
	 */
	private $hook_suffixes = array();

	/**
	 * Registers hooks.
	 *
	 * @return void
	 */
	public function init() {
		add_action( 'admin_menu', array( $this, 'register_menu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_filter( 'plugin_action_links_' . plugin_basename( CFIS_PLUGIN_FILE ), array( $this, 'add_plugin_action_links' ) );
	}

	/**
	 * Adds a direct app entry beside Deactivate on the Plugins screen.
	 *
	 * @param array $links Existing plugin action links.
	 * @return array
	 */
	public function add_plugin_action_links( $links ) {
		if ( ! current_user_can( CFIS_MANAGE_CAPABILITY ) ) {
			return $links;
		}

		$open_link = sprintf(
			'<a href="%1$s">%2$s</a>',
			esc_url( $this->app_url() ),
			esc_html__( 'Open CatalogFrame', 'catalogframe-image-studio' )
		);

		array_unshift( $links, $open_link );

		return $links;
	}

	/**
	 * Registers the plugin under Products when available, with a fallback when WooCommerce is absent.
	 *
	 * @return void
	 */
	public function register_menu() {
		if ( post_type_exists( 'product' ) ) {
			$this->hook_suffixes[] = add_submenu_page(
				'edit.php?post_type=product',
				__( 'CatalogFrame Image Studio', 'catalogframe-image-studio' ),
				__( 'CatalogFrame Images', 'catalogframe-image-studio' ),
				CFIS_MANAGE_CAPABILITY,
				self::PAGE_SLUG,
				array( $this, 'render_app' )
			);
		} else {
			$this->hook_suffixes[] = add_menu_page(
				__( 'CatalogFrame Image Studio', 'catalogframe-image-studio' ),
				__( 'CatalogFrame', 'catalogframe-image-studio' ),
				CFIS_MANAGE_CAPABILITY,
				self::PAGE_SLUG,
				array( $this, 'render_app' ),
				'dashicons-format-image',
				58
			);
		}
	}

	/**
	 * Returns the admin app URL.
	 *
	 * @return string
	 */
	private function app_url() {
		if ( post_type_exists( 'product' ) ) {
			return admin_url( 'edit.php?post_type=product&page=' . self::PAGE_SLUG );
		}

		return admin_url( 'admin.php?page=' . self::PAGE_SLUG );
	}

	/**
	 * Enqueues app assets on the plugin page.
	 *
	 * @param string $hook_suffix Current admin hook.
	 * @return void
	 */
	public function enqueue_assets( $hook_suffix ) {
		if ( ! in_array( $hook_suffix, $this->hook_suffixes, true ) ) {
			return;
		}

		$style_url  = $this->asset_url( 'css' );
		$script_url = $this->asset_url( 'js' );
		if ( '' === $style_url || '' === $script_url ) {
			return;
		}

		wp_enqueue_media();

		wp_enqueue_style(
			'catalogframe-image-studio-admin',
			$style_url,
			array(),
			CFIS_VERSION
		);

		wp_enqueue_script(
			'catalogframe-image-studio-admin',
			$script_url,
			array( 'wp-api-fetch' ),
			CFIS_VERSION,
			true
		);
		wp_script_add_data( 'catalogframe-image-studio-admin', 'type', 'module' );
		add_filter( 'script_loader_tag', array( $this, 'add_module_script_type' ), 10, 3 );

		wp_localize_script(
			'catalogframe-image-studio-admin',
			'CatalogFrameStudio',
			array(
				'restNamespace' => Rest_Controller::NAMESPACE,
				'restNonce'     => wp_create_nonce( 'wp_rest' ),
				'customGptUrl'  => self::CUSTOM_GPT_URL,
				'connectorsUrl' => admin_url( 'options-connectors.php' ),
				'productsUrl'   => admin_url( 'edit.php?post_type=product' ),
				'supportUrl'    => self::SUPPORT_URL,
				'donationUrl'   => self::DONATION_URL,
					'wooAvailable'  => post_type_exists( 'product' ) && function_exists( 'wc_get_product_id_by_sku' ),
				'i18n'          => array(
					'closeWarning' => __( 'CatalogFrame is generating images. Closing this tab will stop the job after the current request. Leave anyway?', 'catalogframe-image-studio' ),
				),
			)
		);
	}

	/**
	 * Ensures the built Vite admin bundle can use module syntax such as import.meta.url.
	 *
	 * @param string $tag    Script tag.
	 * @param string $handle Script handle.
	 * @param string $src    Script URL.
	 * @return string
	 */
	public function add_module_script_type( $tag, $handle, $src ) {
		if ( 'catalogframe-image-studio-admin' !== $handle || empty( $src ) ) {
			return $tag;
		}

		return wp_get_script_tag(
			array(
				'type' => 'module',
				'src'  => $src,
				'id'   => $handle . '-js',
			)
		);
	}

	/**
	 * Returns a built Vite asset URL.
	 *
	 * @param string $type Asset type.
	 * @return string
	 */
	private function asset_url( $type ) {
		$manifest_path = CFIS_PLUGIN_DIR . 'assets/build/.vite/manifest.json';
		if ( file_exists( $manifest_path ) ) {
			$manifest = json_decode( (string) file_get_contents( $manifest_path ), true );
			$entry    = is_array( $manifest ) && isset( $manifest['src/main.tsx'] ) ? $manifest['src/main.tsx'] : null;

			if ( is_array( $entry ) ) {
				if ( 'js' === $type && ! empty( $entry['file'] ) ) {
					return CFIS_PLUGIN_URL . 'assets/build/' . ltrim( (string) $entry['file'], '/' );
				}

				if ( 'css' === $type && ! empty( $entry['css'][0] ) ) {
					return CFIS_PLUGIN_URL . 'assets/build/' . ltrim( (string) $entry['css'][0], '/' );
				}
			}
		}

		return '';
	}

	/**
	 * Renders the admin app shell.
	 *
	 * @return void
	 */
	public function render_app() {
		if ( ! current_user_can( CFIS_MANAGE_CAPABILITY ) ) {
			wp_die( esc_html__( 'You do not have permission to use CatalogFrame Image Studio.', 'catalogframe-image-studio' ) );
		}

		if ( '' === $this->asset_url( 'js' ) || '' === $this->asset_url( 'css' ) ) {
			echo '<div class="notice notice-error"><p>' . esc_html__( 'CatalogFrame admin assets are missing. Reinstall the plugin package and try again.', 'catalogframe-image-studio' ) . '</p></div>';
			return;
		}
		?>
		<div class="wrap catalogframe-admin-wrap">
			<div id="catalogframe-admin-root"></div>
		</div>
		<?php
	}
}
