<?php

declare(strict_types=1);

namespace SiteFort\Modules\Cloud\Service;

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

use SiteFort\Includes\Capabilities;
use SiteFort\Includes\SettingsStore;

/**
 * wp-admin notice for a pending Console connection request.
 *
 * SiteFort's own admin pages suppress WordPress admin_notices (see Admin.php) and instead render
 * an equivalent in-app banner, so this notice only ever surfaces on other wp-admin screens.
 */
class ConsoleGateNotice {

	private const NOTICE_DISMISSED_AT_KEY = 'console_gate_notice_dismissed_at';

	/**
	 * Whether the pending-connection-request notice/banner should currently show.
	 *
	 * Shared by the wp-admin notice below and the in-app banner's window.sitefortData payload, so
	 * both surfaces always agree on visibility and dismissing either one dismisses both.
	 */
	public static function pending_notice_is_active(): bool {
		$status = ConsoleGate::status();
		if ( ! $status['pending_request'] ) {
			return false;
		}

		$dismissed_at = absint( SettingsStore::get_field( SettingsStore::COL_STATE, self::NOTICE_DISMISSED_AT_KEY, 0 ) );
		return $dismissed_at !== $status['last_request_at'];
	}

	public static function render(): void {
		if ( ! Capabilities::can_manage_plugin() || ! self::pending_notice_is_active() ) {
			return;
		}

		$review_url = add_query_arg(
			'tab',
			'integrations',
			admin_url( 'admin.php?page=sitefort-settings' )
		) . '#console-connection';
		?>
		<div id="sitefort-console-gate-pending-notice"
			class="notice notice-warning sitefort-console-gate-notice"
			data-nonce="<?php echo esc_attr( wp_create_nonce( 'sitefort_nonce' ) ); ?>"
			data-ajax-url="<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>">
			<div>
				<strong><?php esc_html_e( 'A Console connection request is awaiting approval.', 'sitefort' ); ?></strong>
				<?php
				printf(
					/* translators: %1$s: opening link tag to the Integrations settings screen, %2$s: closing link tag */
					esc_html__( '%1$sReview the request%2$s in SiteFort > Settings > Integrations.', 'sitefort' ),
					'<a href="' . esc_url( $review_url ) . '">',
					'</a>'
				);
				?>
			</div>
			<button type="button" class="notice-dismiss" data-sitefort-dismiss-console-gate-notice>
				<span class="screen-reader-text"><?php esc_html_e( 'Dismiss this notice.', 'sitefort' ); ?></span>
			</button>
		</div>
		<?php
	}

	/**
	 * Dismiss (cosmetic only) the pending-request notice/banner until a new request arrives.
	 */
	public static function handle_dismiss_pending_ajax(): void {
		check_ajax_referer( 'sitefort_nonce', false );
		if ( ! Capabilities::can_manage_plugin() ) {
			wp_send_json_error( [ 'message' => 'Unauthorized' ], 403 );
		}

		$status = ConsoleGate::status();
		SettingsStore::set_field( SettingsStore::COL_STATE, self::NOTICE_DISMISSED_AT_KEY, $status['last_request_at'] );
		wp_send_json_success();
	}
}
