<?php
/**
 * Maintenance page renderer.
 *
 * @package MacaHold
 */

defined( 'ABSPATH' ) || exit;

/**
 * Renders maintenance templates.
 */
class Maca_Hold_Template_Renderer {

	/**
	 * Output maintenance page and stop execution.
	 *
	 * @param array<string, mixed> $settings Plugin settings.
	 * @return void
	 */
	public function render( array $settings ) {
		$retry_after = max( 0, absint( $settings['retry_after'] ) );

		status_header( 503 );
		if ( $retry_after > 0 ) {
			header( 'Retry-After: ' . $retry_after );
		}

		/**
		 * Fires before the maintenance page is rendered.
		 *
		 * @param array<string, mixed> $settings Plugin settings.
		 */
		do_action( 'maca_hold_before_render', $settings );

		$maca_hold_settings           = $settings;
		$maca_hold_template           = $this->get_template_path( $settings['template'] ?? 'maintenance' );
		$maca_hold_countdown_target   = $this->get_countdown_target( $settings );
		$maca_hold_logo_url           = $settings['logo_url'] ?? '';
		$maca_hold_logo_alt           = $settings['logo_alt'] ?? '';
		$maca_hold_title              = $settings['title'] ?? '';
		$maca_hold_subtitle           = $settings['subtitle'] ?? '';
		$maca_hold_message            = $settings['message'] ?? '';
		$maca_hold_footer_text        = $settings['footer_text'] ?? '';
		$maca_hold_background_slug    = $settings['background_image'] ?? '';
		$maca_hold_background_image_url = Maca_Hold_Backgrounds::get_url( $maca_hold_background_slug );
		$maca_hold_has_bg_image       = '' !== $maca_hold_background_image_url;
		$maca_hold_links              = Maca_Hold_Settings::sanitize_links( $settings['links'] ?? array() );
		$maca_hold_badge_text         = Maca_Hold_Settings::get_badge_text( $settings, $maca_hold_has_bg_image );
		$maca_hold_countdown_label    = Maca_Hold_Settings::get_countdown_label( $settings );
		$maca_hold_show_login_link    = ! empty( $settings['show_login_link'] );
		$maca_hold_login_link_label   = $settings['login_link_label'] ?? '';
		$maca_hold_contrast_profile   = $maca_hold_has_bg_image ? Maca_Hold_Backgrounds::get_contrast_profile( $maca_hold_background_slug ) : null;
		$maca_hold_template_slug      = $settings['template'] ?? 'maintenance';
		$maca_hold_inline_styles      = $this->get_inline_styles( $settings, $maca_hold_contrast_profile );
		$maca_hold_body_class         = $this->get_body_class( $settings, $settings['template'] ?? 'maintenance', $maca_hold_contrast_profile );

		$this->enqueue_assets( $maca_hold_has_bg_image, null !== $maca_hold_countdown_target );

		include $maca_hold_template;
		exit;
	}

	/**
	 * Register and enqueue maintenance page assets.
	 *
	 * @param bool $has_bg_image      Whether a background image is active.
	 * @param bool $has_countdown     Whether the countdown script is needed.
	 * @return void
	 */
	private function enqueue_assets( $has_bg_image, $has_countdown ) {
		wp_register_style(
			'maca-hold-maintenance',
			MACA_HOLD_URL . 'assets/css/maintenance.css',
			array(),
			MACA_HOLD_VERSION
		);
		wp_enqueue_style( 'maca-hold-maintenance' );

		wp_register_script(
			'maca-hold-strings',
			MACA_HOLD_URL . 'assets/js/strings.js',
			array(),
			MACA_HOLD_VERSION,
			false
		);
		wp_enqueue_script( 'maca-hold-strings' );
		wp_add_inline_script(
			'maca-hold-strings',
			'window.macaHoldStrings = ' . wp_json_encode( Maca_Hold_I18n::get_script_strings() ) . ';',
			'before'
		);

		if ( $has_bg_image ) {
			wp_register_script(
				'maca-hold-maintenance',
				MACA_HOLD_URL . 'assets/js/maintenance.js',
				array(),
				MACA_HOLD_VERSION,
				false
			);
			wp_enqueue_script( 'maca-hold-maintenance' );
			wp_script_add_data( 'maca-hold-maintenance', 'strategy', 'defer' );
		}

		if ( $has_countdown ) {
			wp_register_script(
				'maca-hold-countdown',
				MACA_HOLD_URL . 'assets/js/countdown.js',
				array( 'maca-hold-strings' ),
				MACA_HOLD_VERSION,
				true
			);
			wp_enqueue_script( 'maca-hold-countdown' );
		}
	}

	/**
	 * Resolve template file path.
	 *
	 * @param string $template Template slug.
	 * @return string
	 */
	private function get_template_path( $template ) {
		$template = sanitize_key( $template );
		$path     = MACA_HOLD_PATH . 'public/templates/' . $template . '.php';

		/**
		 * Filter the maintenance template path.
		 *
		 * @param string $path     Template file path.
		 * @param string $template Template slug.
		 */
		$path = apply_filters( 'maca_hold_template_path', $path, $template );

		if ( ! file_exists( $path ) ) {
			$path = MACA_HOLD_PATH . 'public/templates/maintenance.php';
		}

		return $path;
	}

	/**
	 * Build inline CSS variables for templates.
	 *
	 * @param array<string, mixed>      $settings Plugin settings.
	 * @param array<string, mixed>|null $contrast_profile Contrast settings for background images.
	 * @return string
	 */
	public function get_inline_styles( array $settings, $contrast_profile = null ) {
		$background = $settings['background_color'] ?? '#1e1e2e';
		$text       = $settings['text_color'] ?? '#f5f5f5';
		$accent     = $settings['accent_color'] ?? '#7c9cbf';
		$bg_image   = Maca_Hold_Backgrounds::get_url( $settings['background_image'] ?? '' );

		if ( is_array( $contrast_profile ) ) {
			$text   = $contrast_profile['text'] ?? $text;
			$accent = $contrast_profile['accent'] ?? $accent;
		}

		$styles = sprintf(
			'--maca-hold-bg:%1$s;--maca-hold-text:%2$s;--maca-hold-accent:%3$s;',
			esc_attr( $background ),
			esc_attr( $text ),
			esc_attr( $accent )
		);

		if ( '' !== $bg_image ) {
			$styles .= sprintf(
				"--maca-hold-bg-image:url('%s');",
				esc_url( $bg_image )
			);
		}

		return $styles;
	}

	/**
	 * Build body classes for maintenance templates.
	 *
	 * @param array<string, mixed>      $settings Plugin settings.
	 * @param string                    $template Template slug.
	 * @param array<string, mixed>|null $contrast_profile Contrast settings for background images.
	 * @return string
	 */
	public function get_body_class( array $settings, $template, $contrast_profile = null ) {
		$classes = array(
			'maca-hold-template',
			'maca-hold-template-' . sanitize_key( $template ),
		);

		if ( '' !== Maca_Hold_Backgrounds::get_url( $settings['background_image'] ?? '' ) ) {
			$classes[] = 'maca-hold-has-bg-image';

			if ( is_array( $contrast_profile ) && ! empty( $contrast_profile['class'] ) ) {
				$classes[] = $contrast_profile['class'];
			}
		}

		return implode( ' ', $classes );
	}

	/**
	 * Get countdown target timestamp for the active schedule.
	 *
	 * @param array<string, mixed> $settings Plugin settings.
	 * @return int|null
	 */
	private function get_countdown_target( array $settings ) {
		if ( empty( $settings['show_countdown'] ) || empty( $settings['schedule_end'] ) ) {
			return null;
		}

		return Maca_Hold_Scheduler::parse_datetime( $settings['schedule_end'] );
	}
}
