<?php
/**
 * Admin class.
 *
 * @package MemberRead
 * @since 1.0.0
 */

namespace MemberRead;

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

/**
 * Admin class.
 */
class Admin {

	/**
	 * User Registration and Membership reference key.
	 *
	 * @var string
	 */
	const URM_REF = 'urm_reference_key';

	/**
	 * Admin constructor.
	 */
	public function __construct() {
		$this->setup_admin_hooks();
		$this->add_install_time();
	}

	/**
	 * Add the installation time.
	 * This is needed here while the SDK is not available.
	 * Once the SDK is available, this can safely be removed.
	 *
	 * @return void
	 */
	private function add_install_time() {
		$install = get_option( Constants::PRODUCT_KEY . '_install', 0 );
		if ( 0 === $install ) {
			update_option( Constants::PRODUCT_KEY . '_install', time() );
		}
	}

	/**
	 * Setup admin hooks.
	 *
	 * @return void
	 */
	public function setup_admin_hooks() {
		add_action( 'admin_notices', array( $this, 'render_welcome_notice' ), 0 );
		add_action( 'activated_plugin', array( $this, 'after_urm_activation' ) );
		add_action( 'wp_ajax_member_read_dismiss_welcome_notice', array( $this, 'remove_welcome_notice' ) );
		add_action( 'wp_ajax_member_read_set_urm_ref', array( $this, 'set_urm_ref' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'register_internal_page' ) );
	}

	/**
	 * Render the welcome notice.
	 *
	 * @return void
	 */
	public function render_welcome_notice() {
		if ( ! $this->should_show_welcome_notice() ) {
			return;
		}

		$urm_status = $this->get_urm_status();

		Assets_Manager::enqueue_style( Assets_Manager::ASSETS_SLUGS['welcome-notice'], 'welcome-notice' );
		Assets_Manager::enqueue_script(
			Assets_Manager::ASSETS_SLUGS['welcome-notice'],
			'welcome-notice',
			true,
			array(),
			array(
				'nonce'         => wp_create_nonce( 'member-read-dismiss-welcome-notice' ),
				'urmRefNonce'   => wp_create_nonce( 'member-read-set-urm-ref' ),
				'ajaxUrl'       => esc_url( admin_url( 'admin-ajax.php' ) ),
				'urmStatus'     => $urm_status,
				'activationUrl' => esc_url(
					add_query_arg(
						array(
							'plugin_status' => 'all',
							'paged'         => '1',
							'action'        => 'activate',
							'plugin'        => rawurlencode( 'user-registration/user-registration.php' ),
							'_wpnonce'      => wp_create_nonce( 'activate-plugin_user-registration/user-registration.php' ),
						),
						admin_url( 'plugins.php' )
					)
				),
				'redirectUrl'   => esc_url( admin_url( 'admin.php?page=user-registration-welcome' ) ),
				'activating'    => __( 'Activating', 'member-read' ) . '&hellip;',
				'installing'    => __( 'Installing', 'member-read' ) . '&hellip;',
				'done'          => __( 'Done', 'member-read' ),
			)
		);

		$notice_html  = '<div class="notice notice-info member-read-welcome-notice">';
		$notice_html .= '<button type="button" class="notice-dismiss"><span class="screen-reader-text">' . esc_html__( 'Dismiss this notice.', 'member-read' ) . '</span></button>';
		$notice_html .= '<div class="notice-content">';

		$notice_html .= '<div class="notice-copy">';

		$notice_html .= '<h2 class="notice-subtitle">';
		$notice_html .= '<img class="notice-subtitle-icon" src="' . esc_url( Assets_Manager::get_image_url( 'user-registration-and-membership.png' ) ) . '" alt="' . esc_attr__( 'User Registration & Membership preview', 'member-read' ) . '"/>';
		$notice_html .= __( 'This theme works best with User Registration & Membership', 'member-read' );
		$notice_html .= '</h2>';

		$notice_html .= '<h1 class="notice-title">';
		/* translators: %s: User Registration & Membership */
		$notice_html .= sprintf( __( 'Build Powerful Membership Sites with %s!', 'member-read' ), '<span>User Registration & Membership</span>' );
		$notice_html .= '</h1>';

		$notice_html .= '<p class="description">' . __( 'The complete WordPress membership solution to build communities, manage users, restrict content, and monetize your site with ease.', 'member-read' ) . '</p>';

		$notice_html .= '<p class="description"><span class="dashicons dashicons-yes"></span><strong>' . __( 'Easy user registration & profiles', 'member-read' ) . '</strong> - ' . __( 'Let users sign up, log in, and manage their accounts effortlessly from your site.', 'member-read' ) . '</p>';

		$notice_html .= '<p class="description"><span class="dashicons dashicons-yes"></span><strong>' . __( 'Content restriction controls', 'member-read' ) . '</strong> - ' . __( 'Protect posts, pages, and digital resources based on membership levels or user roles.', 'member-read' ) . '</p>';

		$notice_html .= '<p class="description"><span class="dashicons dashicons-yes"></span><strong>' . __( 'Flexible membership management', 'member-read' ) . '</strong> - ' . __( 'Create plans, manage subscribers, and control access rules with complete flexibility.', 'member-read' ) . '</p>';

		$notice_html .= '<div class="actions">';

		$notice_html .= '<button id="member-read-install-urm" class="button button-primary button-hero">';
		$notice_html .= '<span class="dashicons dashicons-update hidden"></span>';
		$notice_html .= '<span class="text">';
		$notice_html .= 'installed' === $urm_status ?
			/* translators: %s: User Registration & Membership */
			sprintf( __( 'Activate %s', 'member-read' ), 'User Registration & Membership' ) :
			/* translators: %s: User Registration & Membership */
			sprintf( __( 'Install & Activate %s', 'member-read' ), 'User Registration & Membership' );
		$notice_html .= '</span>';
		$notice_html .= '</button>';

		$notice_html .= '<a href="https://wordpress.org/plugins/user-registration/" target="_blank" class="button button-secondary button-hero">';
		$notice_html .= '<span>' . __( 'Learn More', 'member-read' ) . '</span>';
		$notice_html .= '<span class="dashicons dashicons-external member-read-icon"></span>';
		$notice_html .= '</a>';

		$notice_html .= '</div>';

		$notice_html .= '</div>';

		$notice_html .= '<img class="urm-preview" src="' . esc_url( Assets_Manager::get_image_url( 'welcome-notice.png' ) ) . '" alt="' . esc_attr__( 'User Registration & Membership preview', 'member-read' ) . '"/>';
		$notice_html .= '</div>';
		$notice_html .= '</div>';

		echo wp_kses_post( $notice_html );
	}

	/**
	 * Dismiss the welcome notice.
	 *
	 * @return void
	 */
	public function remove_welcome_notice() {
		if ( ! isset( $_POST['nonce'] ) ) {
			return;
		}
		if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'member-read-dismiss-welcome-notice' ) ) {
			return;
		}
		update_option( Constants::CACHE_KEYS['dismissed-welcome-notice'], 'yes' );
		wp_die();
	}

	/**
	 * Should we show the welcome notice?
	 *
	 * @return bool
	 */
	private function should_show_welcome_notice(): bool {
		// Already using URM.
		if ( is_plugin_active( 'user-registration/user-registration.php' ) ) {
			return false;
		}

		// Notice was dismissed.
		if ( get_option( Constants::CACHE_KEYS['dismissed-welcome-notice'], 'no' ) === 'yes' ) {
			return false;
		}

		$screen = get_current_screen();

		// Only show in dashboard/themes.
		if ( ! in_array( $screen->id, array( 'dashboard', 'themes' ), true ) ) {
			return false;
		}

		// AJAX actions.
		if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
			return false;
		}

		// Don't show in network admin.
		if ( is_network_admin() ) {
			return false;
		}

		// User can't dismiss. We don't show it.
		if ( ! current_user_can( 'manage_options' ) ) {
			return false;
		}

		// User can't install plugins. We don't show it.
		if ( ! current_user_can( 'install_plugins' ) ) {
			return false;
		}

		// Block editor context.
		if ( $screen->is_block_editor() ) {
			return false;
		}

		// Dismiss after one week from activation.
		$activated_time = get_option( 'member_read_install' );

		if ( ! empty( $activated_time ) && time() - intval( $activated_time ) > WEEK_IN_SECONDS ) {
			update_option( Constants::CACHE_KEYS['dismissed-welcome-notice'], 'yes' );
			return false;
		}

		return true;
	}

	/**
	 * Get the URM plugin status.
	 *
	 * @return string
	 */
	private function get_urm_status(): string {
		$status = 'not-installed';

		if ( is_plugin_active( 'user-registration/user-registration.php' ) ) {
			return 'active';
		}

		if ( file_exists( ABSPATH . 'wp-content/plugins/user-registration/user-registration.php' ) ) {
			return 'installed';
		}

		return $status;
	}

	/**
	 * Run after URM activation.
	 *
	 * @param string $plugin Plugin name.
	 *
	 * @return void
	 */
	public function after_urm_activation( $plugin ) {
		if ( 'user-registration/user-registration.php' !== $plugin ) {
			return;
		}

		update_option( Constants::CACHE_KEYS['dismissed-welcome-notice'], 'yes' );
		exit;
	}

	/**
	 * Update URM reference key.
	 *
	 * @return void
	 */
	public function set_urm_ref() {
		if ( empty( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'member-read-set-urm-ref' ) ) {
			return;
		}

		update_option( self::URM_REF, 'member-read' );

		wp_send_json_success();
	}

	/**
	 * Register internal pages.
	 *
	 * @return void
	 */
	public function register_internal_page() {
		$screen = get_current_screen();

		if ( 'dashboard' !== $screen->id && 'themes' !== $screen->id ) {
			return;
		}

		do_action( 'themegrill_internal_page', Constants::PRODUCT_SLUG, $screen->id );
	}
}

// Initialize Admin class.
new Admin();
