<?php //Custom Post Type :: UPCOMING EVENTS

function custom_post_type_events() {
    $labels = array(
        'name'                => __('Upcoming Events', 'kipya' ),
        'add_new_item'        => __( 'Add New Event', 'kipya' ),
        'add_new'             => __( 'Add New Event', 'kipya' ),
        'edit_item'           => __( 'Edit Event', 'kipya' ),
        'update_item'         => __( 'Update Event', 'kipya' ),
        'all_items'           => __( 'All Events', 'kipya' ),
        'search_items'        => __( 'Search Event', 'kipya' ),
        'singular_name'       => __('Event'),
    );
    $supports = array(
        'title',        // Post title
        'editor',      // Allows short description
        'thumbnail',    // Allows feature images
    );
    $args = array(
        'labels'              => $labels,
        'description'         => 'For all Upcoming Events', 
        'supports'            => $supports,
        'hierarchical'        => false, 
        'public'              => true,  // Makes the post type public
        'show_ui'             => true,  // Displays an interface for this post type
        'show_in_menu'        => true,  // Displays in the Admin Menu (the left panel)
        'show_in_admin_bar'   => true,  // Displays in the black admin bar
        'menu_position'       => 6,     // The position number in the left menu
        'menu_icon'           => 'dashicons-calendar',  
        'can_export'          => true,  // Allows content export using Tools -> Export
        'has_archive'         => true,  // Enables post type archive (by month, date, or year)
        'exclude_from_search' => false, 
        'capability_type'     => 'post', // Allows read, edit, delete like “Post”
        'register_meta_box_cb' => 'add_custom_meta_boxes_events',
    );
    register_post_type('events', $args);
}
add_action('init', 'custom_post_type_events');

//Add Custom Meta Boxes on Upcoming Events
function add_custom_meta_boxes_events() {
    add_meta_box('event_details', 'Event Details', 'render_custom_meta_box_events', 'events', 'normal', 'high');
}

// Render custom meta boxes
function render_custom_meta_box_events($post) {
    // Get existing values
    $post_id = $post->ID;
    $start_date = get_post_meta($post->ID, '_start_date', true);
    $end_date = get_post_meta($post->ID, '_end_date', true);
    $location = get_post_meta($post->ID, '_location', true);
    $link = get_post_meta($post->ID, '_link', true);

    // Output fields
    ?>
    <div class="row">
        <div class="col-md-6 mb-3" style="width: 50%; margin-bottom:10px;float:left;">
            <label for="start_date"><b>Start Date</b></label><br/>
            <input type="datetime-local" id="start_date" name="start_date" style="width: 90%;" value="<?= esc_attr($start_date); ?>">
        </div>
        <div class="col-md-6 mb-3" style="width: 50%; margin-bottom:10px;float:left;">
            <label for="end_date"><b>End Date</b></label><br/>
            <input type="datetime-local" id="end_date" name="end_date" style="width: 90%;" value="<?= esc_attr($end_date); ?>">
        </div>
        <div class="col-md-12 mb-3" style="width: 100%; margin-bottom:10px;">
            <label for="location" class="form-label"><b>Location</b></label><br/>
            <textarea id="location" name="location" rows="5" style="width: 100%"><?= esc_textarea($location); ?></textarea>
        </div>
        <div class="col-md-12 mb-3">
            <label for="link" class="form-label"><b>Link</b></label><br/>
            <input type="text" id="link" name="link" style="width: 100%" value="<?= esc_attr($link); ?>">
        </div>
    </div>
    <?php
}

// Save custom meta box data
function save_custom_meta_box_events($post_id) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;

    // Save custom fields
    // Define an array of field names
    $fields = array('start_date', 'end_date', 'location', 'link');

    // Loop through the fields and update post meta
    foreach ($fields as $field) {
        // Check if the field key is set in $_POST
        if (isset($_POST[$field])) {
            // If set, update post meta
            if ($field === 'location') {
                update_post_meta($post_id, '_' . $field, wp_kses_post($_POST[$field]));
            } else {
                update_post_meta($post_id, '_' . $field, sanitize_text_field($_POST[$field]));
            }
        } else {
            // If not set, handle accordingly (you can leave it empty or provide a default value)
            update_post_meta($post_id, '_' . $field, ''); // Setting it to an empty string in this case
        }
    }

}

add_action('add_meta_boxes', 'add_custom_meta_boxes_events');
add_action('save_post', 'save_custom_meta_box_events');

// Add custom columns to the events post type - DASHBOARD
function add_custom_columns_to_events($columns) {
    // Add new columns
    $columns['event_photo'] = 'Photo';
    $columns['event_start_date'] = 'Start Date';
    $columns['event_end_date'] = 'End Date';
    $columns['event_location'] = 'Location';

    // Remove unwanted columns if needed
    unset($columns['date']); // Remove default date column

    return $columns;
}
add_filter('manage_events_posts_columns', 'add_custom_columns_to_events');

// Populate custom columns with data
function populate_custom_columns($column, $post_id) {
    switch ($column) {
        case 'event_photo':
            // Display the featured image
            $photo_url = get_the_post_thumbnail_url($post_id, 'thumbnail'); // You can adjust the image size ('thumbnail', 'medium', 'large', 'full')
            if ($photo_url) {
                echo '<img src="' . esc_url($photo_url) . '" alt="Event Photo" style="max-height: 50px; width: auto;" />';
            } else {
                echo 'No photo available';
            }
            break;        

        case 'event_start_date':
            // Display the start date
            $start_date = get_post_meta($post_id, '_start_date', true);
            echo esc_html($start_date);
            break;

        case 'event_end_date':
            // Display the end date
            $end_date = get_post_meta($post_id, '_end_date', true);
            echo esc_html($end_date);
            break;

        case 'event_location':
                // Display the end date
                $location = get_post_meta($post_id, '_location', true);
                echo esc_html($location);
                break;
    }
}
add_action('manage_events_posts_custom_column', 'populate_custom_columns', 10, 2);




/** =================================================================
 *  SHORTCODE - UPCOMING EVENTS
 *===================================================================*/
function upcoming_events_shortcode($atts) {
    // Define shortcode attributes, if needed
    $atts = shortcode_atts(
        array(
            'posts_per_page' => 5,
        ),
        $atts,
        'upcoming_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()) :
        echo '<div class="row">';
        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)); // Format for Date
            $formatted_start_month = date('F', strtotime($start_date)); // Format for Month
            $formatted_start_time = date('g:i A', strtotime($start_date)); // Format for Time
            ?>
            
            <div class="col-xl-3 col-lg-4 col-sm-6 kpy_events">
            <a data-bs-toggle="offcanvas" data-bs-target="#staticBackdrop-<?php echo $post_id; ?>" aria-controls="staticBackdrop-<?php echo $post_id; ?>" style="cursor: pointer;">
                <div class="card shadow-sm mb-3 border-0" data-aos="fade-up">
					<div class="post-thumbnail">
						<?php // Display the post thumbnail
							if (has_post_thumbnail()) {
								the_post_thumbnail(); 
							}else{
								echo '<img src="'. get_template_directory_uri().'/assets/images/photo-placeholder.jpg" alt="NGO Forum" class="img-fluid"/>';
							}
						?>
					</div><!-- thumbnail !-->
					<div class="card-body">
					    <div class="date">
					        <i class="bi bi-calendar2-event"></i>  <?= esc_html($formatted_start_date); ?>
					    </div>
						<h3><?php the_title(); ?></h3>
						<span class="location"><i class="bi bi-geo-alt"></i>  <?= esc_html($location); ?></span>
					</div><!-- card body !-->
				</div><!-- card !-->
            </a>
            </div><!-- col !-->
            
            <!-- Full Event !-->
            <div class="offcanvas offcanvas-end kpy_event_details"  tabindex="-1" id="staticBackdrop-<?php echo $post_id; ?>" aria-labelledby="staticBackdropLabel-<?php echo $post_id; ?>">
                <?php // Display the post thumbnail
							if (has_post_thumbnail()) {
								the_post_thumbnail(); 
							}else{
								echo '<img src="'. get_template_directory_uri().'/assets/images/photo-placeholder.jpg" alt="NGO Forum" class="img-fluid"/>';
							}
				?>
                <div class="offcanvas-header">
                    <h5 class="offcanvas-title" id="staticBackdropLabel"><?php the_title(); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
                </div>
                <div class="offcanvas-body">
                    <div class="row mb-4">
                        <div class="col-6 time">
                            <i class="bi bi-calendar-check"></i>  <?= esc_html($formatted_start_date); ?>
                        </div>
                        <div class="col-6 location">
                            <i class="bi bi-geo-alt"></i>  <?php echo esc_html($location); ?>
                        </div>
                    </div><!-- Date & Location !-->
                    <div>
                    <?= esc_html(the_content()); ?>
                    </div>
                </div>
            </div><!-- offcanvas !-->
            <?php
        endwhile;
        wp_reset_postdata();
    else :
        echo 'No upcoming events found.';
        echo '</div>';
    endif;
     
    return ob_get_clean();
}

add_shortcode('upcoming_events', 'upcoming_events_shortcode');
