<?php

namespace RTMCustomMails\EmailSections\Defaults;

use RTMCustomMails\Email\RTMCustomEmail;
use RTMCustomMails\SerializerFactory;
use RTMMailComposer\Model\EmailSection;
use Symfony\Component\Serializer\Serializer;
use WC_Emails;
use WordpressModels\Traits\SingletonTrait;

class DefaultLoader
{

    use SingletonTrait;

    /**
     * Stores the default templates interfaces to be loaded on plugin activation or manual reset
     */
    public array $defaultTemplates;

    private Serializer $serializer;

    private function __construct()
    {
        add_filter('wrce_register_default_template', [$this, 'registerDefaultTemplate']);
        add_action('wrce_load_default_template', [$this, 'loadDefaultTemplate']);
        add_action('wp_ajax_wrce_reset_to_defaults', [$this, 'ajaxResetToDefaults']);

        $this->serializer = SerializerFactory::create();

        $this->registerWCDefaultTemplates();
    }


    /**
     * Registers a new default template
     * @param DefaultTemplateInterface $defaultTemplateInterface Instance of DefaultTemplateInterface implementation to register
     */
    public function registerDefaultTemplate(DefaultTemplateInterface $defaultTemplateInterface)
    {
        $this->defaultTemplates[$defaultTemplateInterface->getEmailId()] = $defaultTemplateInterface->getDefaultSections();
    }

    /**
     * Registers the default WooCommerce email templates
     */
    public function registerWCDefaultTemplates()
    {
        $wcTemplates = [
            new AdminCancelledOrderDefaultTemplate(),
            new AdminNewOrderDefaultTemplate(),
            new AdminFailedOrderDefaultTemplate(),
            new CustomerOnHoldDefaultTemplate(),
            new CustomerProcessingOrderDefaultTemplate(),
            new CustomerCompletedOrderDefaultTemplate(),
            new CustomerRefundedOrderDefaultTemplate(),
            new CustomerInvoiceDefaultTemplate(),
            new CustomerNoteDefaultTemplate(),
            new CustomerResetPasswordDefaultTemplate(),
            new CustomerNewAccountDefaultTemplate()
        ];

        foreach ($wcTemplates as $template) {
            apply_filters('wrce_register_default_template', $template);
        }
    }

    /**
     * Loads the default template associated with given Email object based on Email ID
     * @param RTMCustomEmail $email The email object to load a default template for
     */
    public function loadDefaultTemplate(RTMCustomEmail $email)
    {
        $defaultSections = $this->defaultTemplates[$email->id] ?? null;
        //if default section exists for this e-mail id
        if ($defaultSections) {
            $email->setSections(array_map(fn($section) => $this->serializer->denormalize($section, EmailSection::class), $defaultSections));
        }
    }


    /**
     * Ajax request to reset all mails to the default sections
     */
    public function ajaxResetToDefaults()
    {
        check_ajax_referer('wrce_settings_nonce');

        $emails = WC_Emails::instance()->get_emails();
        foreach ($emails as $email) {
            $customEmail = RTMCustomEmail::asCustomEmail($email);
            do_action('wrce_load_default_template', $customEmail);
        }

        wp_send_json_success();
    }
}
