<?php
/**
 * Plugin Name: Upcoming Events Shortcode
 * Description: Adds a shortcode [upcomingevents] to display and submit events.
 * Version: 1.4
 * Author: Your Name
 */

// Create default category on plugin activation
register_activation_hook(__FILE__, 'uesc_create_default_category');
function uesc_create_default_category() {
    if (!term_exists('event', 'category')) {
        wp_insert_term('event', 'category');
    }
}

// Customizer additions for Firefly > Events section
add_action('customize_register', 'firefly_customize_events_section');
function firefly_customize_events_section($wp_customize) {
    $wp_customize->add_section('firefly_events_section', array(
        'title'       => __('Firefly Events', 'firefly'),
        'priority'    => 91,
        'description' => __('Customize how event boxes appear.', 'firefly'),
    ));

    $colour_choices_text = array(
        'colour1' => array('color' => get_theme_mod('firefly_colour_1', '#dd3333'), 'label' => 'Colour 1'),
        'colour2' => array('color' => get_theme_mod('firefly_colour_2', '#1e73be'), 'label' => 'Colour 2'),
        'colour3' => array('color' => get_theme_mod('firefly_colour_3', '#8224e3'), 'label' => 'Colour 3'),
        'colour4' => array('color' => get_theme_mod('firefly_colour_4', '#ededc4'), 'label' => 'Colour 4'),
        'black'   => array('color' => '#000000', 'label' => 'Black'),
        'white'   => array('color' => '#ffffff', 'label' => 'White'),
    );

    // Background color palette version
    $wp_customize->add_setting('firefly_event_background_colour_key', array(
        'default'           => 'colour3',
        'sanitize_callback' => 'sanitize_text_field',
    ));
    $wp_customize->add_control(new Firefly_Radio_Colour_Control_Text(
        $wp_customize,
        'firefly_event_background_colour_key_control',
        array(
            'label'    => __('Event Box Background Colour (Palette)', 'firefly'),
            'section'  => 'firefly_events_section',
            'settings' => 'firefly_event_background_colour_key',
            'choices'  => $colour_choices_text,
        )
    ));

    // Indent setting (formerly Width)
    $wp_customize->add_setting('firefly_event_indent', array(
        'default'           => '0px',
        'sanitize_callback' => function($value) {
            return preg_match('/^\d+px$/', trim($value)) ? $value : '0px';
        }
    ));
    $wp_customize->add_control('firefly_event_indent', array(
        'label'    => __('Event Box Indent (Left/Right)', 'firefly'),
        'section'  => 'firefly_events_section',
        'settings' => 'firefly_event_indent',
        'type'     => 'select',
        'choices'  => array_combine(
            array_map(fn($i) => $i.'px', range(0, 80, 5)),
            array_map(fn($i) => $i.'px', range(0, 80, 5))
        )
    ));

    // Helper for px choices
$px_choices = array_combine(
    array_map(fn($i) => $i . 'px', range(0, 30, 5)),
    array_map(fn($i) => $i . 'px', range(0, 30, 5))
);

// Margin Top
$wp_customize->add_setting('firefly_event_margin_top', [
    'default' => '0px',
    'sanitize_callback' => fn($value) => preg_match('/^\d+px$/', $value) ? $value : '0px'
]);
$wp_customize->add_control('firefly_event_margin_top', [
    'label' => __('Event Box Margin Top', 'firefly'),
    'section' => 'firefly_events_section',
    'type' => 'select',
    'choices' => $px_choices,
]);

// Margin Bottom
$wp_customize->add_setting('firefly_event_margin_bottom', [
    'default' => '0px',
    'sanitize_callback' => fn($value) => preg_match('/^\d+px$/', $value) ? $value : '0px'
]);
$wp_customize->add_control('firefly_event_margin_bottom', [
    'label' => __('Event Box Margin Bottom', 'firefly'),
    'section' => 'firefly_events_section',
    'type' => 'select',
    'choices' => $px_choices,
]);

// Padding Top
$wp_customize->add_setting('firefly_event_padding_top', [
    'default' => '0px',
    'sanitize_callback' => fn($value) => preg_match('/^\d+px$/', $value) ? $value : '0px'
]);
$wp_customize->add_control('firefly_event_padding_top', [
    'label' => __('Event Box Padding Top', 'firefly'),
    'section' => 'firefly_events_section',
    'type' => 'select',
    'choices' => $px_choices,
]);

// Padding Bottom
$wp_customize->add_setting('firefly_event_padding_bottom', [
    'default' => '0px',
    'sanitize_callback' => fn($value) => preg_match('/^\d+px$/', $value) ? $value : '0px'
]);
$wp_customize->add_control('firefly_event_padding_bottom', [
    'label' => __('Event Box Padding Bottom', 'firefly'),
    'section' => 'firefly_events_section',
    'type' => 'select',
    'choices' => $px_choices,
]);

// Text Alignment
$wp_customize->add_setting('firefly_event_text_align', [
    'default' => 'left',
    'sanitize_callback' => fn($value) => in_array($value, ['left', 'center']) ? $value : 'left'
]);
$wp_customize->add_control('firefly_event_text_align', [
    'label' => __('Align Event Content!', 'firefly'),
    'section' => 'firefly_events_section',
    'type' => 'radio',
    'choices' => [
        'left' => __('Left', 'firefly'),
        'center' => __('Centered', 'firefly'),
    ]
]);




    // Font size choices
$font_sizes = array_combine(
    array_map(fn($i) => $i . 'px', range(16, 36, 2)),
    array_map(fn($i) => $i . 'px', range(16, 36, 2))
);

// Event Heading Font Size
$wp_customize->add_setting('firefly_event_heading_font_size', [
    'default' => '24px',
    'sanitize_callback' => fn($v) => preg_match('/^\d+px$/', $v) ? $v : '24px',
]);
$wp_customize->add_control('firefly_event_heading_font_size', [
    'label' => __('Event Title Font Size', 'firefly'),
    'section' => 'firefly_events_section',
    'type' => 'select',
    'choices' => $font_sizes,
]);

// Event Date Font Size
$wp_customize->add_setting('firefly_event_date_font_size', [
    'default' => '18px',
    'sanitize_callback' => fn($v) => preg_match('/^\d+px$/', $v) ? $v : '18px',
]);
$wp_customize->add_control('firefly_event_date_font_size', [
    'label' => __('Event Date Font Size', 'firefly'),
    'section' => 'firefly_events_section',
    'type' => 'select',
    'choices' => $font_sizes,
]);


// Event Font Weight
$wp_customize->add_setting('firefly_event_heading_font_weight', [
    'default' => 'normal',
    'sanitize_callback' => fn($v) => in_array($v, ['normal', 'bold']) ? $v : 'normal',
]);
$wp_customize->add_control('firefly_event_heading_font_weight', [
    'label' => __('Event Font Weight', 'firefly'),
    'section' => 'firefly_events_section',
    'type' => 'radio',
    'choices' => [
        'normal' => __('Plain', 'firefly'),
        'bold'   => __('Bold', 'firefly'),
    ],
]);

// Date Font Weight
$wp_customize->add_setting('firefly_event_date_font_weight', [
    'default' => 'normal',
    'sanitize_callback' => fn($v) => in_array($v, ['normal', 'bold']) ? $v : 'normal',
]);
$wp_customize->add_control('firefly_event_date_font_weight', [
    'label' => __('Date Font Weight', 'firefly'),
    'section' => 'firefly_events_section',
    'type' => 'radio',
    'choices' => [
        'normal' => __('Plain', 'firefly'),
        'bold'   => __('Bold', 'firefly'),
    ],
]);


$wp_customize->add_setting('firefly_event_heading_order', [
    'default' => 'event_above_date',
    'sanitize_callback' => function($value) {
        $valid = ['date_above_event', 'event_above_date', 'inline_date_event', 'inline_event_date'];
        return in_array($value, $valid) ? $value : 'event_above_date';
    }
]);

$wp_customize->add_control('firefly_event_heading_order', [
    'label' => __('Date / Event Order', 'firefly'),
    'section' => 'firefly_events_section',
    'type' => 'radio',
    'choices' => [
        'date_above_event'     => __('Date above Event', 'firefly'),
        'event_above_date'     => __('Event above Date', 'firefly'),
        'inline_date_event'    => __('Date: Event', 'firefly'),
        'inline_event_date'    => __('Event: Date', 'firefly'),
    ],
]);



    // Radio palette colour selectors
    $wp_customize->add_setting('firefly_event_heading_colour', array(
        'default' => 'colour1',
        'sanitize_callback' => 'sanitize_text_field',
    ));
    $wp_customize->add_control(new Firefly_Radio_Colour_Control_Text(
        $wp_customize,
        'firefly_event_heading_colour_control',
        array(
            'label'    => __('Event Heading Colour', 'firefly'),
            'section'  => 'firefly_events_section',
            'settings' => 'firefly_event_heading_colour',
            'choices'  => $colour_choices_text,
        )
    ));

    $wp_customize->add_setting('firefly_event_date_colour', array(
        'default' => 'black',
        'sanitize_callback' => 'sanitize_text_field',
    ));
    $wp_customize->add_control(new Firefly_Radio_Colour_Control_Text(
        $wp_customize,
        'firefly_event_date_colour_control',
        array(
            'label'    => __('Event Date Colour', 'firefly'),
            'section'  => 'firefly_events_section',
            'settings' => 'firefly_event_date_colour',
            'choices'  => $colour_choices_text,
        )
    ));

    $wp_customize->add_setting('firefly_event_text_colour', array(
        'default' => 'black',
        'sanitize_callback' => 'sanitize_text_field',
    ));
    $wp_customize->add_control(new Firefly_Radio_Colour_Control_Text(
        $wp_customize,
        'firefly_event_text_colour_control',
        array(
            'label'    => __('Event Details Text Colour', 'firefly'),
            'section'  => 'firefly_events_section',
            'settings' => 'firefly_event_text_colour',
            'choices'  => $colour_choices_text,
        )
    ));





    $wp_customize->add_section('firefly_events_section', array(
        'title'       => __('Firefly Events', 'firefly'),
        'priority'    => 91,
        'description' => __('Customize how event boxes appear.', 'firefly'),
    ));

    $colour_choices_text = array(
        'colour1' => array('color' => get_theme_mod('firefly_colour_1', '#dd3333'), 'label' => 'Colour 1'),
        'colour2' => array('color' => get_theme_mod('firefly_colour_2', '#1e73be'), 'label' => 'Colour 2'),
        'colour3' => array('color' => get_theme_mod('firefly_colour_3', '#8224e3'), 'label' => 'Colour 3'),
        'colour4' => array('color' => get_theme_mod('firefly_colour_4', '#ededc4'), 'label' => 'Colour 4'),
        'black'   => array('color' => '#000000', 'label' => 'Black'),
        'white'   => array('color' => '#ffffff', 'label' => 'White'),
    );

    // 🔹 Add link button style setting
    $wp_customize->add_setting('firefly_event_link_style', [
        'default' => 'text',
        'sanitize_callback' => function($value) {
            $valid = ['text', 'bold', 'heading', 'button1', 'button2', 'button3', 'button4', 'button5', 'button6'];
            return in_array($value, $valid) ? $value : 'text';
        }
    ]);


    $colour1 = get_theme_mod('firefly_colour_1', '#dd3333');
$colour2 = get_theme_mod('firefly_colour_2', '#1e73be');
$colour3 = get_theme_mod('firefly_colour_3', '#8224e3');
$colour4 = get_theme_mod('firefly_colour_4', '#ededc4');

$link_style_choices = [
    'text'    => 'More info...',
    'bold'    => '<strong>More info...</strong>',
    'heading' => '<span style="font-size:22px;">More info...</span>',
    'button1' => "<span style=\"background:{$colour1};color:white;padding:6px 12px;border-radius:4px;display:inline-block;\">More info...</span>",
    'button2' => "<span style=\"background:{$colour2};color:white;padding:6px 12px;border-radius:4px;display:inline-block;\">More info...</span>",
    'button3' => "<span style=\"background:{$colour3};color:black;padding:6px 12px;border-radius:4px;display:inline-block;\">More info...</span>",
    'button4' => "<span style=\"background:{$colour4};color:black;padding:6px 12px;border-radius:4px;display:inline-block;\">More info...</span>",
    'button5' => "<span style=\"border:2px solid {$colour1};padding:6px 12px;display:inline-block;\">More info...</span>",
    'button6' => "<span style=\"border:2px solid {$colour2};padding:6px 12px;display:inline-block;\">More info...</span>",
];


$wp_customize->add_control(new Firefly_Radio_Button_Style_Control(
    $wp_customize,
    'firefly_event_link_style',
    [
        'label'    => __('Link Button Style', 'firefly'),
        'section'  => 'firefly_events_section',
        'settings' => 'firefly_event_link_style',
        'choices'  => $link_style_choices,
    ]
));



}

// Inject custom styles based on Customizer settings





// [...rest of your plugin code here remains unchanged, starting with add_action('init', 'uesc_handle_event_save_or_update');...]


//===================================================


add_action('init', 'uesc_handle_event_save_or_update');

function uesc_build_event_content($data) {
    // Only store the description in post_content, not the formatted date/time info
    return wp_kses_post($data['event_description']);
}

function uesc_handle_event_save_or_update() {
    if (
        isset($_POST['uesc_event_submit']) &&
        current_user_can('manage_options')
    ) {
        // Get or create "event" category
        $event_cat_id = get_cat_ID('event');
        if ($event_cat_id == 0) {
            $new_cat = wp_insert_term('event', 'category');
            if (!is_wp_error($new_cat)) {
                $event_cat_id = $new_cat['term_id'];
            }
        }

        // Process form data - store ONLY the description in post_content
               // Get raw values
               $title      = sanitize_text_field($_POST['event_title']);
               $content    = wp_kses_post($_POST['event_description']);
               $event_day  = sanitize_text_field($_POST['event_day']);
               $end_day    = isset($_POST['event_end_day']) ? sanitize_text_field($_POST['event_end_day']) : '';
       
               // Generate post_name (slug-safe)
               $post_name = sanitize_title($title);
       
               // Build date range
               $date_range = $event_day;
               if (!empty($end_day) && $end_day !== $event_day) {
                   $date_range .= ' – ' . $end_day;
               }
       
               // Construct excerpt: post_name - dates
               // Format event_day
$formatted_start = $event_day ? date('l, j F Y', strtotime($event_day)) : 'Unknown date';

// Format end_day only if it's different and valid
$formatted_end = '';
if (!empty($end_day) && $end_day !== $event_day) {
    $formatted_end = ' – ' . date('l, j F Y', strtotime($end_day));
}

// Combine for excerpt
$date_range = $formatted_start . $formatted_end;
$excerpt = $title . ' - ' . $date_range;

       
               $post_data = [
                   'post_title'   => $title,
                   'post_content' => $content,
                   'post_status'  => 'publish',
                   'post_type'    => 'post',
                   'post_excerpt' => $excerpt,
               ];
       

        // Process categories
        $selected_cats = [];
        if (!empty($_POST['event_categories']) && is_array($_POST['event_categories'])) {
            $selected_cats = array_map('intval', $_POST['event_categories']);
        }
        
        // Add new category if specified
        $new_category = isset($_POST['new_category']) ? sanitize_text_field($_POST['new_category']) : '';
        if (!empty($new_category)) {
            $new_cat = wp_insert_term($new_category, 'category');
            if (!is_wp_error($new_cat)) {
                $selected_cats[] = $new_cat['term_id'];
            }
        }


          // Assign author
  
        
   
    

        // Ensure event category is included
        $post_data['post_category'] = array_unique(array_merge([$event_cat_id], $selected_cats));



       // Build post category array
$post_data['post_category'] = array_unique(array_merge([$event_cat_id], $selected_cats));

// Get category IDs for comparison
$classes_cat = get_category_by_slug('classes');
$retreats_cat = get_category_by_slug('retreats');

$classes_id = $classes_cat ? $classes_cat->term_id : 0;
$retreats_id = $retreats_cat ? $retreats_cat->term_id : 0;

$selected_author = isset($_POST['event_author']) ? intval($_POST['event_author']) : 0;

if ($selected_author > 0) {
    $post_data['post_author'] = $selected_author;
} elseif (in_array($classes_id, $post_data['post_category'])) {
    $post_data['post_author'] = 3;
} elseif (in_array($retreats_id, $post_data['post_category'])) {
    $post_data['post_author'] = 4;
} else {
    $post_data['post_author'] = get_current_user_id(); // default fallback
}

        // Update or insert post
        if (!empty($_POST['event_id'])) {
            $post_data['ID'] = intval($_POST['event_id']);
            $post_id = wp_update_post($post_data);
            $updated = 1;
        } else {
            $post_id = wp_insert_post($post_data);
            $updated = 0;
        }

        // Save event metadata
        if ($post_id) {
            update_post_meta($post_id, 'event_day', sanitize_text_field($_POST['event_day']));
            update_post_meta($post_id, 'event_end_day', isset($_POST['event_end_day']) ? sanitize_text_field($_POST['event_end_day']) : '');
            update_post_meta($post_id, 'event_time', isset($_POST['event_time']) ? sanitize_text_field($_POST['event_time']) : '');
            update_post_meta($post_id, 'event_end_time', isset($_POST['event_end_time']) ? sanitize_text_field($_POST['event_end_time']) : '');
            update_post_meta($post_id, 'event_venue', isset($_POST['event_venue']) ? sanitize_text_field($_POST['event_venue']) : '');

           update_post_meta($post_id, 'event_link', trim($_POST['event_link'] ?? ''));

            update_post_meta($post_id, 'event_link_text', sanitize_text_field($_POST['event_link_text'] ?? ''));

            // Redirect with status message
            $current_url = home_url(strtok($_SERVER["REQUEST_URI"], '?'));
            $redirect = add_query_arg($updated ? 'event_updated' : 'event_added', '1', $current_url);
            wp_redirect($redirect);
            exit;
        }
    }
}

// Handle event deletion
add_action('init', 'uesc_handle_event_delete');
function uesc_handle_event_delete() {
    if (
        isset($_POST['uesc_delete_event']) &&
        current_user_can('manage_options') &&
        wp_verify_nonce($_POST['_wpnonce'] ?? '', 'delete_event_' . $_POST['uesc_delete_event'])
    ) {
        $post_id = intval($_POST['uesc_delete_event']);
        if (get_post_type($post_id) === 'post') {
            wp_delete_post($post_id, true);
            wp_redirect(add_query_arg('event_deleted', '1', wp_get_referer()));
            exit;
        }
    }
}

// Format the event date for display
function uesc_format_event_date($day, $end_day = '') {
    if (empty($day)) {
        return 'Unknown date';
    }
    
    $date = date('l, jS F Y', strtotime($day));
    if (!empty($end_day) && $end_day !== $day) {
        $date_end = date('l, jS F Y', strtotime($end_day));
        $date .= ' – ' . $date_end;
    }
    
    return $date;
}

// Main shortcode function
add_shortcode('upcomingevents', 'uesc_display_upcoming_events');
function uesc_display_upcoming_events($atts) {
    ob_start();

    // Process shortcode attributes
    $atts = shortcode_atts([
        'show' => 10, // Default to 10 events
        'category' => '', // Optional category filter
        'heading' => 'Upcoming events...',
        'style' => 'box',
    ], $atts, 'upcomingevents');


    $eventboxstyle = $atts["style"];
    // Edit mode
    $edit_event_id = isset($_GET['edit_event']) ? intval($_GET['edit_event']) : 0;
    $edit_event = $edit_event_id ? get_post($edit_event_id) : null;
    
    $edit_title = '';
    $edit_description = '';
    $edit_day = '';
    $edit_end_day = '';
    $edit_time = '';
    $edit_end_time = '';
    $edit_venue = '';
    
    if ($edit_event) {
        $edit_title = esc_attr($edit_event->post_title);
        // Just use the content directly - it should now contain only the description
        $edit_description = $edit_event->post_content;
        
        // Get event details from custom fields


        $edit_day = get_post_meta($edit_event_id, 'event_day', true);
        $edit_end_day = get_post_meta($edit_event_id, 'event_end_day', true);
        $edit_time = get_post_meta($edit_event_id, 'event_time', true);
        $edit_end_time = get_post_meta($edit_event_id, 'event_end_time', true);
        $edit_venue = get_post_meta($edit_event_id, 'event_venue', true);
         $event_link = get_post_meta($edit_event_id, 'event_link', true);
          $event_link_text = get_post_meta($edit_event_id, 'event_link_text', true);



    }

    // Admin form for adding/editing events
    if (current_user_can('manage_options')) {

        echo '<div class="firefly-admin-1">';
        echo '<div class="firefly-admin-2">Firefly event options</div>';
        echo '<div class="firefly-admin-3">';
        echo '<a href="#" id="show-event-form" class="firefly-admin-link">Add an event</a> | ';
    echo '<a href="#" id="toggle-all-events"class="firefly-admin-link">Show all events</a>';
?>

<div id="all-events" style="display:none; margin-top:20px;background-color:white; padding:15px;font-size:14px;">
    <h3>All Events</h3>
    <ul style="list-style:disc; padding-left: 20px;">
    <?php
    $all_events = new WP_Query([
        'post_type'  => 'post',
        'meta_key'   => 'event_day',
        'orderby'    => 'meta_value',
        'order'      => 'ASC',
        'posts_per_page' => -1,
        'meta_query' => [
            [
                'key'     => 'event_day',
                'compare' => 'EXISTS',
                'type'    => 'DATE'
            ]
        ],
        'category_name' => 'event'
    ]);

    if ($all_events->have_posts()) {
        while ($all_events->have_posts()) {
            $all_events->the_post();
            $event_id = get_the_ID();
            $title = get_the_title();
            $event_day = get_post_meta($event_id, 'event_day', true);
            $formatted_day = $event_day ? date('l, jS F Y', strtotime($event_day)) : 'Unknown date';

            echo '<li>';
            echo '<strong>' . esc_html($formatted_day) . '</strong>: ';
            echo esc_html($title);

            if (current_user_can('edit_post', $event_id)) {
                echo ' <a href="?edit_event=' . esc_attr($event_id) . '">[Edit]</a>';
            }

            echo '</li>';
        }
        wp_reset_postdata();
    } else {
        echo '<li>No events found.</li>';
    }
    ?>
    </ul>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const toggleLink = document.getElementById('toggle-all-events');
    const allEvents = document.getElementById('all-events');

    toggleLink.addEventListener('click', function(e) {
        e.preventDefault();
        const isVisible = allEvents.style.display === 'block';
        allEvents.style.display = isVisible ? 'none' : 'block';
        toggleLink.textContent = isVisible ? 'Show all events' : 'Hide all events';
    });
});
</script>


        <div id="event-form" style="display:none; margin-top:20px;">
            <form method="post" style="display:grid; gap:15px; max-width:600px;">
                <input type="hidden" name="uesc_event_submit" value="1">
                <?php if ($edit_event_id): ?>
                    <input type="hidden" name="event_id" value="<?= esc_attr($edit_event_id) ?>">
                <?php endif; ?>
                <label><strong>Event Title:</strong><br>
                    <input type="text" name="event_title" value="<?= $edit_title ?>" style="width:100%;" required>
                </label>
                <label><strong>Description (optional):</strong><br>
                    <textarea name="event_description" style="width:100%; height:80px;"><?= esc_textarea($edit_description) ?></textarea>
                </label>
                <label><strong>Date:</strong><br>
                    <input type="date" name="event_day" value="<?= esc_attr($edit_day) ?>" required>
                </label>
                <label><strong>End Date (optional - for multi-day events):</strong><br>
                    <input type="date" name="event_end_day" value="<?= esc_attr($edit_end_day) ?>">
                </label>
                <label><strong>Start Time (optional):</strong><br>
                    <input type="time" name="event_time" value="<?= esc_attr($edit_time) ?>">
                </label>
                <label><strong>End Time (optional):</strong><br>
                    <input type="time" name="event_end_time" value="<?= esc_attr($edit_end_time) ?>">
                </label>
                <label><strong>Venue (optional):</strong><br>
                    <input type="text" name="event_venue" value="<?= esc_attr($edit_venue) ?>" style="width:100%;">
                </label>

                <label><strong>Link (optional):</strong><br>
                  <small>Enter a full URL (https://...) or a page path like <code>events</code> or <code>/events</code>.</small>



            <input type="text" name="event_link" value="<?= esc_attr(get_post_meta($edit_event_id, 'event_link', true)) ?>" style="width:100%;" placeholder="e.g. /events or https://...">
 </label>

            <label><strong>Link Text (optional):</strong><br>
                <input type="text" name="event_link_text" value="<?= esc_attr(get_post_meta($edit_event_id, 'event_link_text', true)) ?>" style="width:100%;">
            </label>


                <!-- Category Selection -->
                <div class="uesc-form-group">
                    <label><strong>Categories</strong></label>
                    <div class="uesc-category-select">
                        <?php
                        $categories = get_categories(['hide_empty' => false]);
                        $post_categories = $edit_event_id ? wp_get_post_categories($edit_event_id) : [];

                        foreach ($categories as $cat):
                            if ($cat->slug === 'uncategorized') continue;
                            if ($cat->slug != 'event') {
                            ?>
                            <label>
                                <input type="checkbox" name="event_categories[]" value="<?php echo $cat->term_id; ?>"
                                    <?php echo in_array($cat->term_id, $post_categories) ? 'checked' : ''; ?>>
                                <?php echo esc_html($cat->name); ?>
                            </label>
                        <?php 
                        }
                    endforeach; ?>
                    </div>
                    <input type="text" name="new_category" placeholder="Add new category">
                </div>


                
<!-- Author Selection -->
<div class="uesc-form-group">
    <label><strong><?php
    
// quilters work around

    $domain = $_SERVER['HTTP_HOST'];
    if (str_contains($domain, 'quilters')) {
        echo "<B>If you want the form to appear on the full retreats form, select 'full retreats' as the author. If you want the event to appear on the mini retreats form, select 'mini retreat as the author below.</B><BR>";
    }
      ?>  
        Author:
    </strong></label>
    <select name="event_author" style="width:100%;">
        <?php
        $users = get_users(['fields' => ['ID', 'display_name']]);
        $current_author = $edit_event_id ? get_post_field('post_author', $edit_event_id) : get_current_user_id();

        foreach ($users as $user) {
            $selected = ($user->ID == $current_author) ? 'selected' : '';
            echo "<option value='" . esc_attr($user->ID) . "' $selected>" . esc_html($user->display_name) . " (ID: {$user->ID})</option>";
        }
        ?>
    </select>
</div>

                <input type="submit" value="<?= $edit_event_id ? 'Update Event' : 'Submit Event' ?>" style="background-color:#005A9C;color:white;padding:10px;border:none;cursor:pointer;">
            
              <a href="/">Cancel</a>
            </form>
        </div>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                if (window.location.search.includes("edit_event=")) {
                    document.getElementById('event-form').style.display = 'block';
                    const showBtn = document.getElementById('show-event-form');
                   // if (showBtn) showBtn.style.display = 'none';
                }

                document.getElementById('show-event-form').addEventListener('click', function(e) {
                    e.preventDefault();
                    document.getElementById('event-form').style.display = 'block';
                  //  this.style.display = 'none';
                });
            });
        </script>
        </div>   </div>  
        <?php
    }

    // Display upcoming events
    $max_events = intval($atts['show']);
    
    // Build query arguments
    $args = [
        'post_type'      => 'post',
        'posts_per_page' => $max_events,
        'meta_key'       => 'event_day',
        'orderby'        => 'meta_value',
        'order'          => 'ASC',
        'meta_query'     => [
            [
                'key'     => 'event_day',
                'value'   => date('Y-m-d'),
                'compare' => '>=',
                'type'    => 'DATE'
            ]
        ]
    ];

    // Add category filter if specified
    $category_slug = sanitize_title($atts['category'] ?? '');




    if (!empty($category_slug)) {
        $category = get_category_by_slug($category_slug);
        if ($category) {
            $args['cat'] = $category->term_id;
        }
    } else {
        // If no category specified, include default "event" category
        $event_cat = get_category_by_slug('event');
        if ($event_cat) {
            $args['cat'] = $event_cat->term_id;
        }
    }

    // Get events
    $events = new WP_Query($args);

    if ($events->have_posts()) {

        if ($eventboxstyle == "box") {
            echo '<div class="upcoming-events-wrapper">
              <div class="upcoming-events-box">';
    }
    
    
    if ($eventboxstyle == "plain") {
        echo '<div class="upcoming-events-wrapper-plain">
          <div class="upcoming-events-box">';
        }

        

              echo "<h2>". $atts['heading']. "</h2>"; 
        while ($events->have_posts()) {
            $events->the_post();
            $event_id = get_the_ID();
            
            // Get event meta
            $day       = get_post_meta($event_id, 'event_day', true);
            $end_day   = get_post_meta($event_id, 'event_end_day', true);
            $time      = get_post_meta($event_id, 'event_time', true);
            $end_time  = get_post_meta($event_id, 'event_end_time', true);
            $venue     = get_post_meta($event_id, 'event_venue', true);
            
            // Get description (post_content now contains only the description)
            $description = get_the_content();
            
            // Format the date range
            $date = uesc_format_event_date($day, $end_day);
            
            // Display the event
            echo '<div class="event">';
            echo '<hr>';



if (current_user_can('edit_post', get_the_ID())) {
    $post_id = get_the_ID();
    
    echo '<div class="firefly-admin-1" style="width:100%;">';
    echo '<div class="firefly-admin-2">Event options</div>';
    echo '<div class="firefly-admin-3">';

    // Edit link as a form (GET)
    echo '<form method="get" style="display:inline;">';
    echo '<input type="hidden" name="edit_event" value="' . esc_attr($post_id) . '">';
    echo '<button type="submit" style="background:none;border:none;color:black;cursor:pointer;">Edit this event</button>';
    echo '</form> | ';

    // Delete link as a form (POST)
    echo '<form method="post" style="display:inline;" onsubmit="return confirm(\'Are you sure you want to delete this event?\');">';
    echo '<input type="hidden" name="uesc_delete_event" value="' . esc_attr($post_id) . '">';
    echo wp_nonce_field('delete_event_' . $post_id, '_wpnonce', true, false);
    echo '<button type="submit" style="background:none;border:none;color:black;cursor:pointer;">Delete this event</button>';
    echo '</form>';

    echo '</div>';
    echo '</div>';
}



$heading_order = get_theme_mod('firefly_event_heading_order', 'event_above_date');
$title_html = '<span class="eventheading">' . get_the_title() . '</span>';
$date_html = '<span class="eventdate">' . esc_html($date);

if ($time) {
    $formatted_time = date('g:ia', strtotime($time));
    $date_html .= ' - ' . esc_html($formatted_time);
}

$date_html .= '</span>';

switch ($heading_order) {
    case 'date_above_event':
        echo "<span class='eventheading'>$date_html</span><br> <span class='eventdate'>$title_html</span>";
        break;
    case 'inline_date_event':
     //   echo "<h3 style='line-height:130% !important;'>$date_html: $title_html</h3>";
          echo "<span class='eventheading'>$date_html</span>: <span class='eventdate'>$title_html</span>";
        break;
    case 'inline_event_date':
       // echo "<h3 style='line-height:130% !important;'>$title_html: $date_html</h3>";
          echo "<span class='eventdate'>$title_html</span>: <span class='eventheading'>$date_html</span> ";
        break;
    default: // event_above_date
       // echo "<h3 style='line-height:130% !important;'>$title_html<br>$date_html</h3>";
          echo "<span class='eventdate'>$title_html</span><br><span class='eventheading'>$date_html</span> ";
        break;
}



        
            // Display description
            if (!empty($description)) {
                echo "
                <div>";
                echo $description;
               echo "</div>";
            }
            
            // Display venue
            if ($venue) {
                echo '
                <div><strong>Venue:</strong> ' . esc_html($venue) . '</div>';
            }
            
          


             $link_raw = trim(get_post_meta($event_id, 'event_link', true));
$link_text = trim(get_post_meta($event_id, 'event_link_text', true));

if (!empty($link_raw) && !empty($link_text)) {
    // Determine full URL for the link
    if (preg_match('#^https?://#', $link_raw)) {
        $link = esc_url_raw($link_raw);
    } else {
        $relative = '/' . ltrim($link_raw, '/');
        $link = home_url($relative);
    }

    // Normalize for comparison
    $current_path = strtok($_SERVER['REQUEST_URI'], '?#');           // current path, no query/hash
    $current_url  = untrailingslashit(home_url($current_path));

    $target_path = parse_url($link, PHP_URL_PATH) ?? '';
    $target_url  = untrailingslashit(home_url($target_path));

    // Only show link if it doesn't match current page
    if ($current_url !== $target_url) {
        $is_external = parse_url($link, PHP_URL_HOST) && parse_url($link, PHP_URL_HOST) !== $_SERVER['HTTP_HOST'];
        $target = $is_external ? ' target="_blank" rel="noopener"' : '';
        echo '<div class="event_link"><a href="' . esc_url($link) . '" class="event-link"' . $target . '>' . esc_html($link_text) . '</a></div>';
    }
}



            // Admin controls for editing/deleting
           
            
            echo "</div>
            
            
            ";
        }
        
        echo '<BR></div></div>
        
        ';
        wp_reset_postdata();
    } else {
        echo '<div class="upcoming-events-box"><h2>Upcoming events</h2><p>No events found.</p></div>';
    }

    return ob_get_clean();
}


add_action('customize_preview_init', function () {
    wp_enqueue_script('firefly-event-customizer-preview', plugin_dir_url(__FILE__) . 'event-customizer-preview.js', array('customize-preview'), '1.0', true);
});


add_action('wp_head', 'firefly_event_custom_styles');
function firefly_event_custom_styles() {


    $indent = get_theme_mod('firefly_event_indent', '0px');

    $bg_key = get_theme_mod('firefly_event_background_colour_key', 'colour3');
    $event_background_colour = match ($bg_key) {
        'colour1' => get_theme_mod('firefly_colour_1', '#dd3333'),
        'colour2' => get_theme_mod('firefly_colour_2', '#1e73be'),
        'colour3' => get_theme_mod('firefly_colour_3', '#8224e3'),
        'colour4' => get_theme_mod('firefly_colour_4', '#ededc4'),
        'white'   => '#ffffff',
        default   => '#ffffff',
    };

    $heading_colour_key = get_theme_mod('firefly_event_heading_colour', 'colour1');
    $heading_colour = match ($heading_colour_key) {
        'colour1' => get_theme_mod('firefly_colour_1', '#dd3333'),
        'colour2' => get_theme_mod('firefly_colour_2', '#1e73be'),
        'colour3' => get_theme_mod('firefly_colour_3', '#8224e3'),
        'colour4' => get_theme_mod('firefly_colour_4', '#ededc4'),
        'white'   => '#ffffff',
        default   => '#000000',
    };

    $date_colour_key = get_theme_mod('firefly_event_date_colour', 'black');
    $date_colour = match ($date_colour_key) {
        'colour1' => get_theme_mod('firefly_colour_1', '#dd3333'),
        'colour2' => get_theme_mod('firefly_colour_2', '#1e73be'),
        'colour3' => get_theme_mod('firefly_colour_3', '#8224e3'),
        'colour4' => get_theme_mod('firefly_colour_4', '#ededc4'),
        'white'   => '#ffffff',
        default   => '#000000',
    };

    $text_colour_key = get_theme_mod('firefly_event_text_colour', 'black');
    $text_colour = match ($text_colour_key) {
        'colour1' => get_theme_mod('firefly_colour_1', '#dd3333'),
        'colour2' => get_theme_mod('firefly_colour_2', '#1e73be'),
        'colour3' => get_theme_mod('firefly_colour_3', '#8224e3'),
        'colour4' => get_theme_mod('firefly_colour_4', '#ededc4'),
        'white'   => '#ffffff',
        default   => '#000000',
    };


    $page_width   = get_theme_mod('my_plugin_page_width', 'full-width');
    $max_width    = get_theme_mod('my_plugin_max_width', '95%');
    $padding_lr   = get_theme_mod('my_plugin_padding_lr', '15px');

 $bg_choice     = get_theme_mod('layout_bg_color_choice', 'black');
    $content_choice = get_theme_mod('layout_content_color_choice', 'white');


    // ✅ Resolve choice into actual color values
    $colours = array(
        'colour1' => get_theme_mod('firefly_colour_1', '#dd3333'),
        'colour2' => get_theme_mod('firefly_colour_2', '#1e73be'),
        'colour3' => get_theme_mod('firefly_colour_3', '#8224e3'),
        'colour4' => get_theme_mod('firefly_colour_4', '#ededc4'),
        'black'   => '#000000',
        'white'   => '#ffffff',
    );


    $bg_color = isset($colours[$bg_choice]) ? $colours[$bg_choice] : '#000000';
    $content_color = isset($colours[$content_choice]) ? $colours[$content_choice] : '#ffffff';

    $margin_top    = get_theme_mod('firefly_event_margin_top', '0px');
    $margin_bottom = get_theme_mod('firefly_event_margin_bottom', '0px');
    $padding_top   = get_theme_mod('firefly_event_padding_top', '0px');
    $padding_bottom= get_theme_mod('firefly_event_padding_bottom', '0px');
    $text_align    = get_theme_mod('firefly_event_text_align', 'left');
    $heading_font_size = get_theme_mod('firefly_event_heading_font_size', '24px');
    $date_font_size = get_theme_mod('firefly_event_date_font_size', '18px');

    $heading_font_weight = get_theme_mod('firefly_event_heading_font_weight', 'normal');
$date_font_weight    = get_theme_mod('firefly_event_date_font_weight', 'normal');
$firefly_event_link_style    = get_theme_mod('firefly_event_link_style', 'normal');

 $colour1= get_theme_mod('firefly_colour_1', '#8224e3');
  $colour2 = get_theme_mod('firefly_colour_2', '#8224e3');
  $colour3 = get_theme_mod('firefly_colour_3', '#8224e3');
  $colour4 = get_theme_mod('firefly_colour_4', '#8224e3');

    echo "<style id='firefly-event-preview-css'>



        .upcoming-events-wrapper {
            max-width: {$max_width} !important; 

            margin:0 auto !important;
            jeff:heff;
           margin-left: {$padding_lr};
            margin-right: {$padding_lr};
            background-color:{$content_color};
            padding:0px;
        }

         .upcoming-events-box {
            background-color: {$event_background_colour};
            width: 100%;
            padding-left: {$indent} !important;
            margin-top: {$margin_top};
            margin-bottom: {$margin_bottom};
            padding-top: {$padding_top};
            padding-bottom: {$padding_bottom};
            text-align: {$text_align};
        }


        

        .event {
            padding-left:0px !important;
        }


        .eventheading {
          color: {$heading_colour};
          margin-left:0px;
          font-size: {$heading_font_size};
          line-height:130%;
           font-weight: {$heading_font_weight};
        }
        .eventdate {
            color: {$date_colour};
            font-size: {$date_font_size};
             line-height:140%;
             font-weight: {$date_font_weight};
        }

        .upcoming-events-box .event {
        
            color: {$text_colour};
            padding:0px;
            padding-left:0px;
        }
  

        .upcoming-events-wrapper .upcoming-events-box h2 {

          margin:0px;
          padding-left:0px;
        }

         .upcoming-events-wrapper .upcoming-events-box h3 {
          margin:0px;
          padding-left:0px;
        }

          .upcoming-events-wrapper .upcoming-events-box p {
          margin:0px;
          padding-left:0px;
        }

";

if ($text_align == "left") {
    echo "
    .event_link {
        text-align:left;
          margin-top:15px !important;
    }
    ";
}
else
{
    echo "
    .event_link {
       margin:0 auto !important;
         margin-top:15px !important;
    }
    ";
}
         

if ($firefly_event_link_style == "normal") {
       echo "";
}


if ($firefly_event_link_style == "bold") {
       echo "
       .event_link {
       font-weight:bold;
       margin-top:15px !important;
       }
       ";
}


if ($firefly_event_link_style == "heading") {
       echo "
       .event_link {
        color: {$heading_colour};
          margin-left:0px;
          font-size: {$heading_font_size};
          line-height:130%;
           font-weight: {$heading_font_weight};
       }
       ";
}


if ($firefly_event_link_style == "button1") {
       echo "
       .event_link {
       background-color:{$colour1}; 
       padding:10px;
        color: white !important;
          margin-left:0px;
      
          line-height:130%;
           font-weight: {$heading_font_weight};
           width:300px;
          
       }
       ";
}


if ($firefly_event_link_style == "button1") {
       echo "
       .event_link a {
        color: white !important;
       }
       ";
}

if ($firefly_event_link_style == "button2") {
       echo "
       .event_link a {
        color: white !important;
       }
       ";
}


if ($firefly_event_link_style == "button2") {
       echo "
       .event_link {
       background-color:{$colour2}; 
       padding:10px;
        color: white !important;
          margin-left:0px;
          line-height:130%;
           font-weight: {$heading_font_weight};
           width:300px;
       }
       ";
}



if ($firefly_event_link_style == "button3") {
       echo "
       .event_link {
       background-color:{$colour3}; 
       padding:10px;
        color: black !important;
          margin-left:0px;
          line-height:130%;
           font-weight: {$heading_font_weight};
           width:300px;
       }
       ";
}



if ($firefly_event_link_style == "button4") {
       echo "
       .event_link {
       background-color:{$colour4}; 
       padding:10px;
        color: black !important;
          margin-left:0px;
          line-height:130%;
           font-weight: {$heading_font_weight};
           width:300px;
       }
       ";
}



if ($firefly_event_link_style == "button5") {
       echo "
       .event_link {
       border:2px solid {$colour1} !important; 
       padding:10px;
        color: black !important;
          margin-left:0px;
          line-height:130%;
           font-weight: {$heading_font_weight};
           width:300px;
       }
       ";
}



if ($firefly_event_link_style == "button6") {
       echo "
       .event_link {
        border:2px solid {$colour2} !important; 
       padding:10px;
        color: black !important;
          margin-left:0px;
          line-height:130%;
           font-weight: {$heading_font_weight};
           width:300px;
       }
       ";
}


echo "
    </style>";
}

if (class_exists('WP_Customize_Control')) {
    class Firefly_Radio_Button_Style_Control extends WP_Customize_Control {
        public $type = 'radio_button_style';

        public function render_content() {
            if (empty($this->choices)) return;

            echo '<span class="customize-control-title">' . esc_html($this->label) . '</span>';

            foreach ($this->choices as $value => $label_html) {
                ?>
                <label style="display:block; margin-bottom:10px;">
                    <input type="radio" name="<?php echo esc_attr($this->id); ?>"
                           value="<?php echo esc_attr($value); ?>"
                           <?php $this->link(); checked($this->value(), $value); ?> />
                    <span style="margin-left:8px; vertical-align:middle;"><?php echo $label_html; ?></span>
                </label>
                <?php
            }
        }
    }
}
