<?php

if( ! class_exists( 'PS_AEDL_Content_Type_Compatibility' ) ):
class PS_AEDL_Content_Type_Compatibility {

    private static $instance = null;
    private $content_type = false;
    public $email_id = false;

    /**
     * Get the instance of the class
     * 
     * @since 1.2.2
     */
    public static function get_instance() {

        if( null == self::$instance ) {

            self::$instance = new self;

        }

        return self::$instance;

    }

    /**
     * constructor of the class
     * 
     * @since 1.2.2
     */
    public function __construct() {

        add_filter( 'ps_aedl_pre_wp_mail', array( $this, 'set_content_type' ) );

    }

    /**
     * Set the content type of the email
     * 
     * @since 1.2.2
     */
    public function set_content_type( $log ) {
        
        // Support both array and object for $log
        $is_array = is_array($log);

        // Get headers and message
        $headers = $is_array ? ($log['original_headers'] ?? '') : ($log->original_headers ?? '');
        $message = $is_array ? ($log['original_message'] ?? '') : ($log->original_message ?? '');

        // Convert headers to array if they are a string
        if ( ! is_array( $headers ) ) {
            $headers = explode( "\n", $headers );
        }

        // if has html content and Content-Type not already set
        if (
            strpos($message, '<html') !== false &&
            (
                !is_array($headers) ||
                (is_array($headers) && !in_array('Content-Type: text/html', $headers))
            )
        ) {
            $headers[] = 'Content-Type: text/html';
            add_filter( 'wp_mail_content_type', array( $this, 'mail_content_type' ) );
        }

        // Set back the headers
        if ($is_array) {
            $log['original_headers'] = $headers;
        } else {
            $log->original_headers = $headers;
        }

        return $log;
    }
	
	
	/**
     * Sets mail content type | Filter Callback
     * 
     * @since 1.2.2
     */
	public function mail_content_type() {
		
        return "text/html";
		
    }

}
PS_AEDL_Content_Type_Compatibility::get_instance();
endif;