<?php

namespace The7\Admin\Notices\Announcements;

use The7\Admin\Pages\Dashboard;
use The7_Feature_Access;

defined( 'ABSPATH' ) || exit;

/**
 * Capability Available Announcement for the `theme_updates` Feature Access capability.
 *
 * The granted-with-message mirror of the Capability Lock Notice: when the server grants
 * `theme_updates` and ships a message (e.g. "upgrade to v15 available"), this dismissible
 * announcement shows it on the The7 dashboard screen. Mutually exclusive with the lock
 * notice by construction.
 * See docs/adr/0006-capability-available-notice-surface.md.
 */
class Theme_Upgrade_Available extends Abstract_Announcement {

	/**
	 * Feature Access capability key (server-owned wire identifier).
	 */
	const CAPABILITY = 'theme_updates';

	/**
	 * Dismissal code persisted in the7_dismissed_admin_notices.
	 */
	const CODE = 'the7_theme_updates_available';

	public function render() {
		// Server-authored message: prose + links + announcement shortcodes (e.g.
		// [upgrade_button]). Sanitized, expanded, and stripped by the shared pipeline.
		echo $this->render_announcement_content( The7_Feature_Access::get_sanitized_message( self::CAPABILITY ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- wp_kses_post + theme-owned shortcode output.
	}

	public function is_visible() {
		if ( ! Dashboard::is_current_screen() ) {
			return false;
		}

		return current_user_can( 'update_themes' ) && The7_Feature_Access::is_granted_with_message( self::CAPABILITY );
	}

	public function get_code() {
		return self::CODE;
	}

	/**
	 * Keep the notice re-notifying on a fresh grant after a lapse.
	 *
	 * Mirror of the lock notice: dismissal is valid only while granted, so whenever the
	 * capability is blocked any stale dismissal is cleared — a later renewal then shows an
	 * undismissed notice. Stateless — no previous verdict is stored.
	 *
	 * @return void
	 */
	public static function sync_dismissal() {
		if ( ! The7_Feature_Access::is_blocked( self::CAPABILITY ) ) {
			return;
		}

		$notices = the7_admin_notices();
		if ( $notices->notice_is_dismissed( self::CODE ) ) {
			$notices->reset( self::CODE );
		}
	}
}
