<?php
/**
 * License Expired Email
 *
 * @package Jeremias\WcLicensedProduct\Email
 */

declare(strict_types=1);

namespace Jeremias\WcLicensedProduct\Email;

use Jeremias\WcLicensedProduct\License\License;
use WC_Email;

/**
 * License Expired Email class
 *
 * Sends email notifications to customers when their licenses have expired.
 * Uses WooCommerce's transactional email system for consistent styling and customization.
 */
class LicenseExpiredEmail extends WC_Email
{
    /**
     * License object
     */
    public ?License $license = null;

    /**
     * Product name
     */
    public string $product_name = '';

    /**
     * Expiration date formatted
     */
    public string $expiration_date = '';

    /**
     * Customer display name
     */
    public string $customer_name = '';

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->id = 'wclp_license_expired';
        $this->customer_email = true;
        $this->title = __('License Expired', 'wc-licensed-product');
        $this->description = __('License expired emails are sent to customers when their licenses have expired.', 'wc-licensed-product');

        $this->placeholders = [
            '{site_title}' => $this->get_blogname(),
            '{product_name}' => '',
            '{expiration_date}' => '',
        ];

        // Call parent constructor
        parent::__construct();
    }

    /**
     * Get email subject
     */
    public function get_default_subject(): string
    {
        return __('[{site_title}] Your license for {product_name} has expired', 'wc-licensed-product');
    }

    /**
     * Get email heading
     */
    public function get_default_heading(): string
    {
        return __('License Expired', 'wc-licensed-product');
    }

    /**
     * Trigger the email
     *
     * @param License $license License object
     */
    public function trigger(License $license): bool
    {
        $this->setup_locale();

        $customer = get_userdata($license->getCustomerId());
        if (!$customer || !$customer->user_email) {
            $this->restore_locale();
            return false;
        }

        $this->license = $license;
        $this->recipient = $customer->user_email;
        $this->customer_name = $customer->display_name ?: __('Customer', 'wc-licensed-product');

        $product = wc_get_product($license->getProductId());
        $this->product_name = $product ? $product->get_name() : __('Unknown Product', 'wc-licensed-product');

        $expiresAt = $license->getExpiresAt();
        $this->expiration_date = $expiresAt ? $expiresAt->format(get_option('date_format')) : '';

        // Update placeholders
        $this->placeholders['{product_name}'] = $this->product_name;
        $this->placeholders['{expiration_date}'] = $this->expiration_date;

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

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

        $this->restore_locale();

        return $result;
    }

    /**
     * Get content HTML
     */
    public function get_content_html(): string
    {
        ob_start();

        // Use WooCommerce's email header
        wc_get_template('emails/email-header.php', ['email_heading' => $this->get_heading()]);

        $this->render_email_body_html();

        // Use WooCommerce's email footer
        wc_get_template('emails/email-footer.php', ['email' => $this]);

        return ob_get_clean();
    }

    /**
     * Get content plain text
     */
    public function get_content_plain(): string
    {
        ob_start();

        echo "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n";
        echo esc_html(wp_strip_all_tags($this->get_heading()));
        echo "\n=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n";

        $this->render_email_body_plain();

        return ob_get_clean();
    }

    /**
     * Render HTML email body content
     */
    private function render_email_body_html(): void
    {
        $account_url = wc_get_account_endpoint_url('licenses');
        ?>
        <p><?php printf(esc_html__('Hello %s,', 'wc-licensed-product'), esc_html($this->customer_name)); ?></p>

        <p style="color: #dc3232; font-weight: 600;">
            <?php printf(
                esc_html__('Your license for %1$s has expired on %2$s.', 'wc-licensed-product'),
                '<strong>' . esc_html($this->product_name) . '</strong>',
                esc_html($this->expiration_date)
            ); ?>
        </p>

        <p>
            <?php esc_html_e('Your license is no longer valid and the product will stop working until you renew.', 'wc-licensed-product'); ?>
        </p>

        <h2><?php esc_html_e('Expired License Details', 'wc-licensed-product'); ?></h2>

        <div style="margin-bottom: 40px;">
            <table class="td" cellspacing="0" cellpadding="6" style="width: 100%; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;" border="1">
                <tbody>
                    <tr>
                        <th class="td" scope="row" style="text-align:<?php echo is_rtl() ? 'right' : 'left'; ?>;"><?php esc_html_e('Product:', 'wc-licensed-product'); ?></th>
                        <td class="td" style="text-align:<?php echo is_rtl() ? 'right' : 'left'; ?>;"><?php echo esc_html($this->product_name); ?></td>
                    </tr>
                    <tr>
                        <th class="td" scope="row" style="text-align:<?php echo is_rtl() ? 'right' : 'left'; ?>;"><?php esc_html_e('License Key:', 'wc-licensed-product'); ?></th>
                        <td class="td" style="text-align:<?php echo is_rtl() ? 'right' : 'left'; ?>;">
                            <code style="background: #f5f5f5; padding: 3px 8px; border-radius: 3px; font-family: monospace;">
                                <?php echo esc_html($this->license->getLicenseKey()); ?>
                            </code>
                        </td>
                    </tr>
                    <tr>
                        <th class="td" scope="row" style="text-align:<?php echo is_rtl() ? 'right' : 'left'; ?>;"><?php esc_html_e('Domain:', 'wc-licensed-product'); ?></th>
                        <td class="td" style="text-align:<?php echo is_rtl() ? 'right' : 'left'; ?>;"><?php echo esc_html($this->license->getDomain()); ?></td>
                    </tr>
                    <tr>
                        <th class="td" scope="row" style="text-align:<?php echo is_rtl() ? 'right' : 'left'; ?>;"><?php esc_html_e('Expired on:', 'wc-licensed-product'); ?></th>
                        <td class="td" style="text-align:<?php echo is_rtl() ? 'right' : 'left'; ?>; color: #dc3232; font-weight: 600;"><?php echo esc_html($this->expiration_date); ?></td>
                    </tr>
                    <tr>
                        <th class="td" scope="row" style="text-align:<?php echo is_rtl() ? 'right' : 'left'; ?>;"><?php esc_html_e('Status:', 'wc-licensed-product'); ?></th>
                        <td class="td" style="text-align:<?php echo is_rtl() ? 'right' : 'left'; ?>;">
                            <span style="background: #f8d7da; color: #721c24; padding: 3px 10px; border-radius: 12px; font-size: 12px; font-weight: 500;">
                                <?php esc_html_e('Expired', 'wc-licensed-product'); ?>
                            </span>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <?php
        $additional_content = $this->get_additional_content();
        if ($additional_content) :
            ?>
            <p><?php echo wp_kses_post($additional_content); ?></p>
        <?php endif; ?>

        <p style="margin-top: 25px;">
            <a href="<?php echo esc_url($account_url); ?>" class="button" style="display: inline-block; background-color: #7f54b3; color: #ffffff; padding: 12px 24px; text-decoration: none; border-radius: 4px; font-weight: 600;">
                <?php esc_html_e('View My Licenses', 'wc-licensed-product'); ?>
            </a>
        </p>
        <?php
    }

    /**
     * Render plain text email body content
     */
    private function render_email_body_plain(): void
    {
        printf(esc_html__('Hello %s,', 'wc-licensed-product'), esc_html($this->customer_name));
        echo "\n\n";

        printf(
            esc_html__('Your license for %1$s has expired on %2$s.', 'wc-licensed-product'),
            esc_html($this->product_name),
            esc_html($this->expiration_date)
        );
        echo "\n\n";

        echo esc_html__('Your license is no longer valid and the product will stop working until you renew.', 'wc-licensed-product');
        echo "\n\n";

        echo "----------\n";
        echo esc_html__('Expired License Details', 'wc-licensed-product') . "\n";
        echo "----------\n\n";

        echo esc_html__('Product:', 'wc-licensed-product') . ' ' . esc_html($this->product_name) . "\n";
        echo esc_html__('License Key:', 'wc-licensed-product') . ' ' . esc_html($this->license->getLicenseKey()) . "\n";
        echo esc_html__('Domain:', 'wc-licensed-product') . ' ' . esc_html($this->license->getDomain()) . "\n";
        echo esc_html__('Expired on:', 'wc-licensed-product') . ' ' . esc_html($this->expiration_date) . "\n";
        echo esc_html__('Status:', 'wc-licensed-product') . ' ' . esc_html__('Expired', 'wc-licensed-product') . "\n\n";

        $additional_content = $this->get_additional_content();
        if ($additional_content) {
            echo "----------\n\n";
            echo esc_html(wp_strip_all_tags(wptexturize($additional_content)));
            echo "\n\n";
        }

        echo esc_html__('View My Licenses', 'wc-licensed-product') . ': ' . esc_url(wc_get_account_endpoint_url('licenses')) . "\n\n";

        echo "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n";
    }

    /**
     * Default content to show below main email content
     */
    public function get_default_additional_content(): string
    {
        return __('To continue using this product, please renew your license.', 'wc-licensed-product');
    }

    /**
     * Initialize settings form fields
     */
    public function init_form_fields(): void
    {
        $placeholder_text = sprintf(
            /* translators: %s: list of placeholders */
            __('Available placeholders: %s', 'wc-licensed-product'),
            '<code>{site_title}, {product_name}, {expiration_date}</code>'
        );

        $this->form_fields = [
            'enabled' => [
                'title' => __('Enable/Disable', 'wc-licensed-product'),
                'type' => 'checkbox',
                'label' => __('Enable this email notification', 'wc-licensed-product'),
                'default' => 'yes',
            ],
            'subject' => [
                'title' => __('Subject', 'wc-licensed-product'),
                'type' => 'text',
                'desc_tip' => true,
                'description' => $placeholder_text,
                'placeholder' => $this->get_default_subject(),
                'default' => '',
            ],
            'heading' => [
                'title' => __('Email heading', 'wc-licensed-product'),
                'type' => 'text',
                'desc_tip' => true,
                'description' => $placeholder_text,
                'placeholder' => $this->get_default_heading(),
                'default' => '',
            ],
            'additional_content' => [
                'title' => __('Additional content', 'wc-licensed-product'),
                'description' => __('Text to appear below the main email content.', 'wc-licensed-product') . ' ' . $placeholder_text,
                'css' => 'width:400px; height: 75px;',
                'placeholder' => $this->get_default_additional_content(),
                'type' => 'textarea',
                'default' => '',
                'desc_tip' => true,
            ],
            'email_type' => [
                'title' => __('Email type', 'wc-licensed-product'),
                'type' => 'select',
                'description' => __('Choose which format of email to send.', 'wc-licensed-product'),
                'default' => 'html',
                'class' => 'email_type wc-enhanced-select',
                'options' => $this->get_email_type_options(),
                'desc_tip' => true,
            ],
        ];
    }
}
