<?php
/**
 * Turns a license-duration form selection into a DATE string (or null for lifetime).
 *
 * $duration one of: '1y', '2y', '3y', 'lifetime', 'custom'
 * $customDate only used when $duration === 'custom' (expects 'Y-m-d')
 * $fromDate the date to count the duration from (defaults to today) - pass
 *           an existing expiry date here when RENEWING/extending a license
 *           so the new period stacks on top instead of starting over.
 */
function calculateLicenseExpiry(string $duration, ?string $customDate = null, ?string $fromDate = null): ?string
{
    $base = $fromDate ? new DateTime($fromDate) : new DateTime();

    switch ($duration) {
        case '1y':
            $base->modify('+1 year');
            return $base->format('Y-m-d');
        case '2y':
            $base->modify('+2 years');
            return $base->format('Y-m-d');
        case '3y':
            $base->modify('+3 years');
            return $base->format('Y-m-d');
        case 'custom':
            if ($customDate && preg_match('/^\d{4}-\d{2}-\d{2}$/', $customDate)) {
                return $customDate;
            }
            return null;
        case 'lifetime':
        default:
            return null;
    }
}

/** Human-readable label for a license_expiry value, for display in the dashboard/edit pages. */
function licenseExpiryLabel(?string $expiry): string
{
    if (!$expiry) return 'Lifetime (no expiry)';
    $today = new DateTime();
    $exp = new DateTime($expiry);
    $diffDays = (int) $today->diff($exp)->format('%r%a');
    if ($diffDays < 0) return 'Expired on ' . $exp->format('d M Y');
    if ($diffDays <= 30) return $exp->format('d M Y') . " ({$diffDays} days left)";
    return $exp->format('d M Y');
}