<?php
/**
 * HVAC Community Events - Email Debugging Class
 *
 * Provides debugging tools for email functionality.
 *
 * @package HVAC_Community_Events
 * @subpackage Community
 */

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

/**
 * Class HVAC_Email_Debug
 *
 * Debugging tools for email functionality.
 */
class HVAC_Email_Debug {
    /**
     * Initialize debugging hooks
     */
    public static function init() {
        // Add debugging AJAX action
        add_action('wp_ajax_hvac_debug_email_attendees', [self::class, 'debug_email_attendees']);
        
        // Add debugging button to admin footer on email attendees page
        add_action('wp_footer', [self::class, 'add_debug_button']);
        
        // Debug wp_mail
        add_action('wp_mail_failed', [self::class, 'log_mail_error']);
    }
    
    /**
     * Add debug button to the email attendees page
     */
    public static function add_debug_button() {
        // Only add on email attendees page
        if (!is_page('email-attendees')) {
            return;
        }
        
        // Get event ID from URL
        $event_id = isset($_GET['event_id']) ? intval($_GET['event_id']) : 0;
        if ($event_id <= 0) {
            return;
        }
        
        // Add debug button
        ?>
        <div style="position: fixed; bottom: 20px; right: 20px; z-index: 9999;">
            <button id="hvac-debug-email" class="button" data-event-id="<?php echo esc_attr($event_id); ?>">Debug Email System</button>
        </div>
        
        <div id="hvac-debug-output" style="display:none; position: fixed; top: 50px; left: 50px; right: 50px; bottom: 50px; background: #fff; border: 2px solid #333; padding: 20px; overflow: auto; z-index: 10000;">
            <h2>Email System Debug Output</h2>
            <pre id="hvac-debug-content" style="white-space: pre-wrap; font-family: monospace;"></pre>
            <button id="hvac-debug-close" class="button" style="position: absolute; top: 10px; right: 10px;">Close</button>
        </div>
        
        <script>
            jQuery(document).ready(function($) {
                $('#hvac-debug-email').on('click', function() {
                    var eventId = $(this).data('event-id');
                    $('#hvac-debug-content').html('Loading debug information...');
                    $('#hvac-debug-output').show();
                    
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'hvac_debug_email_attendees',
                            event_id: eventId,
                            nonce: '<?php echo wp_create_nonce('hvac_debug_email'); ?>'
                        },
                        success: function(response) {
                            $('#hvac-debug-content').html(response.data || 'No debug data returned.');
                        },
                        error: function() {
                            $('#hvac-debug-content').html('Error fetching debug information.');
                        }
                    });
                });
                
                $('#hvac-debug-close').on('click', function() {
                    $('#hvac-debug-output').hide();
                });
            });
        </script>
        <?php
    }
    
    /**
     * Debug email attendees functionality
     */
    public static function debug_email_attendees() {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'hvac_debug_email')) {
            wp_send_json_error('Invalid nonce');
            return;
        }
        
        // Get event ID
        $event_id = isset($_POST['event_id']) ? intval($_POST['event_id']) : 0;
        if ($event_id <= 0) {
            wp_send_json_error('Invalid event ID');
            return;
        }
        
        // Create debug output
        $output = "=== EMAIL SYSTEM DEBUG ===\n\n";
        
        // Check if user is logged in
        $output .= "User login status: " . (is_user_logged_in() ? 'Logged in' : 'Not logged in') . "\n";
        if (is_user_logged_in()) {
            $current_user = wp_get_current_user();
            $output .= "Current user: " . $current_user->display_name . " (" . $current_user->user_email . ")\n";
            $output .= "User roles: " . implode(', ', $current_user->roles) . "\n";
            
            // Check additional user profile data
            $output .= "\n=== USER PROFILE DATA ===\n";
            $business_name = get_user_meta($current_user->ID, 'business_name', true);
            $contact_email = get_user_meta($current_user->ID, 'contact_email', true);
            $phone = get_user_meta($current_user->ID, 'phone', true);
            
            $output .= "Business Name: " . ($business_name ? $business_name : 'Not set') . "\n";
            $output .= "Contact Email: " . ($contact_email ? $contact_email : 'Not set') . "\n";
            $output .= "Phone: " . ($phone ? $phone : 'Not set') . "\n";
            
            // List all meta fields for debugging
            $output .= "\nAll user meta fields:\n";
            $user_meta = get_user_meta($current_user->ID);
            foreach ($user_meta as $key => $value) {
                if (is_array($value) && isset($value[0])) {
                    $output .= "- {$key}: " . (strlen($value[0]) > 50 ? substr($value[0], 0, 50) . "..." : $value[0]) . "\n";
                }
            }
        }
        
        // Check event
        $output .= "\n=== EVENT INFORMATION ===\n";
        $event = get_post($event_id);
        if (!$event) {
            $output .= "Event ID {$event_id} not found.\n";
        } else {
            $output .= "Event ID: {$event_id}\n";
            $output .= "Event title: " . get_the_title($event) . "\n";
            $output .= "Event status: " . get_post_status($event) . "\n";
            $output .= "Event author: " . $event->post_author . "\n";
            
            // Check if user can edit event
            $output .= "Current user can edit event: " . (get_current_user_id() === (int)$event->post_author || current_user_can('edit_posts') ? 'Yes' : 'No') . "\n";
        }
        
        // Get attendees
        $output .= "\n=== ATTENDEES DATA ===\n";
        require_once HVAC_PLUGIN_DIR . 'includes/community/class-email-attendees-data.php';
        $email_data = new HVAC_Email_Attendees_Data($event_id);
        
        // Check if event is valid
        $output .= "Event is valid: " . ($email_data->is_valid_event() ? 'Yes' : 'No') . "\n";
        $output .= "User can email attendees: " . ($email_data->user_can_email_attendees() ? 'Yes' : 'No') . "\n";
        
        // Get attendees
        $attendees = $email_data->get_attendees();
        $output .= "Number of attendees found: " . count($attendees) . "\n\n";
        
        if (!empty($attendees)) {
            $output .= "Attendee details:\n";
            foreach ($attendees as $index => $attendee) {
                $output .= "--- Attendee " . ($index + 1) . " ---\n";
                $output .= "Name: " . (!empty($attendee['name']) ? $attendee['name'] : 'No name') . "\n";
                $output .= "Email: " . (!empty($attendee['email']) ? $attendee['email'] : 'No email') . "\n";
                $output .= "Ticket: " . (!empty($attendee['ticket_name']) ? $attendee['ticket_name'] : 'No ticket name') . "\n";
                $output .= "Attendee ID: " . (!empty($attendee['attendee_id']) ? $attendee['attendee_id'] : 'No ID') . "\n";
                $output .= "Order ID: " . (!empty($attendee['order_id']) ? $attendee['order_id'] : 'No order ID') . "\n\n";
            }
        }
        
        // Test direct attendee query
        $output .= "\n=== DIRECT ATTENDEE QUERY ===\n";
        $query_args = [
            'post_type' => 'tribe_tpp_attendees',
            'posts_per_page' => -1,
            'meta_query' => [
                [
                    'key' => '_tribe_tpp_event',
                    'value' => $event_id,
                    'compare' => '=',
                ],
            ],
        ];
        
        $attendees_query = new WP_Query($query_args);
        $output .= "Direct query found posts: " . $attendees_query->found_posts . "\n";
        
        if ($attendees_query->have_posts()) {
            while ($attendees_query->have_posts()) {
                $attendees_query->the_post();
                $attendee_id = get_the_ID();
                
                $output .= "- Post ID: {$attendee_id}, Title: " . get_the_title() . "\n";
                
                // Get metadata
                $email = get_post_meta($attendee_id, '_tribe_tickets_email', true);
                if (empty($email)) {
                    $email = get_post_meta($attendee_id, '_tribe_tpp_email', true);
                }
                
                $output .= "  Email: " . ($email ?: 'None') . "\n";
                
                // Check other important meta
                $ticket_id = get_post_meta($attendee_id, '_tribe_tpp_product', true);
                $output .= "  Ticket ID: " . ($ticket_id ?: 'None') . "\n";
                
                if ($ticket_id) {
                    $output .= "  Ticket Title: " . get_the_title($ticket_id) . "\n";
                }
                
                $output .= "  Order ID: " . get_post_meta($attendee_id, '_tribe_tpp_order', true) . "\n";
                $output .= "  Check-in: " . get_post_meta($attendee_id, '_tribe_tpp_checkin', true) . "\n";
                $output .= "\n";
            }
            wp_reset_postdata();
        }
        
        // Test email functionality
        $output .= "\n=== EMAIL FUNCTIONALITY ===\n";
        $output .= "WordPress mail function available: " . (function_exists('wp_mail') ? 'Yes' : 'No') . "\n";
        $output .= "PHP mail function available: " . (function_exists('mail') ? 'Yes' : 'No') . "\n";
        
        // Get mail settings
        $output .= "\nMail configuration:\n";
        $admin_email = get_option('admin_email');
        $output .= "Admin email: {$admin_email}\n";
        
        // Check for mail plugins
        $output .= "\nMail plugins:\n";
        $all_plugins = get_option('active_plugins', array());
        $mail_plugins_found = false;
        
        foreach ($all_plugins as $plugin) {
            if (strpos($plugin, 'mail') !== false || strpos($plugin, 'smtp') !== false) {
                $output .= "- {$plugin}\n";
                $mail_plugins_found = true;
            }
        }
        
        if (!$mail_plugins_found) {
            $output .= "No mail plugins detected\n";
        }
        
        // Check WP Mail SMTP settings if installed
        if (in_array('wp-mail-smtp/wp_mail_smtp.php', $all_plugins)) {
            $output .= "\nWP Mail SMTP settings:\n";
            $smtp_settings = get_option('wp_mail_smtp', array());
            
            if (!empty($smtp_settings)) {
                // Don't show passwords, just configuration status
                $output .= "Mailer: " . (isset($smtp_settings['mail']['mailer']) ? $smtp_settings['mail']['mailer'] : 'Not set') . "\n";
                $output .= "From Email: " . (isset($smtp_settings['mail']['from_email']) ? $smtp_settings['mail']['from_email'] : 'Not set') . "\n";
                $output .= "From Name: " . (isset($smtp_settings['mail']['from_name']) ? $smtp_settings['mail']['from_name'] : 'Not set') . "\n";
                $output .= "Return Path: " . (isset($smtp_settings['mail']['return_path']) ? 'Enabled' : 'Disabled') . "\n";
                
                if (isset($smtp_settings['mail']['mailer'])) {
                    $mailer = $smtp_settings['mail']['mailer'];
                    $output .= "SMTP Host: " . (isset($smtp_settings[$mailer]['host']) ? 'Configured' : 'Not configured') . "\n";
                    $output .= "SMTP Encryption: " . (isset($smtp_settings[$mailer]['encryption']) ? $smtp_settings[$mailer]['encryption'] : 'Not set') . "\n";
                    $output .= "SMTP Auth: " . (isset($smtp_settings[$mailer]['auth']) ? 'Enabled' : 'Disabled') . "\n";
                    $output .= "SMTP Port: " . (isset($smtp_settings[$mailer]['port']) ? $smtp_settings[$mailer]['port'] : 'Not set') . "\n";
                }
            } else {
                $output .= "WP Mail SMTP settings not found\n";
            }
        }
        
        // Add test button that will send an actual test email
        $output .= "\nEmail testing:\n";
        $output .= "If you need to send a test email, please use one of these options:\n";
        $output .= "1. Use the form on this page with a single recipient\n";
        $output .= "2. If using WP Mail SMTP, go to WP Mail SMTP settings and use their test email feature\n";
        $output .= "3. Contact your hosting provider if mail is still not working\n";
        
        // Return debug output
        wp_send_json_success($output);
    }
    
    /**
     * Log mail errors
     */
    public static function log_mail_error($wp_error) {
        $error_message = $wp_error->get_error_message();
        error_log('WordPress Mail Error: ' . $error_message);
        
        // Also log to our custom file if logging is enabled
        if (class_exists('HVAC_Logger')) {
            HVAC_Logger::error('WordPress Mail Error: ' . $error_message, 'Email System');
        }
    }
}

// Initialize the debugging class
HVAC_Email_Debug::init();