<?php
/**
 * Plugin Name:       Bandboss' Upcoming Events Manager
 * Description:       Manage and display upcoming events via a shortcode.
 * Version:           2.10.7
 * Author:            Bandbosswebdesign
 * Plugin URI:        https://bandbosswebdesign.nl/upcoming-events-manager-pro
 * Author URI:        https://bandbosswebdesign.nl/
 * Requires at least: 6.0
 * Tested up to:      7.0
 * Requires PHP:      7.4
 * License:           GPL-2.0-or-later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       bandboss-upcoming-events-manager
 * Domain Path:       /languages
 */

if (!defined('ABSPATH'))
    exit;

/** === Globals / constants (freemium friendly) === */
if (!defined('BANDUPEV_IS_FREE'))
    define('BANDUPEV_IS_FREE', true);
if (!defined('BANDUPEV_VERSION'))
    define('BANDUPEV_VERSION', '2.10.7');
if (!defined('BANDUPEV_PLUGIN_FILE'))
    define('BANDUPEV_PLUGIN_FILE', __FILE__);
if (!defined('BANDUPEV_PLUGIN_URL'))
    define('BANDUPEV_PLUGIN_URL', plugin_dir_url(__FILE__));
if (!defined('BANDUPEV_PLUGIN_PATH'))
    define('BANDUPEV_PLUGIN_PATH', plugin_dir_path(__FILE__));

/** === Gedeelde CPT-definitie (Free/Pro) === */
if (!defined('BANDUPEV_CPT'))
    define('BANDUPEV_CPT', 'upcoming_event');
if (!defined('BANDUPEV_REST_BASE'))
    define('BANDUPEV_REST_BASE', 'upcoming-events');

/** Register CPT vroeg (en alleen als nog niet gedaan) */
function bandupev_register_cpt_shared()
{
    if (post_type_exists(BANDUPEV_CPT))
        return;
    register_post_type(BANDUPEV_CPT, array(
        'labels' => array(
            'name' => __('Upcoming Events', 'bandboss-upcoming-events-manager'),
            'singular_name' => __('Upcoming Event', 'bandboss-upcoming-events-manager'),
        ),
        'public' => false,
        'show_ui' => true,
        'menu_position' => 25,
        'menu_icon' => 'dashicons-list-view',
        'supports' => array('title'),
        'show_in_rest' => true,
        'rest_base' => BANDUPEV_REST_BASE,
        'map_meta_cap' => true,
    ));
}
add_action('init', 'bandupev_register_cpt_shared', 0);

/** Safety net (admin): voorkom "Invalid post type" */
add_action('admin_init', function () {
    if (!post_type_exists(BANDUPEV_CPT)) {
        bandupev_register_cpt_shared();
    }
}, 1);

/** === Migratie: oud CPT + meta → nieuw === */
function bandupev_free_migrate()
{
    if (get_option('bandupev_free_migrated_cpt_meta'))
        return;

    global $wpdb;

    // 1) Oud CPT naar nieuw
    $wpdb->update($wpdb->posts, array('post_type' => BANDUPEV_CPT), array('post_type' => 'bandupev_event'));

    // 2) Meta key mapping
    $map = array(
        'bandupev_event_date' => 'upcoming_event_date',
        'bandupev_event_start_time' => 'upcoming_event_start_time',
        'bandupev_event_entrance_fee' => 'upcoming_event_entrance_fee',
        'bandupev_event_venue' => 'upcoming_event_venue',
        'bandupev_event_city' => 'upcoming_event_city',
        'bandupev_event_country' => 'upcoming_event_country',
        'bandupev_event_ticket_sale' => 'upcoming_event_ticket_sale',
        'bandupev_event_facebook_event' => 'upcoming_event_facebook_event',
        'bandupev_event_website' => 'upcoming_event_website',
        'bandupev_event_highlighted' => 'upcoming_event_highlighted',
        'bandupev_event_sold_out' => 'upcoming_event_sold_out',
    );

    $ids = $wpdb->get_col("SELECT ID FROM {$wpdb->posts} WHERE post_type='" . esc_sql(BANDUPEV_CPT) . "'");
    foreach ((array) $ids as $pid) {
        foreach ($map as $old => $new) {
            $new_val = get_post_meta($pid, $new, true);
            $old_val = get_post_meta($pid, $old, true);
            if (($new_val === '' || $new_val === null) && ($old_val !== '' && $old_val !== null)) {
                if (in_array($new, array('upcoming_event_highlighted', 'upcoming_event_sold_out'), true)) {
                    $old_val = ((string) $old_val === '1') ? '1' : '';
                }
                update_post_meta($pid, $new, $old_val);
            }
        }
    }

    update_option('bandupev_free_migrated_cpt_meta', time());
}
register_activation_hook(__FILE__, 'bandupev_free_migrate');
add_action('admin_init', function () {
    if (!get_option('bandupev_free_migrated_cpt_meta'))
        bandupev_free_migrate();
});

/** === Meta-registratie (alleen upcoming_event_*) === */
add_action('init', function () {
    foreach (array(
        'upcoming_event_date',
        'upcoming_event_start_time',
        'upcoming_event_entrance_fee',
        'upcoming_event_venue',
        'upcoming_event_city',
        'upcoming_event_country'
    ) as $k) {
        register_post_meta(BANDUPEV_CPT, $k, array(
            'type' => 'string',
            'single' => true,
            'show_in_rest' => true,
            'sanitize_callback' => 'sanitize_text_field',
        ));
    }
    foreach (array('upcoming_event_ticket_sale', 'upcoming_event_facebook_event', 'upcoming_event_website') as $k) {
        register_post_meta(BANDUPEV_CPT, $k, array(
            'type' => 'string',
            'single' => true,
            'show_in_rest' => array('schema' => array('type' => 'string', 'format' => 'uri')),
            'sanitize_callback' => 'esc_url_raw',
        ));
    }
    foreach (array('upcoming_event_highlighted', 'upcoming_event_sold_out') as $k) {
        register_post_meta(BANDUPEV_CPT, $k, array(
            'type' => 'boolean',
            'single' => true,
            'show_in_rest' => array('schema' => array('type' => 'boolean', 'default' => false)),
            'default' => false,
        ));
    }
});

/** === Admin assets (alleen op onze schermen) === */
function bandupev_admin_assets($hook)
{
    $screen = get_current_screen();
    if (!$screen || !in_array($screen->id, array('edit-' . BANDUPEV_CPT, BANDUPEV_CPT, BANDUPEV_CPT . '_page_bandupev_settings'), true)) {
        return;
    }

    // CSS
    wp_register_style('bandupev-admin', BANDUPEV_PLUGIN_URL . 'style/upcoming-events-admin-style.css', array(), BANDUPEV_VERSION);
    wp_enqueue_style('bandupev-admin');

    // Color Picker
    wp_enqueue_style('wp-color-picker');
    wp_enqueue_script('wp-color-picker');

    // JS (optioneel bestand, inline helpers werken ook zonder file)
    wp_register_script('bandupev-admin-js', BANDUPEV_PLUGIN_URL . 'assets/js/admin.js', array('jquery'), BANDUPEV_VERSION, true);
    wp_enqueue_script('bandupev-admin-js');

    // Kleine inline helper (copy shortcode + soldout toggle)
    $inline = <<<JS
document.addEventListener('DOMContentLoaded',function(){
  document.querySelectorAll('.copy-shortcode-btn').forEach(function(btn){
    btn.addEventListener('click',function(){
      var id=btn.getAttribute('data-target'), el=document.getElementById(id);
      if(!el) return;
      navigator.clipboard.writeText(el.textContent).then(function(){
        btn.innerText='✅'; setTimeout(function(){btn.innerText='📋';},1500);
      });
    });
  });
  var sold=document.getElementById('upcoming_event_sold_out'), ticket=document.getElementById('upcoming_event_ticket_sale');
  if(sold && ticket){var t=function(){ sold.checked ? ticket.classList.add('soldout') : ticket.classList.remove('soldout');}; sold.addEventListener('change',t); t();}
});
JS;
    wp_add_inline_script('bandupev-admin-js', $inline, 'after');
}
add_action('admin_enqueue_scripts', 'bandupev_admin_assets');

/** === Frontend CSS === */
function bandupev_frontend_styling()
{
    wp_enqueue_style('bandupev-frontend', BANDUPEV_PLUGIN_URL . 'style/event-dates-style.css', array(), BANDUPEV_VERSION);
}
add_action('wp_enqueue_scripts', 'bandupev_frontend_styling');

/** === Helpers (landenlijst) === */
function bandupev_get_countries()
{
    return array(
        'us' => 'United States',
        'gb' => 'United Kingdom',
        'de' => 'Germany',
        'fr' => 'France',
        'nl' => 'Netherlands',
        'be' => 'Belgium',
        'it' => 'Italy',
        'es' => 'Spain',
        'pt' => 'Portugal',
        'pl' => 'Poland',
        'ro' => 'Romania',
        'se' => 'Sweden',
        'no' => 'Norway',
        'fi' => 'Finland',
        'dk' => 'Denmark',
        'ee' => 'Estland',
        'ie' => 'Ireland',
        'cz' => 'Czech Republic',
        'at' => 'Austria',
        'ch' => 'Switzerland',
        'hu' => 'Hungary',
        'gr' => 'Greece',
        'tr' => 'Turkey',
        'ru' => 'Russia',
        'ua' => 'Ukraine',
        'ca' => 'Canada',
        'mx' => 'Mexico',
        'br' => 'Brazil',
        'ar' => 'Argentina',
        'cl' => 'Chile',
        'co' => 'Colombia',
        'au' => 'Australia',
        'nz' => 'New Zealand',
        'jp' => 'Japan',
        'kr' => 'South Korea',
        'cn' => 'China',
        'hk' => 'Hong Kong',
        'sg' => 'Singapore',
        'id' => 'Indonesia',
        'th' => 'Thailand',
        'vn' => 'Vietnam',
        'in' => 'India',
        'za' => 'South Africa',
        'eg' => 'Egypt',
        'sa' => 'Saudi Arabia',
        'ae' => 'United Arab Emirates',
        'il' => 'Israel',
        'my' => 'Malaysia',
        'ph' => 'Philippines',
        'ke' => 'Kenya',
        'ng' => 'Nigeria',
    );
}

/** === Metabox === */
function bandupev_add_meta_box()
{
    add_meta_box(
        'bandupev_events_meta',
        esc_html__('Upcoming Event Details', 'bandboss-upcoming-events-manager'),
        'bandupev_render_meta_box',
        BANDUPEV_CPT,
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'bandupev_add_meta_box');

function bandupev_render_meta_box($post)
{
    wp_nonce_field('bandupev_events_meta_nonce_action', 'bandupev_events_meta_nonce');

    $highlighted = get_post_meta($post->ID, 'upcoming_event_highlighted', true);

    echo '<table class="form-table">';

    // Highlighted (Free: disabled)
    echo '<tr>';
    echo '<th><label for="upcoming_event_highlighted">' . esc_html__('Highlighted', 'bandboss-upcoming-events-manager') . '</label></th>';
    echo '<td colspan="2"><label class="bandupev-switch">';
    printf(
        '<input type="checkbox" id="upcoming_event_highlighted" name="upcoming_event_highlighted" value="1"%s %s />',
        checked($highlighted, '1', false),
        disabled(true, true, false)
    );
    echo '<span class="bandupev-slider"></span></label></td>';
    echo '</tr>';

    $fields = array(
        'date' => esc_html__('Date', 'bandboss-upcoming-events-manager'),
        'start_time' => esc_html__('Start Time', 'bandboss-upcoming-events-manager'),
        'entrance_fee' => esc_html__('Entrance Fee', 'bandboss-upcoming-events-manager'),
        'venue' => esc_html__('Venue', 'bandboss-upcoming-events-manager'),
        'city' => esc_html__('City', 'bandboss-upcoming-events-manager'),
        'ticket_sale' => esc_html__('Ticket Sale Link', 'bandboss-upcoming-events-manager'),
        'facebook_event' => esc_html__('Facebook Event Link', 'bandboss-upcoming-events-manager'),
        'website' => esc_html__('Venue/Festival Website', 'bandboss-upcoming-events-manager'),
    );

    foreach ($fields as $key => $label) {
        $value = get_post_meta($post->ID, 'upcoming_event_' . $key, true);
        $type = in_array($key, array('ticket_sale', 'facebook_event', 'website'), true) ? 'url'
            : ($key === 'date' ? 'date' : ($key === 'start_time' ? 'time' : 'text'));

        echo '<tr>';
        printf('<th width="170"><label for="upcoming_event_%1$s">%2$s</label></th>', esc_attr($key), esc_html($label));
        printf(
            '<td width="500"><input type="%1$s" id="upcoming_event_%2$s" name="upcoming_event_%2$s" value="%3$s" class="bandupev_input regular-text" /></td>',
            esc_attr($type),
            esc_attr($key),
            esc_attr($value)
        );

        if ($key === 'ticket_sale') {
            $sold_out = get_post_meta($post->ID, 'upcoming_event_sold_out', true);
            echo '<td><label for="upcoming_event_sold_out">' . esc_html__('Sold Out', 'bandboss-upcoming-events-manager') . '</label> <label class="bandupev-switch">';
            printf(
                '<input type="checkbox" id="upcoming_event_sold_out" name="upcoming_event_sold_out" value="1"%s %s />',
                checked($sold_out, '1', false),
                disabled(true, true, false)
            );
            echo '<span class="bandupev-slider"></span></label></td>';
        } else {
            echo '<td></td>';
        }
        echo '</tr>';

        if ($key === 'city') {
            $country_value = get_post_meta($post->ID, 'upcoming_event_country', true);
            $countries = bandupev_get_countries();

            echo '<tr>';
            echo '<th><label for="upcoming_event_country">' . esc_html__('Country', 'bandboss-upcoming-events-manager') . '</label></th>';
            echo '<td><select id="upcoming_event_country" name="upcoming_event_country" class="bandupev_input regular-text">';
            echo '<option value="">' . esc_html__('— Select Country —', 'bandboss-upcoming-events-manager') . '</option>';

            foreach ($countries as $code => $name) {
                printf(
                    '<option value="%1$s"%2$s>%3$s</option>',
                    esc_attr($code),
                    selected($country_value, $code, false),
                    esc_html($name)
                );
            }

            echo '</select></td><td></td>';
            echo '</tr>';
        }
    }

    echo '</table>';
}

/** Save meta (Free: force highlight/soldout uit) */
function bandupev_save_meta_box_data($post_id)
{
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return;
    if (get_post_type($post_id) !== BANDUPEV_CPT)
        return;

    if (
        !isset($_POST['bandupev_events_meta_nonce']) ||
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['bandupev_events_meta_nonce'])), 'bandupev_events_meta_nonce_action')
    ) {
        return;
    }
    if (!current_user_can('edit_post', $post_id))
        return;

    $text_fields = array('date', 'start_time', 'entrance_fee', 'venue', 'city');
    $url_fields = array('ticket_sale', 'facebook_event', 'website');

    foreach ($text_fields as $key) {
        if (isset($_POST['upcoming_event_' . $key])) {
            update_post_meta($post_id, 'upcoming_event_' . $key, sanitize_text_field(wp_unslash($_POST['upcoming_event_' . $key])));
        }
    }
    foreach ($url_fields as $key) {
        if (isset($_POST['upcoming_event_' . $key])) {
            update_post_meta($post_id, 'upcoming_event_' . $key, esc_url_raw(wp_unslash($_POST['upcoming_event_' . $key])));
        }
    }

    // Free: altijd uit
    update_post_meta($post_id, 'upcoming_event_highlighted', '');
    update_post_meta($post_id, 'upcoming_event_sold_out', '');

    if (isset($_POST['upcoming_event_country'])) {
        update_post_meta($post_id, 'upcoming_event_country', sanitize_text_field(wp_unslash($_POST['upcoming_event_country'])));
    }
}
add_action('save_post', 'bandupev_save_meta_box_data');

/** Verberg "Custom Fields" metabox en support (voorkomt dubbele velden) */
add_action('add_meta_boxes', function () {
    remove_meta_box('postcustom', BANDUPEV_CPT, 'normal');
}, 99);
add_action('init', function () {
    if (post_type_exists(BANDUPEV_CPT))
        remove_post_type_support(BANDUPEV_CPT, 'custom-fields');
}, 20);
add_filter('default_hidden_meta_boxes', function ($hidden, $screen) {
    if (isset($screen->id) && $screen->id === BANDUPEV_CPT)
        $hidden[] = 'postcustom';
    return array_unique($hidden);
}, 10, 2);

/** === Admin lijst: extra kolom + sorteren === */
function bandupev_add_custom_columns($columns)
{
    $new = array();
    foreach ($columns as $key => $label) {
        $new[$key] = $label;
        if ($key === 'title')
            $new['event_date'] = esc_html__('Event Date', 'bandboss-upcoming-events-manager');
    }
    return $new;
}
add_filter('manage_' . BANDUPEV_CPT . '_posts_columns', 'bandupev_add_custom_columns');

function bandupev_render_custom_columns($column, $post_id)
{
    if ($column === 'event_date') {
        $date = get_post_meta($post_id, 'upcoming_event_date', true);
        echo $date ? esc_html(wp_date('d M Y', strtotime($date))) : '<em>' . esc_html__('No date', 'bandboss-upcoming-events-manager') . '</em>';
    }
}
add_action('manage_' . BANDUPEV_CPT . '_posts_custom_column', 'bandupev_render_custom_columns', 10, 2);

function bandupev_sortable_columns($columns)
{
    $columns['event_date'] = 'upcoming_event_date';
    return $columns;
}
add_filter('manage_edit-' . BANDUPEV_CPT . '_sortable_columns', 'bandupev_sortable_columns');

function bandupev_orderby_event_date($query)
{
    if (!is_admin() || !$query->is_main_query())
        return;
    if ($query->get('orderby') === 'upcoming_event_date') {
        $query->set('meta_key', 'upcoming_event_date');
        $query->set('orderby', 'meta_value');
        $query->set('meta_type', 'DATE');
    }
}
add_action('pre_get_posts', 'bandupev_orderby_event_date');

function bandupev_default_admin_order($query)
{
    if (!is_admin() || !$query->is_main_query())
        return;
    global $pagenow;
    if ($pagenow === 'edit.php' && $query->get('post_type') === BANDUPEV_CPT && !$query->get('orderby')) {
        $query->set('meta_key', 'upcoming_event_date');
        $query->set('orderby', 'meta_value');
        $query->set('order', 'ASC');
        $query->set('meta_type', 'DATE');
    }
}
add_action('pre_get_posts', 'bandupev_default_admin_order');

/** === Settings (submenu) – alleen basisopties in Free === */
function bandupev_add_settings_menu()
{
    add_submenu_page(
        'edit.php?post_type=' . BANDUPEV_CPT,
        esc_html__('Upcoming events Settings', 'bandboss-upcoming-events-manager'),
        esc_html__('Settings', 'bandboss-upcoming-events-manager'),
        'manage_options',
        'bandupev_settings',
        'bandupev_render_settings_page'
    );
}
add_action('admin_menu', 'bandupev_add_settings_menu');

function bandupev_render_settings_page()
{
    if (isset($_POST['bandupev_events_settings_submit'])) {
        if (!current_user_can('manage_options'))
            wp_die(esc_html__('You do not have permission to do this.', 'bandboss-upcoming-events-manager'));
        check_admin_referer('bandupev_settings_action', 'bandupev_settings_nonce');

        update_option('bandupev_events_display_mode', sanitize_text_field(wp_unslash($_POST['bandupev_events_display_mode'] ?? 'number')));
        update_option('bandupev_events_number_of_items', intval($_POST['bandupev_events_number_of_items'] ?? 3));
        update_option('bandupev_events_end_date', sanitize_text_field(wp_unslash($_POST['bandupev_events_end_date'] ?? '')));
        echo '<div class="updated"><p>' . esc_html__('Settings saved.', 'bandboss-upcoming-events-manager') . '</p></div>';
    }

    $mode = get_option('bandupev_events_display_mode', 'number');
    $number = get_option('bandupev_events_number_of_items', 3);
    $end_date = get_option('bandupev_events_end_date', wp_date('Y-m-d', strtotime('+3 months', current_time('timestamp'))));
    ?>
    <div class="wrap event-dates-settings">
        <div class="notice notice-info" style="margin:16px 0;">
            <p><strong><?php echo esc_html__('Pro functions:', 'bandboss-upcoming-events-manager'); ?></strong>
                <?php echo esc_html__('Sold-out, Highlight-event and Styling are part of', 'bandboss-upcoming-events-manager'); ?>
                <em>Upcoming Events Manager Pro</em> (€2,99/m).
                <a href="https://bandbosswebdesign.nl/upcoming-events-manager-pro/?utm_source=wp-admin&utm_medium=plugin-settings"
                    target="_blank" rel="noopener noreferrer">
                    <?php echo esc_html__('More info & download', 'bandboss-upcoming-events-manager'); ?>
                </a>
            </p>
        </div>

        <h1><?php echo esc_html__('Upcoming events Settings', 'bandboss-upcoming-events-manager'); ?></h1>

        <form method="post">
            <?php wp_nonce_field('bandupev_settings_action', 'bandupev_settings_nonce'); ?>
            <table class="form-table">
                <tr>
                    <th colspan="2">
                        <h2><?php echo esc_html__('Show only a number of posts', 'bandboss-upcoming-events-manager'); ?>
                        </h2>
                    </th>
                </tr>
                <tr>
                    <th scope="row"><?php echo esc_html__('Show selection type', 'bandboss-upcoming-events-manager'); ?>
                    </th>
                    <td>
                        <select name="bandupev_events_display_mode" id="bandupev_events_display_mode">
                            <option value="number" <?php selected($mode, 'number'); ?>>
                                <?php echo esc_html__('Number of items', 'bandboss-upcoming-events-manager'); ?></option>
                            <option value="date" <?php selected($mode, 'date'); ?>>
                                <?php echo esc_html__('Till this date', 'bandboss-upcoming-events-manager'); ?></option>
                        </select>
                    </td>
                </tr>
                <tr class="row-number">
                    <th scope="row"><?php echo esc_html__('Number of items', 'bandboss-upcoming-events-manager'); ?></th>
                    <td><input type="number" name="bandupev_events_number_of_items"
                            value="<?php echo esc_attr($number); ?>" /></td>
                </tr>
                <tr class="row-date">
                    <th scope="row"><?php echo esc_html__('Show till this date', 'bandboss-upcoming-events-manager'); ?>
                    </th>
                    <td><input type="date" name="bandupev_events_end_date" value="<?php echo esc_attr($end_date); ?>" />
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <?php echo esc_html__('Shortcode for the selection', 'bandboss-upcoming-events-manager'); ?></th>
                    <td>
                        <div style="display:flex;align-items:center;gap:12px;margin-bottom:8px;">
                            <code id="shortcode1">[bandboss_upcoming_events]</code>
                            <button type="button" class="copy-shortcode-btn" data-target="shortcode1"
                                title="<?php echo esc_attr__('Copy shortcode', 'bandboss-upcoming-events-manager'); ?>">📋</button>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <?php echo esc_html__('Shortcode to show all eventdates (from today onwards)', 'bandboss-upcoming-events-manager'); ?>
                    </th>
                    <td>
                        <div style="display:flex;align-items:center;gap:12px;">
                            <code id="shortcode2">[bandboss_upcoming_events show_all="true"]</code>
                            <button type="button" class="copy-shortcode-btn" data-target="shortcode2"
                                title="<?php echo esc_attr__('Copy shortcode', 'bandboss-upcoming-events-manager'); ?>">📋</button>
                        </div>
                        <p class="description" style="margin-top:6px;">
                            <?php echo esc_html__('This shortcode automatically shows "Coming" and "Past" tabs. Past events are paginated (25 per page). Add max_items to limit the Coming tab, e.g.:', 'bandboss-upcoming-events-manager'); ?>
                        </p>
                        <div style="display:flex;align-items:center;gap:12px;margin-top:4px;">
                            <code id="shortcode3">[bandboss_upcoming_events show_all="true" max_items="25"]</code>
                            <button type="button" class="copy-shortcode-btn" data-target="shortcode3"
                                title="<?php echo esc_attr__('Copy shortcode', 'bandboss-upcoming-events-manager'); ?>">📋</button>
                        </div>
                    </td>
                </tr>
            </table>
            <?php submit_button(esc_html__('Save settings', 'bandboss-upcoming-events-manager'), 'primary', 'bandupev_events_settings_submit'); ?>
        </form>
    </div>
    <?php
}

/** Plugin action links (Settings + Pro) */
add_filter('plugin_action_links_' . plugin_basename(__FILE__), function ($links) {
    $settings_url = admin_url('edit.php?post_type=' . BANDUPEV_CPT . '&page=bandupev_settings');
    $settings_link = '<a href="' . esc_url($settings_url) . '">' . esc_html__('Settings', 'bandboss-upcoming-events-manager') . '</a>';
    $pro_url = 'https://bandbosswebdesign.nl/upcoming-events-manager-pro/?utm_source=wp-admin&utm_medium=plugin-list';
    $pro_link = '<a href="' . esc_url($pro_url) . '" target="_blank" rel="noopener noreferrer" style="color:#ea38a2;font-weight:700;">' . esc_html__('Get Pro', 'bandboss-upcoming-events-manager') . '</a>';
    array_unshift($links, $settings_link);
    $links[] = $pro_link;
    return $links;
});

/** === REST fallback: zorg dat meta via REST altijd wordt bewaard === */
add_action('rest_after_insert_' . BANDUPEV_CPT, function ($post, $request, $creating) {
    $incoming = $request->get_param('meta');
    if (!is_array($incoming) || empty($incoming))
        return;

    $allowed = array(
        'upcoming_event_date',
        'upcoming_event_start_time',
        'upcoming_event_entrance_fee',
        'upcoming_event_venue',
        'upcoming_event_city',
        'upcoming_event_country',
        'upcoming_event_ticket_sale',
        'upcoming_event_facebook_event',
        'upcoming_event_website',
        'upcoming_event_highlighted',
        'upcoming_event_sold_out',
    );

    foreach ($allowed as $key) {
        if (!array_key_exists($key, $incoming))
            continue;
        $val = $incoming[$key];

        switch ($key) {
            case 'upcoming_event_ticket_sale':
            case 'upcoming_event_facebook_event':
            case 'upcoming_event_website':
                $val = esc_url_raw((string) $val);
                break;
            case 'upcoming_event_highlighted':
            case 'upcoming_event_sold_out':
                $val = $val ? '1' : '';
                break;
            default:
                $val = is_string($val) ? sanitize_text_field($val) : (string) $val;
        }
        update_post_meta($post->ID, $key, $val);
    }
}, 10, 3);

/** === Shortcode === */
function bandupev_detect_show_all($atts)
{
    if (
        (isset($_GET['bandupev_show_all']) && 'true' === sanitize_text_field(wp_unslash($_GET['bandupev_show_all'])))
        || (isset($_GET['show_all_upcoming_events']) && 'true' === sanitize_text_field(wp_unslash($_GET['show_all_upcoming_events'])))
    ) {
        $atts['show_all'] = 'true';
    }
    return bandupev_upcoming_events_shortcode($atts);
}
add_shortcode('bandboss_upcoming_events', 'bandupev_detect_show_all');

/** Output include */
include BANDUPEV_PLUGIN_PATH . 'includes/shortcode-output.php';
