<?php
/**
 * Event List Template - Based on event-list-template.html design
 * Used by [EM-LIST] shortcode
 */

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

// Check if we're viewing a single event dynamically
if (isset($_GET['em_single'])) {
    $single_event_id = intval($_GET['em_single']);
    if ($single_event_id && get_post_type($single_event_id) === 'awl_event_monster') {
        // Set global variables for the single event template
        global $em_id;
        $em_id = $single_event_id;

        // Get back URL for navigation
        $back_url = isset($_GET['em_back']) ? wp_validate_redirect(urldecode($_GET['em_back']), get_home_url()) : get_home_url();

        // Display single event with back button
        echo '<div class="em-single-event-wrapper">';
        echo '<div class="em-back-navigation" style="margin-bottom: 1rem; padding: 1rem; background: #f8fafc; border-radius: 0.5rem;">';
        echo '<a href="' . esc_url($back_url) . '" style="display: inline-flex; align-items: center; gap: 0.5rem; color: #6366f1; text-decoration: none; font-weight: 500;">';
        echo '<svg width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">';
        echo '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>';
        echo '</svg>';
        echo __('Back to Events', 'event-monster');
        echo '</a>';
        echo '</div>';

        // Include the single event template
        include EM_FREE_PLUGIN_DIR . 'templates/frontend/single-event-template.php';

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

// Get shortcode attributes
$atts = shortcode_atts(array(
    'limit' => -1,
    'category' => '',
    'show_filters' => 'yes',
    'view_mode' => 'page', // 'page' or 'modal'
    'columns' => '3' // 1, 2, 3, or 4
), $atts ?? array());

// Get events
$args = array(
    'post_type' => 'awl_event_monster',
    'post_status' => 'publish',
    'posts_per_page' => intval($atts['limit']),
    'meta_query' => array()
);

// Add category filter if specified
if (!empty($atts['category'])) {
    // Try WordPress taxonomy first
    $term = get_term_by('name', $atts['category'], 'awplife-event-categories');
    if ($term) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'awplife-event-categories',
                'field'    => 'term_id',
                'terms'    => $term->term_id,
            ),
        );
    } else {
        // Fallback to meta query for backward compatibility
        $args['meta_query'][] = array(
            'key' => 'em_event_category',
            'value' => $atts['category'],
            'compare' => 'LIKE'
        );
    }
}

$events_query = isset($events_query) ? $events_query : new WP_Query($args);

// Get all categories for filter
$all_events = get_posts(array(
    'post_type' => 'awl_event_monster',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'fields' => 'ids'
));

$categories = array();

// Get categories from WordPress taxonomy
$wp_categories = get_terms(array(
    'taxonomy' => 'awplife-event-categories',
    'hide_empty' => true,
));

if (!is_wp_error($wp_categories) && !empty($wp_categories)) {
    foreach ($wp_categories as $term) {
        $categories[] = $term->name;
    }
}

// Also get categories from meta fields (for backward compatibility)
foreach ($all_events as $event_id) {
    $event_settings = get_post_meta($event_id, 'awl_em_settings_' . $event_id, true);
    if (isset($event_settings['em_event_category']) && !empty($event_settings['em_event_category'])) {
        $cat = $event_settings['em_event_category'];
        if (!in_array($cat, $categories)) {
            $categories[] = $cat;
        }
    }
}

// Remove duplicates and sort
$categories = array_unique($categories);
sort($categories);

// Debug: Check what categories we found
// error_log('Event Monster Categories found: ' . print_r($categories, true));

// Generate unique ID for this list instance
$list_id = 'em-list-' . uniqid();
?>

<!-- Styles are now loaded via compiled Tailwind CSS -->

<div class="em-list-container" id="<?php echo esc_attr($list_id); ?>">
   

    <?php if ($atts['show_filters'] === 'yes'): ?>
        <?php include EM_FREE_PLUGIN_DIR . 'templates/frontend/components/event-list-filters.php'; ?>
    <?php endif; ?>

    <!-- Event List Grid -->
    <div class="em-events-grid em-cols-<?php echo esc_attr($atts['columns']); ?>" id="em-event-list-<?php echo esc_attr($list_id); ?>">
        <?php if ($events_query->have_posts()): ?>
            <?php while ($events_query->have_posts()): $events_query->the_post(); ?>
                <?php
                $event_id = get_the_ID();
                $event_post = get_post($event_id); // Set $event_post for component compatibility
                $event_settings = get_post_meta($event_id, 'awl_em_settings_' . $event_id, true);
                if (!is_array($event_settings)) $event_settings = array();

                // Get event data
                $event_title = get_the_title();
                $event_description = get_the_excerpt();
                if (empty($event_description)) {
                    $event_description = wp_trim_words(get_the_content(), 20);
                }

                // Get event dates
                $start_date = isset($event_settings['em_start_date']) ? $event_settings['em_start_date'] : '';
                $end_date = isset($event_settings['em_end_date']) ? $event_settings['em_end_date'] : '';
                $start_time = isset($event_settings['em_start_time']) ? $event_settings['em_start_time'] : '';

                // Format dates
                $formatted_date = '';
                if ($start_date) {
                    $start_timestamp = strtotime($start_date);
                    if ($end_date && $end_date !== $start_date) {
                        $end_timestamp = strtotime($end_date);
                        $formatted_date = date_i18n('F j', $start_timestamp) . ' - ' . date_i18n('F j, Y', $end_timestamp);
                    } else {
                        $formatted_date = date_i18n('F j, Y', $start_timestamp);
                    }
                    if ($start_time) {
                        $formatted_date .= ' at ' . date_i18n('g:i A', strtotime($start_time));
                    }
                }

                // Get location
                $location = isset($event_settings['em_event_location']) ? $event_settings['em_event_location'] : '';

                // Get category
                $category = isset($event_settings['em_event_category']) ? $event_settings['em_event_category'] : '';

                // Get featured image - with fallback to event banner (em_upload_image)
                $featured_image = get_the_post_thumbnail_url($event_id, 'medium');
                
                // Fallback to event banner image from settings
                if (!$featured_image) {
                    if (isset($event_settings['em_upload_image']) && !empty($event_settings['em_upload_image'])) {
                        $featured_image = $event_settings['em_upload_image'];
                    }
                }
                
                // Final fallback: use a placeholder image
                if (!$featured_image) {
                    $featured_image = EM_FREE_PLUGIN_URL . 'images/placeholder-840x630.png';
                }

                // Determine view URL
                if ($atts['view_mode'] === 'modal') {
                    $view_url = '#';
                    $view_class = 'em-view-modal';
                    $view_data = 'data-event-id="' . esc_attr($event_id) . '"';
                } else {
                    // Get the actual current page URL (not the event's permalink)
                    // This is important for backward compatibility when [EM] shortcode is used on various pages
                    global $wp;
                    $current_url = home_url(add_query_arg(array(), $wp->request));
                    
                    // Fallback: try using the queried object if available
                    if (empty($current_url) || $current_url === home_url()) {
                        $queried_object = get_queried_object();
                        if ($queried_object && isset($queried_object->ID)) {
                            $current_url = get_permalink($queried_object->ID);
                        }
                    }
                    
                    // Final fallback: use the current request URI
                    if (empty($current_url) || $current_url === home_url()) {
                        $current_url = home_url($_SERVER['REQUEST_URI']);
                    }
                    
                    // Remove any existing em_single parameter from current URL
                    $current_url = remove_query_arg('em_single', $current_url);
                    $current_url = remove_query_arg('em_back', $current_url);
                    
                    $view_url = add_query_arg(array(
                        'em_single' => $event_id,
                        'em_back' => urlencode($current_url)
                    ), $current_url);
                    $view_class = '';
                    $view_data = '';
                }
                ?>

                <?php
                // Use the same component for consistency
                include EM_FREE_PLUGIN_DIR . 'templates/frontend/components/event-card.php';
                ?>
            <?php endwhile; ?>

            <!-- No Results Message -->
            <div id="em-no-results-<?php echo esc_attr($list_id); ?>" class="em-no-results em-hidden">
                <h3><?php _e('No Events Found', 'event-monster'); ?></h3>
                <p><?php _e('Try adjusting your filters to find what you\'re looking for.', 'event-monster'); ?></p>
            </div>

        <?php else: ?>
            <div class="em-no-results">
                <h3><?php _e('No Events Available', 'event-monster'); ?></h3>
                <p><?php _e('There are currently no events to display.', 'event-monster'); ?></p>
            </div>
        <?php endif; ?>
    </div>

    <!-- Load More Button -->
    <?php
    $show_load_more = $events_query->have_posts() && intval($atts['limit']) > 0;
    ?>
    <?php if ($show_load_more): ?>
    <div class="em-load-more-container em-text-center em-mt-8">
        <button id="em-load-more-btn-<?php echo esc_attr($list_id); ?>"
                class="em-load-more-btn em-px-6 em-py-3 em-bg-indigo-600 em-text-white em-font-semibold em-rounded-lg hover:em-bg-indigo-700 em-transition-colors em-shadow-lg"
                data-list-id="<?php echo esc_attr($list_id); ?>"
                data-page="2"
                data-limit="<?php echo esc_attr($atts['limit']); ?>"
                data-category="<?php echo esc_attr($atts['category']); ?>"
                data-view-mode="<?php echo esc_attr($atts['view_mode']); ?>"
                data-columns="<?php echo esc_attr($atts['columns']); ?>"
                data-show-filters="<?php echo esc_attr($atts['show_filters']); ?>">
            <span class="em-load-more-text"><?php _e('Load More Events', 'event-monster'); ?></span>
            <span class="em-load-more-spinner em-hidden em-ml-2">
                <svg class="em-animate-spin em-h-4 em-w-4" fill="none" viewBox="0 0 24 24">
                    <circle class="em-opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="em-opacity-75" fill="currentColor" d="m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
            </span>
        </button>
    </div>
    <?php endif; ?>
</div>

<script>
// Wait for jQuery to be available
function waitForJQuery(callback) {
    if (typeof jQuery !== 'undefined') {
        callback(jQuery);
    } else {
        setTimeout(function() {
            waitForJQuery(callback);
        }, 100);
    }
}

// Initialize when jQuery is available
if (typeof jQuery !== 'undefined') {
    initializeEventList(jQuery);
} else {
    waitForJQuery(initializeEventList);
}

function initializeEventList($) {
    console.log('jQuery is now available, $ is:', typeof $);

    $(document).ready(function() {
        console.log('Document ready fired');

        const listId = '<?php echo esc_js($list_id); ?>';
        console.log('Initializing event list:', listId);

        // Set up filtering if filters are enabled
        <?php if ($atts['show_filters'] === 'yes'): ?>
        if (typeof window.emFilterEvents === 'function') {
            // Initial filter setup is handled by the external JS file
            console.log('Event list filters initialized for:', listId);
        }
        <?php endif; ?>

        // Handle modal view mode
        <?php if ($atts['view_mode'] === 'modal'): ?>
        // Create global modal function if it doesn't exist
        if (typeof window.showEventModal !== 'function') {
            window.showEventModal = function(eventId) {
                console.log('Opening modal for event ID:', eventId);

                // STANDARDIZED: Use same approach as calendar modal
                // Create modal container if it doesn't exist (matches calendar-integration.js)
                let modalContainer = document.getElementById('em-event-modal');
                if (!modalContainer) {
                    modalContainer = document.createElement('div');
                    modalContainer.id = 'em-event-modal';
                    modalContainer.className = 'em-modal-overlay';
                    document.body.appendChild(modalContainer);
                }

                // CRITICAL: Reset modal state before showing (fixes reopen issue)
                // Remove em-hidden class that might have been added during close
                jQuery(modalContainer).removeClass('em-hidden');
                modalContainer.style.opacity = '1';
                modalContainer.style.display = 'flex';

                // Show loading state
                modalContainer.innerHTML = `
                    <div class="em-event-modal-content">
                        <div class="em-loading-spinner">
                            <div class="em-spinner"></div>
                            <p>Loading event details...</p>
                        </div>
                    </div>
                `;
                document.body.classList.add('em-modal-open');

                // Load event content via AJAX
                var ajaxUrl = '<?php echo admin_url("admin-ajax.php"); ?>';
                $.ajax({
                    url: ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'em_get_event_modal_content',
                        event_id: eventId,
                        nonce: em_ajax_object.nonce
                    },
                    success: function(response) {
                        console.log('AJAX response:', response);
                        if (response.success) {
                            // Wrap content with modal header and close button
                            var modalHTML = `
                                <div class="em-event-modal-content">
                                    <div class="em-modal-header">
                                        <h2 class="em-modal-title">` + (response.data.title || 'Event Details') + `</h2>
                                        <button type="button" class="em-modal-close">
                                            <span>&times;</span>
                                        </button>
                                    </div>
                                    <div class="em-modal-body">
                                        ` + response.data.content + `
                                    </div>
                                </div>
                            `;

                            modalContainer.innerHTML = modalHTML;

                            // Make ajaxUrl available globally for registration component
                            window.ajaxUrl = ajaxUrl;
                            console.log('🌐 Set global ajaxUrl for list modal context:', window.ajaxUrl);

                            // CRITICAL: Execute both external AND inline scripts that were inserted via innerHTML
                            setTimeout(function() {
                                // Execute external scripts
                                var externalScripts = modalContainer.querySelectorAll('script[src]');
                                externalScripts.forEach(function(scriptElement) {
                                    var src = scriptElement.getAttribute('src');
                                    if (src && !document.querySelector('script[src="' + src + '"]')) {
                                        console.log('🔗 Loading external script:', src);
                                        var script = document.createElement('script');
                                        script.src = src;
                                        script.async = true;
                                        document.head.appendChild(script);
                                    }
                                });

                                // Execute inline scripts (CRITICAL FIX for form submission handlers)
                                var inlineScripts = modalContainer.querySelectorAll('script:not([src])');
                                inlineScripts.forEach(function(scriptElement) {
                                    console.log('📜 Executing inline script in list modal');
                                    try {
                                        // Create a new script element and execute it
                                        var newScript = document.createElement('script');
                                        newScript.textContent = scriptElement.textContent;
                                        document.body.appendChild(newScript);
                                        // Remove it immediately after execution
                                        document.body.removeChild(newScript);
                                    } catch (error) {
                                        console.error('❌ Error executing inline script:', error);
                                    }
                                });

                                console.log('✅ List modal content loaded with external and inline script handling');
                            }, 100);

                            // Initialize maps with additional delay to ensure modal is fully rendered
                            setTimeout(function() {
                                var mapContainers = modalContainer.querySelectorAll('[id^="em-map-"]');
                                if (mapContainers.length > 0 && typeof window.initEventMap === 'function') {
                                    console.log('🗺️ Found ' + mapContainers.length + ' map(s) in list template modal, initializing...');
                                    mapContainers.forEach(function(mapContainer) {
                                        var mapId = mapContainer.getAttribute('id');
                                        console.log('🗺️ Initializing map:', mapId);
                                        window.initEventMap(mapId);
                                    });
                                }
                            }, 500);

                            console.log('📋 List view modal loaded with standardized approach');
                        } else {
                            console.error('AJAX error:', response.data);
                            modalContainer.innerHTML = '<div class="em-event-modal-content"><p>Error: ' + (response.data || 'Unknown error') + '</p></div>';
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('AJAX request failed:', {
                            status: status,
                            error: error,
                            responseText: xhr.responseText
                        });
                        modalContainer.innerHTML = '<div class="em-event-modal-content"><p>Error loading event details: ' + error + '</p></div>';
                    }
                });
            };

            // STANDARDIZED: Use same close behavior as calendar modal
            window.closeEventModal = function() {
                const modalContainer = document.getElementById('em-event-modal');
                if (modalContainer) {
                    // Destroy all maps before closing modal
                    if (typeof window.destroyAllEventMaps === 'function') {
                        console.log('🗑️ Destroying maps before closing modal...');
                        window.destroyAllEventMaps();
                    }

                    // Fade out animation
                    modalContainer.style.opacity = '0';

                    setTimeout(function() {
                        modalContainer.style.display = 'none';
                        modalContainer.innerHTML = '';
                        modalContainer.style.opacity = '1'; // Reset for next time
                        document.body.classList.remove('em-modal-open');

                        // CRITICAL: Remove any lingering backdrop/overlay classes and elements
                        jQuery('body, html').removeClass('em-modal-open');

                        // Hide any visible .em-modal-overlay elements (registration modals)
                        // IMPORTANT: Exclude the main modal container (#em-event-modal) to avoid breaking reopen
                        jQuery('.em-modal-overlay:visible').not('#em-event-modal').addClass('em-hidden').hide();

                        // Also remove em-modal-open class that might have been added by registration modal
                        jQuery('body').css('overflow', ''); // Reset overflow

                        console.log('✅ Modal closed and all overlays cleaned up');
                    }, 300); // Match CSS transition duration
                }
            };
        }

        // STANDARDIZED: Global event handlers (only added once)
        // Handle clicks on modal overlay and close button
        $(document).on('click', '#em-event-modal', function(e) {
            // Close if clicking on overlay (not on modal content)
            if (e.target.id === 'em-event-modal') {
                window.closeEventModal();
            }
        });

        $(document).on('click', '.em-modal-close', function(e) {
            e.preventDefault();
            e.stopPropagation();
            window.closeEventModal();
        });

        // Keyboard support for closing modal
        $(document).on('keydown', function(e) {
            const modalContainer = document.getElementById('em-event-modal');
            if (e.key === 'Escape' && modalContainer && modalContainer.style.display === 'flex') {
                window.closeEventModal();
            }
        });

        // Handle success messages in nested modals (registration within event modal)
        $(document).on('DOMNodeInserted', '#em-event-modal', function(e) {
            // Check for success messages
            var $successMsg = $(e.target).find('.em-success-message, .success-message, .em-payment-success, .alert-success');
            if ($successMsg.length > 0) {
                // Make sure success message is visible
                $successMsg.css({
                    'display': 'block !important',
                    'visibility': 'visible !important',
                    'opacity': '1 !important',
                    'z-index': '999999 !important',
                    'position': 'relative !important'
                });

                // Scroll to success message
                setTimeout(function() {
                    if ($successMsg[0]) {
                        $successMsg[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
                    }
                }, 100);
            }
        });

        // Also handle success messages that might be added via AJAX
        $(document).ajaxComplete(function(event, xhr, settings) {
            if ($('#em-event-modal').is(':visible')) {
                setTimeout(function() {
                    var $successMsg = $('#em-event-modal').find('.em-success-message, .success-message, .em-payment-success, .alert-success');
                    if ($successMsg.length > 0) {
                        $successMsg.css({
                            'display': 'block !important',
                            'visibility': 'visible !important',
                            'opacity': '1 !important',
                            'z-index': '999999 !important',
                            'position': 'relative !important'
                        });
                        if ($successMsg[0]) {
                            $successMsg[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
                        }
                    }
                }, 500);
            }
        });

        // Handle registration modal buttons (force them to work in AJAX loaded content)
        $(document).on('click', 'button[id^="em-show-registration-modal-"]', function(e) {
            e.preventDefault();
            var eventId = $(this).attr('id').replace('em-show-registration-modal-', '');
            var $modal = $('#em-registration-modal-' + eventId);

            console.log('Registration button clicked for event:', eventId);
            console.log('Modal found:', $modal.length > 0);

            if ($modal.length > 0) {
                // Force show the modal
                $modal.removeClass('em-hidden').show().css({
                    'display': 'flex !important',
                    'visibility': 'visible',
                    'opacity': '1'
                });
                $('body, html').addClass('em-modal-open');
                console.log('Modal should now be visible');
            } else {
                console.error('Registration modal not found for event:', eventId);
            }
        });

        // Handle registration modal close buttons
        $(document).on('click', 'button[id^="em-close-modal-"]', function(e) {
            e.preventDefault();
            var eventId = $(this).attr('id').replace('em-close-modal-', '');
            $('#em-registration-modal-' + eventId).addClass('em-hidden').hide();
            $('body, html').removeClass('em-modal-open');
        });
    }

    $('.em-view-modal').on('click', function(e) {
        e.preventDefault();
        const eventId = $(this).data('event-id');
        if (eventId) {
            window.showEventModal(eventId);
        }
    });
    <?php endif; ?>

    // Debug: Check if load more button exists
    console.log('Load more buttons found:', $('.em-load-more-btn').length);
    console.log('Load more button HTML:', $('.em-load-more-btn').length > 0 ? $('.em-load-more-btn')[0].outerHTML : 'No button found');

    // Test click detection
    $('.em-load-more-btn').each(function() {
        console.log('Button found with ID:', $(this).attr('id'));
        console.log('Button classes:', $(this).attr('class'));
    });

    // Handle Load More Events
    $(document).on('click', '.em-load-more-btn', function(e) {
        e.preventDefault();

        var $btn = $(this);
        var $text = $btn.find('.em-load-more-text');
        var $spinner = $btn.find('.em-load-more-spinner');
        var listId = $btn.data('list-id');
        var page = parseInt($btn.data('page'));

        // Show loading state
        $text.text('<?php _e('Loading...', 'event-monster'); ?>');
        $spinner.removeClass('em-hidden');
        $btn.prop('disabled', true);

        // AJAX request
        var ajaxUrl = '<?php echo admin_url("admin-ajax.php"); ?>';
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'em_load_more_events',
                page: page,
                limit: $btn.data('limit'),
                category: $btn.data('category'),
                view_mode: $btn.data('view-mode'),
                columns: $btn.data('columns'),
                show_filters: $btn.data('show-filters'),
                nonce: em_ajax_object.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Append new events
                    $('#em-event-list-' + listId).append(response.data.html);

                    // Update page number
                    $btn.data('page', page + 1);

                    // Hide button if no more events
                    if (!response.data.has_more) {
                        $btn.hide();
                    }
                } else {
                    console.error('Load more error:', response.data);
                    alert('<?php _e('Error loading more events. Please try again.', 'event-monster'); ?>');
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error:', error);
                alert('<?php _e('Error loading more events. Please try again.', 'event-monster'); ?>');
            },
            complete: function() {
                // Reset button state
                $text.text('<?php _e('Load More Events', 'event-monster'); ?>');
                $spinner.addClass('em-hidden');
                $btn.prop('disabled', false);
            }
        });

        // REMOVED: Duplicate load more handler that was causing double AJAX calls

        // REMOVED: Debug code that was automatically triggering load more and causing duplicate posts
    });
    });
}
</script>

<?php wp_reset_postdata(); ?>