<?php
/**
 * Site-wide "under construction" gate for visitors (not logged in).
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Frontend;

final class ConstructionMode {

	public const OPTION         = 'aptb_construction';
	public const OPTION_TITLE   = 'aptb_construction_title';
	public const OPTION_MESSAGE = 'aptb_construction_message';
	/** Legacy option keys (pre-1.0.2). */
	public const OPTION_LEGACY         = 'aura_builder_construction';
	public const OPTION_TITLE_LEGACY   = 'aura_builder_construction_title';
	public const OPTION_MESSAGE_LEGACY = 'aura_builder_construction_message';

	public function hooks(): void {
		add_action( 'template_redirect', array( $this, 'maybe_show' ), 0 );
	}

	public static function is_enabled(): bool {
		$v = get_option( self::OPTION, null );
		if ( $v === null ) {
			$v = get_option( self::OPTION_LEGACY, '0' );
		}
		return $v === '1';
	}

	public static function set_enabled( bool $on ): void {
		update_option( self::OPTION, $on ? '1' : '0', true );
	}

	/**
	 * @param mixed $default Default.
	 */
	private static function option( string $key, string $legacy, $default = '' ) {
		$v = get_option( $key, null );
		if ( $v === null || $v === false ) {
			return get_option( $legacy, $default );
		}
		return $v;
	}

	public function maybe_show(): void {
		if ( ! self::is_enabled() ) {
			return;
		}

		// Logged-in users see the real site (editors/admins working on redesign).
		if ( is_user_logged_in() ) {
			return;
		}

		// Never block login, admin, cron, REST auth flows, or feeds for tools.
		if ( is_admin() || wp_doing_ajax() || wp_doing_cron() ) {
			return;
		}

		// Allow login / lost password / REST login-related.
		global $pagenow;
		if ( isset( $pagenow ) && in_array( $pagenow, array( 'wp-login.php', 'wp-register.php' ), true ) ) {
			return;
		}

		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized next line.
		$request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( (string) $_SERVER['REQUEST_URI'] ) ) : '';
		if ( preg_match( '#/(wp-login|wp-admin|wp-cron|xmlrpc)\.php#', $request_uri ) ) {
			return;
		}

		// Optional: allow preview with secret query for share (disabled by default).
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! empty( $_GET['ab_preview'] ) && current_user_can( 'edit_posts' ) ) {
			return;
		}

		$this->render_page();
		exit;
	}

	private function render_page(): void {
		nocache_headers();
		status_header( 503 );
		header( 'Retry-After: 3600' );

		$site_name = get_bloginfo( 'name' ) ?: 'Nosso site';
		$title     = (string) self::option( self::OPTION_TITLE, self::OPTION_TITLE_LEGACY, '' );
		$message   = (string) self::option( self::OPTION_MESSAGE, self::OPTION_MESSAGE_LEGACY, '' );

		if ( $title === '' ) {
			$title = 'Estamos em construção';
		}
		if ( $message === '' ) {
			$message = 'Estamos desenvolvendo um novo design para o site. Em breve você poderá conferir uma experiência renovada, mais moderna e pensada para você.';
		}

		$logo_html = '';
		if ( function_exists( 'has_custom_logo' ) && has_custom_logo() ) {
			$logo_id = (int) get_theme_mod( 'custom_logo' );
			if ( $logo_id ) {
				$src = wp_get_attachment_image_url( $logo_id, 'medium' );
				if ( $src ) {
					$logo_html = '<img class="ab-cc-logo" src="' . esc_url( $src ) . '" alt="' . esc_attr( $site_name ) . '" width="96" height="96"/>';
				}
			}
		}
		if ( $logo_html === '' && defined( 'AURA_BUILDER_LOGO_URL' ) ) {
			$logo_html = '<img class="ab-cc-logo" src="' . esc_url( AURA_BUILDER_LOGO_URL ) . '" alt="' . esc_attr( $site_name ) . '" width="96" height="96"/>';
		}

		$login_url = wp_login_url( home_url( '/' ) );

		// Plugin CSS file (no arbitrary CSS) — print via WP style API.
		$css_file = AURA_BUILDER_PATH . 'frontend/css/construction.css';
		$css_ver  = is_file( $css_file ) ? (string) filemtime( $css_file ) : AURA_BUILDER_VERSION;
		wp_register_style(
			'aptb-construction',
			AURA_BUILDER_URL . 'frontend/css/construction.css',
			array(),
			$css_ver
		);
		wp_enqueue_style( 'aptb-construction' );

		?><!DOCTYPE html>
<html lang="<?php echo esc_attr( get_bloginfo( 'language' ) ?: 'pt-BR' ); ?>">
<head>
	<meta charset="<?php echo esc_attr( get_bloginfo( 'charset' ) ?: 'UTF-8' ); ?>"/>
	<meta name="viewport" content="width=device-width, initial-scale=1"/>
	<meta name="robots" content="noindex,nofollow"/>
	<title><?php echo esc_html( $title . ' · ' . $site_name ); ?></title>
	<?php
	// Print only our registered style (standalone 503 page — no full wp_head).
	wp_print_styles( array( 'aptb-construction' ) );
	?>
</head>
<body>
	<main class="ab-cc" role="main">
		<?php echo $logo_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- built with esc_url/esc_attr above. ?>
		<div class="ab-cc-badge"><i></i> <?php echo esc_html__( 'Em desenvolvimento', 'auranet-page-theme-builder' ); ?></div>
		<h1><?php echo esc_html( $title ); ?></h1>
		<p class="ab-cc-site"><?php echo esc_html( $site_name ); ?></p>
		<p class="ab-cc-msg"><?php echo esc_html( $message ); ?></p>
		<div class="ab-cc-bar" aria-hidden="true"><span></span></div>
		<a class="ab-cc-login" href="<?php echo esc_url( $login_url ); ?>"><?php echo esc_html__( 'Acesso da equipe', 'auranet-page-theme-builder' ); ?></a>
		<p class="ab-cc-foot"><?php echo esc_html__( 'Obrigado pela compreensão · Auranet Builder', 'auranet-page-theme-builder' ); ?></p>
	</main>
</body>
</html>
		<?php
	}
}
