<?php

/**
 * Tenant branding colors (primary_color/secondary_color) end up interpolated
 * directly into <style> blocks (login page, main layout, PDF invoices) as
 * CSS custom properties. Running them through esc(..., 'css') looks like
 * the right call, but isn't: CSS-escaping a literal '#' produces `\23 `,
 * and while that's a spec-correct escape, browsers store it verbatim in a
 * custom property's value and fail to re-parse it back into a valid color
 * when substituted via var() elsewhere — the whole declaration using that
 * var() then silently falls back to its initial value (transparent, for
 * background-color), with no console error. Confirmed via
 * getComputedStyle().getPropertyValue('--bs-btn-bg') showing the literal
 * string "\23 4f46e5" instead of a resolved color.
 *
 * The correct defense for a value from this constrained a domain is
 * allow-list validation, not escaping: only ever accept a well-formed
 * #rrggbb string (from a tenant's saved branding, so untrusted input in
 * principle) and fall back to a safe default otherwise. A validated hex
 * string needs no further escaping to be safely interpolated into CSS.
 */
if (! function_exists('safe_hex_color')) {
    function safe_hex_color(?string $value, string $fallback): string
    {
        if ($value !== null && preg_match('/^#[0-9a-fA-F]{6}$/', $value)) {
            return $value;
        }

        return $fallback;
    }
}
