<?php

namespace RTMCustomMails\Sender;

use PHPMailer\PHPMailer\PHPMailer;
use RTMMailComposer\Model\CustomMail;
use RTMMailComposer\Sender\EmailSenderInterface;
use WC_Email;

class WPEmailSender implements EmailSenderInterface
{

    /**
     * @inheritDoc
     */
    public function send(string $to, string $subject, string $message, string $headers, array $attachments, CustomMail $mail): bool
    {
        add_filter('wp_mail_from', array($mail, 'get_from_address'));
        add_filter('wp_mail_from_name', array($mail, 'get_from_name'));
        add_filter('wp_mail_content_type', array($mail, 'get_content_type'));

        $message = apply_filters('woocommerce_mail_content', $message);
        $mail_callback = apply_filters('woocommerce_mail_callback', 'wp_mail', $mail);
        $mail_callback_params = apply_filters('woocommerce_mail_callback_params', array($to, wp_specialchars_decode($subject), $message, $headers, $attachments), $mail);
        $return = $mail_callback(...$mail_callback_params);

        remove_filter('wp_mail_from', array($mail, 'get_from_address'));
        remove_filter('wp_mail_from_name', array($mail, 'get_from_name'));
        remove_filter('wp_mail_content_type', array($mail, 'get_content_type'));

        // Clear the AltBody (if set) so that it does not leak across to different emails.
        global $phpmailer;

        if ($phpmailer instanceof PHPMailer) {
            $phpmailer->AltBody = ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
        }

        /**
         * Action hook fired when an email is sent.
         *
         * @param bool $return Whether the email was sent successfully.
         * @param int $id Email ID.
         * @param WC_Email $this WC_Email instance.
         * @since 5.6.0
         */
        do_action('woocommerce_email_sent', $return, $mail->id, $mail);

        return $return;
    }
}
