<?php

declare( strict_types=1 );

namespace Org\Wplake\Advanced_Views\Post_Selections;

use Org\Wplake\Advanced_Views\Assets\Front_Assets;
use Org\Wplake\Advanced_Views\Front_Asset\Html_Wrapper;
use Org\Wplake\Advanced_Views\Groups\Post_Selection_Settings;
use Org\Wplake\Advanced_Views\Groups\Post_Selection_Layout_Settings;
use Org\Wplake\Advanced_Views\Plugin\Cpt\Pub\Public_Cpt;
use Org\Wplake\Advanced_Views\Template_Engines\Template_Engines;
use Org\Wplake\Advanced_Views\Template_Engines\Template_Generator;

defined( 'ABSPATH' ) || exit;

class Post_Selection_Markup {
	private Front_Assets $front_assets;
	private Template_Engines $template_engines;
	private Public_Cpt $public_cpt;

	public function __construct( Front_Assets $front_assets, Template_Engines $template_engines, Public_Cpt $public_cpt ) {
		$this->front_assets     = $front_assets;
		$this->template_engines = $template_engines;
		$this->public_cpt       = $public_cpt;
	}

	protected function get_template_engines(): Template_Engines {
		return $this->template_engines;
	}

	protected function print_extra_markup( Post_Selection_Settings $post_selection_settings ): void {
		if ( Post_Selection_Settings::ITEMS_SOURCE_CONTEXT_POSTS !== $post_selection_settings->items_source ) {
			return;
		}

		$template_generator = $this->template_engines->get_template_generator( $post_selection_settings->template_engine );

		echo "\r\n\t";

		// 1 < pages_amount
		$template_generator->print_if_for_array_item( '_card', 'pages_amount', '<', 1 );

		echo "\r\n";
		echo "\t\t<div>\r\n";
		echo "\t\t\t";
		$template_generator->print_function_paginate_links();
		echo "\n";
		echo "\t\t" . '</div>' . "\r\n";
		echo "\t";

		$template_generator->print_end_if();

		echo "\r\n";
	}

	protected function print_items_opening_wrapper(
		Post_Selection_Settings $post_selection_settings,
		int &$tabs_number,
		string $class_name = ''
	): void {
		$classes  = '';
		$external = $this->front_assets->get_card_items_wrapper_class( $post_selection_settings );

		if ( Post_Selection_Settings::CLASS_GENERATION_NONE !== $post_selection_settings->classes_generation ) {
			$classes .= $post_selection_settings->get_bem_name() . '__items';
			$classes .= '' !== $class_name ?
				' ' . $class_name :
				'';
		}

		// we never skip the external, e.g. 'splide' as it's a library requirement.
		if ( '' !== $external ) {
			$classes .= '' === $classes ?
				$external :
				' ' . $external;
		}

		echo esc_html( str_repeat( "\t", ++$tabs_number ) );
		printf( '<div class="%s">', esc_html( $classes ) );
		echo "\r\n";
	}

	/**
	 * @param Html_Wrapper[] $item_outers
	 */
	protected function print_opening_item_outers(
		array $item_outers,
		int &$tabs_number,
		Template_Generator $template_generator
	): void {
		foreach ( $item_outers as $outer ) {
			echo esc_html( str_repeat( "\t", ++$tabs_number ) );
			printf( '<%s', esc_html( $outer->tag ) );

			foreach ( $outer->attrs as $attr => $value ) {
				printf( ' %s="%s"', esc_html( $attr ), esc_html( $value ) );
			}

			foreach ( $outer->variable_attrs as $attr => $variable_info ) {
				$template_generator->print_array_item_attribute(
					$attr,
					$variable_info['field_id'],
					$variable_info['item_key']
				);
			}

			echo '>';
			echo "\r\n";
		}
	}

	protected function print_items_closing_wrapper( Post_Selection_Settings $post_selection_settings, int &$tabs_number ): void {
		echo esc_html( str_repeat( "\t", --$tabs_number ) ) . '</div>' . "\r\n";
	}

	/**
	 * @param Html_Wrapper[] $item_outers
	 */
	protected function print_closing_item_outers( array $item_outers, int &$tabs_number ): void {
		foreach ( $item_outers as $outer ) {
			echo esc_html( str_repeat( "\t", --$tabs_number ) );
			printf( '</%s>', esc_html( $outer->tag ) );
			echo "\r\n";
		}
	}

	protected function print_shortcode( Post_Selection_Settings $post_selection_settings ): void {
		$template_generator = $this->template_engines->get_template_generator( $post_selection_settings->template_engine );

		printf( '[%s', esc_html( $this->public_cpt->shortcode() ) );
		$template_generator->print_array_item_attribute( 'id', '_card', 'view_id' );
		$template_generator->print_field_attribute( 'object-id', 'post_id' );

		$asset_attrs = $this->front_assets->get_card_shortcode_attrs( $post_selection_settings );

		foreach ( $asset_attrs as $attr => $value ) {
			printf( ' %s="%s"', esc_html( $attr ), esc_html( $value ) );
		}

		echo ']';
		echo "\r\n";
	}

	public function print_markup(
		Post_Selection_Settings $post_selection_settings,
		bool $is_load_more = false,
		bool $is_ignore_custom_markup = false
	): void {
		if ( false === $is_ignore_custom_markup &&
			'' !== $post_selection_settings->custom_markup &&
			false === $is_load_more ) {
			$custom_markup = trim( $post_selection_settings->custom_markup );

			if ( '' !== $custom_markup ) {
				// @phpcs:ignore WordPress.Security.EscapeOutput
				echo $custom_markup;
				return;
			}
		}

		$template_generator = $this->template_engines->get_template_generator( $post_selection_settings->template_engine );

		ob_start();

		$tabs_number = 1;
		$item_outers = false === $is_load_more ?
			$this->front_assets->get_card_item_outers( $post_selection_settings ) :
			array();

		if ( false === $is_load_more ) {
			printf( '<%s class="', esc_html( $post_selection_settings->get_tag_name() ) );
			$template_generator->print_array_item( '_card', 'classes' );
			echo esc_html( $post_selection_settings->get_bem_name() );
			if ( 'acf-card' === $post_selection_settings->get_bem_name() ) {
				echo ' ' . sprintf( '%s--id--', esc_html( $post_selection_settings->get_bem_name() ) );
				$template_generator->print_array_item( '_card', 'id' );
			}
			echo '">';

			if ( Post_Selection_Settings::WEB_COMPONENT_SHADOW_DOM_DECLARATIVE === $post_selection_settings->web_component ) {
				echo "\r\n";
				echo '<template shadowrootmode="open">';
			}

			echo "\r\n\r\n";
			echo esc_html( str_repeat( "\t", $tabs_number ) );
			$template_generator->print_if_for_array_item( '_card', 'post_ids' );
			echo "\r\n";
			$this->print_items_opening_wrapper( $post_selection_settings, $tabs_number );
			$this->print_opening_item_outers( $item_outers, $tabs_number, $template_generator );
		}

		echo esc_html( str_repeat( "\t", ++$tabs_number ) );
		$template_generator->print_for_of_array_item( '_card', 'post_ids', 'post_id' );
		echo "\r\n";
		echo esc_html( str_repeat( "\t", ++$tabs_number ) );
		$this->print_shortcode( $post_selection_settings );
		echo esc_html( str_repeat( "\t", --$tabs_number ) );
		$template_generator->print_end_for();
		echo "\r\n";

		if ( false === $is_load_more ) {
			$this->print_closing_item_outers( $item_outers, $tabs_number );
			$this->print_items_closing_wrapper( $post_selection_settings, $tabs_number );

			if ( '' !== $post_selection_settings->no_posts_found_message ) {
				echo esc_html( str_repeat( "\t", --$tabs_number ) );
				$template_generator->print_else();
				echo "\r\n";
				echo esc_html( str_repeat( "\t", ++$tabs_number ) );
				$no_posts_message_class = Post_Selection_Settings::CLASS_GENERATION_NONE !== $post_selection_settings->classes_generation ?
					sprintf( '%s__no-posts-message', $post_selection_settings->get_bem_name() ) :
					'';
				printf(
					'<div class="%s">',
					esc_html( $no_posts_message_class )
				);
				$template_generator->print_array_item( '_card', 'no_posts_found_message' );
				echo '</div>';
				echo "\r\n";
			}

			// endif in any case.
			echo esc_html( str_repeat( "\t", --$tabs_number ) );
			$template_generator->print_end_if();
			echo "\r\n";

			$this->print_extra_markup( $post_selection_settings );

			if ( Post_Selection_Settings::WEB_COMPONENT_SHADOW_DOM_DECLARATIVE === $post_selection_settings->web_component ) {
				echo "\r\n";
				echo '</template>';
			}

			echo "\r\n" . sprintf( '</%s>', esc_html( $post_selection_settings->get_tag_name() ) ) . "\r\n";
		}

		$markup = (string) ob_get_clean();

		// remove the empty class attribute if the generation is disabled.
		if ( Post_Selection_Settings::CLASS_GENERATION_NONE === $post_selection_settings->classes_generation ) {
			$markup = str_replace( ' class=""', '', $markup );
		}

		// @phpcs:ignore WordPress.Security.EscapeOutput
		echo $markup;
	}

	public function print_layout_css( Post_Selection_Settings $post_selection_settings ): void {
		if ( false === $post_selection_settings->is_use_layout_css ) {
			return;
		}

		$message = __(
			'Manually edit these rules by disabling Layout Rules, otherwise these rules are updated every time you press the Update button',
			'acf-views'
		);

		echo "/*BEGIN LAYOUT_RULES*/\n";
		printf( "/*%s*/\n", esc_html( $message ) );

		$safe_rules = array();

		foreach ( $post_selection_settings->layout_rules as $layout_rule ) {
			$screen = 0;
			switch ( $layout_rule->screen ) {
				case Post_Selection_Layout_Settings::SCREEN_TABLET:
					$screen = 576;
					break;
				case Post_Selection_Layout_Settings::SCREEN_DESKTOP:
					$screen = 992;
					break;
				case Post_Selection_Layout_Settings::SCREEN_LARGE_DESKTOP:
					$screen = 1400;
					break;
			}

			$safe_rule = array();

			$safe_rule[] = ' display:grid;';

			switch ( $layout_rule->layout ) {
				case Post_Selection_Layout_Settings::LAYOUT_ROW:
					$safe_rule[] = ' grid-auto-flow:column;';
					$safe_rule[] = sprintf( ' grid-column-gap:%s;', esc_html( $layout_rule->horizontal_gap ) );
					break;
				case Post_Selection_Layout_Settings::LAYOUT_COLUMN:
					// the right way is 1fr,
					// but use "1fr" because CodeMirror doesn't recognize it,
					// "1fr" should be replaced with 1fr on the output.
					$safe_rule[] = ' grid-template-columns:"1fr";';
					$safe_rule[] = sprintf( ' grid-row-gap:%s;', esc_html( $layout_rule->vertical_gap ) );
					break;
				case Post_Selection_Layout_Settings::LAYOUT_GRID:
					$safe_rule[] = sprintf( ' grid-template-columns:repeat(%s, "1fr");', esc_html( (string) $layout_rule->amount_of_columns ) );
					$safe_rule[] = sprintf( ' grid-column-gap:%s;', esc_html( $layout_rule->horizontal_gap ) );
					$safe_rule[] = sprintf( ' grid-row-gap:%s;', esc_html( $layout_rule->vertical_gap ) );
					break;
			}

			$safe_rules[ $screen ] = $safe_rule;
		}

		// order is important in media rules.
		ksort( $safe_rules );

		foreach ( $safe_rules as $screen => $safe_rule ) {
			if ( 0 !== $screen ) {
				printf( "\n@media screen and (min-width:%spx) {", esc_html( (string) $screen ) );
			}

			echo "\n#card .acf-card__items {\n";
			// @phpcs:ignore WordPress.Security.EscapeOutput
			echo join( "\n", $safe_rule );
			echo "\n}\n";

			if ( 0 !== $screen ) {
				echo "}\n";
			}
		}

		echo "\n/*END LAYOUT_RULES*/";
	}
}
