<?php
/**
 * Notification service
 *
 * @package NemtlyBooking
 */

namespace NemtlyBooking\Services;

use NemtlyBooking\Core\Event_Manager;
use NemtlyBooking\Models\Booking;
use NemtlyBooking\Models\Event;

/**
 * Notification Service class
 *
 * Handles email notifications for booking events
 *
 * @since PBOOKING_SINCE
 */
class Notification_Service {

    /**
     * Event manager
     *
     * @var Event_Manager
     */
    private $event_manager;

    /**
     * Constructor
     *
     * @param Event_Manager $event_manager The event manager instance.
     */
    public function __construct( Event_Manager $event_manager ) {
        $this->event_manager = $event_manager;
        $this->register_event_listeners();
    }

    /**
     * Register event listeners
     *
     * @since PBOOKING_SINCE
     */
    private function register_event_listeners() {
        // Booking-created confirmation is sent by Email_Notification_Service via nemtly_booking_event_booking_created to avoid duplicate emails.

        // Listen for booking status changes
        $this->event_manager->add_listener( 'booking.status_changed', [ $this, 'send_status_notification' ] );

        // Listen for booking cancellation
        $this->event_manager->add_listener( 'booking.cancelled', [ $this, 'send_cancellation_notification' ] );

        // Listen for booking reminders
        $this->event_manager->add_listener( 'booking.reminder', [ $this, 'send_reminder_notification' ] );
    }

    /**
     * Get email settings with fallbacks
     *
     * @since PBOOKING_SINCE
     *
     * @return array Email settings array
     */
    private function get_email_settings() {
        $settings_service = new Settings_Service();
        $settings         = $settings_service->get_settings();

        $email_settings = [
            'enabled'              => $settings['email_notifications_enabled'] ?? true,
            'admin_email'          => $settings['admin_email'] ?? get_option( 'admin_email' ),
            'from_name'            => $settings['from_name'] ?? get_option( 'blogname' ),
            'from_email'           => $settings['from_email'] ?? get_option( 'admin_email' ),
            'confirmation_subject' => $settings['confirmation_subject'] ?? __( 'Booking Confirmation - {event_title}', 'nemtly-booking' ),
            'confirmation_message' => $settings['confirmation_message'] ?? $this->get_default_confirmation_message(),
            'reminder_enabled'     => $settings['reminder_enabled'] ?? false,
            'reminder_hours'       => $settings['reminder_hours'] ?? 24,
            'reminder_subject'     => $settings['reminder_subject'] ?? __( 'Reminder: {event_title} tomorrow', 'nemtly-booking' ),
            'reminder_message'     => $settings['reminder_message'] ?? $this->get_default_reminder_message(),
        ];

        return $email_settings;
    }

    /**
     * Get email settings with fallbacks (public helper function)
     *
     * @since PBOOKING_SINCE
     *
     * @return array Email settings array
     */
    public function get_public_email_settings() {
        return $this->get_email_settings();
    }

    /**
     * Get default confirmation message
     *
     * @since PBOOKING_SINCE
     *
     * @return string Default confirmation message
     */
    private function get_default_confirmation_message() {
        return __(
            'Dear {attendee_name},

Thank you for your booking! Your reservation has been confirmed for the following event:

Event: {event_title}
Date: {event_date}
Time: {event_time}
Location: {event_location}
Booking Reference: {booking_uuid}

We look forward to seeing you at the event. If you have any questions, please don\'t hesitate to contact us.

Best regards,
{site_name}

---
This is an automated confirmation email. Please do not reply to this message.',
            'nemtly-booking'
        );
    }

    /**
     * Get default reminder message
     *
     * @since PBOOKING_SINCE
     *
     * @return string Default reminder message
     */
    private function get_default_reminder_message() {
        return __(
            'Dear {attendee_name},

This is a friendly reminder about your upcoming event:

Event: {event_title}
Date: {event_date}
Time: {event_time}
Location: {event_location}
Booking Reference: {booking_uuid}

We look forward to seeing you tomorrow!

Best regards,
{site_name}

---
This is an automated reminder email. Please do not reply to this message.',
            'nemtly-booking'
        );
    }

    /**
     * Send booking confirmation email
     *
     * @param array $data Booking data.
     * @return bool
     */
    public function send_booking_confirmation( $data ) {
        $email_settings = $this->get_email_settings();

        // Check if emails are enabled
        if ( ! $email_settings['enabled'] ) {
            return false;
        }

        $booking = $data['booking'] ?? null;
        if ( ! $booking ) {
            $booking_array = isset( $data['id'] ) || isset( $data['attendee_email'] ) ? $data : null;
            if ( $booking_array ) {
                $booking = new Booking( $booking_array );
            }
        }
        if ( ! $booking ) {
            return false;
        }

        $to      = $booking->get_attendee_email();
        $subject = $this->get_booking_confirmation_subject( $booking );
        $message = $this->get_booking_confirmation_message( $booking );

        $result = $this->send_email( $to, $subject, $message );

        // Send admin notification
        $this->send_admin_notification( 'new_booking', $booking );

        return $result;
    }

    /**
     * Send status change notification
     *
     * @param array $data Status change data.
     * @return bool
     */
    public function send_status_notification( $data ) {
        $booking    = $data['booking'] ?? null;
        $old_status = $data['old_status'] ?? '';
        $new_status = $data['new_status'] ?? '';

        if ( ! $booking || $old_status === $new_status ) {
            return false;
        }

        $to      = $booking->get_attendee_email();
        $subject = $this->get_status_notification_subject( $booking, $new_status );
        $message = $this->get_status_notification_message( $booking, $old_status, $new_status );

        $result = $this->send_email( $to, $subject, $message );

        // Send admin notification
        $this->send_admin_notification( 'status_change', $booking );

        return $result;
    }

    /**
     * Send cancellation notification
     *
     * @param array $data Cancellation data.
     * @return bool
     */
    public function send_cancellation_notification( $data ) {
        $booking = $data['booking'] ?? null;
        if ( ! $booking ) {
            return false;
        }

        $to      = $booking->get_attendee_email();
        $subject = $this->get_cancellation_subject( $booking );
        $message = $this->get_cancellation_message( $booking );

        $result = $this->send_email( $to, $subject, $message );

        // Send admin notification
        $this->send_admin_notification( 'cancellation', $booking );

        return $result;
    }

    /**
     * Send admin notification
     *
     * @param string $type    Notification type (new_booking, cancellation, status_change).
     * @param Booking $booking The booking object.
     * @return bool
     */
    public function send_admin_notification( $type, $booking ) {
        $email_settings = $this->get_email_settings();

        if ( empty( $email_settings['admin_email'] ) ) {
            return false;
        }

        $to      = $email_settings['admin_email'];
        $subject = $this->get_admin_notification_subject( $type, $booking );
        $message = $this->get_admin_notification_message( $type, $booking );

        return $this->send_email( $to, $subject, $message );
    }

    /**
     * Send reminder notification
     *
     * @param array $data Reminder data.
     * @return bool
     */
    public function send_reminder_notification( $data ) {
        $email_settings = $this->get_email_settings();

        // Check if reminders are enabled
        if ( ! $email_settings['reminder_enabled'] ) {
            return false;
        }

        $booking = $data['booking'] ?? null;
        if ( ! $booking ) {
            return false;
        }

        // Check if it's time to send the reminder
        if ( ! $this->should_send_reminder( $booking, $email_settings['reminder_hours'] ) ) {
            return false;
        }

        $to      = $booking->get_attendee_email();
        $subject = $this->get_reminder_subject( $booking );
        $message = $this->get_reminder_message( $booking );

        return $this->send_email( $to, $subject, $message );
    }

    /**
     * Send email notification
     *
     * @param string $to      Recipient email.
     * @param string $subject Email subject.
     * @param string $message Email message.
     * @return bool
     */
    private function send_email( $to, $subject, $message ) {
        // Validate email address
        if ( ! is_email( $to ) ) {
            $this->log_email_failed( $to, $subject, 'Invalid email address' );
            return false;
        }

        $email_settings = $this->get_email_settings();

        // Ensure we have valid from email
        $from_email = $email_settings['from_email'];
        $from_name  = $email_settings['from_name'];

        if ( ! is_email( $from_email ) ) {
            $from_email = get_option( 'admin_email' );
        }

        if ( empty( $from_name ) ) {
            $from_name = get_option( 'blogname' );
        }

        // Prepare headers
        $headers = [
            'Content-Type: text/html; charset=UTF-8',
            'From: ' . $from_name . ' <' . $from_email . '>',
            'Reply-To: ' . $from_email,
        ];

        // Filter headers for compatibility
        $headers = apply_filters( 'nemtly_booking_email_headers', $headers, $to, $subject );

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

        // Log result
        if ( $result ) {
            $this->log_email_sent( $to, $subject );
        } else {
            $this->log_email_failed( $to, $subject, 'wp_mail returned false' );
        }

        return $result;
    }

    /**
     * Get booking confirmation subject
     *
     * @param Booking $booking The booking object.
     * @return string
     */
    private function get_booking_confirmation_subject( $booking ) {
        $email_settings = $this->get_email_settings();
        $event_title    = $this->get_event_title( $booking->get_event_id() );

        $subject = $email_settings['confirmation_subject'];

        // Replace placeholders
        $replacements = [
            '{event_title}'   => $event_title,
            '{attendee_name}' => $booking->get_attendee_name(),
            '{site_name}'     => get_option( 'blogname' ),
        ];

        return str_replace( array_keys( $replacements ), array_values( $replacements ), $subject );
    }

    /**
     * Get booking confirmation message
     *
     * @param Booking $booking The booking object.
     * @return string
     */
    private function get_booking_confirmation_message( $booking ) {
        $email_settings = $this->get_email_settings();
        $event_title    = $this->get_event_title( $booking->get_event_id() );
        $event_date     = $this->get_event_date( $booking->get_event_id() );
        $event_time     = $this->get_event_time( $booking->get_event_id() );
        $event_location = $this->get_event_location( $booking->get_event_id() );

        $template_data = [
            'attendee_name'  => $booking->get_attendee_name(),
            'event_title'    => $event_title,
            'event_date'     => $event_date,
            'event_time'     => $event_time,
            'event_location' => $event_location,
            'booking_uuid'   => $booking->get_booking_uuid(),
            'booking_date'   => $booking->get_booking_date(),
            'site_name'      => get_option( 'blogname' ),
            'site_url'       => get_option( 'home' ),
            'event_url'      => get_permalink( $booking->get_event_id() ),
            'booking_url'    => admin_url( 'admin.php?page=nemtly-booking-bookings&booking_id=' . $booking->get_id() ),
        ];

        return $this->process_custom_template( $email_settings['confirmation_message'], $template_data, true );
    }

    /**
     * Get status notification subject
     *
     * @param Booking $booking    The booking object.
     * @param string  $new_status The new status.
     * @return string
     */
    private function get_status_notification_subject( $booking, $new_status ) {
        $event_title  = $this->get_event_title( $booking->get_event_id() );
        $status_label = $this->get_status_label( $new_status );

        return sprintf(
            /* translators: %1$s: Status label, %2$s: Event title */
            __( 'Booking %1$s - %2$s', 'nemtly-booking' ),
            $status_label,
            $event_title
        );
    }

    /**
     * Get status notification message
     *
     * @param Booking $booking     The booking object.
     * @param string  $old_status  The old status.
     * @param string  $new_status  The new status.
     * @return string
     */
    private function get_status_notification_message( $booking, $old_status, $new_status ) {
        $event_title      = $this->get_event_title( $booking->get_event_id() );
        $old_status_label = $this->get_status_label( $old_status );
        $new_status_label = $this->get_status_label( $new_status );

        $message = $this->get_email_template( 'status_notification' );

        $template_data = [
            'attendee_name' => $booking->get_attendee_name(),
            'event_title'   => $event_title,
            'old_status'    => $old_status_label,
            'new_status'    => $new_status_label,
            'booking_uuid'  => $booking->get_booking_uuid(),
            'site_name'     => get_option( 'blogname' ),
            'site_url'      => get_option( 'home' ),
            'event_url'     => get_permalink( $booking->get_event_id() ),
            'booking_url'   => admin_url( 'admin.php?page=nemtly-booking-bookings&booking_id=' . $booking->get_id() ),
        ];

        return $this->process_custom_template( $message, $template_data, true );
    }

    /**
     * Get cancellation subject
     *
     * @param Booking $booking The booking object.
     * @return string
     */
    private function get_cancellation_subject( $booking ) {
        $event_title = $this->get_event_title( $booking->get_event_id() );
        return sprintf(
            /* translators: %s: Event title */
            __( 'Booking Cancelled - %s', 'nemtly-booking' ),
            $event_title
        );
    }

    /**
     * Get cancellation message
     *
     * @param Booking $booking The booking object.
     * @return string
     */
    private function get_cancellation_message( $booking ) {
        $event_title = $this->get_event_title( $booking->get_event_id() );
        $event_date  = $this->get_event_date( $booking->get_event_id() );

        $message = $this->get_email_template( 'cancellation' );

        $template_data = [
            'attendee_name' => $booking->get_attendee_name(),
            'event_title'   => $event_title,
            'event_date'    => $event_date,
            'booking_uuid'  => $booking->get_booking_uuid(),
            'site_name'     => get_option( 'blogname' ),
            'site_url'      => get_option( 'home' ),
            'event_url'     => get_permalink( $booking->get_event_id() ),
            'booking_url'   => admin_url( 'admin.php?page=nemtly-booking-bookings&booking_id=' . $booking->get_id() ),
        ];

        return $this->process_custom_template( $message, $template_data, true );
    }

    /**
     * Get admin notification subject
     *
     * @param string  $type    Notification type.
     * @param Booking $booking The booking object.
     * @return string
     */
    private function get_admin_notification_subject( $type, $booking ) {
        $event_title   = $this->get_event_title( $booking->get_event_id() );
        $attendee_name = $booking->get_attendee_name();

        switch ( $type ) {
            case 'new_booking':
                return sprintf(
                    /* translators: %1$s: Attendee name, %2$s: Event title */
                    __( 'New Booking: %1$s - %2$s', 'nemtly-booking' ),
                    $attendee_name,
                    $event_title
                );
            case 'cancellation':
                return sprintf(
                    /* translators: %1$s: Attendee name, %2$s: Event title */
                    __( 'Booking Cancelled: %1$s - %2$s', 'nemtly-booking' ),
                    $attendee_name,
                    $event_title
                );
            case 'status_change':
                return sprintf(
                    /* translators: %1$s: Attendee name, %2$s: Event title */
                    __( 'Booking Status Changed: %1$s - %2$s', 'nemtly-booking' ),
                    $attendee_name,
                    $event_title
                );
            default:
                return sprintf(
                    /* translators: %s: Event title */
                    __( 'Booking Notification - %s', 'nemtly-booking' ),
                    $event_title
                );
        }
    }

    /**
     * Get admin notification message
     *
     * @param string  $type    Notification type.
     * @param Booking $booking The booking object.
     * @return string
     */
    private function get_admin_notification_message( $type, $booking ) {
        $event_title    = $this->get_event_title( $booking->get_event_id() );
        $event_date     = $this->get_event_date( $booking->get_event_id() );
        $event_time     = $this->get_event_time( $booking->get_event_id() );
        $event_location = $this->get_event_location( $booking->get_event_id() );

        $template_data = [
            'attendee_name'  => $booking->get_attendee_name(),
            'attendee_email' => $booking->get_attendee_email(),
            'event_title'    => $event_title,
            'event_date'     => $event_date,
            'event_time'     => $event_time,
            'event_location' => $event_location,
            'booking_uuid'   => $booking->get_booking_uuid(),
            'booking_status' => $this->get_status_label( $booking->get_status() ),
            'site_name'      => get_option( 'blogname' ),
            'site_url'       => get_option( 'home' ),
            'event_url'      => get_permalink( $booking->get_event_id() ),
            'booking_url'    => admin_url( 'admin.php?page=nemtly-booking-bookings&booking_id=' . $booking->get_id() ),
        ];

        $template = $this->get_admin_notification_template( $type );

        return $this->process_custom_template( $template, $template_data, true );
    }

    /**
     * Get admin notification template
     *
     * @param string $type Notification type.
     * @return string
     */
    private function get_admin_notification_template( $type ) {
        $template = get_option( "nemtly_booking_admin_template_{$type}", '' );

        if ( empty( $template ) ) {
            $template = $this->get_default_admin_template( $type );
        }

        return $template;
    }

    /**
     * Get default admin notification template
     *
     * @param string $type Notification type.
     * @return string
     */
    private function get_default_admin_template( $type ) {
        $templates = [
            'new_booking'   => $this->get_default_new_booking_admin_template(),
            'cancellation'  => $this->get_default_cancellation_admin_template(),
            'status_change' => $this->get_default_status_change_admin_template(),
        ];

        return $templates[ $type ] ?? $this->get_default_new_booking_admin_template();
    }

    /**
     * Get default new booking admin template
     *
     * @return string
     */
    private function get_default_new_booking_admin_template() {
        return '
        <div style="max-width: 600px; margin: 0 auto;">
            <h2 style="color: #333;">New Booking Received</h2>
            <p>A new booking has been received:</p>
            <div style="background: #f9f9f9; padding: 20px; margin: 20px 0; border-radius: 5px;">
                <h3>{event_title}</h3>
                <p><strong>Attendee:</strong> {attendee_name} ({attendee_email})</p>
                <p><strong>Date:</strong> {event_date}</p>
                <p><strong>Time:</strong> {event_time}</p>
                <p><strong>Location:</strong> {event_location}</p>
                <p><strong>Booking Reference:</strong> {booking_uuid}</p>
                <p><strong>Status:</strong> {booking_status}</p>
            </div>
            <p><a href="{booking_url}" style="background: #0073aa; color: white; padding: 10px 20px; text-decoration: none; border-radius: 3px;">View Booking Details</a></p>
            <p>Best regards,<br>{site_name}</p>
        </div>';
    }

    /**
     * Get default cancellation admin template
     *
     * @return string
     */
    private function get_default_cancellation_admin_template() {
        return '
        <div style="max-width: 600px; margin: 0 auto;">
            <h2 style="color: #333;">Booking Cancelled</h2>
            <p>A booking has been cancelled:</p>
            <div style="background: #f9f9f9; padding: 20px; margin: 20px 0; border-radius: 5px;">
                <h3>{event_title}</h3>
                <p><strong>Attendee:</strong> {attendee_name} ({attendee_email})</p>
                <p><strong>Date:</strong> {event_date}</p>
                <p><strong>Time:</strong> {event_time}</p>
                <p><strong>Location:</strong> {event_location}</p>
                <p><strong>Booking Reference:</strong> {booking_uuid}</p>
            </div>
            <p><a href="{booking_url}" style="background: #0073aa; color: white; padding: 10px 20px; text-decoration: none; border-radius: 3px;">View Booking Details</a></p>
            <p>Best regards,<br>{site_name}</p>
        </div>';
    }

    /**
     * Get default status change admin template
     *
     * @return string
     */
    private function get_default_status_change_admin_template() {
        return '
        <div style="max-width: 600px; margin: 0 auto;">
            <h2 style="color: #333;">Booking Status Changed</h2>
            <p>A booking status has been updated:</p>
            <div style="background: #f9f9f9; padding: 20px; margin: 20px 0; border-radius: 5px;">
                <h3>{event_title}</h3>
                <p><strong>Attendee:</strong> {attendee_name} ({attendee_email})</p>
                <p><strong>Date:</strong> {event_date}</p>
                <p><strong>Time:</strong> {event_time}</p>
                <p><strong>Location:</strong> {event_location}</p>
                <p><strong>Booking Reference:</strong> {booking_uuid}</p>
                <p><strong>New Status:</strong> {booking_status}</p>
            </div>
            <p><a href="{booking_url}" style="background: #0073aa; color: white; padding: 10px 20px; text-decoration: none; border-radius: 3px;">View Booking Details</a></p>
            <p>Best regards,<br>{site_name}</p>
        </div>';
    }

    /**
     * Check if reminder should be sent
     *
     * @param Booking $booking The booking object.
     * @param int     $hours   Hours before event to send reminder.
     * @return bool
     */
    private function should_send_reminder( $booking, $hours ) {
        $event_date = get_post_meta( $booking->get_event_id(), 'nemtly_event_date', true );
        $event_time = get_post_meta( $booking->get_event_id(), 'nemtly_event_time', true );

        if ( ! $event_date || ! $event_time ) {
            return false;
        }

        $event_datetime = strtotime( $event_date . ' ' . $event_time );
        $reminder_time  = $event_datetime - ( $hours * 3600 ); // Convert hours to seconds
        $current_time   = current_time( 'timestamp' );

        // Send reminder if we're within 1 hour of the reminder time
        return abs( $current_time - $reminder_time ) <= 3600;
    }

    /**
     * Get reminder subject
     *
     * @param Booking $booking The booking object.
     * @return string
     */
    private function get_reminder_subject( $booking ) {
        $email_settings = $this->get_email_settings();
        $event_title    = $this->get_event_title( $booking->get_event_id() );

        $subject = $email_settings['reminder_subject'];

        // Replace placeholders
        $replacements = [
            '{event_title}'   => $event_title,
            '{attendee_name}' => $booking->get_attendee_name(),
            '{site_name}'     => get_option( 'blogname' ),
        ];

        return str_replace( array_keys( $replacements ), array_values( $replacements ), $subject );
    }

    /**
     * Get reminder message
     *
     * @param Booking $booking The booking object.
     * @return string
     */
    private function get_reminder_message( $booking ) {
        $email_settings = $this->get_email_settings();
        $event_title    = $this->get_event_title( $booking->get_event_id() );
        $event_date     = $this->get_event_date( $booking->get_event_id() );
        $event_time     = $this->get_event_time( $booking->get_event_id() );
        $event_location = $this->get_event_location( $booking->get_event_id() );

        $template_data = [
            'attendee_name'  => $booking->get_attendee_name(),
            'event_title'    => $event_title,
            'event_date'     => $event_date,
            'event_time'     => $event_time,
            'event_location' => $event_location,
            'booking_uuid'   => $booking->get_booking_uuid(),
            'site_name'      => get_option( 'blogname' ),
            'site_url'       => get_option( 'home' ),
            'event_url'      => get_permalink( $booking->get_event_id() ),
            'booking_url'    => admin_url( 'admin.php?page=nemtly-booking-bookings&booking_id=' . $booking->get_id() ),
        ];

        return $this->process_custom_template( $email_settings['reminder_message'], $template_data, true );
    }

    /**
     * Process custom template with placeholders
     *
     * @since PBOOKING_SINCE
     *
     * @param string $template   The template string with placeholders
     * @param array  $data       Data array containing values for placeholders
     * @param bool   $html_email Whether to format as HTML email
     * @return string Processed template
     */
    private function process_custom_template( $template, $data, $html_email = true ) {
        // Replace all placeholders
        $processed_template = $this->replace_placeholders( $template, $data );

        // If HTML email, ensure proper formatting
        if ( $html_email ) {
            $processed_template = $this->format_html_email( $processed_template );
        } else {
            $processed_template = $this->format_plain_text_email( $processed_template );
        }

        return $processed_template;
    }

    /**
     * Replace placeholders in template
     *
     * @since PBOOKING_SINCE
     *
     * @param string $template Template string
     * @param array  $data     Data array
     * @return string Template with placeholders replaced
     */
    private function replace_placeholders( $template, $data ) {
        $placeholders = [
            '{event_title}'    => $data['event_title'] ?? '',
            '{attendee_name}'  => $data['attendee_name'] ?? '',
            '{event_date}'     => $data['event_date'] ?? '',
            '{event_time}'     => $data['event_time'] ?? '',
            '{event_location}' => $data['event_location'] ?? '',
            '{booking_uuid}'   => $data['booking_uuid'] ?? '',
            '{booking_date}'   => $data['booking_date'] ?? '',
            '{site_name}'      => $data['site_name'] ?? get_option( 'blogname' ),
            '{site_url}'       => $data['site_url'] ?? get_option( 'home' ),
            '{old_status}'     => $data['old_status'] ?? '',
            '{new_status}'     => $data['new_status'] ?? '',
            '{event_url}'      => $data['event_url'] ?? '',
            '{booking_url}'    => $data['booking_url'] ?? '',
        ];

        return str_replace( array_keys( $placeholders ), array_values( $placeholders ), $template );
    }

    /**
     * Format template as HTML email
     *
     * @since PBOOKING_SINCE
     *
     * @param string $content Email content
     * @return string Formatted HTML email
     */
    private function format_html_email( $content ) {
        // If content already contains HTML structure, return as is
        if ( strpos( $content, '<html' ) !== false || strpos( $content, '<body' ) !== false ) {
            return $content;
        }

        // If content contains basic HTML tags, wrap in proper structure
        if ( strpos( $content, '<div' ) !== false || strpos( $content, '<p' ) !== false ) {
            return $this->wrap_html_content( $content );
        }

        // Convert plain text to HTML
        return $this->convert_text_to_html( $content );
    }

    /**
     * Format template as plain text email
     *
     * @since PBOOKING_SINCE
     *
     * @param string $content Email content
     * @return string Formatted plain text email
     */
    private function format_plain_text_email( $content ) {
        // Remove HTML tags and convert to plain text
        $plain_text = wp_strip_all_tags( $content );

        // Convert line breaks to proper format
        $plain_text = str_replace( [ '<br>', '<br/>', '<br />' ], "\n", $plain_text );

        // Clean up multiple line breaks
        $plain_text = preg_replace( '/\n\s*\n/', "\n\n", $plain_text );

        return trim( $plain_text );
    }

    /**
     * Wrap HTML content in proper email structure
     *
     * @since PBOOKING_SINCE
     *
     * @param string $content HTML content
     * @return string Wrapped HTML content
     */
    private function wrap_html_content( $content ) {
        return '
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Pulse Booking Email</title>
        </head>
        <body style="margin: 0; padding: 0; line-height: 1.6; color: #333;">
            <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
                ' . $content . '
            </div>
        </body>
        </html>';
    }

    /**
     * Convert plain text to HTML
     *
     * @since PBOOKING_SINCE
     *
     * @param string $text Plain text content
     * @return string HTML formatted content
     */
    private function convert_text_to_html( $text ) {
        // Convert line breaks to HTML
        $html = nl2br( $text );

        // Wrap in proper structure
        return $this->wrap_html_content( '<div>' . $html . '</div>' );
    }

    /**
     * Get email template
     *
     * @param string $template_name Template name.
     * @return string
     */
    private function get_email_template( $template_name ) {
        $template = get_option( "nemtly_booking_email_template_{$template_name}", '' );

        if ( empty( $template ) ) {
            $template = $this->get_default_template( $template_name );
        }

        return $template;
    }

    /**
     * Get default email template
     *
     * @param string $template_name Template name.
     * @return string
     */
    private function get_default_template( $template_name ) {
        $templates = [
            'booking_confirmation' => $this->get_default_booking_confirmation_template(),
            'status_notification'  => $this->get_default_status_notification_template(),
            'cancellation'         => $this->get_default_cancellation_template(),
            'reminder'             => $this->get_default_reminder_template(),
        ];

        return $templates[ $template_name ] ?? '';
    }

    /**
     * Get default booking confirmation template
     *
     * @return string
     */
    private function get_default_booking_confirmation_template() {
        return '
        <div style="max-width: 600px; margin: 0 auto;">
            <h2 style="color: #333;">Booking Confirmation</h2>
            <p>Dear {attendee_name},</p>
            <p>Your booking has been confirmed for the following event:</p>
            <div style="background: #f9f9f9; padding: 20px; margin: 20px 0; border-radius: 5px;">
                <h3>{event_title}</h3>
                <p><strong>Date:</strong> {event_date}</p>
                <p><strong>Time:</strong> {event_time}</p>
                <p><strong>Location:</strong> {event_location}</p>
                <p><strong>Booking Reference:</strong> {booking_uuid}</p>
            </div>
            <p>Thank you for your booking!</p>
            <p>Best regards,<br>{site_name}</p>
        </div>';
    }

    /**
     * Get default status notification template
     *
     * @return string
     */
    private function get_default_status_notification_template() {
        return '
        <div style="max-width: 600px; margin: 0 auto;">
            <h2 style="color: #333;">Booking Status Update</h2>
            <p>Dear {attendee_name},</p>
            <p>Your booking status has been updated from <strong>{old_status}</strong> to <strong>{new_status}</strong>.</p>
            <div style="background: #f9f9f9; padding: 20px; margin: 20px 0; border-radius: 5px;">
                <h3>{event_title}</h3>
                <p><strong>Booking Reference:</strong> {booking_uuid}</p>
            </div>
            <p>Thank you!</p>
            <p>Best regards,<br>{site_name}</p>
        </div>';
    }

    /**
     * Get default cancellation template
     *
     * @return string
     */
    private function get_default_cancellation_template() {
        return '
        <div style="max-width: 600px; margin: 0 auto;">
            <h2 style="color: #333;">Booking Cancelled</h2>
            <p>Dear {attendee_name},</p>
            <p>Your booking has been cancelled for the following event:</p>
            <div style="background: #f9f9f9; padding: 20px; margin: 20px 0; border-radius: 5px;">
                <h3>{event_title}</h3>
                <p><strong>Date:</strong> {event_date}</p>
                <p><strong>Booking Reference:</strong> {booking_uuid}</p>
            </div>
            <p>If you have any questions, please contact us.</p>
            <p>Best regards,<br>{site_name}</p>
        </div>';
    }

    /**
     * Get default reminder template
     *
     * @return string
     */
    private function get_default_reminder_template() {
        return '
        <div style="max-width: 600px; margin: 0 auto;">
            <h2 style="color: #333;">Event Reminder</h2>
            <p>Dear {attendee_name},</p>
            <p>This is a reminder for your upcoming event:</p>
            <div style="background: #f9f9f9; padding: 20px; margin: 20px 0; border-radius: 5px;">
                <h3>{event_title}</h3>
                <p><strong>Date:</strong> {event_date}</p>
                <p><strong>Time:</strong> {event_time}</p>
                <p><strong>Location:</strong> {event_location}</p>
                <p><strong>Booking Reference:</strong> {booking_uuid}</p>
            </div>
            <p>We look forward to seeing you!</p>
            <p>Best regards,<br>{site_name}</p>
        </div>';
    }

    /**
     * Get event title
     *
     * @param int $event_id Event ID.
     * @return string
     */
    private function get_event_title( $event_id ) {
        $event = get_post( $event_id );
        return $event ? $event->post_title : __( 'Unknown Event', 'nemtly-booking' );
    }

    /**
     * Get event date
     *
     * @param int $event_id Event ID.
     * @return string
     */
    private function get_event_date( $event_id ) {
        $date = get_post_meta( $event_id, 'nemtly_event_date', true );
        return $date ? date_i18n( get_option( 'date_format' ), strtotime( $date ) ) : '';
    }

    /**
     * Get event time
     *
     * @param int $event_id Event ID.
     * @return string
     */
    private function get_event_time( $event_id ) {
        $time = get_post_meta( $event_id, 'nemtly_event_time', true );
        return $time ? date_i18n( get_option( 'time_format' ), strtotime( $time ) ) : '';
    }

    /**
     * Get event location
     *
     * @param int $event_id Event ID.
     * @return string
     */
    private function get_event_location( $event_id ) {
        $location = get_post_meta( $event_id, 'nemtly_event_location', true );

        return $location ? $location : '';
    }

    /**
     * Get status label
     *
     * @param string $status Status.
     * @return string
     */
    private function get_status_label( $status ) {
        $labels = [
            'pending'    => __( 'Pending', 'nemtly-booking' ),
            'confirmed'  => __( 'Confirmed', 'nemtly-booking' ),
            'cancelled'  => __( 'Cancelled', 'nemtly-booking' ),
            'waitlisted' => __( 'Waitlisted', 'nemtly-booking' ),
        ];

        return $labels[ $status ] ?? $status;
    }

    /**
     * Log email sent
     *
     * @param string $to      Recipient email.
     * @param string $subject Email subject.
     */
    private function log_email_sent( $to, $subject ) {
    }

    /**
     * Log email failed
     *
     * @param string $to      Recipient email.
     * @param string $subject Email subject.
     * @param string $reason  Failure reason.
     */
    private function log_email_failed( $to, $subject, $reason = '' ) {
    }
}
