<?php
/**
 * Creates / updates the published "Accessibility Statement" page and the
 * optional footer link.
 */

defined( 'ABSPATH' ) || exit;

class TSFFE_Page {

	const OPTION_STATEMENT   = 'tsffe_statement';
	const OPTION_PAGE_ID     = 'tsffe_page_id';
	const OPTION_FOOTER_LINK = 'tsffe_footer_link';
	const PAGE_SLUG          = 'accessibility-statement';

	public static function init(): void {
		add_action( 'wp_footer', array( __CLASS__, 'maybe_render_footer_link' ) );
	}

	/**
	 * Create or update the statement page from the stored model. Idempotent.
	 *
	 * @param array<string, mixed> $data Sanitized statement model.
	 * @return int Page ID (0 on failure).
	 */
	public static function publish( array $data ): int {
		$content = '<!-- wp:shortcode -->[tsffe_statement]<!-- /wp:shortcode -->';

		$existing = (int) get_option( self::OPTION_PAGE_ID, 0 );

		if ( ! $existing ) {
			// Uninstalling deletes the option but keeps the published page, so after a
			// reinstall we must adopt that page instead of publishing a duplicate.
			$found = get_page_by_path( self::PAGE_SLUG, OBJECT, 'page' );
			if ( $found instanceof WP_Post && 'trash' !== $found->post_status ) {
				$existing = (int) $found->ID;
			}
		}

		$postarr = array(
			'post_title'   => __( 'Accessibility Statement', 'tendforge-statement-forge-for-eaa' ),
			'post_name'    => self::PAGE_SLUG,
			'post_content' => $content,
			'post_status'  => 'publish',
			'post_type'    => 'page',
		);

		if ( $existing && 'page' === get_post_type( $existing ) && 'trash' !== get_post_status( $existing ) ) {
			$postarr['ID'] = $existing;
			$page_id       = wp_update_post( $postarr, true );
		} else {
			$page_id = wp_insert_post( $postarr, true );
		}

		if ( is_wp_error( $page_id ) || ! $page_id ) {
			return 0;
		}

		update_option( self::OPTION_PAGE_ID, (int) $page_id );

		/**
		 * Fires after the accessibility statement page has been published/updated.
		 * Add-ons (e.g. the Pro companion) can use this to snapshot the statement
		 * into a version history or trigger other side effects.
		 *
		 * @param int                  $page_id The published page ID.
		 * @param array<string, mixed> $data    The sanitized statement model.
		 */
		do_action( 'tsffe_statement_published', (int) $page_id, $data );

		return (int) $page_id;
	}

	public static function get_page_id(): int {
		return (int) get_option( self::OPTION_PAGE_ID, 0 );
	}

	public static function maybe_render_footer_link(): void {
		if ( ! get_option( self::OPTION_FOOTER_LINK, false ) ) {
			return;
		}

		$page_id = self::get_page_id();
		if ( ! $page_id ) {
			return;
		}

		$url = get_permalink( $page_id );
		if ( ! $url ) {
			return;
		}

		printf(
			'<div class="tsffe-footer-link" style="text-align:center;padding:1em 0;"><a href="%1$s">%2$s</a></div>',
			esc_url( $url ),
			esc_html__( 'Accessibility Statement', 'tendforge-statement-forge-for-eaa' )
		);
	}
}
