<?php
/**
 * Redirects admin page.
 *
 * @link          https://aleksandrsamokhin.com
 * @since         1.0.0
 *
 * @author        Aleksandr Samokhin
 * @package       Redicl\Admin
 *
 * @copyright (c) 2025, Aleksandr Samokhin
 */

namespace Redicl\Admin;

// Abort if called directly.
defined( 'WPINC' ) || die;

/**
 * Redirects_Page class.
 */
class Redirects_Page {

	/**
	 * The page title.
	 *
	 * @var string
	 */
	private $page_title;

	/**
	 * The page slug.
	 *
	 * @var string
	 */
	private $page_slug = 'redicl';

	/**
	 * Page Assets.
	 *
	 * @var array
	 */
	private $page_scripts = array();

	/**
	 * Assets version.
	 *
	 * @var string
	 */
	private $assets_version = '';

	/**
	 * A unique string id to be used in markup and jsx.
	 *
	 * @var string
	 */
	private $unique_id = '';

	/**
	 * Initializes the page.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public function init() {
		$this->page_title     = __( 'Redirect Cleanup', 'redirect-cleanup' );
		$this->assets_version = ! empty( $this->script_data( 'version' ) ) ? $this->script_data( 'version' ) : REDICL_VERSION;
		$this->unique_id      = "redirect_cleanup_main_wrap-{$this->assets_version}";

		add_action( 'admin_menu', array( $this, 'register_admin_page' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
	}

	/**
	 * Register admin page.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public function register_admin_page() {
		$page = add_management_page(
			$this->page_title,
			$this->page_title,
			'manage_options',
			$this->page_slug,
			array( $this, 'callback' )
		);

		add_action( 'load-' . $page, array( $this, 'prepare_assets' ) );
	}

	/**
	 * The admin page callback method.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public function callback() {
		$this->view();
	}

	/**
	 * Prepares assets.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public function prepare_assets() {
		if ( ! is_array( $this->page_scripts ) ) {
			$this->page_scripts = array();
		}

		$handle       = 'redirect_cleanup_admin_page';
		$src          = REDICL_ASSETS_URL . '/admin/index.js';
		$style_src    = REDICL_ASSETS_URL . '/admin/index.css';
		$dependencies = ! empty( $this->script_data( 'dependencies' ) )
			? $this->script_data( 'dependencies' )
			: array(
				'react',
				'react-dom',
				'wp-element',
				'wp-i18n',
				'wp-api-fetch',
				'wp-components',
			);

		$this->page_scripts[ $handle ] = array(
			'src'       => $src,
			'style_src' => $style_src,
			'deps'      => $dependencies,
			'ver'       => $this->assets_version,
			'strategy'  => true,
			'localize'  => array(
				'dom_element_id'                => $this->unique_id,
				'restEndpointScan'              => 'redirect-cleanup/v1/scan',
				'restEndpointHomeRedirects'     => 'redirect-cleanup/v1/home-redirects',
				'restEndpointProcessBatch'      => 'redirect-cleanup/v1/process-batch',
				'restEndpointPostTypes'         => 'redirect-cleanup/v1/post-types',
				'restEndpointChainRedirects'    => 'redirect-cleanup/v1/chain-redirects',
				'restEndpointFixChainRedirects' => 'redirect-cleanup/v1/fix-chain-redirects',
				'restEndpointStats'             => 'redirect-cleanup/v1/stats',
				'nonce'                         => wp_create_nonce( 'wp_rest' ),
				'isNotPaying'                   => redicl_fs()->is_not_paying(),
				'upgradeUrl'                    => redicl_fs()->get_upgrade_url(),
			),
		);
	}

	/**
	 * Gets assets data for given key.
	 *
	 * @param string $key The key to get.
	 * @return string|array
	 * @since 1.0.0
	 */
	protected function script_data( string $key = '' ) {
		$raw_script_data = $this->raw_script_data();

		return ! empty( $key ) && ! empty( $raw_script_data[ $key ] ) ? $raw_script_data[ $key ] : '';
	}

	/**
	 * Gets the script data from assets php file.
	 *
	 * @return array
	 * @since 1.0.0
	 */
	protected function raw_script_data(): array {
		static $script_data = null;

		if ( is_null( $script_data ) && file_exists( REDICL_DIR . 'build/admin/index.asset.php' ) ) {
			$script_data = include REDICL_DIR . 'build/admin/index.asset.php';
		}

		return (array) $script_data;
	}

	/**
	 * Enqueues assets.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public function enqueue_assets() {
		// Enqueue WordPress components styles for Notice, Button, etc.
		if ( ! wp_style_is( 'wp-components', 'registered' ) ) {
			wp_register_style(
				'wp-components',
				includes_url( 'css/dist/components/style.min.css' ),
				array(),
				get_bloginfo( 'version' )
			);
		}
		wp_enqueue_style( 'wp-components' );

		if ( ! empty( $this->page_scripts ) ) {
			foreach ( $this->page_scripts as $handle => $page_script ) {
				wp_register_script(
					$handle,
					$page_script['src'],
					$page_script['deps'],
					$page_script['ver'],
					$page_script['strategy']
				);

				if ( ! empty( $page_script['localize'] ) ) {
					wp_localize_script( $handle, 'redicl', $page_script['localize'] );
				}

				wp_enqueue_script( $handle );

				if ( ! empty( $page_script['style_src'] ) ) {
					wp_enqueue_style( $handle, $page_script['style_src'], array(), $this->assets_version );
				}
			}
		}
	}

	/**
	 * Prints the wrapper element which React will use as root.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	protected function view() {
		?>
		<div class="wrap">
			<h1><?php echo esc_html( $this->page_title ); ?></h1>
			<p><?php echo esc_html( __( 'This tool will scan your website for homepage redirect URLs and remove them from your posts and pages. It can also detect and fix chain and loop redirects. Currently, it only works with Yoast SEO.', 'redirect-cleanup' ) ); ?></p>
			<div id="<?php echo esc_attr( $this->unique_id ); ?>"></div>
		</div>
		<?php
	}
}

