<?php

namespace Licenzo\Modules\EDD;

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

class EddPurchaseHistoryService
{
    public static function register(): void
    {
        add_action('edd_order_receipt_after_table', [static::class, 'renderLicenseInfoOnReceipt'], 30, 1);
    }

    public static function renderLicenseInfoOnReceipt($order): void
    {
        if (!$order || !isset($order->id)) {
            return;
        }

        $licenses = EddHelper::getLicensesForOrder((int) $order->id);
        if (empty($licenses)) {
            return;
        }

        static::renderLicenseTable($licenses);
    }

    private static function renderLicenseTable(array $licenses): void
    {
        echo '<h3>' . esc_html__('Your License Keys', 'licenzo') . '</h3>';
        echo '<table class="edd-table"><thead><tr>';
        echo '<th>' . esc_html__('Product', 'licenzo') . '</th>';
        echo '<th>' . esc_html__('License Key', 'licenzo') . '</th>';
        echo '<th>' . esc_html__('Status', 'licenzo') . '</th>';
        echo '<th>' . esc_html__('Expires', 'licenzo') . '</th>';
        echo '</tr></thead><tbody>';

        foreach ($licenses as $license) {
            $expireDisplay = $license->expire_date
                ? date_i18n(get_option('date_format'), strtotime($license->expire_date))
                : __('Never', 'licenzo');

            echo '<tr>';
            echo '<td>' . esc_html($license->subscription?->subscription_name ?? '') . '</td>';
            echo '<td><code>' . esc_html($license->license_key) . '</code></td>';
            echo '<td>' . esc_html(ucfirst($license->status)) . '</td>';
            echo '<td>' . esc_html($expireDisplay) . '</td>';
            echo '</tr>';
        }

        echo '</tbody></table>';
    }
}
