<?php

namespace ThimPress\ThimBlocks\Gutenberg\Blocks\Breadcrumb;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

use ThimPress\ThimBlocks\Gutenberg\Blocks\AbstractBlockType;
use ThimPress\ThimBlocks\Gutenberg\Utils\StyleAttributes;
use Throwable;

/**
 * Class BreadcrumbBlockType
 *
 * Handle register, render block template
 */
class BreadcrumbBlockType extends AbstractBlockType {

	public $block_name = 'breadcrumb';

	public function get_supports(): array {
		return array(
			'align'      => array( 'wide', 'full' ),
			'color'      => array(
				'gradients'  => true,
				'background' => true,
				'text'       => true,
			),
			'typography' => array(
				'fontSize'                    => true,
				'__experimentalFontWeight'    => true,
				'__experimentalTextTransform' => true,
			),
			'spacing'    => array(
				'padding' => true,
				'margin'  => true,
			),
		);
	}

	/**
	 * Render content of block tag
	 *
	 * @param array $attributes | Attributes of block tag.
	 *
	 * @return false|string
	 */
	public function render_content_block_template( array $attributes, $content, $block ): string {
		$html = '';

		try {
			$iconDelimiter = $attributes['iconDelimiter'] ?? array();
			$style_vars    = array();

			$devices = array( 'desktop', 'tablet', 'mobile' );

			if ( ! empty( $iconDelimiter['color'] ) ) {
				$style_vars['--tb-delimiter-color'] = $iconDelimiter['color'];
			}

			foreach ( $devices as $device ) {
				if ( ! empty( $iconDelimiter['fontSize'][ $device ] ) ) {
					$style_vars[ "--tb-delimiter-font-size-$device" ] =
						$iconDelimiter['fontSize'][ $device ];
				}
			}

			$fmt_padding = function ( $p ) {
				return sprintf(
					'%s %s %s %s',
					isset( $p['top'] ) ? $p['top'] . 'px' : '0',
					isset( $p['right'] ) ? $p['right'] . 'px' : '0',
					isset( $p['bottom'] ) ? $p['bottom'] . 'px' : '0',
					isset( $p['left'] ) ? $p['left'] . 'px' : '0'
				);
			};

			foreach ( $devices as $device ) {
				if ( ! empty( $iconDelimiter['padding'][ $device ] ) ) {
					$style_vars[ "--tb-delimiter-padding-$device" ] =
						$fmt_padding( $iconDelimiter['padding'][ $device ] );
				}
			}

			$inline_style = '';
			foreach ( $style_vars as $key => $val ) {
				$inline_style .= "$key:$val;";
			}

			$separator   = '<span class="breadcrumb-delimiter"><i class="tb-icon-angle-right"></i></span>';
			$breadcrumbs = array();

			$breadcrumbs[] = '<a href="' . esc_url( home_url( '/' ) ) . '">' . esc_html__( 'Home', 'thim-blocks' ) . '</a>';

			if ( is_home() && ! is_front_page() ) {
				// Blog page
				$posts_page_id = get_option( 'page_for_posts' );
				if ( $posts_page_id ) {
					$breadcrumbs[] = '<span>' . get_the_title( $posts_page_id ) . '</span>';
				}
			} elseif ( is_category() || is_tag() || is_tax() ) {
				// Category, tag, or taxonomy archive
				$breadcrumbs[] = '<span>' . single_term_title( '', false ) . '</span>';
			} elseif ( is_singular( 'post' ) ) {
				// Single post
				$category = get_the_category();
				if ( ! empty( $category ) ) {
					$breadcrumbs[] = '<a href="' . esc_url( get_category_link( $category[0]->term_id ) ) . '">' . esc_html( $category[0]->name ) . '</a>';
				}
				$breadcrumbs[] = '<span>' . get_the_title() . '</span>';
			} elseif ( is_page() && ! is_front_page() ) {
				// Static page
				global $post;
				if ( $post->post_parent ) {
					$parent_id        = $post->post_parent;
					$breadcrumbs_temp = array();
					while ( $parent_id ) {
						$page               = get_page( $parent_id );
						$breadcrumbs_temp[] = '<a href="' . get_permalink( $page->ID ) . '">' . get_the_title( $page->ID ) . '</a>';
						$parent_id          = $page->post_parent;
					}
					$breadcrumbs = array_merge( $breadcrumbs, array_reverse( $breadcrumbs_temp ) );
				}
				$breadcrumbs[] = '<span>' . get_the_title() . '</span>';
			} elseif ( is_search() ) {
				// Search results
				$breadcrumbs[] = '<span>' . esc_html__( 'Search results for:', 'thim-blocks' ) . ' "' . get_search_query() . '"</span>';
			} elseif ( is_404() ) {
				// 404 page
				$breadcrumbs[] = '<span>' . esc_html__( 'Page not found', 'thim-blocks' ) . '</span>';
			} elseif ( is_archive() ) {
				// Archive page
				$breadcrumbs[] = '<span>' . post_type_archive_title( '', false ) . '</span>';
			}
			ob_start();
			$wrapper_attrs = get_block_wrapper_attributes(
				array(
					'class' => 'thim-blocks-breadcrumb',
					'style' => $inline_style ? esc_attr( $inline_style ) : '',
				)
			);
			printf(
				'<div %s>%s</div>',
				wp_kses_post( $wrapper_attrs ),
				wp_kses_post( implode( $separator, $breadcrumbs ) )
			);
			$html = ob_get_clean();
		} catch ( Throwable $e ) {
			return $html;
		}

		return $html;
	}

}
