<?php
/**
 * Event Monster Email Handler
 *
 * Handles all email functionality for Event Monster including:
 * - SMTP and PHP mail configuration
 * - Booking confirmation emails
 * - Email template generation
 * - SMTP connection testing
 *
 * @package    Event_Monster
 * @subpackage Event_Monster/includes
 * @author     A WP Life
 * @since      1.0.0
 */
class Event_Monster_Free_Emails
{
    /**
     * The email sending method ('php' or 'smtp').
     *
     * @since 1.0.0
     * @var string
     */
    private $mailer;

    /**
     * Constructor - Initialize email handler and configure mailer type.
     *
     * Determines whether to use PHP mail or SMTP based on plugin settings
     * and sets up appropriate hooks for SMTP configuration if needed.
     *
     * @since 1.0.0
     */
    public function __construct()
    {
        // Get plugin settings to determine email method
        $settings = get_option('awl_em_common_settings', array());
        $this->mailer = isset($settings['email_carrier']) ? $settings['email_carrier'] : 'php';

        // Hook into PHPMailer for SMTP configuration if SMTP is selected
        if ('smtp' === $this->mailer) {
            add_action('phpmailer_init', array($this, 'configure_smtp'));
        }
    }

    /**
     * Configure PHPMailer for SMTP sending.
     *
     * This method is automatically called by WordPress when SMTP is enabled.
     * It configures all SMTP settings including host, port, authentication,
     * encryption, and sender information.
     *
     * @since 1.0.0
     * @param PHPMailer $phpmailer The PHPMailer object passed by WordPress
     */
    public function configure_smtp($phpmailer)
    {
        // Get plugin settings
        $settings = get_option('awl_em_common_settings', array());

        // Configure SMTP settings
        $phpmailer->isSMTP();
        $phpmailer->Host = isset($settings['em_smtp_host']) ? $settings['em_smtp_host'] : '';
        $phpmailer->SMTPAuth = true;
        $phpmailer->Port = isset($settings['em_smtp_port']) ? absint($settings['em_smtp_port']) : 587;
        $phpmailer->Username = isset($settings['em_smtp_username']) ? $settings['em_smtp_username'] : '';
        $phpmailer->Password = isset($settings['em_smtp_password']) ? $settings['em_smtp_password'] : '';
        $phpmailer->SMTPSecure = isset($settings['em_smtp_encryption']) ? $settings['em_smtp_encryption'] : 'tls';

        // Enable SMTP debugging (2 = detailed debug output)
        $phpmailer->SMTPDebug = 2;

        // Custom debug output handler to log to error_log
        $phpmailer->Debugoutput = function($str, $level) {
            error_log('Event Monster SMTP Debug: ' . $str);
        };

        // Configure sender information with fallback chain
        if (isset($settings['em_smtp_from_email']) && !empty($settings['em_smtp_from_email'])) {
            $phpmailer->From = $settings['em_smtp_from_email'];
        } elseif (isset($settings['em_smtp_username']) && !empty($settings['em_smtp_username'])) {
            $phpmailer->From = $settings['em_smtp_username'];
        } else {
            $phpmailer->From = get_bloginfo('admin_email');
        }

        // Set sender name with fallback
        $phpmailer->FromName = isset($settings['em_smtp_from_name']) && !empty($settings['em_smtp_from_name'])
            ? $settings['em_smtp_from_name']
            : get_bloginfo('name');
    }

    /**
     * Send email using configured method (PHP mail or SMTP).
     *
     * This is the main email sending function that automatically uses
     * the email method configured in the constructor. For PHP mail,
     * it sets appropriate headers. For SMTP, it ensures proper configuration.
     *
     * @since 1.0.0
     * @param string $to Recipient email address
     * @param string $subject Email subject line
     * @param string $message Email message content (HTML)
     * @param array $headers Optional additional email headers
     * @return bool True on success, false on failure
     */
    public function send($to, $subject, $message, $headers = array())
    {
        // Debug log
        error_log('Event Monster: Attempting to send email via ' . $this->mailer);
        error_log('Event Monster: To: ' . $to);
        error_log('Event Monster: Subject: ' . $subject);

        // For SMTP, ensure proper configuration with filters
        if ('smtp' === $this->mailer) {
            $settings = get_option('awl_em_common_settings', array());

            error_log('Event Monster: Using SMTP configuration');
            error_log('Event Monster: SMTP Host: ' . (isset($settings['em_smtp_host']) ? $settings['em_smtp_host'] : 'NOT SET'));
            error_log('Event Monster: SMTP Port: ' . (isset($settings['em_smtp_port']) ? $settings['em_smtp_port'] : 'NOT SET'));

            // Add filter to ensure correct From address for SMTP
            add_filter('wp_mail_from', function($from) use ($settings) {
                if (isset($settings['em_smtp_from_email']) && !empty($settings['em_smtp_from_email'])) {
                    return $settings['em_smtp_from_email'];
                } elseif (isset($settings['em_smtp_username']) && !empty($settings['em_smtp_username'])) {
                    return $settings['em_smtp_username'];
                } else {
                    return get_bloginfo('admin_email');
                }
            });

            add_filter('wp_mail_from_name', function($from_name) use ($settings) {
                return isset($settings['em_smtp_from_name']) && !empty($settings['em_smtp_from_name'])
                    ? $settings['em_smtp_from_name']
                    : get_bloginfo('name');
            });

        } else {
            // For PHP mail, set From header manually
            $settings = get_option('awl_em_common_settings', array());

            error_log('Event Monster: Using PHP Mail');

            // Determine sender name with fallback
            $from_name = isset($settings['em_php_from_name']) && !empty($settings['em_php_from_name'])
                ? $settings['em_php_from_name']
                : get_bloginfo('name');

            // Determine sender email with fallback chain
            $from_email = '';
            if (isset($settings['em_php_from_email']) && !empty($settings['em_php_from_email'])) {
                $from_email = $settings['em_php_from_email'];
            } elseif (isset($settings['em_smtp_from_email']) && !empty($settings['em_smtp_from_email'])) {
                $from_email = $settings['em_smtp_from_email'];
            } elseif (isset($settings['em_smtp_username']) && !empty($settings['em_smtp_username'])) {
                $from_email = $settings['em_smtp_username'];
            } else {
                $from_email = get_bloginfo('admin_email');
            }

            $headers[] = 'From: ' . $from_name . ' <' . $from_email . '>';
            error_log('Event Monster: From: ' . $from_name . ' <' . $from_email . '>');
        }

        // Set content type to HTML
        $headers[] = 'Content-Type: text/html; charset=UTF-8';

        // Send email using WordPress wp_mail function
        $result = wp_mail($to, $subject, $message, $headers);

        if ($result) {
            error_log('Event Monster: wp_mail returned TRUE - Email sent successfully');
        } else {
            error_log('Event Monster: wp_mail returned FALSE - Email FAILED');
        }

        return $result;
    }

    /**
     * Send booking confirmation email to customer.
     *
     * Retrieves booking and attendee information from the database,
     * generates a confirmation email with event details, and sends
     * it to the customer if client notifications are enabled.
     *
     * @since 1.0.0
     * @param int $booking_id The booking ID to send confirmation for
     * @return void
     */
    public function send_booking_confirmation_email($booking_id)
    {
        // Debug log
        error_log('Event Monster: send_booking_confirmation_email called for booking ID: ' . $booking_id);

        // Check if client notifications are enabled
        $settings = get_option('awl_em_common_settings', array());
        if (!isset($settings['em_notification_client']) || $settings['em_notification_client'] !== 'on') {
            error_log('Event Monster: Client notifications are DISABLED. Email not sent.');
            return; // Exit early if notifications are disabled
        }

        error_log('Event Monster: Client notifications are enabled. Proceeding with email...');

        // Get booking information from database
        global $wpdb;
        $booking = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM `{$wpdb->prefix}em_bookings` WHERE id = %d",
            $booking_id
        ));

        if (!$booking) {
            error_log('Event Monster: Booking not found for ID: ' . $booking_id);
            return; // Exit if booking not found
        }

        // Get attendee information from database
        $attendee = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM `{$wpdb->prefix}em_attendees` WHERE id = %d",
            $booking->attendees_id
        ));

        if (!$attendee) {
            error_log('Event Monster: Attendee not found for booking ID: ' . $booking_id);
            return; // Exit if attendee not found
        }

        // Prepare email content
        $event_title = get_the_title($booking->event_id);
        $recipient_email = $attendee->email;
        $attendee_name = $attendee->first_name . ' ' . $attendee->last_name;

        error_log('Event Monster: Preparing to send email to: ' . $recipient_email);

        // Get event details
        $event_settings = get_post_meta($booking->event_id, 'Event_Monster_Free_settings', true);
        $event_start_date = isset($event_settings['em_start_date']) ? $event_settings['em_start_date'] : '';
        $event_end_date = isset($event_settings['em_end_date']) ? $event_settings['em_end_date'] : '';
        $event_start_time = isset($event_settings['em_start_time']) ? $event_settings['em_start_time'] : '';
        $event_end_time = isset($event_settings['em_end_time']) ? $event_settings['em_end_time'] : '';
        $event_venue = isset($event_settings['em_venue']) ? $event_settings['em_venue'] : '';

        // Get common settings for email customization
        $common_settings = get_option('awl_em_common_settings', array());

        // Format dates
        $formatted_start_date = !empty($event_start_date) ? date_i18n('F j, Y', strtotime($event_start_date)) : '';
        $formatted_end_date = !empty($event_end_date) && $event_end_date !== $event_start_date ? ' - ' . date_i18n('F j, Y', strtotime($event_end_date)) : '';
        $formatted_time = '';
        if (!empty($event_start_time)) {
            $formatted_time = date_i18n('g:i A', strtotime($event_start_time));
            if (!empty($event_end_time) && $event_end_time !== $event_start_time) {
                $formatted_time .= ' - ' . date_i18n('g:i A', strtotime($event_end_time));
            }
        }

        // Get currency symbol
        $currency_symbol = isset($event_settings['em_currency_symbol']) ? $event_settings['em_currency_symbol'] : '$';

        // Format amount (use 'amount' column, not 'total_amount')
        $total_amount = floatval($booking->amount);
        $formatted_amount = $currency_symbol . number_format($total_amount, 2);

        // Get ticket information
        $ticket_ids = maybe_unserialize($booking->ticket_id);
        $ticket_details = [];
        $original_total = 0;
        if (is_array($ticket_ids) && !empty($ticket_ids)) {
            foreach ($ticket_ids as $ticket_id => $quantity) {
                if (!empty($quantity)) {
                    $ticket = $wpdb->get_row($wpdb->prepare(
                        "SELECT * FROM `{$wpdb->prefix}em_tickets` WHERE id = %d",
                        $ticket_id
                    ));
                    if ($ticket) {
                        $ticket_details[] = [
                            'name' => $ticket->name,
                            'quantity' => $quantity,
                            'price' => $ticket->price
                        ];
                        $original_total += $ticket->price * $quantity;
                    }
                }
            }
        }

        // Get coupon information if applied
        $coupon_info = null;
        if (!empty($booking->coupon_id)) {
            $coupon = $wpdb->get_row($wpdb->prepare(
                "SELECT * FROM `{$wpdb->prefix}em_coupons` WHERE id = %d",
                $booking->coupon_id
            ));
            if ($coupon) {
                $coupon_info = [
                    'code' => $coupon->coupon_code,
                    'discount_value' => $coupon->discount_value,
                    'discount_type' => $coupon->discount_type
                ];
            }
        }

        // Get customizable email content from common settings
        $email_heading = isset($common_settings['email_heading']) && !empty($common_settings['email_heading'])
            ? $common_settings['email_heading']
            : 'Thank you for your booking!';

        $email_greeting = isset($common_settings['email_greeting']) && !empty($common_settings['email_greeting'])
            ? $common_settings['email_greeting']
            : 'Dear {name},';

        $email_confirmation_message = isset($common_settings['email_confirmation_message']) && !empty($common_settings['email_confirmation_message'])
            ? $common_settings['email_confirmation_message']
            : 'Your booking is confirmed for {event}.';

        $email_closing_message_1 = isset($common_settings['email_closing_message_1']) && !empty($common_settings['email_closing_message_1'])
            ? $common_settings['email_closing_message_1']
            : 'We look forward to seeing you at the event!';

        $email_closing_message_2 = isset($common_settings['email_closing_message_2']) && !empty($common_settings['email_closing_message_2'])
            ? $common_settings['email_closing_message_2']
            : 'If you have any questions, please don\'t hesitate to contact us.';

        // Replace placeholders
        $email_greeting = str_replace('{name}', '<strong>' . esc_html($attendee_name) . '</strong>', $email_greeting);
        $email_confirmation_message = str_replace('{event}', '<strong>' . esc_html($event_title) . '</strong>', $email_confirmation_message);

        // Create email subject and message
        $subject = 'Your Booking Confirmation for ' . $event_title;

        // Build message body
        $message_body = '<h1 style="color: #333333; font-size: 24px; margin: 0 0 20px 0;">' . esc_html($email_heading) . '</h1>';
        $message_body .= '<p style="color: #666666; font-size: 16px; line-height: 1.6; margin: 0 0 20px 0;">' . $email_greeting . '</p>';
        $message_body .= '<p style="color: #666666; font-size: 16px; line-height: 1.6; margin: 0 0 30px 0;">' . $email_confirmation_message . '</p>';

        // Booking Details Table
        $message_body .= '<table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color: #f9f9f9; border-radius: 8px; overflow: hidden; margin-bottom: 30px;">';
        $message_body .= '<tr><td style="padding: 20px;">';
        $message_body .= '<h2 style="color: #333333; font-size: 18px; margin: 0 0 15px 0;">' . esc_html__('Booking Details', 'event-monster') . '</h2>';

        $message_body .= '<table width="100%" cellpadding="8" cellspacing="0" border="0">';

        // Booking ID
        $message_body .= '<tr>';
        $message_body .= '<td style="color: #666666; font-size: 14px; padding: 8px 0; border-bottom: 1px solid #eeeeee;"><strong>' . esc_html__('Booking ID:', 'event-monster') . '</strong></td>';
        $message_body .= '<td style="color: #333333; font-size: 14px; padding: 8px 0; border-bottom: 1px solid #eeeeee; text-align: right;">#' . esc_html($booking->id) . '</td>';
        $message_body .= '</tr>';

        // Event Name
        $message_body .= '<tr>';
        $message_body .= '<td style="color: #666666; font-size: 14px; padding: 8px 0; border-bottom: 1px solid #eeeeee;"><strong>' . esc_html__('Event:', 'event-monster') . '</strong></td>';
        $message_body .= '<td style="color: #333333; font-size: 14px; padding: 8px 0; border-bottom: 1px solid #eeeeee; text-align: right;">' . esc_html($event_title) . '</td>';
        $message_body .= '</tr>';

        // Date
        if (!empty($formatted_start_date)) {
            $message_body .= '<tr>';
            $message_body .= '<td style="color: #666666; font-size: 14px; padding: 8px 0; border-bottom: 1px solid #eeeeee;"><strong>' . esc_html__('Date:', 'event-monster') . '</strong></td>';
            $message_body .= '<td style="color: #333333; font-size: 14px; padding: 8px 0; border-bottom: 1px solid #eeeeee; text-align: right;">' . esc_html($formatted_start_date . $formatted_end_date) . '</td>';
            $message_body .= '</tr>';
        }

        // Time
        if (!empty($formatted_time)) {
            $message_body .= '<tr>';
            $message_body .= '<td style="color: #666666; font-size: 14px; padding: 8px 0; border-bottom: 1px solid #eeeeee;"><strong>' . esc_html__('Time:', 'event-monster') . '</strong></td>';
            $message_body .= '<td style="color: #333333; font-size: 14px; padding: 8px 0; border-bottom: 1px solid #eeeeee; text-align: right;">' . esc_html($formatted_time) . '</td>';
            $message_body .= '</tr>';
        }

        // Venue
        if (!empty($event_venue)) {
            $message_body .= '<tr>';
            $message_body .= '<td style="color: #666666; font-size: 14px; padding: 8px 0; border-bottom: 1px solid #eeeeee;"><strong>' . esc_html__('Venue:', 'event-monster') . '</strong></td>';
            $message_body .= '<td style="color: #333333; font-size: 14px; padding: 8px 0; border-bottom: 1px solid #eeeeee; text-align: right;">' . esc_html($event_venue) . '</td>';
            $message_body .= '</tr>';
        }

        // Tickets Details
        if (!empty($ticket_details)) {
            $message_body .= '<tr>';
            $message_body .= '<td colspan="2" style="padding: 15px 0 8px 0; border-bottom: 1px solid #eeeeee;"><strong style="color: #666666; font-size: 14px;">' . esc_html__('Tickets:', 'event-monster') . '</strong></td>';
            $message_body .= '</tr>';

            foreach ($ticket_details as $ticket) {
                $ticket_price = $currency_symbol . number_format($ticket['price'], 2);
                $ticket_subtotal = $currency_symbol . number_format($ticket['price'] * $ticket['quantity'], 2);

                $message_body .= '<tr>';
                $message_body .= '<td style="color: #333333; font-size: 14px; padding: 8px 0 8px 20px; border-bottom: 1px solid #eeeeee;">';
                $message_body .= esc_html($ticket['name']) . ' <span style="color: #999;">(' . $ticket_price . ' × ' . $ticket['quantity'] . ')</span>';
                $message_body .= '</td>';
                $message_body .= '<td style="color: #333333; font-size: 14px; padding: 8px 0; border-bottom: 1px solid #eeeeee; text-align: right;">' . $ticket_subtotal . '</td>';
                $message_body .= '</tr>';
            }
        }

        // Subtotal (if coupon applied)
        if ($coupon_info) {
            $message_body .= '<tr>';
            $message_body .= '<td style="color: #666666; font-size: 14px; padding: 15px 0 8px 0; border-top: 1px solid #dddddd;"><strong>' . esc_html__('Subtotal:', 'event-monster') . '</strong></td>';
            $message_body .= '<td style="color: #333333; font-size: 14px; padding: 15px 0 8px 0; border-top: 1px solid #dddddd; text-align: right;">' . $currency_symbol . number_format($original_total, 2) . '</td>';
            $message_body .= '</tr>';

            // Coupon discount
            $discount_text = $coupon_info['discount_type'] === '%'
                ? $coupon_info['discount_value'] . '% ' . esc_html__('off', 'event-monster')
                : $currency_symbol . number_format($coupon_info['discount_value'], 2) . ' ' . esc_html__('off', 'event-monster');

            $discount_amount = $original_total - $total_amount;

            $message_body .= '<tr>';
            $message_body .= '<td style="color: #16a34a; font-size: 14px; padding: 8px 0;">';
            $message_body .= '<strong>' . esc_html__('Coupon Discount:', 'event-monster') . '</strong> ';
            $message_body .= '<span style="font-size: 12px;">(' . esc_html($coupon_info['code']) . ' - ' . $discount_text . ')</span>';
            $message_body .= '</td>';
            $message_body .= '<td style="color: #16a34a; font-size: 14px; padding: 8px 0; text-align: right;">-' . $currency_symbol . number_format($discount_amount, 2) . '</td>';
            $message_body .= '</tr>';
        }

        // Total Amount
        $message_body .= '<tr>';
        $message_body .= '<td style="color: #666666; font-size: 14px; padding: 8px 0;"><strong>' . esc_html__('Total Amount:', 'event-monster') . '</strong></td>';
        $message_body .= '<td style="color: #333333; font-size: 16px; font-weight: bold; padding: 8px 0; text-align: right;">' . esc_html($formatted_amount) . '</td>';
        $message_body .= '</tr>';

        $message_body .= '</table>';
        $message_body .= '</td></tr>';
        $message_body .= '</table>';

        // Attendee Information
        $message_body .= '<table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color: #f9f9f9; border-radius: 8px; overflow: hidden; margin-bottom: 30px;">';
        $message_body .= '<tr><td style="padding: 20px;">';
        $message_body .= '<h2 style="color: #333333; font-size: 18px; margin: 0 0 15px 0;">' . esc_html__('Attendee Information', 'event-monster') . '</h2>';

        $message_body .= '<table width="100%" cellpadding="8" cellspacing="0" border="0">';

        $message_body .= '<tr>';
        $message_body .= '<td style="color: #666666; font-size: 14px; padding: 8px 0; border-bottom: 1px solid #eeeeee;"><strong>' . esc_html__('Name:', 'event-monster') . '</strong></td>';
        $message_body .= '<td style="color: #333333; font-size: 14px; padding: 8px 0; border-bottom: 1px solid #eeeeee; text-align: right;">' . esc_html($attendee_name) . '</td>';
        $message_body .= '</tr>';

        $message_body .= '<tr>';
        $message_body .= '<td style="color: #666666; font-size: 14px; padding: 8px 0; border-bottom: 1px solid #eeeeee;"><strong>' . esc_html__('Email:', 'event-monster') . '</strong></td>';
        $message_body .= '<td style="color: #333333; font-size: 14px; padding: 8px 0; border-bottom: 1px solid #eeeeee; text-align: right;">' . esc_html($attendee->email) . '</td>';
        $message_body .= '</tr>';

        if (!empty($attendee->phone)) {
            $message_body .= '<tr>';
            $message_body .= '<td style="color: #666666; font-size: 14px; padding: 8px 0;"><strong>' . esc_html__('Phone:', 'event-monster') . '</strong></td>';
            $message_body .= '<td style="color: #333333; font-size: 14px; padding: 8px 0; text-align: right;">' . esc_html($attendee->phone) . '</td>';
            $message_body .= '</tr>';
        }

        $message_body .= '</table>';
        $message_body .= '</td></tr>';
        $message_body .= '</table>';

        // Closing message
        $message_body .= '<p style="color: #666666; font-size: 16px; line-height: 1.6; margin: 0 0 10px 0;">' . esc_html($email_closing_message_1) . '</p>';
        $message_body .= '<p style="color: #666666; font-size: 14px; line-height: 1.6; margin: 0;">' . esc_html($email_closing_message_2) . '</p>';

        // Wrap message in HTML template
        $full_html = $this->get_html_email_template($message_body);

        // Send the email using configured method
        $result = $this->send($recipient_email, $subject, $full_html);

        if ($result) {
            error_log('Event Monster: Email sent successfully to: ' . $recipient_email);
        } else {
            error_log('Event Monster: Email FAILED to send to: ' . $recipient_email);
        }
    }

    /**
     * Generate HTML email template wrapper.
     *
     * Wraps the provided content in a responsive HTML email template
     * with consistent styling and layout using custom template settings.
     *
     * @since 1.0.0
     * @param string $content The email content to wrap
     * @return string Complete HTML email template
     */
    public function get_html_email_template($content)
    {
        // Get email template settings
        $settings = get_option('awl_em_common_settings', array());

        // Get template settings with defaults
        $email_tem_head = isset($settings['email_tem_head']) ? $settings['email_tem_head'] : 'name';
        $em_upload_image = isset($settings['em_upload_image']) ? $settings['em_upload_image'] : '';
        $logo_name = isset($settings['logo_name']) ? $settings['logo_name'] : get_bloginfo('name');
        $cover_back_color = isset($settings['cover_back_color']) ? $settings['cover_back_color'] : '#010101';
        $header_footer_back_color = isset($settings['header_footer_back_color']) ? $settings['header_footer_back_color'] : '#40BABD';
        $header_footer_font_color = isset($settings['header_footer_font_color']) ? $settings['header_footer_font_color'] : '#FFFFFF';
        $footer_email = isset($settings['footer_email']) ? $settings['footer_email'] : get_bloginfo('admin_email');
        $footer_phone = isset($settings['footer_phone']) ? $settings['footer_phone'] : '';
        $footer_website = isset($settings['footer_website']) ? $settings['footer_website'] : get_bloginfo('url');
        $imp_instructions = isset($settings['imp_instructions']) ? $settings['imp_instructions'] : 'no';
        $instructions_type = isset($settings['instructions_type']) ? $settings['instructions_type'] : '';

        ob_start();
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title><?php echo esc_html(get_bloginfo('name')); ?></title>
        </head>
        <body style="margin: 0; padding: 0; background-color: <?php echo esc_attr($cover_back_color); ?>; font-family: Arial, sans-serif;">
            <table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color: <?php echo esc_attr($cover_back_color); ?>;">
                <tr>
                    <td align="center" style="padding: 40px 20px;">
                        <!-- Main Container -->
                        <table width="600" cellpadding="0" cellspacing="0" border="0" style="background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">

                            <!-- Header -->
                            <tr>
                                <td style="background-color: <?php echo esc_attr($header_footer_back_color); ?>; padding: 30px 40px; text-align: center;">
                                    <?php if ($email_tem_head === 'logo' && !empty($em_upload_image)):
                                        // Ensure absolute URL for email clients
                                        $logo_url = $em_upload_image;
                                        if (!preg_match('/^https?:\/\//', $logo_url)) {
                                            $logo_url = home_url($logo_url);
                                        }
                                    ?>
                                        <img src="<?php echo esc_url($logo_url); ?>"
                                             alt="<?php echo esc_attr(get_bloginfo('name')); ?>"
                                             width="200"
                                             style="max-width: 200px; height: auto; display: block; margin: 0 auto; border: 0; outline: none; text-decoration: none; -ms-interpolation-mode: bicubic;">
                                    <?php else: ?>
                                        <h1 style="margin: 0; color: <?php echo esc_attr($header_footer_font_color); ?>; font-size: 28px; font-weight: bold;">
                                            <?php echo esc_html($logo_name); ?>
                                        </h1>
                                    <?php endif; ?>
                                </td>
                            </tr>

                            <!-- Content -->
                            <tr>
                                <td style="padding: 40px;">
                                    <?php echo $content; ?>
                                </td>
                            </tr>

                            <!-- Important Instructions (if enabled) -->
                            <?php if ($imp_instructions === 'yes' && !empty($instructions_type)): ?>
                            <tr>
                                <td style="padding: 20px 40px; background-color: #f9f9f9; border-top: 1px solid #eeeeee;">
                                    <h3 style="margin: 0 0 10px 0; color: #333333; font-size: 16px;"><?php echo esc_html__('Important Instructions', 'event-monster'); ?></h3>
                                    <p style="margin: 0; color: #666666; font-size: 14px; line-height: 1.6;">
                                        <?php echo nl2br(esc_html($instructions_type)); ?>
                                    </p>
                                </td>
                            </tr>
                            <?php endif; ?>

                            <!-- Footer -->
                            <tr>
                                <td style="background-color: <?php echo esc_attr($header_footer_back_color); ?>; padding: 30px 40px; text-align: center;">
                                    <table width="100%" cellpadding="0" cellspacing="0" border="0">
                                        <tr>
                                            <td style="text-align: center; padding-bottom: 15px;">
                                                <p style="margin: 0; color: <?php echo esc_attr($header_footer_font_color); ?>; font-size: 14px; font-weight: bold;">
                                                    <?php echo esc_html(get_bloginfo('name')); ?>
                                                </p>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td style="text-align: center;">
                                                <?php if (!empty($footer_email)): ?>
                                                <p style="margin: 5px 0; color: <?php echo esc_attr($header_footer_font_color); ?>; font-size: 13px;">
                                                    📧 <a href="mailto:<?php echo esc_attr($footer_email); ?>" style="color: <?php echo esc_attr($header_footer_font_color); ?>; text-decoration: none;">
                                                        <?php echo esc_html($footer_email); ?>
                                                    </a>
                                                </p>
                                                <?php endif; ?>

                                                <?php if (!empty($footer_phone)): ?>
                                                <p style="margin: 5px 0; color: <?php echo esc_attr($header_footer_font_color); ?>; font-size: 13px;">
                                                    📞 <?php echo esc_html($footer_phone); ?>
                                                </p>
                                                <?php endif; ?>

                                                <?php if (!empty($footer_website)): ?>
                                                <p style="margin: 5px 0; color: <?php echo esc_attr($header_footer_font_color); ?>; font-size: 13px;">
                                                    🌐 <a href="<?php echo esc_url($footer_website); ?>" style="color: <?php echo esc_attr($header_footer_font_color); ?>; text-decoration: none;">
                                                        <?php echo esc_html(parse_url($footer_website, PHP_URL_HOST)); ?>
                                                    </a>
                                                </p>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td style="text-align: center; padding-top: 15px;">
                                                <p style="margin: 0; color: <?php echo esc_attr($header_footer_font_color); ?>; font-size: 12px; opacity: 0.8;">
                                                    © <?php echo wp_date('Y'); ?> <?php echo esc_html(get_bloginfo('name')); ?>. <?php echo esc_html__('All rights reserved.', 'event-monster'); ?>
                                                </p>
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>

                        </table>
                    </td>
                </tr>
            </table>
        </body>
        </html>
        <?php
        return ob_get_clean();
    }

    /**
     * Test SMTP connection by sending a test email.
     *
     * Sends a test email to verify that SMTP configuration is working
     * correctly. Only works when SMTP is enabled in settings.
     *
     * @since 1.0.0
     * @return array Result array with success status and message
     */
    public function test_smtp_connection()
    {
        $settings = get_option('awl_em_common_settings', array());

        // Check if SMTP is enabled
        if (!isset($settings['email_carrier']) || $settings['email_carrier'] !== 'smtp') {
            return array(
                'success' => false,
                'message' => 'SMTP is not enabled in settings'
            );
        }

        // Determine test email recipient
        $test_email = '';
        if (isset($settings['em_smtp_from_email']) && !empty($settings['em_smtp_from_email'])) {
            $test_email = $settings['em_smtp_from_email'];
        } else {
            $test_email = get_bloginfo('admin_email');
        }

        // Prepare test email content
        $subject = 'Event Monster SMTP Test';
        $message = 'This is a test email to verify that your SMTP configuration is working correctly.';

        // Send test email
        $result = $this->send($test_email, $subject, $message);

        // Return result
        if ($result) {
            return array(
                'success' => true,
                'message' => 'SMTP test email sent successfully to ' . $test_email
            );
        } else {
            return array(
                'success' => false,
                'message' => 'SMTP test failed. Please check your settings and try again.'
            );
        }
    }
}