<?php

function more_events_shortcode($atts) {
    // Define shortcode attributes, if needed
    $atts = shortcode_atts(
        array(
            'posts_per_page' => 15,
        ),
        $atts,
        'more_events'
    );

    // Custom query to retrieve upcoming events
    $events_args = array(
        'post_type' => 'events', // Replace with your custom post type slug
        'posts_per_page' => $atts['posts_per_page'],
        'order' => 'ASC',
        'orderby' => 'meta_value',
        'meta_key' => '_start_date',
        'meta_query' => array(
            array(
                'key' => '_start_date',
                'value' => date('Y-m-d'),
                'compare' => '>=',
                'type' => 'DATE',
            ),
        ),
    );

    $events_query = new WP_Query($events_args);

    ob_start();

    // Check if there are upcoming events
    if ($events_query->have_posts()) :
        while ($events_query->have_posts()) : $events_query->the_post();
            $post_id = get_the_ID();
            $text = get_the_content();
            $url =  get_post_meta(get_the_ID(), '_link', true);
            $location =  get_post_meta(get_the_ID(), '_location', true);
            $start_date = get_post_meta(get_the_ID(), '_start_date', true);
            $formatted_start_date = date('jS, F Y', strtotime($start_date));
            $formatted_start_day = date('d', strtotime($start_date));
            $formatted_start_month = date('F', strtotime($start_date)); 
            $formatted_start_time = date('g:i A', strtotime($start_date)); // Format for Time
            ?>
            <a href="<?= esc_url(get_permalink()); ?>">
            <div class="card card-body rounded-0 border-0 kpy_events shadow-sm mb-3" data-aos="fade-up">
                <div class="row">
                    <div class="col-3">
                        <div class="cal-badge">
                            <div class="kdate"><?= esc_html($formatted_start_day); ?></div>
                            <div class="kmonth"><?= esc_html($formatted_start_month); ?></div>
                        </div>
                    </div>
                    <div class="col-9">
                        
                        <div class="text-muted mt-2"><small> <i class="bi bi-geo-alt"></i>  <?= esc_html($location); ?></small>
                        </div>
                        <h2><?php the_title(); ?></h2>
                    </div>
                </div>
            </div>
            </a>
            <?php
        endwhile;
        wp_reset_postdata();
    else :
        echo 'No school Events';
    endif;

    return ob_get_clean();
}

add_shortcode('more_events', 'more_events_shortcode');