<?php

namespace RTMCustomMails\WooCommerce;

use DateTime;
use DateTimeInterface;
use RTMCustomMails\Email\RTMCustomEmail;
use RTMCustomMails\Schedule\ScheduledEmails;
use WC_Abstract_Order;
use WordpressModels\Traits\SingletonTrait;

class WooCommerceEmails
{

    use SingletonTrait;

    public function __construct()
    {
        add_filter('woocommerce_email_classes', [$this, 'addCustomEmails']);
        add_action('woocommerce_email_sent', [$this, 'addMetaOnEmailSent'], 10, 3);
    }

    /**
     *  Add a custom email to the list of emails WooCommerce should load
     *
     * @param array $email_classes available email classes
     * @return array filtered available email classes
     * @since 0.1
     */
    public function addCustomEmails(array $email_classes = []): array
    {
        return $email_classes;
    }


    public function addMetaOnEmailSent($return, $id, $emailInstance): void
    {
        if ($emailInstance instanceof RTMCustomEmail) {
            $atomDate = (new DateTime())->format(DateTimeInterface::ATOM);
            if ($emailInstance->getObjectType() === 'order' && ($order = $emailInstance->object ?? false)) {
                /** @var WC_Abstract_Order $order */
                if ($return) {
                    // add sent metadata to order
                    $order->add_meta_data("_wrce_{$id}_sent", $atomDate);
                    $order->save();

                    $currentActionId = ScheduledEmails::instance()->getCurrentActionId();
                    if ($currentActionId && method_exists($order, 'add_order_note')) {
                        $order->add_order_note('Email "' . $emailInstance->get_title() . '" was sent successfully.');
                    }
                } else {
                    // failed to send email (or at least `wp_mail` hook returned `false`
                    if (method_exists($order, 'add_order_note')) {
                        $rtmMailSettings = get_option('rtm_mail_settings', []);
                        $msg = 'Failed to send email <strong>' . $emailInstance->get_title() . '</strong>';

                        if (class_exists('\RtmMail\Core') && ($rtmMailSettings['block_emails'] ?? false) === true) {
                            $msg .= " (RTM Mail plugin is blocking emails)";
                        } else {
                            $msg .= " (something blocking emails / transport failed)";
                        }

                        $order->add_order_note($msg);
                    }

                    $failures = $order->get_meta("_wrce_{$id}_send_failure") ?: [];
                    $failures[] = $atomDate;
                    $order->update_meta_data("_wrce_{$id}_send_failure", $failures);
                    $order->save_meta_data();
                }
            } else {
                do_action('wrce_add_meta_on_sent', $return, $id, $emailInstance);
            }
        }
    }

}