<?php
/**
 * Theme setup page.
 *
 * Displays the Wira welcome screen and installs or activates Wira Templates.
 *
 * @package Wira
 * @since   1.0.1
 */

namespace Wira;

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

if ( ! class_exists( 'Setup_Page' ) ) {

	/**
	 * Setup page controller.
	 */
	class Setup_Page {

		/**
		 * Singleton instance.
		 *
		 * @var self|null
		 */
		private static $instance = null;

		/**
		 * Wira Templates plugin file path.
		 */
		private const WIRA_TEMPLATES_PLUGIN_FILE = 'wira-templates/wira-templates.php';

		/**
		 * Wira Templates plugin slug.
		 */
		private const WIRA_TEMPLATES_PLUGIN_SLUG = 'wira-templates';

		/**
		 * Theme setup page slug.
		 */
		private const PAGE_SLUG = 'wira-setup';

		/**
		 * Get singleton instance.
		 *
		 * @return self
		 */
		public static function get_instance() {
			if ( null === self::$instance ) {
				self::$instance = new self();
			}

			return self::$instance;
		}

		/**
		 * Private constructor.
		 */
		private function __construct() {
			add_action( 'admin_menu', array( $this, 'register_menu' ) );
			add_action( 'admin_init', array( $this, 'maybe_redirect_to_setup_page' ) );
			add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
			add_action( 'after_switch_theme', array( $this, 'flag_setup_redirect' ) );
		}

		/**
		 * Prevent cloning of the singleton.
		 *
		 * @return void
		 */
		private function __clone() {}

		/**
		 * Prevent unserializing of the singleton.
		 *
		 * @throws \Exception If unserialization is attempted.
		 * @return void
		 */
		public function __wakeup() {
			throw new \Exception( 'Cannot unserialize singleton' );
		}

		/**
		 * Register the theme setup page.
		 *
		 * @return void
		 */
		public function register_menu() {
			if ( $this->is_wira_templates_active() ) {
				return;
			}

			add_menu_page(
				__( 'Wira Setup', 'wira' ),
				__( 'Wira Setup', 'wira' ),
				'manage_options',
				self::PAGE_SLUG,
				array( $this, 'render_page' ),
				trailingslashit( WIRA_URI ) . 'assets/img/wira-icon.svg',
				61
			);
		}

		/**
		 * Enqueue assets for the setup page.
		 *
		 * @param string $hook_suffix Admin page hook suffix.
		 * @return void
		 */
		public function enqueue_assets( $hook_suffix ) {
			if ( $this->is_wira_templates_active() ) {
				return;
			}

			if ( 'toplevel_page_' . self::PAGE_SLUG !== $hook_suffix ) {
				return;
			}

			wp_enqueue_style(
				'wira-setup-page',
				trailingslashit( WIRA_URI ) . 'assets/css/admin-setup.css',
				array(),
				WIRA_VERSION
			);

			wp_enqueue_script( 'wp-util' );

			wp_enqueue_script(
				'wira-setup-page',
				trailingslashit( WIRA_URI ) . 'assets/js/admin-setup.js',
				array( 'wp-util' ),
				WIRA_VERSION,
				true
			);

			wp_localize_script(
				'wira-setup-page',
				'WiraSetupData',
				array(
					'pluginSlug'   => self::WIRA_TEMPLATES_PLUGIN_SLUG,
					'pluginFile'   => self::WIRA_TEMPLATES_PLUGIN_FILE,
					'pluginName'   => __( 'Wira Templates', 'wira' ),
					'openUrl'      => admin_url( 'admin.php?page=wira-templates' ),
					'installNonce' => wp_create_nonce( 'updates' ),
					'labels'       => array(
						'processing' => __( 'Processing...', 'wira' ),
						'failed'     => __( 'Unable to complete setup. Please try again.', 'wira' ),
					),
				)
			);
		}

		/**
		 * Flag the setup page redirect after theme activation.
		 *
		 * @return void
		 */
		public function flag_setup_redirect() {
			set_transient( 'wira_setup_redirect', 1, MINUTE_IN_SECONDS );
		}

		/**
		 * Redirect once to the setup page after theme activation.
		 *
		 * @return void
		 */
		public function maybe_redirect_to_setup_page() {
			if ( ! is_admin() ) {
				return;
			}

			if ( $this->is_wira_templates_active() ) {
				delete_transient( 'wira_setup_redirect' );
				return;
			}

			if ( empty( $_GET['page'] ) || self::PAGE_SLUG === sanitize_key( wp_unslash( $_GET['page'] ) ) ) {
				return;
			}

			if ( ! get_transient( 'wira_setup_redirect' ) ) {
				return;
			}

			delete_transient( 'wira_setup_redirect' );
			wp_safe_redirect( admin_url( 'admin.php?page=' . self::PAGE_SLUG ) );
			exit;
		}

		/**
		 * Check whether Wira Templates is active.
		 *
		 * @return bool
		 */
		private function is_wira_templates_active() {
			return defined( 'WIRAT_VERSION' ) || class_exists( 'Wirat_Templates_Plugin' ) || class_exists( 'Wirat_Template_Importer' );
		}

		/**
		 * Check if Wira Templates is installed and active.
		 *
		 * @return array
		 */
		private function get_setup_state() {
			$plugin_file  = self::WIRA_TEMPLATES_PLUGIN_FILE;
			$is_installed = file_exists( WP_PLUGIN_DIR . '/' . $plugin_file );
			$is_active    = $this->is_wira_templates_active();

			$state = array(
				'mode'        => 'install',
				'button_text' => __( 'Complete Setup', 'wira' ),
				'open_url'    => admin_url( 'admin.php?page=wira-templates' ),
			);

			if ( $is_active ) {
				$state['mode']        = 'active';
				$state['button_text'] = __( 'Open Wira Templates', 'wira' );
				return $state;
			}

			if ( $is_installed ) {
				$state['mode'] = 'activate';
			}

			return $state;
		}

		/**
		 * Render the setup page.
		 *
		 * @return void
		 */
		public function render_page() {
			$state = $this->get_setup_state();
			?>
			<div class="wrap wira-setup-page wira-card">
				<div class="wira-setup-page__banner">
					<div class="wira-setup-page__content">
						<h1 class="wira-setup-page__title text-white">
							<?php echo esc_html__( 'Unlock Features - Launch Professional Website Faster, Just For a Minute Using', 'wira' ); ?>
							<span><?php echo esc_html__( 'Wira Templates', 'wira' ); ?></span>
						</h1>

						<p class="wira-setup-page__text">
							<?php echo esc_html__( 'Complete setup by installing Wira Templates, your companion library for one-click full site import, premium Elementor kits, CMS-ready content, custom fields, post types, and adjusted single post layouts.', 'wira' ); ?>
						</p>

						<div class="wira-setup-page__actions">
							<?php if ( 'active' === $state['mode'] ) : ?>
								<a class="button button-primary button-hero wira-setup-page__button" href="<?php echo esc_url( $state['open_url'] ); ?>">
									<?php echo esc_html( $state['button_text'] ); ?>
								</a>
							<?php else : ?>
								<button
									type="button"
									class="button button-primary button-hero wira-setup-page__button"
									data-wira-setup-action="<?php echo esc_attr( $state['mode'] ); ?>"
								>
									<?php echo esc_html( $state['button_text'] ); ?>
								</button>
							<?php endif; ?>
						</div>
					</div>

					<div class="wira-setup-page__visual">
						<img src="<?php echo esc_url( trailingslashit( WIRA_URI ) . '/assets/img/setup-img.png' ); ?>" alt="<?php echo esc_attr__( 'Wira theme preview', 'wira' ); ?>">
					</div>
				</div>
			</div>
			<?php
		}
	}
}
