<?php
/**
 * Booking/Registration form component with ticket selection
 */
if (!defined('ABSPATH')) exit;

// Get registration settings
$em_accept_registration = $event_settings['em_accept_registration'] ?? 'no';
$em_registration_type = $event_settings['em_registration_type'] ?? 'internal';
$em_external_link = $event_settings['em_external_link'] ?? '';
$em_reg_btn_txt = $event_settings['em_reg_btn_txt'] ?? 'Register Now';
$em_reg_btn_color = $event_settings['em_reg_btn_color'] ?? '#3B82F6';
$em_registration_modal = $event_settings['em_registration_modal'] ?? 'inline'; // New setting: 'inline' or 'modal'

// Check if event is cancelled
$em_event_cancelled = $event_settings['em_event_cancelled'] ?? 'no';

// Don't show registration if event is cancelled
if ($em_event_cancelled === 'yes') {
    return;
}

// Only show if registration is enabled
if ($em_accept_registration !== 'yes') {
    return;
}

// Get ticket settings for internal registration
$em_tkt_selected = $event_settings['em_tkt_select'] ?? array();
$em_tkt_quantity = $event_settings['em_tkt_quantity'] ?? array();
$em_tkt_max_range = $event_settings['em_tkt_max_range'] ?? array();

// Free version fallback: If no tickets are selected, auto-assign the first available ticket
if (empty($em_tkt_selected)) {
    global $wpdb;
    $em_tickets_table_fallback = $wpdb->prefix . 'em_tickets';
    $first_ticket = $wpdb->get_row($wpdb->prepare("SELECT id FROM `$em_tickets_table_fallback` WHERE `status` = %s ORDER BY id ASC LIMIT 1", 'available'));
    if ($first_ticket) {
        $em_tkt_selected = array($first_ticket->id);
    }
}

// Get currency settings
$em_common_settings = get_option('awl_em_common_settings');
$em_currency = $em_common_settings['em_currency_code'] ?? 'USD';

// Payment gateways are Pro-only features
// PayPal, Stripe, Razorpay, and Square settings removed from free version.

// Get currency symbol (with prepared query for WP guidelines)
global $wpdb;
$em_currency_table = $wpdb->prefix . "em_currency";
$em_currency_symbol = $wpdb->get_row($wpdb->prepare("SELECT `symbol` FROM `$em_currency_table` WHERE `code` = %s", $em_currency));
$event_currency_symbol = $em_currency_symbol ? $em_currency_symbol->symbol : '$';

// Check if magazine layout
$layout_preference = $event_settings['em_layout_preference'] ?? 'default';
$rounded_class = ($layout_preference === 'magazine') ? 'em-rounded-2xl' : '';
?>
<section class="em-bg-white em-p-6 em-border em-border-slate-200 em-shadow-lg em-animate-fade-in em-animate-delay-700 <?php echo esc_attr($rounded_class); ?>">

    <?php if ($em_registration_modal === 'inline'): ?>
        <!-- Inline Registration Form -->
        <div class="em-text-center em-mb-6">
            <h2 class="em-text-2xl em-font-bold em-text-slate-900"><?php echo esc_html($event_post->post_title ?? 'Event Registration'); ?></h2>
            <p class="em-text-slate-500 em-text-sm em-mt-1">Complete the steps below to secure your spot.</p>
        </div>
    <?php else: ?>
        <!-- Modal Registration Button -->
        <div class="em-flex em-flex-col em-items-center em-justify-center em-text-center">
            <h2 class="em-text-xl em-font-bold em-text-slate-900">Ready to Join?</h2>
            <p class="em-text-slate-500 em-text-sm em-mt-1">Secure your spot at the forefront of creative tech.</p>
        </div>
    <?php endif; ?>

    <?php if ($em_registration_type === 'external' && $em_external_link): ?>
        <!-- External Registration -->
        <a href="<?php echo esc_url($em_external_link); ?>"
           target="_blank"
           class="em-w-full md:em-w-auto em-mt-4 em-py-3 em-px-8 em-bg-indigo-600 em-text-white em-font-bold em-rounded-lg em-shadow-lg em-shadow-indigo-500/20 hover:em-bg-indigo-700 em-transition-all em-text-center em-block">
            <?php echo esc_html($em_reg_btn_txt); ?>
        </a>

    <?php elseif ($em_registration_type === 'internal'): ?>

        <?php if ($em_registration_modal === 'modal'): ?>
            <!-- Modal Registration Button -->
            <div class="em-flex em-justify-center">
                <button type="button"
                        id="em-show-registration-modal-<?php echo $event_id; ?>"
                        class="em-w-full md:em-w-auto em-mt-4 em-py-2 em-px-4 em-bg-indigo-600 em-text-white em-text-sm em-font-semibold em-rounded-lg em-shadow-md em-shadow-indigo-500/20 hover:em-bg-indigo-700 em-transition-all">
                    <?php echo esc_html($em_reg_btn_txt); ?>
                </button>
            </div>
        <?php endif; ?>

        <!-- Registration Form with Tickets -->
        <div id="em-registration-form-<?php echo $event_id; ?>" class="em-registration-form <?php echo ($em_registration_modal === 'modal') ? 'em-hidden' : ''; ?>">

            <!-- Ticket Selection -->
            <?php if (!empty($em_tkt_selected)): ?>
            <div class="em-mb-6">

                <div class="em-space-y-3">
                    <?php
                    $em_tickets_table = $wpdb->prefix . 'em_tickets';
                    $em_tickets_result = $wpdb->get_results($wpdb->prepare("SELECT * FROM `$em_tickets_table` WHERE `status` = %s", 'available'));

                    if ($em_tickets_result) {
                        foreach ($em_tickets_result as $ticket) {
                            if (in_array($ticket->id, $em_tkt_selected)) {
                                $max_qty = $em_tkt_max_range[$ticket->id] ?? 10;
                                $is_single = (count($em_tkt_selected) === 1);
                                $chk_style = $is_single ? 'style="display:none;"' : '';
                                $chk_checked = $is_single ? 'checked="checked"' : '';
                                $qty_disabled = $is_single ? '' : 'disabled';
                                ?>
                                <label for="ticket-<?php echo $ticket->id; ?>" class="em-flex em-justify-between em-items-center em-bg-slate-50 em-p-4 em-rounded-lg em-border-2 em-border-transparent has-[:checked]:em-bg-slate-100 em-transition-all em-cursor-pointer">
                                    <div class="em-flex em-items-center em-gap-4">
                                        <input type="checkbox" <?php echo $chk_style; ?> <?php echo $chk_checked; ?>
                                               id="ticket-<?php echo $ticket->id; ?>"
                                               class="ticket-checkbox em-h-5 em-w-5 em-rounded em-border-gray-300 em-text-indigo-600 focus:em-ring-indigo-500"
                                               data-ticket-id="<?php echo $ticket->id; ?>"
                                               data-price="<?php echo $ticket->price; ?>">
                                        <div>
                                            <span class="em-font-semibold em-text-slate-800"><?php echo esc_html($ticket->name); ?></span>
                                            <p class="em-text-sm em-text-slate-800 em-font-bold">
                                                <?php echo esc_html($event_currency_symbol . number_format($ticket->price, 2)); ?>
                                            </p>
                                        </div>
                                    </div>
                                    <select name="ticket_qty[<?php echo $ticket->id; ?>]"
                                            id="qty-<?php echo $ticket->id; ?>"
                                            class="ticket-quantity em-border-slate-300 em-rounded-md em-text-center em-font-semibold em-bg-white em-w-20"
                                            data-ticket-id="<?php echo $ticket->id; ?>"
                                            data-price="<?php echo $ticket->price; ?>"
                                            <?php echo $qty_disabled; ?>>
                                        <option value="0" <?php echo $is_single ? '' : 'selected'; ?>>0</option>
                                        <?php for ($i = 1; $i <= $max_qty; $i++): ?>
                                            <option value="<?php echo $i; ?>" <?php echo ($is_single && $i === 1) ? 'selected' : ''; ?>><?php echo $i; ?></option>
                                        <?php endfor; ?>
                                    </select>
                                </label>
                                <?php
                            }
                        }
                    }
                    ?>
                </div>

                <?php
                ?>

                <!-- Total Price Display -->
                <div class="em-mb-6">
                    <div class="em-flex em-justify-between em-items-center em-p-4 em-bg-indigo-600 em-text-white em-rounded-lg">
                        <span class="em-font-semibold"><?php _e('Total Amount', 'event-monster'); ?></span>
                        <span id="total-price" class="em-text-2xl em-font-bold">
                            <?php echo $event_currency_symbol; ?>0.00
                        </span>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Attendee Information Form -->
            <form id="em-booking-form-<?php echo $event_id; ?>" method="post" action="#" class="em-space-y-4">

                <div class="em-grid em-grid-cols-2 sm:em-grid-cols-2 em-gap-4">
                    <div>
                        <label for="first_name_<?php echo $event_id; ?>" class="em-block em-text-xs em-font-medium em-text-slate-600 em-mb-1">
                            <?php _e('First Name', 'event-monster'); ?> *
                        </label>
                        <input type="text" id="first_name_<?php echo $event_id; ?>" name="first_name" required
                               class="em-w-full em-border-slate-300 em-rounded-md em-px-3 em-py-2 em-text-sm focus:em-ring-indigo-500 focus:em-border-indigo-500"
                               placeholder="Jane">
                    </div>
                    <div>
                        <label for="last_name_<?php echo $event_id; ?>" class="em-block em-text-xs em-font-medium em-text-slate-600 em-mb-1">
                            <?php _e('Last Name', 'event-monster'); ?> *
                        </label>
                        <input type="text" id="last_name_<?php echo $event_id; ?>" name="last_name" required
                               class="em-w-full em-border-slate-300 em-rounded-md em-px-3 em-py-2 em-text-sm focus:em-ring-indigo-500 focus:em-border-indigo-500"
                               placeholder="Doe">
                    </div>
                </div>

                <div class="em-grid em-grid-cols-1 sm:em-grid-cols-2 em-gap-4">
                    <div>
                        <label for="email_<?php echo $event_id; ?>" class="em-block em-text-xs em-font-medium em-text-slate-600 em-mb-1">
                            <?php _e('Email Address', 'event-monster'); ?> *
                        </label>
                        <input type="email" id="email_<?php echo $event_id; ?>" name="email" required
                               class="em-w-full em-border-slate-300 em-rounded-md em-px-3 em-py-2 em-text-sm focus:em-ring-indigo-500 focus:em-border-indigo-500"
                               placeholder="jane.doe@example.com">
                    </div>
                    <div>
                        <label for="mobile_number_<?php echo $event_id; ?>" class="em-block em-text-xs em-font-medium em-text-slate-600 em-mb-1">
                            <?php _e('Mobile Number', 'event-monster'); ?>
                        </label>
                        <input type="tel" id="mobile_number_<?php echo $event_id; ?>" name="mobile_number"
                               class="em-w-full em-border-slate-300 em-rounded-md em-px-3 em-py-2 em-text-sm focus:em-ring-indigo-500 focus:em-border-indigo-500"
                               placeholder="(555) 123-4567">
                    </div>
                </div>

                <button type="submit"
                        class="em-w-full em-py-3 em-px-6 em-bg-indigo-600 em-text-white em-font-bold em-rounded-lg em-shadow-lg em-shadow-indigo-500/20 hover:em-bg-indigo-700 em-transition-all">
                    <?php _e('Complete Booking', 'event-monster'); ?>
                </button>

                <input type="hidden" name="event_id" value="<?php echo esc_attr($event_id); ?>">
                <input type="hidden" name="action" value="em_book_tickets">
                <?php wp_nonce_field('em_book_tickets', 'em_booking_nonce'); ?>
            </form>
        </div>
    <?php endif; ?>
</section>

<?php if ($em_registration_modal === 'modal' && $em_registration_type === 'internal'): ?>
<!-- Modal Registration Form -->
<div id="em-registration-modal-<?php echo $event_id; ?>" class="em-modal-overlay em-fixed em-inset-0 em-bg-black em-bg-opacity-50 em-flex em-items-center em-justify-center em-hidden" style="z-index: 999999 !important;">
    <div class="em-registration-modal-content em-bg-white em-rounded-2xl em-shadow-2xl em-max-w-2xl em-w-full em-mx-4 em-max-h-screen em-overflow-y-auto">
        <div class="em-modal-header em-flex em-justify-between em-items-center em-p-6 em-border-b em-border-slate-200">
            <div>
                <h2 class="em-text-2xl em-font-bold em-text-slate-900"><?php echo esc_html($event_post->post_title ?? 'Event Registration'); ?></h2>
                <p class="em-text-slate-500 em-text-sm em-mt-1">Complete the steps below to secure your spot.</p>
            </div>
            <button type="button" id="em-close-modal-<?php echo $event_id; ?>" class="em-modal-close-btn em-text-slate-400 hover:em-text-slate-600 em-text-2xl em-font-bold em-leading-none" style="padding: 5px; background: darkgrey; border-radius: 50%;">
                <svg class="em-close-icon" xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="#fff" viewBox="0 0 256 256" style="transition: transform 0.3s ease-in-out; display: block;"><path d="M208.49,191.51a12,12,0,0,1-17,17L128,145,64.49,208.49a12,12,0,0,1-17-17L111,128,47.51,64.49a12,12,0,0,1,17-17L128,111l63.51-63.52a12,12,0,0,1,17,17L145,128Z"></path></svg>
            </button>
        </div>

        <div class="em-modal-body em-p-6">
            <!-- Ticket Selection -->
            <?php if (!empty($em_tkt_selected)): ?>
            <div class="em-mb-6">

                <div class="em-space-y-3">
                    <?php
                    if ($em_tickets_result) {
                        foreach ($em_tickets_result as $ticket) {
                            if (in_array($ticket->id, $em_tkt_selected)) {
                                $max_qty = $em_tkt_max_range[$ticket->id] ?? 10;
                                $is_single = (count($em_tkt_selected) === 1);
                                $chk_style = $is_single ? 'style="display:none;"' : '';
                                $chk_checked = $is_single ? 'checked="checked"' : '';
                                $qty_disabled = $is_single ? '' : 'disabled';
                                ?>
                                <label for="modal-ticket-<?php echo $ticket->id; ?>" class="em-flex em-justify-between em-items-center em-bg-slate-50 em-p-4 em-rounded-lg em-border-2 em-border-transparent has-[:checked]:em-bg-slate-100 em-transition-all em-cursor-pointer">
                                    <div class="em-flex em-items-center em-gap-4">
                                        <input type="checkbox" <?php echo $chk_style; ?> <?php echo $chk_checked; ?>
                                               id="modal-ticket-<?php echo $ticket->id; ?>"
                                               class="modal-ticket-checkbox em-h-5 em-w-5 em-rounded em-border-gray-300 em-text-indigo-600 focus:em-ring-indigo-500"
                                               data-ticket-id="<?php echo $ticket->id; ?>"
                                               data-price="<?php echo $ticket->price; ?>">
                                        <div>
                                            <span class="em-font-semibold em-text-slate-800"><?php echo esc_html($ticket->name); ?></span>
                                            <p class="em-text-sm em-text-slate-800 em-font-bold">
                                                <?php echo esc_html($event_currency_symbol . number_format($ticket->price, 2)); ?>
                                            </p>
                                        </div>
                                    </div>
                                    <select name="modal_ticket_qty[<?php echo $ticket->id; ?>]"
                                            id="modal-qty-<?php echo $ticket->id; ?>"
                                            class="modal-ticket-quantity em-border-slate-300 em-rounded-md em-text-center em-font-semibold em-bg-white em-w-20"
                                            data-ticket-id="<?php echo $ticket->id; ?>"
                                            data-price="<?php echo $ticket->price; ?>"
                                            <?php echo $qty_disabled; ?>>
                                        <option value="0" <?php echo $is_single ? '' : 'selected'; ?>>0</option>
                                        <?php for ($i = 1; $i <= $max_qty; $i++): ?>
                                            <option value="<?php echo $i; ?>" <?php echo ($is_single && $i === 1) ? 'selected' : ''; ?>><?php echo $i; ?></option>
                                        <?php endfor; ?>
                                    </select>
                                </label>
                                <?php
                            }
                        }
                    }
                    ?>
                </div>

                <?php
                ?>

                <!-- Total Price Display -->
                <div class="em-mb-6">
                    <div class="em-flex em-justify-between em-items-center em-p-4 em-bg-indigo-600 em-text-white em-rounded-lg">
                        <span class="em-font-semibold"><?php _e('Total Amount', 'event-monster'); ?></span>
                        <span id="modal-total-price" class="em-text-2xl em-font-bold">
                            <?php echo $event_currency_symbol; ?>0.00
                        </span>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Attendee Information Form -->
            <form id="em-modal-booking-form-<?php echo $event_id; ?>" method="post" action="#" class="em-space-y-4">

                <div class="em-grid em-grid-cols-2 sm:em-grid-cols-2 em-gap-4">
                    <div>
                        <label for="modal_first_name_<?php echo $event_id; ?>" class="em-block em-text-xs em-font-medium em-text-slate-600 em-mb-1">
                            <?php _e('First Name', 'event-monster'); ?> *
                        </label>
                        <input type="text" id="modal_first_name_<?php echo $event_id; ?>" name="first_name" required
                               class="em-w-full em-border-slate-300 em-rounded-md em-px-3 em-py-2 em-text-sm focus:em-ring-indigo-500 focus:em-border-indigo-500"
                               placeholder="Jane">
                    </div>
                    <div>
                        <label for="modal_last_name_<?php echo $event_id; ?>" class="em-block em-text-xs em-font-medium em-text-slate-600 em-mb-1">
                            <?php _e('Last Name', 'event-monster'); ?> *
                        </label>
                        <input type="text" id="modal_last_name_<?php echo $event_id; ?>" name="last_name" required
                               class="em-w-full em-border-slate-300 em-rounded-md em-px-3 em-py-2 em-text-sm focus:em-ring-indigo-500 focus:em-border-indigo-500"
                               placeholder="Doe">
                    </div>
                </div>

                <div class="em-grid em-grid-cols-2 sm:em-grid-cols-2 em-gap-4">
                    <div>
                        <label for="modal_email_<?php echo $event_id; ?>" class="em-block em-text-xs em-font-medium em-text-slate-600 em-mb-1">
                            <?php _e('Email Address', 'event-monster'); ?> *
                        </label>
                        <input type="email" id="modal_email_<?php echo $event_id; ?>" name="email" required
                               class="em-w-full em-border-slate-300 em-rounded-md em-px-3 em-py-2 em-text-sm focus:em-ring-indigo-500 focus:em-border-indigo-500"
                               placeholder="jane.doe@example.com">
                    </div>
                    <div>
                        <label for="modal_mobile_number_<?php echo $event_id; ?>" class="em-block em-text-xs em-font-medium em-text-slate-600 em-mb-1">
                            <?php _e('Mobile Number', 'event-monster'); ?>
                        </label>
                        <input type="tel" id="modal_mobile_number_<?php echo $event_id; ?>" name="mobile_number"
                               class="em-w-full em-border-slate-300 em-rounded-md em-px-3 em-py-2 em-text-sm focus:em-ring-indigo-500 focus:em-border-indigo-500"
                               placeholder="(555) 123-4567">
                    </div>
                </div>

                <button type="submit"
                        class="em-w-full em-py-3 em-px-6 em-bg-indigo-600 em-text-white em-font-bold em-rounded-lg em-shadow-lg em-shadow-indigo-500/20 hover:em-bg-indigo-700 em-transition-all">
                    <?php _e('Complete Booking', 'event-monster'); ?>
                </button>

                <input type="hidden" name="event_id" value="<?php echo esc_attr($event_id); ?>">
                <input type="hidden" name="action" value="em_book_tickets">
                <?php wp_nonce_field('em_book_tickets', 'em_booking_nonce'); ?>
            </form>
        </div>
    </div>
</div>

<!-- Success/Error Modal -->
<div id="em-message-modal-<?php echo $event_id; ?>" class="em-modal-overlay em-hidden">
    <div class="em-registration-modal-content" style="max-width: 28rem !important;">
        <div class="em-modal-body em-p-6 em-text-center">
            <div id="em-message-content-<?php echo $event_id; ?>">
                <!-- Dynamic content will be inserted here -->
            </div>
            <button type="button" id="em-close-message-modal-<?php echo $event_id; ?>"
                    class="em-mt-4 em-px-6 em-py-2 em-bg-indigo-600 hover:em-bg-indigo-700 em-text-white em-rounded-lg em-transition-colors">
                <?php _e('Close', 'event-monster'); ?>
            </button>
        </div>
    </div>
</div>

<!-- CSS for Close Button Hover Effect -->
<style>
    /* Close button hover rotation effect */
    .em-modal-close-btn:hover .em-close-icon {
        transform: rotate(180deg);
    }

    /* Ensure smooth transition on hover out */
    .em-close-icon {
        transition: transform 0.3s ease-in-out;
        display: block;
    }

    /* Optional: Add a subtle scale effect on button hover */
    .em-modal-close-btn {
        transition: background-color 0.3s ease-in-out, transform 0.2s ease-in-out;
        cursor: pointer;
    }

    .em-modal-close-btn:hover {
        background-color: #6b7280 !important; /* Slightly lighter grey on hover */
    }

    .em-modal-close-btn:active {
        transform: scale(0.95);
    }

    /* Force padding on success message paragraph */
    #modal-success-message-<?php echo $event_id; ?> p.em-px-12 {
        padding-left: 4rem !important;
        padding-right: 4rem !important;
    }

    #modal-success-message-<?php echo $event_id; ?> p.em-py-4 {
        padding-top: 1rem !important;
        padding-bottom: 1rem !important;
    }
</style>
<?php endif; ?>

<script>
jQuery(document).ready(function($) {
    if ($('.modal-ticket-checkbox').length === 1) {
        $('.modal-ticket-checkbox').prop('checked', true).trigger('change');
        $('.modal-ticket-checkbox').hide();
    }
    const urlParams = new URLSearchParams(window.location.search);
    const bookingStatus = urlParams.get('em_booking_status');
    const eventId = urlParams.get('event_id');

    if (bookingStatus === 'Completed' && eventId == <?php echo $event_id; ?>) {
        <?php if ($em_registration_modal === 'modal'): ?>
            showModalMessage('success', '<?php _e("Payment Completed!", "event-monster"); ?>', '<?php _e("Your booking has been confirmed successfully!", "event-monster"); ?>');
        <?php else: ?>
            showBookingSuccess();
        <?php endif; ?>
        // Don't disable button - allow multiple bookings

        // Clean URL
        const url = new URL(window.location);
        url.searchParams.delete('em_booking_status');
        url.searchParams.delete('em_booking_id');
        url.searchParams.delete('event_id');
        window.history.replaceState({}, document.title, url);
    }

    // Currency symbol as JavaScript variable to avoid encoding issues
    var currencySymbol = '<?php echo addslashes($event_currency_symbol); ?>';
    // Decode HTML entities in currency symbol
    var tempDiv = document.createElement('div');
    tempDiv.innerHTML = currencySymbol;
    currencySymbol = tempDiv.textContent || tempDiv.innerText || currencySymbol;

    var ajaxUrl = '<?php echo admin_url('admin-ajax.php'); ?>';
    var isModalMode = <?php echo ($em_registration_modal === 'modal') ? 'true' : 'false'; ?>;

    // Modal functionality
    if (isModalMode) {
        // Show modal
        $('#em-show-registration-modal-<?php echo $event_id; ?>').on('click', function() {
            $('#em-registration-modal-<?php echo $event_id; ?>').removeClass('em-hidden');
            $('body, html').addClass('em-modal-open');
        });

        // Close modal - Close button (specific handler)
        $('#em-close-modal-<?php echo $event_id; ?>').on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            console.log('🔴 Close button clicked');
            $('#em-registration-modal-<?php echo $event_id; ?>').addClass('em-hidden');
            $('body, html').removeClass('em-modal-open');
        });

        // Close modal - Click outside (overlay)
        $('#em-registration-modal-<?php echo $event_id; ?>').on('click', function(e) {
            // Only close if clicking directly on the overlay (not on modal content)
            if (e.target === this) {
                console.log('🔴 Clicked outside modal');
                $(this).addClass('em-hidden');
                $('body, html').removeClass('em-modal-open');
            }
        });

        // Close message modal
        $('#em-close-message-modal-<?php echo $event_id; ?>').on('click', function() {
            $('#em-message-modal-<?php echo $event_id; ?>').addClass('em-hidden');
            $('body, html').removeClass('em-modal-open');
        });

        // Escape key to close modal
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape') {
                $('#em-registration-modal-<?php echo $event_id; ?>, #em-message-modal-<?php echo $event_id; ?>').addClass('em-hidden');
                $('body, html').removeClass('em-modal-open');
            }
        });
    }

    // Handle ticket checkbox selection (both inline and modal)
    // Always bind handlers - they should work in all contexts
    $('.ticket-checkbox, .modal-ticket-checkbox').on('change', function() {
        var ticketId = $(this).data('ticket-id');
        var isModal = $(this).hasClass('modal-ticket-checkbox');
        var quantitySelect = isModal ? $('#modal-qty-' + ticketId) : $('#qty-' + ticketId);

        console.log('🎫 Registration component handler - ticket:', ticketId, 'checked:', $(this).is(':checked'));

        if ($(this).is(':checked')) {
            quantitySelect.prop('disabled', false);
            quantitySelect.val('1'); // Set default quantity to 1
            console.log('✅ Registration component enabled quantity field:', ticketId);
        } else {
            quantitySelect.prop('disabled', true);
            quantitySelect.val('0');
            console.log('❌ Registration component disabled quantity field:', ticketId);
        }

        if (isModal) {
            calculateModalTotal();
        } else {
            calculateTotal();
        }
    });

    // Also bind handlers using event delegation for dynamically loaded content
    $(document).on('change', '.ticket-checkbox, .modal-ticket-checkbox', function() {
        var ticketId = $(this).data('ticket-id');
        var isModal = $(this).hasClass('modal-ticket-checkbox');
        var quantitySelect = isModal ? $('#modal-qty-' + ticketId) : $('#qty-' + ticketId);

        console.log('🎫 Delegated handler - ticket:', ticketId, 'checked:', $(this).is(':checked'));

        if ($(this).is(':checked')) {
            quantitySelect.prop('disabled', false);
            quantitySelect.val('1');
            console.log('✅ Delegated handler enabled quantity field:', ticketId);
        } else {
            quantitySelect.prop('disabled', true);
            quantitySelect.val('0');
            console.log('❌ Delegated handler disabled quantity field:', ticketId);
        }

        if (isModal) {
            calculateModalTotal();
        } else {
            calculateTotal();
        }
    });

    // Handle quantity changes (both inline and modal)
    $('.ticket-quantity, .modal-ticket-quantity').on('change', function() {
        var isModal = $(this).hasClass('modal-ticket-quantity');
        if (isModal) {
            calculateModalTotal();
        } else {
            calculateTotal();
        }
    });


    // Calculate total price for inline form
    function calculateTotal() {
        var total = 0;

        $('.ticket-checkbox:checked').each(function() {
            var ticketId = $(this).data('ticket-id');
            var price = parseFloat($(this).data('price')) || 0;
            var quantity = parseInt($('#qty-' + ticketId).val()) || 0;

            total += price * quantity;
        });



        $('#total-price').html(currencySymbol + total.toFixed(2));
    }

    // Calculate total price for modal form
    function calculateModalTotal() {
        var total = 0;

        $('.modal-ticket-checkbox:checked').each(function() {
            var ticketId = $(this).data('ticket-id');
            var price = parseFloat($(this).data('price')) || 0;
            var quantity = parseInt($('#modal-qty-' + ticketId).val()) || 0;

            total += price * quantity;
        });



        $('#modal-total-price').html(currencySymbol + total.toFixed(2));
    }

    // Handle booking form submission (both inline and modal)
    // This handler should work for both single events and calendar modals
    $('#em-booking-form-<?php echo $event_id; ?>, #em-modal-booking-form-<?php echo $event_id; ?>').off('submit.registration').on('submit.registration', function(e) {
        e.preventDefault();

        console.log('🎯 FORM SUBMISSION HANDLER CALLED!', {
            formId: $(this).attr('id'),
            ajaxUrlDefined: typeof ajaxUrl !== 'undefined',
            ajaxUrlValue: typeof ajaxUrl !== 'undefined' ? ajaxUrl : 'UNDEFINED',
            inCalendarModal: $('#em-event-modal').length > 0 && $('#em-event-modal').is(':visible'),
            formAction: $(this).find('input[name="action"]').val()
        });

        // Check if ajaxUrl is defined
        if (typeof ajaxUrl === 'undefined') {
            console.error('❌ ajaxUrl is not defined! This will cause form to submit normally and reload page.');
            alert('AJAX URL not defined - this will cause page reload. Check console for details.');
            return false;
        }

        console.log('📝 Form submission - handling with AJAX');

        var isModal = $(this).attr('id').includes('modal');
        var ticketCheckboxes = isModal ? $('.modal-ticket-checkbox') : $('.ticket-checkbox');

        // Check if at least one ticket is selected
        var hasTickets = ticketCheckboxes.filter(':checked').length > 0;

        if (!hasTickets) {
            if (isModal) {
                showModalMessage('error', '<?php _e("Selection Required", "event-monster"); ?>', '<?php _e("Please select at least one ticket.", "event-monster"); ?>');
            } else {
                alert('<?php _e("Please select at least one ticket.", "event-monster"); ?>');
            }
            return;
        }

        var formData = $(this).serialize();

        // Add selected ticket data to form
        ticketCheckboxes.filter(':checked').each(function() {
            var ticketId = $(this).data('ticket-id');
            var qtySelector = isModal ? '#modal-qty-' + ticketId : '#qty-' + ticketId;
            var quantity = $(qtySelector).val();
            formData += '&ticket_qty[' + ticketId + ']=' + quantity;
        });


        // Debug: Log the form data being sent
        console.log('📤 Form data being sent:', formData);
        console.log('🌐 AJAX URL:', ajaxUrl);
        console.log('🚀 Making AJAX call...');

        $.post(ajaxUrl, formData, function(response) {
            console.log('✅ AJAX Response received:', response);
            if (response.success) {
                // Free version: All bookings are free — show success immediately
                if (isModal) {
                    showModalMessage('success', '<?php _e("Booking Confirmed!", "event-monster"); ?>', '<?php _e("Your free ticket has been booked successfully!", "event-monster"); ?>');
                } else {
                    showBookingSuccess();
                }
            } else {
                var errorMessage = response.data.message || '<?php _e("Booking failed. Please try again.", "event-monster"); ?>';
                if (isModal) {
                    showModalMessage('error', '<?php _e("Booking Failed", "event-monster"); ?>', errorMessage);
                } else {
                    alert(errorMessage);
                }
            }
        }).fail(function(xhr, status, error) {
            console.error('❌ AJAX Error:', {
                status: status,
                error: error,
                responseText: xhr.responseText,
                ajaxUrl: ajaxUrl,
                formData: formData
            });

            var errorMessage = '<?php _e("An error occurred. Please try again.", "event-monster"); ?>';
            if (isModal) {
                showModalMessage('error', '<?php _e("Connection Error", "event-monster"); ?>', errorMessage);
            } else {
                alert(errorMessage + ' Check console for details.');
            }
        });
    });


    // Show modal success message by inserting in registration area (FIXED: Don't replace modal content)
    function showModalSuccessMessage(title, message) {
        console.log("🎉 showModalSuccessMessage called:", title, message);

        // Prevent any page reloads
        if (window.event) {
            window.event.preventDefault();
            window.event.stopPropagation();
        }

        // Check if we're in a calendar modal context
        var inCalendarModal = $('#em-event-modal').length > 0 && $('#em-event-modal').is(':visible');
        var targetModal = inCalendarModal ? '#em-event-modal' : '#em-registration-modal-<?php echo $event_id; ?>';

        console.log("🔍 Success message context:", {
            inCalendarModal: inCalendarModal,
            targetModal: targetModal
        });

        // ENHANCED: Hide all form content (ticket selection, registration form, payment section)
        console.log("🔒 Hiding all form content for clean success message display");

        // Hide payment section if exists
        $(targetModal).find('#modal-payment-section-<?php echo $event_id; ?>').hide();

        // Hide registration form
        $(targetModal).find('#em-modal-booking-form-<?php echo $event_id; ?>, #em-booking-form-<?php echo $event_id; ?>, .em-registration-form').hide();

        // Hide ticket selection section - find parent div containing ticket checkboxes
        $(targetModal).find('.modal-ticket-checkbox, .ticket-checkbox').closest('div').parent().hide();

        // Hide total amount display specifically
        $(targetModal).find('#modal-total-price, #total-price').closest('.em-mb-6').hide();

        // Also hide any remaining ticket-related containers
        $(targetModal).find('label[for^="modal-ticket-"], label[for^="ticket-"]').parent().hide();


        console.log("✅ All form content hidden");

        // FIXED: Insert success message in registration area instead of replacing entire modal
        var successHtml = `
            <div id="modal-success-message-<?php echo $event_id; ?>" class="em-text-center em-p-6 ">
                <div class="em-w-16 em-h-16 em-mx-auto em-mb-4 em-bg-green-100 em-rounded-full em-flex em-items-center em-justify-center">
                    <svg class="em-w-8 em-h-8 em-text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                    </svg>
                </div>
                <h3 class="em-text-xl em-font-bold em-text-green-800 em-mb-6">${title}</h3>
                <p class="em-text-slate-600 em-mb-6 em-px-12 em-py-4">${message}</p>
                <button type="button" id="modal-success-close-<?php echo $event_id; ?>"
                        class="em-px-6 em-py-2 em-bg-green-600 hover:em-bg-green-700 em-text-white em-rounded em-transition-colors">
                    <?php _e('Close', 'event-monster'); ?>
                </button>
            </div>
        `;

        // Find the modal body to insert the success message
        var $modalBody = $(targetModal).find('.em-modal-body');

        if ($modalBody.length > 0) {
            console.log("✅ Appending success message to modal body");
            $modalBody.append(successHtml);
        } else {
            console.log("⚠️ Fallback: Appending to target modal");
            $(targetModal).append(successHtml);
        }

        console.log("✅ Success message displayed (all form content hidden)");
    }

    // Show modal error message by replacing modal content
    function showModalErrorMessage(title, message) {
        console.log("❌ showModalErrorMessage called:", title, message);

        // Prevent any page reloads
        if (window.event) {
            window.event.preventDefault();
            window.event.stopPropagation();
        }

        // Check if we're in a calendar modal context
        var inCalendarModal = $('#em-event-modal').length > 0 && $('#em-event-modal').is(':visible');
        console.log("🔍 Calendar modal context:", inCalendarModal);

        if (inCalendarModal) {
            // If in calendar modal, replace the entire calendar modal content with error message
            console.log("📅 Replacing calendar modal content with error message");
            $('#em-event-modal .em-modal-body').html(`
                <div class="em-text-center em-p-8">
                    <div class="em-w-20 em-h-20 em-mx-auto em-mb-6 em-bg-red-100 em-rounded-full em-flex em-items-center em-justify-center">
                        <svg class="em-w-10 em-h-10 em-text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                        </svg>
                    </div>
                    <h2 class="em-text-2xl em-font-bold em-text-red-800 em-mb-4">${title}</h2>
                    <p class="em-text-slate-600 em-mb-8 em-text-lg">${message}</p>
                    <button type="button" onclick="$('#em-event-modal').addClass('em-hidden').hide(); $('body, html').removeClass('em-modal-open');"
                            class="em-px-8 em-py-3 em-bg-red-600 hover:em-bg-red-700 em-text-white em-rounded-lg em-transition-colors em-text-lg">
                        <?php _e('Close', 'event-monster'); ?>
                    </button>
                </div>
            `);
        } else {
            // Replace the registration modal body content with error message
            console.log("📝 Replacing registration modal content with error message");
            $('#em-registration-modal-<?php echo $event_id; ?> .em-modal-body').html(`
                <div class="em-text-center">
                    <div class="em-w-16 em-h-16 em-mx-auto em-mb-4 em-bg-red-100 em-rounded-full em-flex em-items-center em-justify-center">
                        <svg class="em-w-8 em-h-8 em-text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                        </svg>
                    </div>
                    <h3 class="em-text-xl em-font-bold em-text-red-800 em-mb-2">${title}</h3>
                    <p class="em-text-slate-600 em-mb-6">${message}</p>
                    <button type="button" onclick="$('#em-registration-modal-<?php echo $event_id; ?>').addClass('em-hidden'); $('body, html').removeClass('em-modal-open');"
                            class="em-px-6 em-py-2 em-bg-red-600 hover:em-bg-red-700 em-text-white em-rounded-lg em-transition-colors">
                        <?php _e('Close', 'event-monster'); ?>
                    </button>
                </div>
            `);
        }

        console.log("✅ Modal content replaced with error message");
    }

    // Show modal message (success/error) - Keep for backward compatibility
    function showModalMessage(type, title, message) {
        console.log("showModalMessage called:", type, title, message);
        if (type === 'success') {
            showModalSuccessMessage(title, message);
        } else {
            showModalErrorMessage(title, message);
        }
    }

    // Show modal payment section

    // showModalPaymentSection and showPaymentSection removed (Pro-only feature)
    // Payment gateways (PayPal, Stripe, Razorpay, Square) are available in Event Monster Pro.

    calculateTotal();
    calculateModalTotal();
});
</script>

<!-- Modal CSS to prevent conflicts -->
<style>
/* Event Monster Modal Styles - Scoped to prevent conflicts */
.em-modal-overlay {
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    right: 0 !important;
    bottom: 0 !important;
    background-color: rgba(0, 0, 0, 0.5) !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    z-index: 999999 !important; /* Very high z-index to avoid conflicts */
    padding: 1rem !important;
}

.em-modal-overlay.em-hidden {
    display: none !important;
}

/* Debug: Force message modal to be visible when not hidden */
#em-message-modal-<?php echo $event_id; ?>:not(.em-hidden) {
    display: flex !important;
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    right: 0 !important;
    bottom: 0 !important;
    background-color: rgba(0, 0, 0, 0.8) !important;
    z-index: 999999 !important;
    align-items: center !important;
    justify-content: center !important;
}

/* Debug: Force message modal content to be visible */
#em-message-modal-<?php echo $event_id; ?> .em-modal-content {
    background: white !important;
    border-radius: 1rem !important;
    padding: 2rem !important;
    max-width: 28rem !important;
    width: 90% !important;
    box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5) !important;
    border: 3px solid #10b981 !important; /* Green border for debugging */
}

#em-registration-modal-<?php echo $event_id; ?> .em-modal-content {
    background: white !important;
    border-radius: 1rem !important;
    box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25) !important;
    max-width: 32rem !important;
    width: 100% !important;
    max-height: 90vh !important;
    overflow-y: auto !important;
    position: relative !important;
}

.em-modal-header {
    display: flex !important;
    justify-content: space-between !important;
    align-items: flex-start !important;
    padding: 1rem !important;
    border-bottom: 1px solid #e2e8f0 !important;
}

.em-modal-body {
    padding: 1.5rem !important;
}

/* Prevent body scroll when modal is open */
body.em-modal-open {
    overflow: hidden !important;
}

/* Responsive modal */
@media (max-width: 640px) {
    .em-modal-wrapper {
        padding: 0.5rem !important;
    }

    .em-modal-content {
        max-width: calc(100vw - 1rem) !important;
        width: calc(100vw - 1rem) !important;
    }

    .em-modal-header,
    .em-modal-body {
        padding: 1rem !important;
    }
}

@media (max-height: 600px) {
    .em-modal-wrapper {
        vertical-align: top !important;
        padding-top: 2rem !important;
    }
}

/* Animation for modal */
.em-modal-overlay {
    animation: em-fadeIn 0.2s ease-out !important;
}

@keyframes em-fadeIn {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}

.em-modal-content {
    animation: em-slideIn 0.2s ease-out !important;
}

@keyframes em-slideIn {
    from {
        transform: translateY(-20px);
        opacity: 0;
    }
    to {
        transform: translateY(0);
        opacity: 1;
    }
}
</style>












