<?php
// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

/**
 * Admin landing page shown after upgrading to 5.0+ from older versions.
 */
class WC_Appointments_Admin_Whats_New {

	public const OPTION_KEY = 'wc_appointments_show_whats_new';
	public const PAGE_SLUG  = 'wc-appointments-whats-new';

	/**
	 * Bootstrap hooks.
	 */
	public static function init(): void {
		add_action( 'admin_menu', [ self::class, 'register_page' ], 999 );
		add_action( 'admin_init', [ self::class, 'maybe_redirect' ] );
	}

	/**
	 * Add a submenu page under Appointments we can redirect to.
	 */
	public static function register_page(): void {
		add_submenu_page(
		    'edit.php?post_type=wc_appointment',
		    __( "What's New in WooCommerce Appointments", 'woocommerce-appointments' ),
		    __( "What's New", 'woocommerce-appointments' ),
		    self::get_capability(),
		    self::PAGE_SLUG,
		    [ self::class, 'render_page' ],
		);
	}

	/**
	 * Redirects privileged users to the landing page right after the upgrade.
	 * Disabled - no longer redirects to what's new page.
	 */
	public static function maybe_redirect(): void {
		// Redirect functionality disabled
		return;
		
		if ( ! is_admin() || wp_doing_ajax() ) {
			return;
		}

		if ( ! current_user_can( self::get_capability() ) ) {
			return;
		}

		$flag = get_option( self::OPTION_KEY );

		if ( ! $flag || WC_APPOINTMENTS_VERSION !== $flag ) {
			return;
		}

		// Avoid redirect loops while on the page already.
		if ( isset( $_GET['page'] ) && self::PAGE_SLUG === sanitize_key( wp_unslash( $_GET['page'] ) ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			return;
		}

		wp_safe_redirect( admin_url( 'edit.php?post_type=wc_appointment&page=' . self::PAGE_SLUG ) );
		exit;
	}

	/**
	 * Render the landing page.
	 */
	public static function render_page(): void {
		if ( ! current_user_can( self::get_capability() ) ) {
			wp_die( esc_html( 'You do not have permission to access this page.' ) );
		}

		// Mark as seen so we only redirect once.
		delete_option( self::OPTION_KEY );

		include __DIR__ . '/views/html-wc-appointments-whats-new.php';
	}

	/**
     * Capability helper so we can change it centrally later.
     */
    private static function get_capability(): string {
		return 'manage_woocommerce';
	}
}

WC_Appointments_Admin_Whats_New::init();
