<?php
/**
 * Event Monster Calendar Integration
 * Handles FullCalendar integration for event display
 * 
 * @package EventMonster
 * @since 4.1.0
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

class Event_Monster_Free_Calendar
{
    /**
     * Calendar configuration
     */
    private $config;

    /**
     * Event query handler
     */
    private $event_query;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->init_config();
        $this->init_hooks();
        // Initialize query handler after class is defined
        add_action('init', array($this, 'init_query_handler'));
    }

    /**
     * Initialize configuration
     */
    private function init_config()
    {
        $this->config = array(
            'fullcalendar_version' => '6.1.10',
            'default_view' => 'dayGridMonth',
            'default_height' => 'auto',
            'category_colors' => array(
                'conference' => '#6366f1',
                'workshop' => '#10b981',
                'seminar' => '#f59e0b',
                'networking' => '#ef4444',
                'training' => '#8b5cf6',
                'webinar' => '#06b6d4',
            ),
        );
    }

    /**
     * Initialize WordPress hooks
     */
    private function init_hooks()
    {
        add_action('wp_enqueue_scripts', array($this, 'enqueue_calendar_assets'));
        add_action('wp_ajax_em_get_calendar_events', array($this, 'handle_calendar_events_ajax'));
        add_action('wp_ajax_nopriv_em_get_calendar_events', array($this, 'handle_calendar_events_ajax'));
        add_action('wp_ajax_em_get_event_modal', array($this, 'handle_event_modal_ajax'));
        add_action('wp_ajax_nopriv_em_get_event_modal', array($this, 'handle_event_modal_ajax'));
    }

    /**
     * Initialize query handler
     */
    public function init_query_handler()
    {
        if (class_exists('Event_Monster_Free_Calendar_Query')) {
            $this->event_query = new Event_Monster_Free_Calendar_Query();
        }
    }

    /**
     * Enqueue FullCalendar assets
     */
    public function enqueue_calendar_assets()
    {
        // Only enqueue when calendar is being used
        if (!$this->should_enqueue_calendar()) {
            return;
        }

        // 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 Google Fonts
        wp_enqueue_style(
            'em-google-fonts',
            'https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap',
            array(),
            null
        );

        // Enqueue compiled Tailwind CSS (CRITICAL for modal styles)
        wp_enqueue_style(
            'em-tailwind-css',
            EM_FREE_PLUGIN_URL . 'assets/css/tailwind.css',
            array('em-google-fonts'),
            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')
        );

        // FullCalendar CSS
        wp_enqueue_style(
            'fullcalendar-css',
            'https://cdn.jsdelivr.net/npm/fullcalendar@6.1.10/index.global.min.css',
            array('em-tailwind-css'),
            '6.1.10'
        );

        // FullCalendar JS
        wp_enqueue_script(
            'fullcalendar-js',
            'https://cdn.jsdelivr.net/npm/fullcalendar@6.1.10/index.global.min.js',
            array(),
            '6.1.10',
            true
        );

        // Payment gateway SDKs removed from free version (PayPal, Stripe, etc.)
        // Upgrade to Event Monster Pro for payment processing in calendar modals.

        // Our calendar integration JS
        wp_enqueue_script(
            'em-calendar-integration',
            EM_FREE_PLUGIN_URL . 'assets/js/calendar-integration.js',
            array('jquery', 'fullcalendar-js'),
            filemtime(EM_FREE_PLUGIN_DIR . 'assets/js/calendar-integration.js'),
            true
        );

        // Localize script for AJAX
        wp_localize_script('em-calendar-integration', 'emCalendar', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('em_calendar_nonce'),
            'strings' => array(
                'loading' => __('Loading events...', 'event-monster'),
                'noEvents' => __('No events found', 'event-monster'),
                'viewDetails' => __('View Details', 'event-monster'),
                'register' => __('Register', 'event-monster'),
            )
        ));
    }

    /**
     * Check if calendar assets should be enqueued
     */
    private function should_enqueue_calendar()
    {
        global $post;

        // Check if current post/page contains calendar shortcode
        if ($post && has_shortcode($post->post_content, 'EM-CALENDAR')) {
            return true;
        }

        // Only load on pages that actually have the calendar shortcode
        // Don't load on all pages/singles - this was causing unnecessary loading
        return false;
    }

    /**
     * Handle calendar events AJAX request
     */
    public function handle_calendar_events_ajax()
    {
        try {
            // Verify nonce
            if (!wp_verify_nonce($_POST['nonce'] ?? '', 'em_calendar_nonce')) {
                throw new Exception('Security check failed');
            }

            $start = sanitize_text_field($_POST['start'] ?? '');
            $end = sanitize_text_field($_POST['end'] ?? '');
            $category = sanitize_text_field($_POST['category'] ?? '');

            if (empty($start) || empty($end)) {
                throw new Exception('Invalid date range');
            }

        // Get all events (we'll filter by date after getting the data)
        $args = array(
            'post_type' => 'awl_event_monster',
            'post_status' => 'publish',
            'posts_per_page' => -1,
        );

        // Add category filter if specified
        if (!empty($category)) {
            $term = get_term_by('name', $category, 'awplife-event-categories');
            if ($term) {
                $args['tax_query'] = array(
                    array(
                        'taxonomy' => 'awplife-event-categories',
                        'field'    => 'term_id',
                        'terms'    => $term->term_id,
                    ),
                );
            }
        }

        $events_query = new WP_Query($args);
        $calendar_events = array();

        if ($events_query->have_posts()) {
            while ($events_query->have_posts()) {
                $events_query->the_post();
                $event_id = get_the_ID();
                $event_settings = get_post_meta($event_id, 'awl_em_settings_' . $event_id, true);
                
                if (!is_array($event_settings)) {
                    $event_settings = array();
                }

                $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_date;

                // Skip events without dates
                if (empty($start_date)) {
                    continue;
                }

                // Filter by date range
                $event_start = strtotime($start_date);
                $range_start = strtotime($start);
                $range_end = strtotime($end);

                // Skip events outside the requested date range
                if ($event_start < $range_start || $event_start > $range_end) {
                    continue;
                }

                $start_time = isset($event_settings['em_start_time']) ? $event_settings['em_start_time'] : '';
                $end_time = isset($event_settings['em_end_time']) ? $event_settings['em_end_time'] : '';

                // Get category
                $event_category = '';
                $wp_categories = get_the_terms($event_id, 'awplife-event-categories');
                if (!is_wp_error($wp_categories) && !empty($wp_categories)) {
                    $event_category = $wp_categories[0]->name;
                } elseif (isset($event_settings['em_event_category'])) {
                    $event_category = $event_settings['em_event_category'];
                }

                // Filter by category if specified
                if (!empty($category) && strtolower(trim($event_category)) !== strtolower(trim($category))) {
                    continue;
                }

                // Format dates for FullCalendar
                $calendar_start = $start_date;
                $calendar_end = $end_date;

                if ($start_time) {
                    $calendar_start .= 'T' . $start_time;
                }
                if ($end_time && $end_date) {
                    $calendar_end .= 'T' . $end_time;
                }

                // Get event image for tooltip
                $event_image = get_the_post_thumbnail_url($event_id, 'medium');

                // Get custom primary color from event settings, fallback to category color
                $event_color = isset($event_settings['em_primary_color']) && !empty($event_settings['em_primary_color'])
                    ? $event_settings['em_primary_color']
                    : $this->get_category_color($event_category);

                $calendar_events[] = array(
                    'id' => $event_id,
                    'title' => get_the_title(),
                    'start' => $calendar_start,
                    'end' => $calendar_end,
                    'url' => '#',
                    'backgroundColor' => $event_color,
                    'borderColor' => $event_color,
                    'extendedProps' => array(
                        'eventId' => $event_id,
                        'category' => $event_category,
                        'location' => isset($event_settings['em_event_location']) ? $event_settings['em_event_location'] : '',
                        'description' => get_the_excerpt(),
                        'image' => $event_image
                    )
                );
            }
        }

            wp_reset_postdata();

            wp_send_json_success($calendar_events);

        } catch (Exception $e) {
            error_log('Event Monster Calendar Error: ' . $e->getMessage());
            wp_send_json_error($e->getMessage());
        }
    }

    /**
     * Handle event modal AJAX request
     */
    public function handle_event_modal_ajax()
    {
        try {
            // Verify nonce
            if (!wp_verify_nonce($_POST['nonce'] ?? '', 'em_calendar_nonce')) {
                throw new Exception('Security check failed');
            }

            $event_id = absint($_POST['event_id'] ?? 0);

            if (empty($event_id) || get_post_type($event_id) !== 'awl_event_monster') {
                throw new Exception('Invalid event ID');
            }

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

            // Set global variables for template compatibility
            global $em_id;
            $em_id = $event_id;

            // Use the same modal content generation as the list view
            if (class_exists('Event_Monster_Free_Ajax')) {
                $ajax_handler = new Event_Monster_Free_Ajax();
                $modal_content = $this->generate_calendar_modal_content($event_post, $event_settings);
            } else {
                $modal_content = $this->generate_fallback_modal_content($event_post, $event_settings);
            }

            // Generate modal HTML with proper structure
            ob_start();
            ?>
            <div class="em-event-modal-content">
                <div class="em-modal-header">
                    <h2 class="em-modal-title"><?php echo esc_html($event_post->post_title); ?></h2>
                  
                     <button type="button" onclick="closeEventModal()" 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">
                    <?php echo $modal_content; ?>
                </div>
            </div>
            <?php
            $modal_html = ob_get_clean();

            wp_send_json_success(array('html' => $modal_html));

        } catch (Exception $e) {
            error_log('Event Monster Modal Error: ' . $e->getMessage());
            wp_send_json_error($e->getMessage());
        }
    }

    /**
     * Generate calendar modal content using the same method as list view
     */
    private function generate_calendar_modal_content($event_post, $event_settings)
    {
        $event_id = $event_post->ID;

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

        // Start output buffering to capture the full single event template
        ob_start();

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

        $full_content = ob_get_clean();

        // Remove footer from modal content
        $full_content = preg_replace('/<footer[^>]*>.*?<\/footer>/is', '', $full_content);

        // Apply the exact same styling as AJAX class
        $modal_content = '<div class="em-modal-single-event">';
        $modal_content .= $full_content;
        $modal_content .= '</div>';

        // Add the exact same CSS as AJAX class generate_simple_modal_content
        $modal_content .= '<style>
        .em-modal-single-event {
            font-family: inherit;
            width: 100%;
            max-width: none;
        }
        .em-modal-single-event .em-bg-slate-50 {
            background: white !important;
            padding: 0 !important;
            min-height: auto !important;
        }
        .em-modal-single-event .em-event-container {
            opacity: 1 !important;
            max-width: none !important;
            margin: 0 !important;
            padding: 0 !important;
            width: 100% !important;
        }
        .em-modal-single-event .em-container {
            max-width: none !important;
            padding: 0 !important;
            width: 100% !important;
        }
        .em-modal-single-event .em-p-5 {
            padding: 1rem !important;
        }
        .em-modal-single-event .em-p-6 {
            padding: 1rem !important;
        }
        .em-modal-single-event .em-registration-section {
            border: 2px solid #10b981 !important;
            border-radius: 0.5rem !important;
            background: #f0fdf4 !important;
        }
        .em-modal-single-event footer {
            display: none !important;
        }
        .em-modal-single-event .em-modal-overlay {
            display: none;
        }
        .em-modal-single-event .em-modal-content {
            border-radius: 1rem !important;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25) !important;
            max-width: 32rem !important;
            width: 100% !important;
            overflow-y: auto !important;
            position: relative !important;
        }
        /* Prevent modal conflicts */
        .em-modal-single-event .em-modal-overlay {
            display: none;
        }
        /* Fix registration modal styles within event modal */
        .em-modal-single-event .em-modal-content {
            border-radius: 1rem !important;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25) !important;
            max-width: 32rem !important;
            width: 100% !important;
            overflow-y: auto !important;
            position: relative !important;
        }
        </style>';

        return $modal_content;
    }

    /**
     * Generate fallback modal content if AJAX class is not available
     */
    private function generate_fallback_modal_content($event_post, $event_settings)
    {
        $event_id = $event_post->ID;

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

        // Start output buffering
        ob_start();

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

        $content = ob_get_clean();

        // Basic styling wrapper
        return '<div class="em-modal-single-event" style="width: 100%; max-width: none; font-family: inherit;">' . $content . '</div>';
    }



    /**
     * Get color for category
     */
    private function get_category_color($category)
    {
        $colors = array(
            'conference' => '#6366f1',
            'workshop' => '#10b981',
            'seminar' => '#f59e0b',
            'networking' => '#ef4444',
            'training' => '#8b5cf6',
            'webinar' => '#06b6d4',
        );

        $category_key = strtolower(trim($category));
        return isset($colors[$category_key]) ? $colors[$category_key] : '#6366f1';
    }

    /**
     * Render calendar shortcode
     */
    public function render_calendar_shortcode($atts)
    {
        $atts = shortcode_atts(array(
            'view' => 'dayGridMonth',
            'height' => 'auto',
            'category' => '',
            'show_filters' => 'yes',
            'view_mode' => 'modal',
        ), $atts, 'EM-CALENDAR');

        // Enqueue assets
        $this->enqueue_calendar_assets();

        // Generate unique ID
        $calendar_id = 'em-calendar-' . uniqid();

        ob_start();
        include EM_FREE_PLUGIN_DIR . 'templates/frontend/calendar-template.php';
        return ob_get_clean();
    }
}

/**
 * Event Monster Calendar Query Handler
 * Handles database queries for calendar events
 */
class Event_Monster_Free_Calendar_Query
{
    /**
     * Get events for date range
     */
    public function get_events_for_range($start_date, $end_date, $category = '')
    {
        $args = $this->build_query_args($start_date, $end_date, $category);
        return new WP_Query($args);
    }

    /**
     * Build WP_Query arguments
     */
    private function build_query_args($start_date, $end_date, $category = '')
    {
        $args = array(
            'post_type' => 'awl_event_monster',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'meta_query' => array(
                array(
                    'key' => 'em_start_date',
                    'value' => array($start_date, $end_date),
                    'compare' => 'BETWEEN',
                    'type' => 'DATE'
                )
            )
        );

        // Add category filter if specified
        if (!empty($category)) {
            $term = get_term_by('name', $category, 'awplife-event-categories');
            if ($term) {
                $args['tax_query'] = array(
                    array(
                        'taxonomy' => 'awplife-event-categories',
                        'field'    => 'term_id',
                        'terms'    => $term->term_id,
                    ),
                );
            }
        }

        return $args;
    }

    /**
     * Format event for FullCalendar
     */
    public function format_event_for_calendar($event_id, $event_settings)
    {
        $start_date = $event_settings['em_start_date'] ?? '';
        $end_date = $event_settings['em_end_date'] ?? $start_date;
        $start_time = $event_settings['em_start_time'] ?? '';
        $end_time = $event_settings['em_end_time'] ?? '';

        // Get category
        $category = $this->get_event_category($event_id, $event_settings);

        // Format dates for FullCalendar
        $calendar_start = $start_date;
        $calendar_end = $end_date;

        if ($start_time) {
            $calendar_start .= 'T' . $start_time;
        }
        if ($end_time && $end_date) {
            $calendar_end .= 'T' . $end_time;
        }

        // Get custom primary color from event settings, fallback to category color
        $event_color = isset($event_settings['em_primary_color']) && !empty($event_settings['em_primary_color'])
            ? $event_settings['em_primary_color']
            : $this->get_category_color($category);

        return array(
            'id' => $event_id,
            'title' => get_the_title($event_id),
            'start' => $calendar_start,
            'end' => $calendar_end,
            'url' => '#',
            'backgroundColor' => $event_color,
            'borderColor' => $event_color,
            'extendedProps' => array(
                'eventId' => $event_id,
                'category' => $category,
                'location' => $event_settings['em_event_location'] ?? '',
                'description' => get_the_excerpt($event_id),
            )
        );
    }

    /**
     * Get event category
     */
    private function get_event_category($event_id, $event_settings)
    {
        $wp_categories = get_the_terms($event_id, 'awplife-event-categories');
        if (!is_wp_error($wp_categories) && !empty($wp_categories)) {
            return $wp_categories[0]->name;
        }

        return $event_settings['em_event_category'] ?? '';
    }

    /**
     * Get color for category
     */
    private function get_category_color($category)
    {
        $colors = array(
            'conference' => '#6366f1',
            'workshop' => '#10b981',
            'seminar' => '#f59e0b',
            'networking' => '#ef4444',
            'training' => '#8b5cf6',
            'webinar' => '#06b6d4',
        );

        $category_key = strtolower(trim($category));
        return $colors[$category_key] ?? '#6366f1';
    }
}
