<?php
    if (isset($block['data']['isExample']) && $block['data']['isExample']) {
        echo '<img src="' . esc_url( $block['data']['preview_image'] ) . '"style="max-width:100%; min-width:100%" alt="Preview" />';
        return;
    }

    global $rdgb;
    $rdgb = (!empty($rdgb)) ? $rdgb : Rdg_Blocks::instance();

    $block_styles = [];
    $block_classes = ['rdg-latest-post'];
    $block_latest_post = $rdgb->settings->getBlock(BLOCK_RDG_LATEST_POST);

    if (!empty($block['backgroundColor'])) {
        $block_classes[] = 'has-background';
        $block_classes[] = 'has-'.$block['backgroundColor'].'-background-color';
    }

    if (!empty($block['style']['color']['background'])) {
        $block_styles[] = 'background-color: '.$block['style']['color']['background'].';';
    }

    $position_block = $rdgb->helpers->getBlocksSpaces(get_fields());
    $elements = $block_latest_post->get_elements_type(get_fields());
    $show = get_field('show');
    $titles = get_field('titles');

    $style_separator = '';
    $show_separator = (!empty(get_field('separator_show'))) ? get_field('separator_show') : null;
    $color_separator = (!empty(get_field('separator_color'))) ? get_field('separator_color') : '#CCC';
    $width_separator = (!empty(get_field('separator_width'))) ? get_field('separator_width').'px' : '1px';
    $presentation = (!empty(get_field('presentation'))) ? get_field('presentation') : 'small';
    $post_type = (!empty(get_field('post_type'))) ? get_field('post_type') : null;

    if (!empty($show_separator) && $show_separator == 'show') {
        $style_separator = '--color-separator-latest-post: '.$color_separator.'; --width-separator-latest-post: '.$width_separator.';'; 
    }
?>
<div class="rdg-blocks">
    <div class="<?php echo esc_attr(join(' ', $block_classes)); ?>" style="<?php echo $position_block . esc_attr(join(' ', $block_styles)); ?>">
        <?php require RDGBLOCKS_PLUGIN_BLOCKS_DIR.'partials/titles.php'; ?>

        <?php if (is_array($elements) && count($elements) > 0 && $post_type): ?>
            <div class="posts" style="<?php echo (!empty($show_separator)) ? $style_separator : ''; ?>">
                <?php $i = 1; ?>
                <?php foreach($elements as $element): ?>
                    <?php 
                        $description = $block_latest_post->get_description($element);
                        if (empty($description)) {
                            continue;
                        }
                        ?>
                    <div class="item<?php echo (!empty($title) && $i == 1) ? ' first-item-line' : ''; ?><?php echo ($presentation == 'small') ? ' small' : ''; ?>">
                        <div class="content">
                            <div class="title">
                                <a href="<?php echo get_permalink($element); ?>">
                                    <?php echo (!empty($element->post_title)) ? $element->post_title : $element['title']; ?>
                                </a>
                            </div>

                            
                            <?php if (!empty($description)): ?>
                                <div class="description">
                                    <?php echo wp_trim_words($description, 30, false); ?>
                                </div>
                            <?php endif; ?>

                            <div class="published">
                                <span>
                                    <?php
                                        $date = (!empty($element->post_date)) ? $element->post_date : $element['date'];
                                        
                                        // Robust date parsing with multiple formats
                                        $game_datetime = false;
                                        $date_formats = [
                                            'Y-m-d H:i:s',      // 2025-11-03 12:00:00
                                            'Y-m-d H:i',        // 2025-11-03 12:00
                                            'Y-m-d\TH:i:s',     // 2025-11-03T12:00:00 (ISO)
                                            'Y-m-d\TH:i:sP',    // 2025-11-03T12:00:00+00:00 (ISO with timezone)
                                            'Y-m-d\TH:i:s.uP',  // 2025-11-03T12:00:00.000000+00:00 (ISO with microseconds)
                                        ];
                                        
                                        foreach ($date_formats as $format) {
                                            $game_datetime = DateTime::createFromFormat($format, $date);
                                            if ($game_datetime !== false) {
                                                break;
                                            }
                                        }
                                        
                                        // If all formats fail, try strtotime as fallback
                                        if ($game_datetime === false) {
                                            $timestamp = strtotime($date);
                                            if ($timestamp !== false) {
                                                $game_datetime = new DateTime();
                                                $game_datetime->setTimestamp($timestamp);
                                            }
                                        }
                                        
                                        // Display relative time if valid
                                        if ($game_datetime !== false) {
                                            $posted = $game_datetime->format('U');
                                            echo human_time_diff($posted, current_time('U')). " ago";
                                        } else {
                                            echo 'Recently';
                                        }
                                    ?>
                                </span>
                            </div>
                        </div>

                        <?php
                            $image = '';
                            if (in_array($show, [BLOCK_RDG_LATEST_TYPE_LATEST, BLOCK_RDG_LATEST_TYPE_SPECIFIC]) ) {
                                $image = $block_latest_post->get_image($element->ID);
                            } else {
                                if (isset($element['image']['url']) && !empty($element['image']['url'])) {
                                    $image = $element['image']['url'];
                                }
                            }
                        ?>
                        <div class="image" style="background-image: url(<?php echo $image; ?>);"></div>
                    </div>
                    <?php $i++; ?>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <?php if (empty($post_type)): ?>
                <div class="message danger">
                    <span><?php echo __('You must configure the RDG Latest Post block.') ?></span>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</div>
