<?php
/**
 * Template part for displaying post footer in attachment.php
 *
 * @package errigal
 * @since 1.0.0
 */

defined( 'ABSPATH' ) || exit;

use Errigal\Constant\{
	Errigal_Accessibility_Class as Accessibility_Class,
	Errigal_Html_Attr as Html_Attr,
	Errigal_Html_Option as Html_Option,
};
use Errigal\Content\Errigal_Content as Content;
use Errigal\Shared\{
	Errigal_Html_Builder as Html_Builder,
	Errigal_Validator as Validator,
};

Html_Builder::create()->create_footer(
	array(
		Html_Option::ATTRS => array(
			Html_Attr::CLASS_NAME => 'attachment-metadata',
		),
	)
)->render_element(
	function ( $html_builder ) {
		if ( ! Html_Builder::is_html_builder( $html_builder ) ) {
			return;
		}

		$post_parent_id = Content::get_post_parent_id();

		if ( Validator::is_positive_int( $post_parent_id ) ) {
			$html_builder->create_div(
				array(
					Html_Option::ATTRS => array(
						Html_Attr::CLASS_NAME => 'published-in',
					),
				)
			)->render_element(
				function ( $html_builder ) use ( $post_parent_id ) {
					if ( ! Html_Builder::is_html_builder( $html_builder ) ) {
						return;
					}

					printf(
						/* translators: %s: Parent post. */
						esc_html__( 'Published in %s', 'errigal' ),
						wp_kses_post(
							$html_builder->create_a(
								array(
									Html_Option::ATTRS => array(
										Html_Attr::HREF => get_the_permalink( $post_parent_id ),
									),
								)
							)->get_element(
								esc_html( get_the_title( $post_parent_id ) )
							)
						)
					);
				}
			);
		}

		$metadata = wp_get_attachment_metadata();
		$url      = wp_get_attachment_url();

		if (
			Validator::has_array_key( $metadata, Content::ATTACHMENT_WIDTH ) &&
			Validator::has_array_key( $metadata, Content::ATTACHMENT_HEIGHT ) &&
			Validator::is_non_empty_string( $url )
		) {
			$html_builder->create_div(
				array(
					Html_Option::ATTRS => array(
						Html_Attr::CLASS_NAME => 'full-size-link',
					),
				)
			)->render_element(
				function ( $html_builder ) use ( $metadata, $url ) {
					if ( ! Html_Builder::is_html_builder( $html_builder ) ) {
						return;
					}

					$html_builder->create_span(
						array(
							Html_Option::ATTRS => array(
								Html_Attr::CLASS_NAME => Accessibility_Class::SCREEN_READER_TEXT,
							),
						)
					)->render_element(
						esc_html__( 'Full size', 'errigal' )
					);
					$html_builder->create_a(
						array(
							Html_Option::ATTRS => array(
								Html_Attr::HREF => $url,
							),
						)
					)->render_element(
						esc_html(
							sprintf(
								'%s &times; %s',
								absint( $metadata[ Content::ATTACHMENT_WIDTH ] ),
								absint( $metadata[ Content::ATTACHMENT_HEIGHT ] )
							)
						)
					);
				}
			);
		}
	}
);
