<?php

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

class AIEO_DMM_Events extends AIEO_DMM_Module_Base {

    const NONCE = 'aieo_events';

    const SETTINGS_OPTION = 'aieo_events_settings';

    public function get_id()       { return 'events'; }
    public function get_label()    { return __('Events', 'ai-eshop-optimizer'); }
    public function get_priority() { return 45; } 
    public function get_group()    { return 'custom_post_types'; }

    public function is_pro_locked() { return true; }

    public function get_pro_promo() {
        return array(
            'title'       => __('Events', 'ai-eshop-optimizer'),
            'description' => __('Run events — launches, brand presentations, professional seminars — with a branded landing page, desktop/mobile creatives, a guest list, invitation emails and RSVP tracking.', 'ai-eshop-optimizer'),
            'bullets'     => array(
                __('Schedule with start, end and RSVP deadline', 'ai-eshop-optimizer'),
                __('Branded landing page with desktop + mobile creatives', 'ai-eshop-optimizer'),
                __('Associate brands, categories and products', 'ai-eshop-optimizer'),
                __('Invitation subject + rich-text invitation body', 'ai-eshop-optimizer'),
                __('Guest list with invited / confirmed / declined tracking', 'ai-eshop-optimizer'),
            ),
        );
    }

    public function register_hooks() {
        
        
        if (!class_exists('AIEO_Event_CPT') && defined('AIEO_DIR') && file_exists(AIEO_DIR . 'includes/dmm/events/class-aieo-event-cpt.php')) {
            require_once AIEO_DIR . 'includes/dmm/events/class-aieo-event-cpt.php';
        }
        if (class_exists('AIEO_Event_CPT')) {
            AIEO_Event_CPT::register();
        }
        
        
        
        if (!class_exists('AIEO_Event_Participants') && defined('AIEO_DIR') && file_exists(AIEO_DIR . 'includes/dmm/events/class-aieo-event-participants.php')) {
            require_once AIEO_DIR . 'includes/dmm/events/class-aieo-event-participants.php';
        }
        if (class_exists('AIEO_Event_Participants') && method_exists('AIEO_Event_Participants', 'register')) {
            AIEO_Event_Participants::register();
        }
        
        if (!class_exists('AIEO_Event_RSVP') && defined('AIEO_DIR') && file_exists(AIEO_DIR . 'includes/dmm/events/class-aieo-event-rsvp.php')) {
            require_once AIEO_DIR . 'includes/dmm/events/class-aieo-event-rsvp.php';
        }
        if (class_exists('AIEO_Event_RSVP') && method_exists('AIEO_Event_RSVP', 'register')) {
            AIEO_Event_RSVP::register();
        }
        
        
        if (!class_exists('AIEO_Event_SelfReg') && defined('AIEO_DIR') && file_exists(AIEO_DIR . 'includes/dmm/events/class-aieo-event-selfreg.php')) {
            require_once AIEO_DIR . 'includes/dmm/events/class-aieo-event-selfreg.php';
        }
        if (class_exists('AIEO_Event_SelfReg') && method_exists('AIEO_Event_SelfReg', 'register')) {
            AIEO_Event_SelfReg::register();
        }
        add_action('wp_ajax_aieo_events_save', array($this, 'ajax_save'));
        add_action('wp_ajax_aieo_events_settings_save', array($this, 'ajax_save_settings'));

        
        
        add_action('admin_post_aieo_events_import', array($this, 'handle_import'));
        add_action('admin_post_aieo_events_participant_delete', array($this, 'handle_participant_delete'));

        
        add_action('admin_post_aieo_events_invites_send', array($this, 'handle_invites_send'));
        add_action('admin_post_aieo_events_invites_settings', array($this, 'handle_invites_settings'));

        
        add_action('admin_post_aieo_events_export', array($this, 'handle_export'));
    }

    
    private static function tab_url($args = array()) {
        $url = admin_url('admin.php?page=ai-eshop-dmm&dmm_tab=events');
        return empty($args) ? $url : add_query_arg($args, $url);
    }

    
    public static function get_settings() {
        $s = get_option(self::SETTINGS_OPTION, array());
        return is_array($s) ? $s : array();
    }

    public function enqueue_admin_assets() {
        if (!self::is_aieo_pro_user()) { return; } 
        wp_enqueue_media();
        
        
        if (class_exists('AIEO_Event_CPT') && method_exists('AIEO_Event_CPT', 'enqueue_picker_bundle')) {
            AIEO_Event_CPT::enqueue_picker_bundle();
        }
        $handle = 'aieo-events-admin';
        wp_enqueue_script(
            $handle,
            plugins_url('assets/js/aieo-events-admin.js', AIEO_FILE),
            array('jquery'),
            defined('AIEO_VERSION') ? AIEO_VERSION : '1.0',
            true
        );
        wp_localize_script($handle, 'aieoEvents', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce'   => wp_create_nonce(self::NONCE),
            'i18n'    => array(
                'select' => __('Select image', 'ai-eshop-optimizer'),
                'use'    => __('Use this image', 'ai-eshop-optimizer'),
                'saving' => __('Saving…', 'ai-eshop-optimizer'),
                'saved'  => __('Saved.', 'ai-eshop-optimizer'),
                'noname' => __('Please enter an event name.', 'ai-eshop-optimizer'),
            ),
        ));
    }

    public function render_subtab() {
        
        $manage_id = isset($_GET['manage']) ? (int) $_GET['manage'] : 0; 
        if ($manage_id > 0 && class_exists('AIEO_Event_CPT') && get_post_type($manage_id) === AIEO_Event_CPT::POST_TYPE) {
            $this->render_manage_screen($manage_id);
            return;
        }

        echo '<h2>' . esc_html__('Events', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description" style="max-width:760px;">' . esc_html__('Create an event, set its schedule and location, add a short description and desktop/mobile creatives, then compose the invitation. Each event becomes a landing page (use the native editor for the full agenda). Guest import, invitation send and RSVP tracking are managed per event.', 'ai-eshop-optimizer') . '</p>';

        
        echo '<div class="card" style="max-width:100%;padding:16px 20px;">';
        echo '<h3 style="margin-top:0;">' . esc_html__('New event', 'ai-eshop-optimizer') . '</h3>';
        echo '<form id="aieo-event-create" onsubmit="return false;">';
        echo '<input type="hidden" id="aieo-event-post-id" value="0">';
        echo '<table class="form-table"><tbody>';

        echo '<tr><th><label for="aieo-event-name">' . esc_html__('Name', 'ai-eshop-optimizer') . '</label></th><td><input type="text" id="aieo-event-name" class="regular-text" placeholder="' . esc_attr__('e.g. Spring Brand Showcase 2026', 'ai-eshop-optimizer') . '"></td></tr>';

        echo '<tr><th>' . esc_html__('Schedule', 'ai-eshop-optimizer') . '</th><td>';
        echo '<label style="margin-right:18px;">' . esc_html__('Starts', 'ai-eshop-optimizer') . ' <input type="datetime-local" id="aieo-event-start"></label>';
        echo '<label style="margin-right:18px;">' . esc_html__('Ends', 'ai-eshop-optimizer') . ' <input type="datetime-local" id="aieo-event-end"></label>';
        echo '<label>' . esc_html__('RSVP deadline', 'ai-eshop-optimizer') . ' <input type="datetime-local" id="aieo-event-rsvp-deadline"></label>';
        echo '<p class="description">' . esc_html__('Optional. Visitors see a “coming soon” notice before the start and an “ended” message after the end; shop managers always see the live page. Leave start/end empty for an always-open event. The RSVP deadline is the date by which guests must respond.', 'ai-eshop-optimizer') . '</p></td></tr>';

        echo '<tr><th><label for="aieo-event-location">' . esc_html__('Location', 'ai-eshop-optimizer') . '</label></th><td><input type="text" id="aieo-event-location" class="regular-text" placeholder="' . esc_attr__('e.g. Athens Concert Hall, Hall B', 'ai-eshop-optimizer') . '"></td></tr>';

        echo '<tr><th><label for="aieo-event-map-url">' . esc_html__('Map link', 'ai-eshop-optimizer') . '</label></th><td><input type="url" id="aieo-event-map-url" class="regular-text" placeholder="https://maps.google.com/…">';
        echo '<p class="description">' . esc_html__('Optional Google Maps URL for directions. If empty, a Maps search link is built from the location.', 'ai-eshop-optimizer') . '</p></td></tr>';

        echo '<tr><th><label for="aieo-event-desc">' . esc_html__('Short description', 'ai-eshop-optimizer') . '</label></th><td><textarea id="aieo-event-desc" rows="3" class="large-text"></textarea>';
        echo '<p class="description">' . esc_html__('A one-line summary. Use the native post editor for the full agenda after creating the event.', 'ai-eshop-optimizer') . '</p></td></tr>';

        echo '<tr><th>' . esc_html__('Creatives', 'ai-eshop-optimizer') . '</th><td><div style="display:flex;gap:24px;flex-wrap:wrap;">';
        $this->image_field('desktop', __('Desktop image', 'ai-eshop-optimizer'));
        $this->image_field('mobile', __('Mobile image', 'ai-eshop-optimizer'));
        echo '</div></td></tr>';

        
        echo '<tr><th><label for="aieo-event-brands">' . esc_html__('Brands', 'ai-eshop-optimizer') . '</label></th><td>';
        echo '<select id="aieo-event-brands" multiple class="aieo-dmm-brand-select regular-text" style="width:100%;max-width:520px;"></select>';
        echo '<p class="description">' . esc_html__('Optional — associate brands so you can later monitor the products they pull.', 'ai-eshop-optimizer') . '</p></td></tr>';
        echo '<tr><th><label for="aieo-event-categories">' . esc_html__('Categories', 'ai-eshop-optimizer') . '</label></th><td>';
        echo '<select id="aieo-event-categories" multiple class="aieo-dmm-category-select regular-text" style="width:100%;max-width:520px;"></select>';
        echo '<p class="description">' . esc_html__('Optional — associate product categories.', 'ai-eshop-optimizer') . '</p></td></tr>';
        if (class_exists('AIEO_DMM_Product_Picker')) {
            echo '<tr><th>' . esc_html__('Products', 'ai-eshop-optimizer') . '</th><td>';
            echo AIEO_DMM_Product_Picker::render_field(array( 
                'name'       => 'event_products',
                'mode'       => 'include',
                'selected'   => array(),
                'help'       => __('Optional — specific products associated with this event (to monitor their pull).', 'ai-eshop-optimizer'),
                'empty_text' => __('No products associated.', 'ai-eshop-optimizer'),
            ));
            echo '</td></tr>';
        }

        
        if (class_exists('AIEO_Event_CPT') && method_exists('AIEO_Event_CPT', 'gf_form_select')) {
            echo '<tr><th><label>' . esc_html__('Self-registration form', 'ai-eshop-optimizer') . '</label></th><td>';
            echo AIEO_Event_CPT::gf_form_select('aieo-event-gf', 0); 
            echo '<p class="description">' . esc_html__('Optional — a Gravity Form guests can use to register themselves (the self-registration front-end is added in a later phase).', 'ai-eshop-optimizer') . '</p></td></tr>';
        }

        
        echo '<tr><th><label for="aieo-event-invite-subject">' . esc_html__('Invitation subject', 'ai-eshop-optimizer') . '</label></th><td>';
        echo '<input type="text" id="aieo-event-invite-subject" class="large-text" placeholder="' . esc_attr__('e.g. You’re invited — Spring Brand Showcase', 'ai-eshop-optimizer') . '"></td></tr>';
        echo '<tr><th><label for="aieo-event-invite-body">' . esc_html__('Invitation body', 'ai-eshop-optimizer') . '</label></th><td>';
        wp_editor('', 'aieoeventinvitebody', array(
            'textarea_name' => 'invite_body',
            'textarea_rows' => 8,
            'media_buttons' => true,
            'teeny'         => false,
            'tinymce'       => true,
            'quicktags'     => true,
        ));
        echo '<p class="description">' . esc_html__('The invitation email content (sent to your guest list in a later phase). Rich text and images are supported.', 'ai-eshop-optimizer') . '</p></td></tr>';

        
        $cur_sym = function_exists('get_woocommerce_currency_symbol') ? get_woocommerce_currency_symbol() : '';
        $cur_code = function_exists('get_woocommerce_currency') ? get_woocommerce_currency() : '';
        echo '<tr><th><label for="aieo-event-fee">' . esc_html__('Admission fee', 'ai-eshop-optimizer') . '</label></th><td>';
        echo '<label style="margin-right:18px;">' . esc_html(trim(sprintf(__('Fee %s', 'ai-eshop-optimizer'), $cur_sym !== '' ? '(' . $cur_sym . ')' : ''))) . ' <input type="number" min="0" step="0.01" id="aieo-event-fee" style="width:120px;"></label>';
        echo '<label>' . esc_html__('Currency', 'ai-eshop-optimizer') . ' <input type="text" id="aieo-event-currency" maxlength="3" value="' . esc_attr($cur_code) . '" style="width:80px;text-transform:uppercase;"></label>';
        echo '<p class="description">' . esc_html__('Optional admission price. Not charged yet — recorded for a future paid-events phase.', 'ai-eshop-optimizer') . '</p></td></tr>';

        echo '</tbody></table>';
        echo '<p><button type="submit" class="button button-primary" id="aieo-event-create-btn">' . esc_html__('Create event', 'ai-eshop-optimizer') . '</button> <span id="aieo-event-create-status" style="margin-left:10px;color:#646970;"></span></p>';
        echo '</form>';
        echo '</div>';

        
        $events = get_posts(array(
            'post_type'   => AIEO_Event_CPT::POST_TYPE,
            'post_status' => array('publish', 'draft', 'pending', 'future'),
            'numberposts' => 200,
            'orderby'     => 'date',
            'order'       => 'DESC',
        ));
        echo '<h3 style="margin-top:28px;">' . esc_html__('Your events', 'ai-eshop-optimizer') . '</h3>';
        if (empty($events)) {
            echo '<p>' . esc_html__('No events yet — create one above.', 'ai-eshop-optimizer') . '</p>';
        } else {
            echo '<table class="wp-list-table widefat fixed striped"><thead><tr>';
            echo '<th>' . esc_html__('Name', 'ai-eshop-optimizer') . '</th><th>' . esc_html__('Status', 'ai-eshop-optimizer') . '</th><th>' . esc_html__('Schedule', 'ai-eshop-optimizer') . '</th><th>' . esc_html__('Participants', 'ai-eshop-optimizer') . '</th><th>' . esc_html__('Page', 'ai-eshop-optimizer') . '</th>';
            echo '</tr></thead><tbody>';
            $sstate_labels = array('before' => __('upcoming', 'ai-eshop-optimizer'), 'live' => __('live', 'ai-eshop-optimizer'), 'ended' => __('ended', 'ai-eshop-optimizer'));
            foreach ($events as $e) {
                $edit = get_edit_post_link($e->ID);
                $view = get_permalink($e->ID);
                echo '<tr>';
                echo '<td><strong><a href="' . esc_url($edit) . '">' . esc_html(get_the_title($e) ?: __('(untitled)', 'ai-eshop-optimizer')) . '</a></strong></td>';
                $sstate = method_exists('AIEO_Event_CPT', 'schedule_state') ? AIEO_Event_CPT::schedule_state($e->ID) : 'live';
                echo '<td>' . esc_html(get_post_status($e)) . ' <span style="color:#646970;font-size:12px;">· ' . esc_html(isset($sstate_labels[$sstate]) ? $sstate_labels[$sstate] : $sstate) . '</span></td>';
                $start_disp = AIEO_Event_CPT::fmt_dt(get_post_meta($e->ID, AIEO_Event_CPT::META_START, true));
                $end_disp   = AIEO_Event_CPT::fmt_dt(get_post_meta($e->ID, AIEO_Event_CPT::META_END, true));
                if ($start_disp === '' && $end_disp === '') {
                    $sched_html = '<span style="color:#646970;">' . esc_html__('Always open', 'ai-eshop-optimizer') . '</span>';
                } else {
                    $sched_html = esc_html__('Starts', 'ai-eshop-optimizer') . ': ' . esc_html($start_disp !== '' ? $start_disp : '—')
                        . '<br>' . esc_html__('Ends', 'ai-eshop-optimizer') . ': ' . esc_html($end_disp !== '' ? $end_disp : '—');
                }
                echo '<td style="font-size:12px;line-height:1.5;white-space:nowrap;">' . $sched_html . '</td>'; 
                $c = class_exists('AIEO_Event_Participants') ? AIEO_Event_Participants::counts($e->ID) : array('invited' => 0, 'confirmed' => 0, 'declined' => 0, 'total' => 0);
                $manage = self::tab_url(array('manage' => $e->ID));
                echo '<td>' . (int) $c['total'] . ' <span style="color:#646970;font-size:12px;">('
                    . (int) $c['confirmed'] . ' ' . esc_html__('confirmed', 'ai-eshop-optimizer')
                    . ', ' . (int) $c['invited'] . ' ' . esc_html__('invited', 'ai-eshop-optimizer')
                    . ((int) $c['declined'] > 0 ? ', ' . (int) $c['declined'] . ' ' . esc_html__('declined', 'ai-eshop-optimizer') : '')
                    . ')</span><br><a href="' . esc_url($manage) . '">' . esc_html__('Manage participants →', 'ai-eshop-optimizer') . '</a></td>';
                echo '<td style="white-space:nowrap;"><a href="' . esc_url($edit) . '">' . esc_html__('Edit', 'ai-eshop-optimizer') . '</a> · <a href="' . esc_url($view) . '" target="_blank" rel="noopener">' . esc_html__('View', 'ai-eshop-optimizer') . '</a></td>';
                echo '</tr>';
            }
            echo '</tbody></table>';
        }

        
        $eset      = self::get_settings();
        $msg_soon  = isset($eset['msg_soon'])  ? (string) $eset['msg_soon']  : '';
        $msg_ended = isset($eset['msg_ended']) ? (string) $eset['msg_ended'] : '';
        echo '<h3 style="margin-top:28px;">' . esc_html__('Page messages', 'ai-eshop-optimizer') . '</h3>';
        echo '<div class="card" style="max-width:100%;padding:16px 20px;">';
        echo '<p class="description">' . esc_html__('Shown on the event page to visitors. These apply to ALL events. Leave a field empty to use the built-in (translatable) default.', 'ai-eshop-optimizer') . '</p>';
        echo '<table class="form-table"><tbody>';
        echo '<tr><th><label for="aieo-event-msg-soon">' . esc_html__('“Coming soon” message', 'ai-eshop-optimizer') . '</label></th><td>';
        echo '<textarea id="aieo-event-msg-soon" rows="2" class="large-text">' . esc_textarea($msg_soon) . '</textarea>';
        echo '<p class="description">' . esc_html__('Shown before an event starts. Use %s where the start date should appear (optional).', 'ai-eshop-optimizer') . '</p></td></tr>';
        echo '<tr><th><label for="aieo-event-msg-ended">' . esc_html__('“Ended” message', 'ai-eshop-optimizer') . '</label></th><td>';
        echo '<textarea id="aieo-event-msg-ended" rows="2" class="large-text">' . esc_textarea($msg_ended) . '</textarea>';
        echo '<p class="description">' . esc_html__('Shown after an event ends.', 'ai-eshop-optimizer') . '</p></td></tr>';
        echo '</tbody></table>';
        echo '<p><button type="button" class="button" id="aieo-event-settings-save">' . esc_html__('Save messages', 'ai-eshop-optimizer') . '</button> <span id="aieo-event-settings-status" style="margin-left:10px;color:#646970;"></span></p>';
        echo '</div>';
    }

    public function ajax_save_settings() {
        if (!check_ajax_referer(self::NONCE, 'nonce', false)) {
            wp_send_json_error(array('message' => __('Security check failed.', 'ai-eshop-optimizer')));
        }
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('You are not allowed to do this.', 'ai-eshop-optimizer')));
        }
        $ended = isset($_POST['msg_ended']) ? sanitize_textarea_field(wp_unslash($_POST['msg_ended'])) : '';
        $soon  = isset($_POST['msg_soon'])  ? sanitize_textarea_field(wp_unslash($_POST['msg_soon']))  : '';
        $settings = self::get_settings(); 
        $settings['msg_soon']  = $soon;
        $settings['msg_ended'] = $ended;
        update_option(self::SETTINGS_OPTION, $settings, false);
        wp_send_json_success(array('saved' => true));
    }

    private function image_field($which, $label) {
        echo '<div class="aieo-event-image-field" data-which="' . esc_attr($which) . '" style="flex:1;min-width:200px;">';
        echo '<label><strong>' . esc_html($label) . '</strong></label><br>';
        echo '<img class="aieo-event-image-preview" src="" style="max-width:100%;height:auto;border:1px solid #dcdcde;border-radius:6px;display:none;"><br>';
        echo '<input type="hidden" class="aieo-event-image-id" value="0">';
        echo '<button type="button" class="button aieo-event-image-select">' . esc_html__('Select image', 'ai-eshop-optimizer') . '</button> ';
        echo '<button type="button" class="button-link aieo-event-image-remove" style="display:none;">' . esc_html__('Remove', 'ai-eshop-optimizer') . '</button>';
        echo '</div>';
    }

    public function ajax_save() {
        if (!check_ajax_referer(self::NONCE, 'nonce', false)) {
            wp_send_json_error(array('message' => __('Security check failed.', 'ai-eshop-optimizer')));
        }
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('You are not allowed to do this.', 'ai-eshop-optimizer')));
        }
        if (!class_exists('AIEO_Event_CPT')) {
            wp_send_json_error(array('message' => __('Events are unavailable.', 'ai-eshop-optimizer')));
        }
        $post_id = isset($_POST['post_id']) ? (int) $_POST['post_id'] : 0;
        $name    = isset($_POST['name']) ? sanitize_text_field(wp_unslash($_POST['name'])) : '';
        if ($name === '') {
            wp_send_json_error(array('message' => __('Please enter an event name.', 'ai-eshop-optimizer')));
        }

        $location      = isset($_POST['location'])      ? sanitize_text_field(wp_unslash($_POST['location']))          : '';
        $desc          = isset($_POST['short_desc'])    ? sanitize_textarea_field(wp_unslash($_POST['short_desc']))    : '';
        $img_d         = isset($_POST['img_desktop'])   ? (int) $_POST['img_desktop']                                  : 0;
        $img_m         = isset($_POST['img_mobile'])    ? (int) $_POST['img_mobile']                                   : 0;
        $start         = isset($_POST['start'])         ? sanitize_text_field(wp_unslash($_POST['start']))            : '';
        $end           = isset($_POST['end'])           ? sanitize_text_field(wp_unslash($_POST['end']))              : '';
        $rsvp_deadline = isset($_POST['rsvp_deadline']) ? sanitize_text_field(wp_unslash($_POST['rsvp_deadline']))    : '';
        $gf            = isset($_POST['gf_id'])          ? (int) $_POST['gf_id']                                        : 0;

        $invite_subject = isset($_POST['invite_subject']) ? sanitize_text_field(wp_unslash($_POST['invite_subject'])) : '';
        $invite_body    = isset($_POST['invite_body'])    ? wp_kses_post(wp_unslash($_POST['invite_body']))           : '';

        $fee      = isset($_POST['fee'])      ? (float) $_POST['fee']                                              : 0;
        $currency = isset($_POST['currency']) ? strtoupper(sanitize_text_field(wp_unslash($_POST['currency'])))   : '';

        $brands     = isset($_POST['brands'])     ? array_map('intval', (array) wp_unslash($_POST['brands']))     : array();
        $categories = isset($_POST['categories']) ? array_map('intval', (array) wp_unslash($_POST['categories'])) : array();
        $products   = class_exists('AIEO_DMM_Product_Picker')
            ? AIEO_DMM_Product_Picker::roll_up_to_parents(AIEO_DMM_Product_Picker::collect_ids('event_products'))
            : (isset($_POST['event_products']) ? array_map('intval', (array) wp_unslash($_POST['event_products'])) : array());

        $args = array(
            'post_type'   => AIEO_Event_CPT::POST_TYPE,
            'post_title'  => $name,
            'post_status' => 'publish',
        );
        if ($post_id > 0) {
            $args['ID'] = $post_id;
            $res = wp_update_post($args, true);
        } else {
            $res = wp_insert_post($args, true);
        }
        if (is_wp_error($res)) {
            wp_send_json_error(array('message' => $res->get_error_message()));
        }
        $post_id = (int) $res;

        
        
        
        AIEO_Event_CPT::persist_fields(
            $post_id, $gf, $desc, $location, $img_d, $img_m,
            $start, $end, $rsvp_deadline, $brands, $categories, $products, $fee, $currency
        );
        
        
        update_post_meta($post_id, AIEO_Event_CPT::META_INVITE_SUBJECT, $invite_subject);
        update_post_meta($post_id, AIEO_Event_CPT::META_INVITE_BODY, $invite_body);

        $map_url = isset($_POST['map_url']) ? esc_url_raw(wp_unslash($_POST['map_url'])) : '';
        update_post_meta($post_id, AIEO_Event_CPT::META_MAP_URL, $map_url);

        wp_send_json_success(array(
            'post_id'  => $post_id,
            'title'    => get_the_title($post_id),
            'edit_url' => get_edit_post_link($post_id, 'raw'),
            'view_url' => get_permalink($post_id),
            'status'   => get_post_status($post_id),
        ));
    }

    

    
    private static function stash_result($data) {
        set_transient('aieo_events_import_' . get_current_user_id(), $data, 60);
    }

    
    private static function pull_result() {
        $k = 'aieo_events_import_' . get_current_user_id();
        $d = get_transient($k);
        if ($d !== false) { delete_transient($k); }
        return is_array($d) ? $d : null;
    }

    
    private function render_manage_screen($event_id) {
        $event_id = (int) $event_id;
        $title    = get_the_title($event_id);

        echo '<h2>' . esc_html(sprintf(__('Participants — %s', 'ai-eshop-optimizer'), $title !== '' ? $title : __('(untitled)', 'ai-eshop-optimizer'))) . '</h2>';
        echo '<p><a href="' . esc_url(self::tab_url()) . '">&larr; ' . esc_html__('Back to events', 'ai-eshop-optimizer') . '</a></p>';

        
        $res = self::pull_result();
        if ($res) {
            if (!empty($res['error'])) {
                echo '<div class="notice notice-error"><p>' . esc_html((string) $res['error']) . '</p></div>';
            } elseif (!empty($res['notice'])) {
                echo '<div class="notice notice-success"><p>' . esc_html((string) $res['notice']) . '</p></div>';
            } else {
                $mode_label = (isset($res['mode']) && $res['mode'] === 'overwrite') ? __('Overwrite', 'ai-eshop-optimizer') : __('Update', 'ai-eshop-optimizer');
                $line = sprintf(
                    
                    __('%1$s complete — %2$d rows read: %3$d added, %4$d updated, %5$d removed, %6$d skipped.', 'ai-eshop-optimizer'),
                    $mode_label,
                    (int) ($res['total'] ?? 0), (int) ($res['inserted'] ?? 0), (int) ($res['updated'] ?? 0),
                    (int) ($res['removed'] ?? 0), (int) ($res['skipped'] ?? 0)
                );
                $cls = !empty($res['errors']) ? 'notice-warning' : 'notice-success';
                echo '<div class="notice ' . esc_attr($cls) . '"><p>' . esc_html($line) . '</p>';
                if (!empty($res['errors']) && is_array($res['errors'])) {
                    $shown = array_slice($res['errors'], 0, 12);
                    echo '<ul style="margin:4px 0 0 18px;list-style:disc;font-size:12px;color:#646970;">';
                    foreach ($shown as $err) { echo '<li>' . esc_html((string) $err) . '</li>'; }
                    if (count($res['errors']) > count($shown)) {
                        echo '<li>' . esc_html(sprintf(__('…and %d more.', 'ai-eshop-optimizer'), count($res['errors']) - count($shown))) . '</li>';
                    }
                    echo '</ul>';
                }
                echo '</div>';
            }
        }

        $st = class_exists('AIEO_Event_Participants')
            ? AIEO_Event_Participants::stats($event_id)
            : array('total' => 0, 'confirmed' => 0, 'declined' => 0, 'invited' => 0, 'responded' => 0, 'response_rate' => 0, 'imported' => 0, 'self_registered' => 0, 'invited_sent' => 0);
        $chip = static function ($label, $value, $color, $suffix = '') {
            return '<span style="display:inline-block;margin:0 16px 8px 0;"><strong style="font-size:18px;color:' . esc_attr($color) . ';">' . esc_html((string) $value . $suffix) . '</strong> <span style="color:#646970;font-size:13px;">' . esc_html($label) . '</span></span>';
        };
        echo '<div style="margin:6px 0 6px;">';
        echo $chip(__('total', 'ai-eshop-optimizer'), (int) $st['total'], '#1d2327'); 
        echo $chip(__('confirmed', 'ai-eshop-optimizer'), (int) $st['confirmed'], '#1f7a45'); 
        echo $chip(__('declined', 'ai-eshop-optimizer'), (int) $st['declined'], '#9a3a36'); 
        echo $chip(__('awaiting reply', 'ai-eshop-optimizer'), (int) $st['invited'], '#8a6d1a'); 
        echo $chip(__('response rate', 'ai-eshop-optimizer'), (int) $st['response_rate'], '#2271b1', '%'); 
        echo '</div>';
        echo '<p style="margin:0 0 10px;color:#646970;font-size:12px;">'
            . esc_html(sprintf(__('%1$d imported · %2$d self-registered · %3$d invitation(s) sent', 'ai-eshop-optimizer'), (int) $st['imported'], (int) $st['self_registered'], (int) $st['invited_sent']))
            . '</p>';

        
        echo '<div class="card" style="max-width:100%;padding:16px 20px;">';
        echo '<h3 style="margin-top:0;">' . esc_html__('Import participants', 'ai-eshop-optimizer') . '</h3>';
        echo '<form method="post" enctype="multipart/form-data" action="' . esc_url(admin_url('admin-post.php')) . '">';
        echo '<input type="hidden" name="action" value="aieo_events_import">';
        echo '<input type="hidden" name="event_id" value="' . esc_attr($event_id) . '">';
        wp_nonce_field('aieo_events_import');
        echo '<p><input type="file" name="participants_file" accept=".xlsx,.csv" required></p>';
        echo '<fieldset style="margin:6px 0 10px;">';
        echo '<label style="display:block;margin-bottom:6px;"><input type="radio" name="mode" value="update" checked> <strong>' . esc_html__('Update', 'ai-eshop-optimizer') . '</strong> — ' . esc_html__('add new guests and refresh existing ones (matched by email). Never removes anyone.', 'ai-eshop-optimizer') . '</label>';
        echo '<label style="display:block;"><input type="radio" name="mode" value="overwrite"> <strong>' . esc_html__('Overwrite', 'ai-eshop-optimizer') . '</strong> — ' . esc_html__('make my imported list exactly match this file. Removes only the guests I previously imported who are no longer in the file (self-registrations, other staff’s imports and existing RSVP responses are kept).', 'ai-eshop-optimizer') . '</label>';
        echo '</fieldset>';
        echo '<p class="description" style="max-width:760px;">' . esc_html__('Accepted: .xlsx or .csv with a header row. Recognised columns (Greek or English, any order): Salutation, Title, Name, Surname, Department, Organization, Email (required), Phone.', 'ai-eshop-optimizer') . '</p>';
        echo '<p><button type="submit" class="button button-primary">' . esc_html__('Upload and import', 'ai-eshop-optimizer') . '</button></p>';
        echo '</form>';
        echo '</div>';

        
        $this->render_invites_card($event_id);

        
        echo '<div class="card" style="max-width:100%;padding:16px 20px;">';
        echo '<h3 style="margin-top:0;">' . esc_html__('Self-registration', 'ai-eshop-optimizer') . '</h3>';
        echo '<p class="description" style="max-width:820px;">' . esc_html__('Let guests sign themselves up: add the AIEO “Event Registration” block to this event’s page, or paste the shortcode below into its content. Self-registrations appear in the guest list tagged “Self-registered”.', 'ai-eshop-optimizer') . '</p>';
        echo '<p><code>[aieo_event_register]</code>';
        $ev_edit = get_edit_post_link($event_id);
        if ($ev_edit) { echo ' &middot; <a href="' . esc_url($ev_edit) . '">' . esc_html__('Edit event →', 'ai-eshop-optimizer') . '</a>'; }
        echo '</p></div>';

        
        $search = isset($_GET['psearch']) ? sanitize_text_field(wp_unslash($_GET['psearch'])) : ''; 
        $per    = 50;
        $page   = max(1, isset($_GET['ppage']) ? (int) $_GET['ppage'] : 1); 
        $total  = class_exists('AIEO_Event_Participants') ? AIEO_Event_Participants::count_for_event($event_id, array('search' => $search)) : 0;
        $rows   = class_exists('AIEO_Event_Participants') ? AIEO_Event_Participants::get_for_event($event_id, array(
            'search'  => $search,
            'orderby' => 'last_name',
            'order'   => 'ASC',
            'limit'   => $per,
            'offset'  => ($page - 1) * $per,
        )) : array();

        echo '<h3 style="margin-top:28px;display:inline-block;margin-right:14px;">' . esc_html__('Guest list', 'ai-eshop-optimizer') . '</h3>';
        if ((int) $st['total'] > 0) {
            $export_url = wp_nonce_url(admin_url('admin-post.php?action=aieo_events_export&event_id=' . $event_id), 'aieo_events_export');
            echo '<a href="' . esc_url($export_url) . '" class="button">' . esc_html__('Export to XLSX', 'ai-eshop-optimizer') . '</a>';
        }

        
        echo '<form method="get" style="margin:8px 0;">';
        echo '<input type="hidden" name="page" value="ai-eshop-dmm">';
        echo '<input type="hidden" name="dmm_tab" value="events">';
        echo '<input type="hidden" name="manage" value="' . esc_attr($event_id) . '">';
        echo '<input type="search" name="psearch" value="' . esc_attr($search) . '" class="regular-text" placeholder="' . esc_attr__('Search name, email, organization…', 'ai-eshop-optimizer') . '"> ';
        echo '<button type="submit" class="button">' . esc_html__('Search', 'ai-eshop-optimizer') . '</button>';
        if ($search !== '') {
            echo ' <a href="' . esc_url(self::tab_url(array('manage' => $event_id))) . '" class="button-link">' . esc_html__('Clear', 'ai-eshop-optimizer') . '</a>';
        }
        echo '</form>';

        if (empty($rows)) {
            echo '<p>' . esc_html($search !== '' ? __('No matching participants.', 'ai-eshop-optimizer') : __('No participants yet — import a list above.', 'ai-eshop-optimizer')) . '</p>';
        } else {
            $src_labels = array('imported' => __('Imported', 'ai-eshop-optimizer'), 'self-registered' => __('Self-registered', 'ai-eshop-optimizer'));
            $rs_labels  = array('invited' => __('Invited', 'ai-eshop-optimizer'), 'confirmed' => __('Confirmed', 'ai-eshop-optimizer'), 'declined' => __('Declined', 'ai-eshop-optimizer'));
            echo '<table class="wp-list-table widefat fixed striped"><thead><tr>';
            foreach (array(
                __('Salutation', 'ai-eshop-optimizer'), __('Title', 'ai-eshop-optimizer'), __('Name', 'ai-eshop-optimizer'),
                __('Surname', 'ai-eshop-optimizer'), __('Organization', 'ai-eshop-optimizer'), __('Department', 'ai-eshop-optimizer'),
                __('Email', 'ai-eshop-optimizer'), __('Phone', 'ai-eshop-optimizer'), __('Source', 'ai-eshop-optimizer'),
                __('RSVP', 'ai-eshop-optimizer'), '',
            ) as $h) {
                echo '<th>' . esc_html($h) . '</th>';
            }
            echo '</tr></thead><tbody>';
            foreach ($rows as $row) {
                $pid    = (int) $row->participant_id;
                $del    = wp_nonce_url(
                    admin_url('admin-post.php?action=aieo_events_participant_delete&event_id=' . $event_id . '&pid=' . $pid),
                    'aieo_events_pdel_' . $pid
                );
                $src    = isset($src_labels[$row->source]) ? $src_labels[$row->source] : $row->source;
                $rs     = isset($rs_labels[$row->rsvp_status]) ? $rs_labels[$row->rsvp_status] : $row->rsvp_status;
                echo '<tr>';
                echo '<td>' . esc_html((string) $row->salutation) . '</td>';
                echo '<td>' . esc_html((string) $row->title) . '</td>';
                echo '<td>' . esc_html((string) $row->first_name) . '</td>';
                echo '<td>' . esc_html((string) $row->last_name) . '</td>';
                echo '<td>' . esc_html((string) $row->organization) . '</td>';
                echo '<td>' . esc_html((string) $row->department) . '</td>';
                echo '<td>' . esc_html((string) $row->email) . '</td>';
                echo '<td>' . esc_html((string) $row->phone) . '</td>';
                echo '<td>' . esc_html((string) $src) . '</td>';
                echo '<td>' . esc_html((string) $rs) . '</td>';
                $rsvp_url = class_exists('AIEO_Event_RSVP') ? AIEO_Event_RSVP::url($row->rsvp_token) : '';
                echo '<td style="white-space:nowrap;">';
                if ($rsvp_url !== '') {
                    echo '<a href="' . esc_url($rsvp_url) . '" target="_blank" rel="noopener" title="' . esc_attr__('Open this guest’s RSVP page', 'ai-eshop-optimizer') . '">' . esc_html__('RSVP', 'ai-eshop-optimizer') . '</a> · ';
                }
                echo '<a href="' . esc_url($del) . '" onclick="return confirm(\'' . esc_js(__('Remove this participant?', 'ai-eshop-optimizer')) . '\');" style="color:#b32d2e;">' . esc_html__('Remove', 'ai-eshop-optimizer') . '</a></td>';
                echo '</tr>';
            }
            echo '</tbody></table>';

            
            $pages = (int) ceil($total / $per);
            if ($pages > 1) {
                echo '<p style="margin-top:10px;">';
                for ($p = 1; $p <= $pages; $p++) {
                    if ($p === $page) {
                        echo '<span style="display:inline-block;padding:3px 9px;margin:0 2px;background:#2271b1;color:#fff;border-radius:3px;">' . (int) $p . '</span>';
                    } else {
                        $u = self::tab_url(array('manage' => $event_id, 'psearch' => $search, 'ppage' => $p));
                        echo '<a href="' . esc_url($u) . '" style="display:inline-block;padding:3px 9px;margin:0 2px;">' . (int) $p . '</a>';
                    }
                }
                echo '</p>';
            }
            echo '<p class="description">' . esc_html(sprintf(__('Showing %1$d of %2$d participants.', 'ai-eshop-optimizer'), count($rows), (int) $total)) . '</p>';
        }
    }

    
    public function handle_import() {
        if (!current_user_can('edit_posts')) {
            wp_die(esc_html__('You are not allowed to do this.', 'ai-eshop-optimizer'));
        }
        check_admin_referer('aieo_events_import');

        $event_id = isset($_POST['event_id']) ? (int) $_POST['event_id'] : 0;
        $mode     = (isset($_POST['mode']) && $_POST['mode'] === 'overwrite') ? 'overwrite' : 'update';

        if ($event_id <= 0 || !class_exists('AIEO_Event_CPT') || get_post_type($event_id) !== AIEO_Event_CPT::POST_TYPE) {
            self::stash_result(array('error' => __('Invalid event.', 'ai-eshop-optimizer')));
            wp_safe_redirect(self::tab_url());
            exit;
        }
        $redirect = self::tab_url(array('manage' => $event_id));

        if (empty($_FILES['participants_file']) || !isset($_FILES['participants_file']['error']) || (int) $_FILES['participants_file']['error'] !== UPLOAD_ERR_OK) {
            self::stash_result(array('error' => __('No file was uploaded, or the upload failed.', 'ai-eshop-optimizer')));
            wp_safe_redirect($redirect);
            exit;
        }
        $file = $_FILES['participants_file']; 
        if (empty($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
            self::stash_result(array('error' => __('The upload could not be verified.', 'ai-eshop-optimizer')));
            wp_safe_redirect($redirect);
            exit;
        }
        $size = isset($file['size']) ? (int) $file['size'] : 0;
        if ($size <= 0 || $size > 12 * 1024 * 1024) {
            self::stash_result(array('error' => __('The file is empty or larger than 12 MB.', 'ai-eshop-optimizer')));
            wp_safe_redirect($redirect);
            exit;
        }
        $ext = strtolower(pathinfo(isset($file['name']) ? (string) $file['name'] : '', PATHINFO_EXTENSION));
        if (!in_array($ext, array('xlsx', 'csv'), true)) {
            self::stash_result(array('error' => __('Unsupported file type. Upload a .xlsx or .csv file.', 'ai-eshop-optimizer')));
            wp_safe_redirect($redirect);
            exit;
        }

        if (!class_exists('AIEO_Event_Importer') && defined('AIEO_DIR') && file_exists(AIEO_DIR . 'includes/dmm/events/class-aieo-event-importer.php')) {
            require_once AIEO_DIR . 'includes/dmm/events/class-aieo-event-importer.php';
        }
        if (!class_exists('AIEO_Event_Importer')) {
            self::stash_result(array('error' => __('The importer is unavailable.', 'ai-eshop-optimizer')));
            wp_safe_redirect($redirect);
            exit;
        }

        $parsed = AIEO_Event_Importer::parse_file($file['tmp_name'], $ext);
        if (is_wp_error($parsed)) {
            self::stash_result(array('error' => $parsed->get_error_message()));
            wp_safe_redirect($redirect);
            exit;
        }
        $summary         = AIEO_Event_Importer::run_import($event_id, $parsed, $mode, get_current_user_id());
        $summary['mode'] = $mode;
        self::stash_result($summary);
        wp_safe_redirect($redirect);
        exit;
    }

    
    public function handle_participant_delete() {
        if (!current_user_can('edit_posts')) {
            wp_die(esc_html__('You are not allowed to do this.', 'ai-eshop-optimizer'));
        }
        $event_id = isset($_GET['event_id']) ? (int) $_GET['event_id'] : 0;
        $pid      = isset($_GET['pid']) ? (int) $_GET['pid'] : 0;
        check_admin_referer('aieo_events_pdel_' . $pid);

        if ($event_id > 0 && $pid > 0 && class_exists('AIEO_Event_Participants')) {
            global $wpdb;
            $wpdb->delete(AIEO_Event_Participants::table(), array('participant_id' => $pid, 'event_id' => $event_id), array('%d', '%d'));
            self::stash_result(array('notice' => __('Participant removed.', 'ai-eshop-optimizer')));
        }
        wp_safe_redirect(self::tab_url(array('manage' => $event_id)));
        exit;
    }

    

    
    private function render_invites_card($event_id) {
        $event_id = (int) $event_id;
        if (!class_exists('AIEO_Event_Invites') && defined('AIEO_DIR') && file_exists(AIEO_DIR . 'includes/dmm/events/class-aieo-event-invites.php')) {
            require_once AIEO_DIR . 'includes/dmm/events/class-aieo-event-invites.php';
        }
        $subject = (string) get_post_meta($event_id, AIEO_Event_CPT::META_INVITE_SUBJECT, true);
        $body    = (string) get_post_meta($event_id, AIEO_Event_CPT::META_INVITE_BODY, true);

        echo '<div class="card" style="max-width:100%;padding:16px 20px;">';
        echo '<h3 style="margin-top:0;">' . esc_html__('Invitations', 'ai-eshop-optimizer') . '</h3>';

        if ($subject === '' || $body === '' || !class_exists('AIEO_Event_Invites')) {
            echo '<p class="description">' . esc_html__('Set the invitation subject and body on the event’s edit screen, then return here to preview and send.', 'ai-eshop-optimizer') . ' ';
            $edit = get_edit_post_link($event_id);
            if ($edit) { echo '<a href="' . esc_url($edit) . '">' . esc_html__('Edit event →', 'ai-eshop-optimizer') . '</a>'; }
            echo '</p></div>';
            return;
        }

        echo '<p class="description" style="max-width:840px;">' . esc_html__('Merge tags for the subject and body:', 'ai-eshop-optimizer')
            . ' <code>{salutation}</code> <code>{title}</code> <code>{name}</code> <code>{first_name}</code> <code>{last_name}</code> <code>{organization}</code> <code>{department}</code> <code>{event_title}</code> <code>{event_date}</code> <code>{event_location}</code> <code>{event_map_link}</code> <code>{event_map_url}</code> <code>{rsvp_link}</code> <code>{rsvp_url}</code>. '
            . esc_html__('If you don’t place an RSVP tag, an RSVP button is appended automatically.', 'ai-eshop-optimizer') . '</p>';

        
        $settings = self::get_settings();
        $live     = !empty($settings['live_send']);
        echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '" style="margin:10px 0 14px;padding:10px 12px;background:' . ($live ? '#eef7f0' : '#fcf3e6') . ';border-radius:6px;">';
        echo '<input type="hidden" name="action" value="aieo_events_invites_settings">';
        echo '<input type="hidden" name="event_id" value="' . esc_attr($event_id) . '">';
        wp_nonce_field('aieo_events_invites_settings');
        echo '<label><input type="checkbox" name="live_send" value="1" ' . checked($live, true, false) . '> <strong>' . esc_html__('Enable live sending', 'ai-eshop-optimizer') . '</strong></label> ';
        echo '<button type="submit" class="button button-small">' . esc_html__('Save', 'ai-eshop-optimizer') . '</button>';
        echo '<span style="margin-left:10px;font-weight:600;color:' . ($live ? '#1f7a45' : '#8a6d1a') . ';">'
            . ($live ? esc_html__('Live sending is ON — Send delivers real emails.', 'ai-eshop-optimizer') : esc_html__('Live sending is OFF — Send runs a dry run (no emails sent).', 'ai-eshop-optimizer')) . '</span>';
        echo '</form>';

        
        $counts  = AIEO_Event_Invites::scope_counts($event_id);
        $confirm = $live ? "return confirm('" . esc_js(__('Send invitations now? Real emails will be delivered.', 'ai-eshop-optimizer')) . "');" : 'return true;';
        echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '" onsubmit="' . esc_attr($confirm) . '">';
        echo '<input type="hidden" name="action" value="aieo_events_invites_send">';
        echo '<input type="hidden" name="event_id" value="' . esc_attr($event_id) . '">';
        wp_nonce_field('aieo_events_invites');
        echo '<fieldset style="margin:4px 0 12px;">';
        echo '<label style="margin-right:18px;"><input type="radio" name="scope" value="pending" checked> ' . esc_html(sprintf(__('Pending — not yet responded (%d)', 'ai-eshop-optimizer'), (int) $counts['pending'])) . '</label>';
        echo '<label style="margin-right:18px;"><input type="radio" name="scope" value="new"> ' . esc_html(sprintf(__('New — never invited (%d)', 'ai-eshop-optimizer'), (int) $counts['new'])) . '</label>';
        echo '<label><input type="radio" name="scope" value="all"> ' . esc_html(sprintf(__('All participants (%d)', 'ai-eshop-optimizer'), (int) $counts['all'])) . '</label>';
        echo '</fieldset>';
        echo '<p><button type="submit" class="button button-primary">' . ($live ? esc_html__('Send invitations', 'ai-eshop-optimizer') : esc_html__('Dry run (no emails sent)', 'ai-eshop-optimizer')) . '</button></p>';
        echo '</form>';

        
        $sample = AIEO_Event_Invites::sample(get_post($event_id));
        echo '<h4 style="margin:18px 0 6px;">' . esc_html__('Preview', 'ai-eshop-optimizer') . '</h4>';
        echo '<p style="margin:0 0 6px;"><strong>' . esc_html__('Subject', 'ai-eshop-optimizer') . ':</strong> ' . esc_html($sample['subject']) . '</p>';
        echo '<iframe title="' . esc_attr__('Invitation preview', 'ai-eshop-optimizer') . '" sandbox="" srcdoc="' . esc_attr($sample['html']) . '" style="width:100%;max-width:640px;height:520px;border:1px solid #dcdcde;border-radius:6px;background:#fff;"></iframe>';

        echo '</div>';
    }

    
    public function handle_invites_send() {
        if (!current_user_can('edit_posts')) {
            wp_die(esc_html__('You are not allowed to do this.', 'ai-eshop-optimizer'));
        }
        check_admin_referer('aieo_events_invites');

        $event_id = isset($_POST['event_id']) ? (int) $_POST['event_id'] : 0;
        $scope    = (isset($_POST['scope']) && in_array($_POST['scope'], array('all', 'new', 'pending'), true)) ? sanitize_key(wp_unslash($_POST['scope'])) : 'pending';

        if ($event_id <= 0 || !class_exists('AIEO_Event_CPT') || get_post_type($event_id) !== AIEO_Event_CPT::POST_TYPE) {
            self::stash_result(array('error' => __('Invalid event.', 'ai-eshop-optimizer')));
            wp_safe_redirect(self::tab_url());
            exit;
        }
        $redirect = self::tab_url(array('manage' => $event_id));

        if (!class_exists('AIEO_Event_Invites') && defined('AIEO_DIR') && file_exists(AIEO_DIR . 'includes/dmm/events/class-aieo-event-invites.php')) {
            require_once AIEO_DIR . 'includes/dmm/events/class-aieo-event-invites.php';
        }
        if (!class_exists('AIEO_Event_Invites')) {
            self::stash_result(array('error' => __('The invitation sender is unavailable.', 'ai-eshop-optimizer')));
            wp_safe_redirect($redirect);
            exit;
        }

        $settings = self::get_settings();
        $live     = !empty($settings['live_send']);
        $res      = AIEO_Event_Invites::run($event_id, $scope, $live);

        if (isset($res['error']) && $res['error'] === 'no_template') {
            self::stash_result(array('error' => __('Set the invitation subject and body on the event’s edit screen first.', 'ai-eshop-optimizer')));
        } elseif (!$live) {
            self::stash_result(array('notice' => sprintf(
                
                __('Dry run — %1$d recipient(s) in scope “%2$s”. No emails were sent. Enable live sending above to send for real.', 'ai-eshop-optimizer'),
                (int) $res['recipients'], $scope
            )));
        } else {
            self::stash_result(array('notice' => sprintf(
                
                __('Invitations: %1$d sent, %2$d failed, %3$d skipped (of %4$d).', 'ai-eshop-optimizer'),
                (int) $res['sent'], (int) $res['failed'], (int) $res['skipped'], (int) $res['recipients']
            )));
        }
        wp_safe_redirect($redirect);
        exit;
    }

    
    public function handle_invites_settings() {
        if (!current_user_can('edit_posts')) {
            wp_die(esc_html__('You are not allowed to do this.', 'ai-eshop-optimizer'));
        }
        check_admin_referer('aieo_events_invites_settings');
        $event_id = isset($_POST['event_id']) ? (int) $_POST['event_id'] : 0;

        $settings = self::get_settings();
        $settings['live_send'] = !empty($_POST['live_send']);
        update_option(self::SETTINGS_OPTION, $settings, false);

        self::stash_result(array('notice' => $settings['live_send']
            ? __('Live sending enabled.', 'ai-eshop-optimizer')
            : __('Live sending disabled (dry-run only).', 'ai-eshop-optimizer')));
        wp_safe_redirect($event_id > 0 ? self::tab_url(array('manage' => $event_id)) : self::tab_url());
        exit;
    }

    

    
    public function handle_export() {
        if (!current_user_can('edit_posts')) {
            wp_die(esc_html__('You are not allowed to do this.', 'ai-eshop-optimizer'));
        }
        check_admin_referer('aieo_events_export');

        $event_id = isset($_GET['event_id']) ? (int) $_GET['event_id'] : 0;
        if ($event_id <= 0 || !class_exists('AIEO_Event_CPT') || get_post_type($event_id) !== AIEO_Event_CPT::POST_TYPE) {
            wp_die(esc_html__('Invalid event.', 'ai-eshop-optimizer'));
        }
        if (!class_exists('AIEO_DMM_XLSX_Writer') && defined('AIEO_DIR') && file_exists(AIEO_DIR . 'includes/dmm/services/class-aieo-dmm-xlsx-writer.php')) {
            require_once AIEO_DIR . 'includes/dmm/services/class-aieo-dmm-xlsx-writer.php';
        }
        if (!class_exists('AIEO_DMM_XLSX_Writer') || !class_exists('AIEO_Event_Participants')) {
            wp_die(esc_html__('Export is unavailable.', 'ai-eshop-optimizer'));
        }

        $rows = AIEO_Event_Participants::get_for_event($event_id, array('orderby' => 'last_name', 'order' => 'ASC'));

        
        $fmt_dt = static function ($gmt) {
            $gmt = (string) $gmt;
            if ($gmt === '' || substr($gmt, 0, 4) === '0000') { return ''; }
            return get_date_from_gmt($gmt, 'Y-m-d H:i');
        };
        $src_labels = array('imported' => __('Imported', 'ai-eshop-optimizer'), 'self-registered' => __('Self-registered', 'ai-eshop-optimizer'));
        $rs_labels  = array('invited' => __('Invited', 'ai-eshop-optimizer'), 'confirmed' => __('Confirmed', 'ai-eshop-optimizer'), 'declined' => __('Declined', 'ai-eshop-optimizer'));

        $w = new AIEO_DMM_XLSX_Writer(__('Participants', 'ai-eshop-optimizer'));
        $w->add_header_row(array(
            __('Salutation', 'ai-eshop-optimizer'), __('Title', 'ai-eshop-optimizer'), __('First name', 'ai-eshop-optimizer'),
            __('Last name', 'ai-eshop-optimizer'), __('Organization', 'ai-eshop-optimizer'), __('Department', 'ai-eshop-optimizer'),
            __('Email', 'ai-eshop-optimizer'), __('Phone', 'ai-eshop-optimizer'), __('Source', 'ai-eshop-optimizer'),
            __('RSVP status', 'ai-eshop-optimizer'), __('Invited at', 'ai-eshop-optimizer'), __('Responded at', 'ai-eshop-optimizer'),
            __('Registered at', 'ai-eshop-optimizer'),
        ));
        foreach ($rows as $r) {
            $w->add_row(array(
                (string) $r->salutation, (string) $r->title, (string) $r->first_name, (string) $r->last_name,
                (string) $r->organization, (string) $r->department, (string) $r->email, (string) $r->phone,
                isset($src_labels[$r->source]) ? $src_labels[$r->source] : (string) $r->source,
                isset($rs_labels[$r->rsvp_status]) ? $rs_labels[$r->rsvp_status] : (string) $r->rsvp_status,
                $fmt_dt($r->invited_at), $fmt_dt($r->responded_at), $fmt_dt($r->created_at),
            ));
        }

        $slug = sanitize_title(get_the_title($event_id));
        $w->stream_download('participants-' . ($slug !== '' ? $slug : $event_id) . '.xlsx'); 
    }
}
