<?php

/* @var Tangibledesign\MyHome\Widgets\BlogPost\BlogPostFeaturedImageWidget $mhCurrentWidget */
global $mhCurrentWidget;

if (!$mhCurrentWidget) {
    return;
}

$mhBlogPost = $mhCurrentWidget->getBlogPost();
if (!$mhBlogPost) {
    return;
}

$mhImageSize = $mhCurrentWidget->getImageSizeSetting();
$mhImage = $mhBlogPost->getImage();
$mhImageUrl = '';
$mhImageAlt = '';

if ($mhImage) {
    $mhImageUrl = $mhImage->getImageUrl($mhImageSize);
    $mhImageAlt = $mhImage->getAlt();
}

if (empty($mhImageUrl)) {
    $mhFallback = $mhCurrentWidget->getFallbackImage();
    if (!empty($mhFallback['id'])) {
        $mhFallbackId = (int)$mhFallback['id'];
        $mhImageUrl = wp_get_attachment_image_url($mhFallbackId, $mhImageSize) ?: wp_get_attachment_image_url($mhFallbackId, 'full');
        $mhImageAlt = get_post_meta($mhFallbackId, '_wp_attachment_image_alt', true);
    } elseif (!empty($mhFallback['url'])) {
        $mhImageUrl = $mhFallback['url'];
    }
}

if (empty($mhImageUrl)) {
    return;
}

if (empty($mhImageAlt)) {
    $mhImageAlt = $mhBlogPost->getName();
}

?>
<figure class="myhome-blog-featured-image-widget">
    <div class="myhome-blog-featured-image-widget__image">
        <img
            src="<?php echo esc_url($mhImageUrl); ?>"
            alt="<?php echo esc_attr($mhImageAlt); ?>"
            loading="lazy"
        />
    </div>
</figure>
