<?php
/**
 * WooCommerce Email Integration for Stripe Subscription Manager.
 *
 * Registers transactional email types with WooCommerce so merchants can
 * enable/disable them, customise subjects and headings, and override
 * templates — all from WooCommerce > Settings > Emails.
 *
 * Email classes listen for do_action() hooks fired by the webhook handler.
 *
 * IMPORTANT: The actual email class definitions (STRP_SUB_Email_Base and its
 * subclasses) live in class-strp-sub-wc-email-classes.php and are loaded
 * ONLY when the `woocommerce_email_classes` filter fires, because they extend
 * WC_Email which is not available during plugin bootstrap.
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// ── Manager ─────────────────────────────────────────────────────────────────

class STRP_SUB_WC_Emails {

    private static $instance = null;
    private static $classes_loaded = false;

    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_filter( 'woocommerce_email_classes', array( $this, 'register_email_classes' ) );
    }

    private function __clone() {}

    public function __wakeup() {
        throw new \RuntimeException( 'Cannot unserialize singleton.' );
    }

    /**
     * Load email class definitions that extend WC_Email.
     *
     * Deferred until WooCommerce is ready so WC_Email exists.
     */
    private static function load_email_classes() {
        if ( self::$classes_loaded ) {
            return;
        }
        self::$classes_loaded = true;

        require_once STRP_SUB_PLUGIN_DIR . 'includes/class-strp-sub-wc-email-classes.php';
        require_once STRP_SUB_PLUGIN_DIR . 'includes/class-strp-sub-wc-email-lifetime.php';
    }

    /**
     * Register all plugin email classes with WooCommerce.
     *
     * @param array $email_classes Existing WooCommerce email class map.
     * @return array
     */
    public function register_email_classes( $email_classes ) {
        self::load_email_classes();

        $email_classes['STRP_SUB_Email_Subscription_Welcome'] = new STRP_SUB_Email_Subscription_Welcome();
        $email_classes['STRP_SUB_Email_Renewal']              = new STRP_SUB_Email_Renewal();
        $email_classes['STRP_SUB_Email_Trial_Converted']      = new STRP_SUB_Email_Trial_Converted();
        $email_classes['STRP_SUB_Email_Payment_Failed']       = new STRP_SUB_Email_Payment_Failed();
        $email_classes['STRP_SUB_Email_Fraud_Block']          = new STRP_SUB_Email_Fraud_Block();
        $email_classes['STRP_SUB_WC_Email_Lifetime']         = new STRP_SUB_WC_Email_Lifetime();
        return $email_classes;
    }
}
