<?php
/**
 * Handles the registration and rendering of all frontend shortcodes.
 * This class replaces the old shortcode.php file.
 */
if (!defined('ABSPATH'))
    exit;

class Event_Monster_Free_Shortcodes
{

    /**
     * Constructor. Hooks all shortcodes into WordPress.
     */
    public function __construct()
    {
        add_shortcode('EM', array($this, 'render_single_event_shortcode'));
        add_shortcode('EM-LIST', array($this, 'render_event_list_shortcode'));
        add_shortcode('EM-CALENDAR', array($this, 'render_calendar_shortcode'));
    }

    /**
     * Renders the [EM id="123"] shortcode for a single event.
     * 
     * For backward compatibility with the old plugin:
     * - [EM id="123"] shows a single event
     * - [EM] without id shows the event list (same as [EM-LIST])
     */
    public function render_single_event_shortcode($atts)
    {
        // Merge with defaults, preserving all attributes for potential list view
        $atts = shortcode_atts(array(
            'id' => 0,
            // List view attributes for backward compatibility
            'limit' => -1,
            'category' => '',
            'show_filters' => 'yes',
            'view_mode' => 'page',
            'columns' => '3'
        ), $atts, 'EM');
        
        $post_id = absint($atts['id']);

        // Backward compatibility: If no ID is provided, show the event list
        // This matches the old plugin behavior where [EM] without id showed all events
        if (!$post_id) {
            return $this->render_event_list_shortcode($atts);
        }

        if (get_post_type($post_id) !== 'awl_event_monster') {
            return '<p>Event not found.</p>';
        }

        // During REST API requests (like when saving in the editor), return a simple placeholder
        // This prevents PHP errors from breaking the JSON response
        if (defined('REST_REQUEST') && REST_REQUEST) {
            return '<div class="em-event-placeholder" data-event-id="' . esc_attr($post_id) . '">' .
                   '<p>Event #' . $post_id . ' will be displayed here.</p>' .
                   '</div>';
        }

        // Get event data
        $event_post = get_post($post_id);
        $event_settings = get_post_meta($post_id, 'awl_em_settings_' . $post_id, true);
        if (!is_array($event_settings))
            $event_settings = array();

        // Set global variables for backward compatibility
        global $em_id;
        $em_id = $post_id;
        $event_id = $post_id;

        // Enqueue required assets
        $this->enqueue_event_assets();

        // Render template with error handling
        ob_start();
        try {
            // Suppress any PHP warnings/notices that might break JSON response
            $template_file = EM_FREE_PLUGIN_DIR . 'templates/frontend/single-event-template.php';
            if (file_exists($template_file)) {
                include $template_file;
            } else {
                echo '<p class="em-error">Template file not found.</p>';
            }
        } catch (Exception $e) {
            // Log error but don't output it (would break JSON)
            if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
                error_log('Event Monster Shortcode Error: ' . $e->getMessage());
            }
            echo '<p class="em-error">Error rendering event. Please check the error log.</p>';
        }
        return ob_get_clean();
    }

    private function enqueue_event_assets()
    {
        // Use the same comprehensive asset loading as event list
        $this->enqueue_event_list_assets();
    }

    /**
     * Renders the [EM-LIST] shortcode for a list of events.
     *
     * Attributes:
     * - limit: Number of events to show (-1 for all)
     * - category: Filter by specific category
     * - show_filters: Show/hide filter section (yes/no)
     * - view_mode: How to view event details (page/modal)
     * - columns: Number of columns (1-4)
     */
    public function render_event_list_shortcode($atts)
    {
        // Parse 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, 'EM-LIST');

        // Enqueue required assets
        $this->enqueue_event_list_assets();

        // Build query args
        $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'])) {
            $args['meta_query'][] = array(
                'key' => 'em_event_category',
                'value' => $atts['category'],
                'compare' => 'LIKE'
            );
        }

        $events_query = new WP_Query($args);

        // Start output buffering
        ob_start();
        // Make $atts available to the template
        include(EM_FREE_PLUGIN_DIR . 'templates/frontend/event-list-template.php');
        wp_reset_postdata();
        return ob_get_clean();
    }

    /**
     * Enqueue assets specific to event list
     */
    private function enqueue_event_list_assets()
    {
        // Ensure jQuery is loaded in header
        wp_enqueue_script('jquery');

        // Force jQuery to load in header to ensure it's available
        global $wp_scripts;
        if (isset($wp_scripts->registered['jquery'])) {
            $wp_scripts->registered['jquery']->extra['group'] = 0; // 0 = header, 1 = footer
        }

        // Enqueue compiled Tailwind CSS
        wp_enqueue_style(
            'em-tailwind-css',
            EM_FREE_PLUGIN_URL . 'assets/css/tailwind.css',
            array(),
            filemtime(EM_FREE_PLUGIN_DIR . 'assets/css/tailwind.css')
        );

        // Enqueue frontend styles (custom styles on top of Tailwind)
        wp_enqueue_style(
            'em-frontend-styles',
            EM_FREE_PLUGIN_URL . 'assets/css/frontend.css',
            array('em-tailwind-css'),
            filemtime(EM_FREE_PLUGIN_DIR . 'assets/css/frontend.css')
        );

        // Enqueue JavaScript
        wp_enqueue_script(
            'em-event-list-filters',
            EM_FREE_PLUGIN_URL . 'assets/js/event-list-filters.js',
            array('jquery'),
            filemtime(EM_FREE_PLUGIN_DIR . 'assets/js/event-list-filters.js'),
            true
        );

        // Localize script for AJAX
        wp_localize_script('em-event-list-filters', 'em_ajax_object', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('em_ajax_nonce')
        ));
    }

    /**
     * Renders the [EM-CALENDAR] shortcode for calendar view
     */
    public function render_calendar_shortcode($atts)
    {
        // Initialize calendar class if not already done
        if (!class_exists('Event_Monster_Free_Calendar')) {
            require_once EM_FREE_PLUGIN_DIR . 'includes/class-event-monster-calendar.php';
        }

        $calendar = new Event_Monster_Free_Calendar();
        return $calendar->render_calendar_shortcode($atts);
    }
}
