<?php

defined('ABSPATH') || exit;

global $ulz_listing;

// Ensure $ulz_listing is properly initialized
if (!isset($ulz_listing) || !is_object($ulz_listing)) {
    return;
}

$gallery = $ulz_listing->get_gallery('ulz_gallery_large');
$video = Ucore()->get('ulz_video');

// Get watermark image
$watermark_img = get_option('ulz_watermark_img');
$watermark_img = stripslashes($watermark_img);
$decoded_data = json_decode($watermark_img, true);
$watermark_path = isset($decoded_data[0]['id']) ? wp_get_attachment_url($decoded_data[0]['id']) : '';

?>

<?php if ($gallery || $video): ?>

<div class="ulz-cover ulz-cover-gallery">

    <?php Utheme()->the_template('single/cover/top'); ?>

    <div class="ulz--asset">

        <?php if ($video): ?>
            <?php
            $video = Ucore()->get_first_array_upload(Ucore()->jsoning('ulz_video'));

            // Use image URL directly for poster
            $video_poster = isset($gallery[0]) ? esc_url($gallery[0]) : '';
            ?>

            <?php if (!empty($video) && isset($gallery[0])): ?>
                <img src="<?php echo esc_url($gallery[0]); ?>" 
                     alt="<?php echo esc_attr(sanitize_title($ulz_listing->post->post_title)); ?>" 
                     data-replace="image">
            <?php endif; ?>

            <video class="ulz--video" controls="controls" controlsList="nodownload" data-observed="true"
                   poster="<?php echo $video_poster; ?>">
                <source src="<?php echo esc_url(wp_get_attachment_url($video)); ?>" type="video/mp4">
            </video>

            <?php if (!empty($watermark_path)): ?>
                <img class="ulz--watermark" src="<?php echo esc_url($watermark_path); ?>" alt="Watermark"
                     style="opacity: 0.5; width:150px; position: absolute; top: 45%; left: 50%; 
                            transform: translate(-50%, -50%); pointer-events: none;">
            <?php endif; ?>

        <?php else: ?>

            <!-- Image Section -->
            <?php foreach ($gallery as $key => $image): ?>
                <?php if ($key >= 1) break; ?>

                <div class="ulz--image">
                    <img src="<?php echo esc_url($image); ?>"
                         alt="<?php echo esc_attr(sanitize_title($ulz_listing->post->post_title)); ?>" 
                         data-replace="image">

                    <?php if (!empty($watermark_path)): ?>
                        <img class="ulz--watermark" src="<?php echo esc_url($watermark_path); ?>" alt="Watermark"
                             style="opacity: 0.5; width:150px; position: absolute; top: 45%; left: 50%;
                                    transform: translate(-50%, -50%); pointer-events: none;">
                    <?php endif; ?>
                </div>

            <?php endforeach; ?>

        <?php endif; ?>

    </div>

</div> <!-- ulz-cover -->

<?php endif; ?>