<?php
/**
 * HVAC Manage Event Handler
 * 
 * Ensures proper shortcode processing for the manage-event page
 * 
 * @package HVAC_Community_Events
 * @since 1.0.0
 */

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

class HVAC_Manage_Event {
    
    /**
     * Constructor
     */
    public function __construct() {
        // DISABLED: Content filtering is now handled directly in the template
        // add_filter('the_content', array($this, 'ensure_shortcode_processing'), 99);
        
        // Add authentication check for manage-event page
        add_action('template_redirect', array($this, 'check_manage_event_auth'));
        
        // Add CSS for the events form
        add_action('wp_head', array($this, 'add_event_form_styles'));
        
        // Debug: Log when this class is instantiated
        if (defined('HVAC_PLUGIN_DIR') && class_exists('HVAC_Logger')) {
            HVAC_Logger::info('HVAC_Manage_Event class instantiated', 'ManageEvent');
        }
    }
    
    /**
     * Ensure shortcode processing for manage-event page
     */
    public function ensure_shortcode_processing($content) {
        // Check if we're on the manage page using multiple methods
        $is_manage_page = false;
        
        // Method 1: Check by specific slugs
        if (is_page('manage-event') || is_page('trainer-event-manage')) {
            $is_manage_page = true;
        }
        
        // Method 2: Check by post ID (if we can get it)
        if (is_page(5334)) {
            $is_manage_page = true;
        }
        
        // Method 3: Check by URL path
        $current_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        if ($current_path === 'trainer/event/manage' || $current_path === 'trainer/event/manage/') {
            $is_manage_page = true;
        }
        
        // Only process on manage page (the event creation page)
        if (!$is_manage_page) {
            return $content;
        }
        
        // Debug logging
        if (class_exists('HVAC_Logger')) {
            HVAC_Logger::info('Processing manage-event page content', 'ManageEvent');
            HVAC_Logger::info('Original content: ' . substr($content, 0, 200), 'ManageEvent');
        }
        
        // Strip WordPress block editor comments - handle all variations
        $content = preg_replace('/<!--\s*wp:shortcode\s*-->/', '', $content);
        $content = preg_replace('/<!--\s*\/wp:shortcode\s*-->/', '', $content);
        
        // Also strip any remaining HTML comments that might contain shortcode references
        $content = preg_replace('/<!--[^>]*wp:shortcode[^>]*-->/', '', $content);
        
        // Clean up any extra whitespace
        $content = trim($content);
        
        // Process all shortcodes in the content
        $processed_content = do_shortcode($content);
        
        // Debug: Log if content changed
        if (class_exists('HVAC_Logger') && $processed_content !== $content) {
            HVAC_Logger::info('Content was processed by do_shortcode', 'ManageEvent');
        }
        
        // If shortcode wasn't processed (plugin might be inactive), show helpful message
        if (strpos($processed_content, '[tribe_community_events') !== false) {
            if (class_exists('HVAC_Logger')) {
                HVAC_Logger::warning('tribe_community_events shortcode not processed - plugin may be inactive', 'ManageEvent');
            }
            
            $error_content = '<div class="hvac-notice hvac-error">
                <p><strong>Event Submission Form Unavailable</strong></p>
                <p>The event submission form is currently unavailable. Please ensure:</p>
                <ul>
                    <li>The Events Calendar plugin is active</li>
                    <li>The Events Calendar Community Events add-on is active</li>
                    <li>You are logged in as a trainer</li>
                </ul>
                <p><a href="' . esc_url(home_url('/hvac-dashboard/')) . '" class="button">Return to Dashboard</a></p>
            </div>';
            
            return $error_content;
        }
        
        // Return the processed content without wrapping
        return $processed_content;
    }
    
    
    /**
     * Add CSS styles for event form
     */
    public function add_event_form_styles() {
        // Check if we're on the manage page
        $is_manage_page = false;
        
        if (is_page('manage-event') || is_page('trainer-event-manage') || is_page(5334)) {
            $is_manage_page = true;
        }
        
        $current_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        if ($current_path === 'trainer/event/manage' || $current_path === 'trainer/event/manage/') {
            $is_manage_page = true;
        }
        
        if (!$is_manage_page) {
            return;
        }
        
        echo '<style>
        /* Style the TEC Community Events form */
        .tribe-community-events-form {
            background: #fff;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }
        
        .tribe-community-events-form .tribe-events-page-title {
            color: #333;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #eee;
        }
        
        /* Form field styling */
        .tribe-community-events-form .tribe-events-form-row {
            margin-bottom: 20px;
        }
        
        .tribe-community-events-form label {
            font-weight: 600;
            color: #333;
            display: block;
            margin-bottom: 8px;
        }
        
        .tribe-community-events-form input[type="text"],
        .tribe-community-events-form input[type="email"],
        .tribe-community-events-form input[type="url"],
        .tribe-community-events-form textarea,
        .tribe-community-events-form select {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            transition: border-color 0.3s ease;
        }
        
        .tribe-community-events-form input:focus,
        .tribe-community-events-form textarea:focus,
        .tribe-community-events-form select:focus {
            outline: none;
            border-color: #007cba;
            box-shadow: 0 0 5px rgba(0, 124, 186, 0.3);
        }
        
        /* Submit button styling */
        .tribe-community-events-form input[type="submit"],
        .tribe-community-events-form .tribe-events-submit {
            background: #007cba;
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        
        .tribe-community-events-form input[type="submit"]:hover,
        .tribe-community-events-form .tribe-events-submit:hover {
            background: #005a87;
        }
        
        /* TinyMCE editor styling */
        .tribe-community-events-form .wp-editor-wrap {
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        /* Date picker styling */
        .tribe-community-events-form .tribe-datetime-block {
            background: #f9f9f9;
            padding: 15px;
            border-radius: 4px;
            margin: 10px 0;
        }
        
        /* Venue fields styling */
        .tribe-community-events-form .tribe-events-venue-form {
            background: #f9f9f9;
            padding: 20px;
            border-radius: 4px;
            margin: 15px 0;
        }
        
        /* Error and success messages */
        .tribe-community-events-form .tribe-events-notices {
            padding: 15px;
            margin: 20px 0;
            border-radius: 4px;
        }
        
        .tribe-community-events-form .tribe-events-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .tribe-community-events-form .tribe-events-success {
            background: #d1e7dd;
            color: #0f5132;
            border: 1px solid #badbcc;
        }
        
        .hvac-notice.hvac-error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
            padding: 20px;
            margin: 20px 0;
            border-radius: 4px;
        }
        .hvac-notice.hvac-error ul {
            margin: 15px 0 15px 30px;
        }
        </style>
        <script>
        // Remove any HTML comments containing wp:shortcode from the DOM
        document.addEventListener("DOMContentLoaded", function() {
            // Get all text nodes in the event manage wrapper
            var wrapper = document.querySelector(".hvac-event-manage-wrapper");
            if (!wrapper) return;
            
            var walker = document.createTreeWalker(
                wrapper,
                NodeFilter.SHOW_ALL,
                null,
                false
            );
            
            var nodesToRemove = [];
            var node;
            
            while (node = walker.nextNode()) {
                // Check for comment nodes
                if (node.nodeType === 8 && node.nodeValue && node.nodeValue.includes("wp:shortcode")) {
                    nodesToRemove.push(node);
                }
                // Also check text nodes that might contain the comment as text
                else if (node.nodeType === 3 && node.nodeValue && node.nodeValue.includes("<!-- wp:shortcode -->")) {
                    node.nodeValue = node.nodeValue.replace(/<!--\s*wp:shortcode\s*-->/g, "").replace(/<!--\s*\/wp:shortcode\s*-->/g, "");
                }
            }
            
            // Remove comment nodes
            nodesToRemove.forEach(function(node) {
                node.remove();
            });
        });
        </script>';
    }
    
    /**
     * Check authentication for manage-event page
     */
    public function check_manage_event_auth() {
        // Check if we're on the manage page using multiple methods
        $is_manage_page = false;
        
        // Method 1: Check by specific slugs
        if (is_page('manage-event') || is_page('trainer-event-manage')) {
            $is_manage_page = true;
        }
        
        // Method 2: Check by post ID
        if (is_page(5334)) {
            $is_manage_page = true;
        }
        
        // Method 3: Check by URL path
        $current_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        if ($current_path === 'trainer/event/manage' || $current_path === 'trainer/event/manage/') {
            $is_manage_page = true;
        }
        
        // Check if we're on the manage page (event creation page) and not logged in
        if ($is_manage_page && !is_user_logged_in()) {
            // Redirect to login page
            wp_redirect(home_url('/training-login/?redirect_to=' . urlencode($_SERVER['REQUEST_URI'])));
            exit;
        }
    }
}