<?php
/**
 * Site Logo Block
 *
 * @package StrategyBlocks
 *
 * @param array $attributes The block's attributes.
 * @param string $content Not used.
 * @param WP_Block $block The block instance.
 */

use StrategyBlocks\Utility;

$id = ! empty( $attributes['anchor'] ) ? $attributes['anchor'] : '';
$class_name = 'lg-block lg-block__site-logo';
$class_name .= Utility\get_block_style_classes( $attributes );
$class_name .= Utility\get_native_wp_classes( $attributes );
$class_name .= Utility\get_visibility_classes( $attributes );
$animations = Utility\get_animation_data( $attributes );

$link = $attributes['link'] ?? true;
$use_alternate = $attributes['useAlternate'] ?? false;
$placeholder_dims = $attributes['placeholderDimensions'] ?? [];

$logo = get_theme_mod( 'custom_logo' );
$design_settings = get_field( 'design_settings', 'options' );

if ( $use_alternate && isset( $design_settings['alternate_logo'] ) ) {
	$logo = $design_settings['alternate_logo'];
}

global $images_loaded;
global $eager_images;

do_action( 'lg_block_site_logo_before' );
?>

	<div <?php echo $id ? 'id="' . esc_attr( $id ) . '"' : ''; ?>
		class="<?php echo esc_attr( $class_name ); ?>"
		<?php echo ! empty( $animations ) ? 'data-animation="' . esc_attr( $animations ) . '"' : ''; ?>>
		<?php if ( $link ) : ?>
		<a href="<?php echo esc_url( home_url() ); ?>" class="site-logo__link">
			<?php
			endif;

		if ( $logo ) {
			if ( 'image/svg+xml' === get_post_mime_type( $logo ) ) {
				$svg_url = wp_get_attachment_url( $logo );
				$svg = Utility\get_svg_by_url_and_format_svg( $svg_url, 'site-logo__img', null, null, 'informational', null, $logo );
				Utility\sanitize_and_output_svg( $svg, true, 'informational' );
			} else {
				$images_loaded++;
				echo wp_get_attachment_image(
					$logo,
					'full',
					false,
					[
						'class'   => 'site-logo__img',
						'loading' => $images_loaded <= $eager_images ? 'eager' : 'lazy',
					]
				);
			}
		} elseif (
				! empty( $placeholder_dims['width'] )
				&& ! empty( $placeholder_dims['height'] )
			) {
			$images_loaded++;
			$placeholder = esc_url( 'https://placehold.co/' . $placeholder_dims['width'] . 'x' . $placeholder_dims['height'] );
			echo '<img class="site-logo__img" src="' . esc_url( $placeholder ) . '" alt="Placeholder - Please Replace Me" title="Placeholder - Please Replace Me" loading="' . ( $images_loaded <= $eager_images ? 'eager' : 'lazy' ) . '" />';
		} else {
			bloginfo( 'name' );
		}

		if ( $link ) :
			?>
			</a>
			<?php
	endif;
		?>
	</div>

<?php do_action( 'lg_block_site_logo_after' ); ?>
