<?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 = [BLOCK_RDG_POSTS_LIST];
    $block_posts_list = $rdgb->settings->getBlock(BLOCK_RDG_POSTS_LIST);

    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'].';';
    }

    $show = get_field('show');
    $titles = get_field('titles');
    $display = (empty(get_field('display')) || get_field('display') == 'default') ? '' : 'flex';

    $elements = $block_posts_list->get_elements_type(get_fields());
    $position_block = $rdgb->helpers->getBlocksSpaces(get_fields());
?>

<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'; ?>

        <div class="body">
            <?php if (is_array($elements) && count($elements) > 0): ?>
                <div class="items <?php echo $display; ?>">
                    <?php foreach($elements as $element): ?>
                        <div class="item">
                            <?php
                                $image = '';
                                if ($element instanceof WP_Post) {
                                    $image = $block_posts_list->get_image($element->ID);
                                } else {
                                    if (isset($element['image']['url']) && !empty($element['image']['url'])) {
                                        $image = $element['image']['url'];
                                    }
                                }
                            ?>
                            
                                <?php
                                    $link_url = '';
                                    $link_target = '_self';
                                    $link_name = 'Read more';
                                    if ($element instanceof WP_Post) {
                                        $link_url = get_permalink($element);
                                    } else {
                                        if (isset($element['link_post']['url']) && !empty($element['link_post']['url'])) {
                                            $link_url = $element['link_post']['url'];
                                        }

                                        if (isset($element['link_post']['target']) && !empty($element['link_post']['target'])) {
                                            $link_target = $element['link_post']['target'];
                                        }

                                        if (isset($element['link_post']['title']) && !empty($element['link_post']['title'])) {
                                            $link_name = $element['link_post']['title'];
                                        }
                                    } 
                                ?>
                                <a href="<?php echo $link_url; ?>" target="<?php echo $link_target; ?>">
                                    <div class="image" style="background-image: url(<?php echo $image; ?>);"></div>
                                </a>
                            
                            <footer>
                                <div class="footer-title">
                                    <a href="<?php echo $link_url; ?>" target="<?php echo $link_target; ?>">
                                        <?php
                                            if ($element instanceof WP_Post) {
                                                echo $element->post_title;
                                            } else {
                                                echo $element['title'] ?? '';
                                            }
                                        ?>
                                    </a>
                                </div>
                                <div class="header">
                                    <div class="date">
                                        <?php
                                            $author_name = '';
                                            $date = (!empty($element->post_date)) ? $element->post_date : $element['date'];

                                            if (isset($element->post_author)) {
                                                $author_name = get_the_author_meta('display_name', $element->post_author);
                                            }

                                            // 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);
                                                }
                                            }
                                            
                                            // Format date if valid
                                            if ($game_datetime !== false) {
                                                $month = $game_datetime->format('F');
                                                $more_date = $game_datetime->format('j, Y');
                                                $date = $month.' '.$more_date;
                                            }
                                        ?>

                                        <span>
                                            <?php echo __('By', 'rdg-blocks-posts-list'); ?>
                                            <?php echo $author_name; ?>
                                            <?php if (isset($month) && !empty($month)): ?>
                                                | <?php echo __($month, 'rdg-blocks-months'); ?>
                                                <?php echo $more_date; ?>
                                            <?php endif; ?>
                                        </span>
                                    </div>
                                </div>
                                <?php
                                    $excerpt = '';
                                    if ($element instanceof WP_Post) {
                                        if (!empty($element->post_excerpt)) {
                                            $excerpt = $element->post_excerpt;
                                        } else {
                                            $excerpt = $element->post_content;
                                        }
                                    } else {
                                        if (isset($element['content']) && !empty($element['content'])) {
                                            $excerpt = $element['content'];
                                        }
                                    }
                                ?>
                                <?php if (!empty($excerpt)): ?>
                                    <div class="footer-description">
                                        <?php echo wp_trim_words($excerpt, 35, false); ?>
                                    </div>
                                <?php endif; ?>
                            </footer>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>
