<?php
/**
 * WooCommerce Email: Lifetime Access Upgrade
 *
 * Extends WC_Email so the store owner can customise the subject, heading,
 * and colors directly from WooCommerce > Settings > Emails, and the email
 * will automatically use the store's branded header/footer template.
 *
 * Registered via the 'woocommerce_email_classes' filter in class-strp-sub-wc-emails.php.
 */

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

if ( ! class_exists( 'WC_Email' ) ) {
    return;
}

class STRP_SUB_WC_Email_Lifetime extends WC_Email {

    /**
     * Number of subscriptions cancelled during the lifetime upgrade.
     *
     * @var int
     */
    protected $cancelled_count = 0;

    /**
     * Display name for the customer.
     *
     * @var string
     */
    protected $user_name = '';

    /**
     * Constructor.
     */
    public function __construct() {
        $this->id             = 'strp_sub_lifetime_upgrade';
        $this->customer_email = true;
        $this->title          = __( 'Lifetime Access Activated', 'subscription-manager-for-stripe' );
        $this->description    = __( 'Sent to the customer when their lifetime access purchase is confirmed and any previous subscriptions have been cancelled.', 'subscription-manager-for-stripe' );

        $this->subject = $this->get_default_subject();
        $this->heading = $this->get_default_heading();

        // Template paths — we use the plain-text fallback from WooCommerce core
        // and inject content via get_content_html() / get_content_plain() below.
        $this->template_html  = 'emails/lifetime-upgrade.php';
        $this->template_plain = 'emails/plain/lifetime-upgrade.php';
        $this->template_base  = STRP_SUB_PLUGIN_DIR . 'templates/';

        parent::__construct();

        add_action( 'strp_sub_send_lifetime_upgrade_email', array( $this, 'trigger' ), 10, 2 );
    }

    /**
     * Default email subject.
     */
    public function get_default_subject() {
        return __( '[{site_title}] Your Lifetime Access Is Now Active', 'subscription-manager-for-stripe' );
    }

    /**
     * Default email heading.
     */
    public function get_default_heading() {
        return __( 'Your lifetime access is confirmed!', 'subscription-manager-for-stripe' );
    }

    /**
     * Trigger the email send.
     *
     * @param int  $order_id        WooCommerce order ID.
     * @param int  $cancelled_count Number of subscriptions cancelled during upgrade.
     */
    public function trigger( $order_id, $cancelled_count = 0 ) {
        $this->setup_locale();

        $this->object         = wc_get_order( $order_id );
        $this->cancelled_count = (int) $cancelled_count;

        if ( ! $this->object ) {
            $this->restore_locale();
            return;
        }

        $customer_id = $this->object->get_customer_id();
        if ( $customer_id > 0 ) {
            $user              = get_userdata( $customer_id );
            $this->recipient   = $user ? $user->user_email : $this->object->get_billing_email();
            $this->user_name   = $user ? ( $user->display_name ?: $user->first_name ) : '';
        } else {
            $this->recipient = $this->object->get_billing_email();
            $this->user_name = $this->object->get_billing_first_name();
        }

        if ( ! $this->is_enabled() || ! $this->get_recipient() ) {
            $this->restore_locale();
            return;
        }

        $this->send(
            $this->get_recipient(),
            $this->get_subject(),
            $this->get_content(),
            $this->get_headers(),
            $this->get_attachments()
        );

        $this->restore_locale();
    }

    /**
     * HTML email content.
     * Falls back to a simple inline template if the theme/plugin template file is absent.
     */
    public function get_content_html() {
        ob_start();
        if ( function_exists( 'wc_get_template' ) ) {
            wc_get_template(
                $this->template_html,
                array(
                    'email'           => $this,
                    'heading'         => $this->get_heading(),
                    'user_name'       => $this->user_name,
                    'cancelled_count' => $this->cancelled_count,
                    'order'           => $this->object,
                ),
                '',
                $this->template_base
            );
        } else {
            $this->render_default_html();
        }
        return ob_get_clean();
    }

    /**
     * Plain-text fallback.
     */
    public function get_content_plain() {
        ob_start();
        $template = $this->template_base . 'emails/plain/lifetime-upgrade.php';
        if ( file_exists( $template ) ) {
            include $template;
        } else {
            $this->render_default_plain();
        }
        return ob_get_clean();
    }

    /**
     * Inline HTML fallback (used when no template file exists yet).
     */
    private function render_default_html() {
        $heading         = $this->get_heading();
        $user_name       = isset( $this->user_name ) ? esc_html( $this->user_name ) : '';
        $cancelled_count = isset( $this->cancelled_count ) ? (int) $this->cancelled_count : 0;
        $site_name       = esc_html( get_bloginfo( 'name' ) );
        $order_id        = $this->object ? (int) $this->object->get_id() : 0;

        // Use WooCommerce's own email header/footer for branded output.
        if ( function_exists( 'wc_get_template' ) ) {
            wc_get_template( 'emails/email-header.php', array( 'email_heading' => $heading ) );
        } else {
            echo '<h1>' . esc_html( $heading ) . '</h1>';
        }
        ?>
        <p><?php
            /* translators: %s: customer name */
            printf( esc_html__( 'Hello %s,', 'subscription-manager-for-stripe' ), $user_name );
        ?></p>
        <p><?php
            /* translators: %s: site name */
            printf( esc_html__( 'Congratulations! Your lifetime access to %s has been activated.', 'subscription-manager-for-stripe' ), $site_name );
        ?></p>
        <?php if ( $cancelled_count > 0 ) : ?>
        <p><?php esc_html_e( 'Your previous recurring subscription has been cancelled automatically — no further payments will be charged.', 'subscription-manager-for-stripe' ); ?></p>
        <?php endif; ?>
        <p><?php esc_html_e( 'You now have permanent access. Thank you for your purchase!', 'subscription-manager-for-stripe' ); ?></p>
        <?php if ( $order_id > 0 ) : ?>
        <p><em><?php
            /* translators: %d: order ID */
            printf( esc_html__( 'Order #%d', 'subscription-manager-for-stripe' ), $order_id );
        ?></em></p>
        <?php endif; ?>
        <?php
        if ( function_exists( 'wc_get_template' ) ) {
            wc_get_template( 'emails/email-footer.php' );
        }
    }

    /**
     * Plain-text fallback.
     */
    private function render_default_plain() {
        $user_name       = isset( $this->user_name ) ? $this->user_name : '';
        $cancelled_count = isset( $this->cancelled_count ) ? (int) $this->cancelled_count : 0;
        $site_name       = get_bloginfo( 'name' );
        $order_id        = $this->object ? (int) $this->object->get_id() : 0;

        echo esc_html( sprintf( __( 'Hello %s,', 'subscription-manager-for-stripe' ), $user_name ) ) . "\n\n";
        echo esc_html( sprintf( __( 'Congratulations! Your lifetime access to %s has been activated.', 'subscription-manager-for-stripe' ), $site_name ) ) . "\n\n";
        if ( $cancelled_count > 0 ) {
            echo esc_html__( 'Your previous recurring subscription has been cancelled automatically — no further payments will be charged.', 'subscription-manager-for-stripe' ) . "\n\n";
        }
        echo esc_html__( 'You now have permanent access. Thank you for your purchase!', 'subscription-manager-for-stripe' ) . "\n\n";
        if ( $order_id > 0 ) {
            echo esc_html( sprintf( __( 'Order #%d', 'subscription-manager-for-stripe' ), $order_id ) ) . "\n";
        }
    }

    /**
     * Admin settings — show email customization fields in WC > Settings > Emails.
     */
    public function init_form_fields() {
        $this->form_fields = array(
            'enabled' => array(
                'title'   => __( 'Enable / Disable', 'subscription-manager-for-stripe' ),
                'type'    => 'checkbox',
                'label'   => __( 'Enable this email notification', 'subscription-manager-for-stripe' ),
                'default' => 'yes',
            ),
            'subject' => array(
                'title'       => __( 'Subject', 'subscription-manager-for-stripe' ),
                'type'        => 'text',
                'placeholder' => $this->get_default_subject(),
                'default'     => '',
            ),
            'heading' => array(
                'title'       => __( 'Email Heading', 'subscription-manager-for-stripe' ),
                'type'        => 'text',
                'placeholder' => $this->get_default_heading(),
                'default'     => '',
            ),
            'email_type' => array(
                'title'   => __( 'Email type', 'subscription-manager-for-stripe' ),
                'type'    => 'select',
                'options' => $this->get_email_type_options(),
                'default' => 'html',
            ),
        );
    }
}
