<?php

namespace Licenzo\Modules\EDD;

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

class EddEmailService
{
    private const SEPARATOR_LENGTH = 40;

    public static function register(): void
    {
        add_action('edd_add_email_tags', [static::class, 'registerEmailTags']);
    }

    public static function registerEmailTags(): void
    {
        edd_add_email_tag(
            'licenzo_license_keys',
            __('Displays Licenzo license keys for the purchase', 'licenzo'),
            [static::class, 'renderLicenseKeysTag']
        );
    }

    /**
     * Render license keys for use in EDD email templates via {licenzo_license_keys} tag.
     */
    public static function renderLicenseKeysTag($paymentId): string
    {
        $licenses = EddHelper::getLicensesForOrder((int) $paymentId);
        if (empty($licenses)) {
            return '';
        }

        $output = "\n" . str_repeat('-', static::SEPARATOR_LENGTH) . "\n";
        $output .= __('License Keys', 'licenzo') . "\n";
        $output .= str_repeat('-', static::SEPARATOR_LENGTH) . "\n";

        foreach ($licenses as $license) {
            $output .= sprintf(
                "%s: %s\n",
                esc_html($license->subscription?->subscription_name ?? __('License', 'licenzo')),
                esc_html($license->license_key)
            );
        }

        return $output;
    }
}
