<?php

/**
 * Copyright 2024-2025 Simply.IN Sp. z o.o.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the EUPL-1.2 or later.
 * You may not use this work except in compliance with the Licence.
 *
 * Copy of the Licence is available at:
 * https://joinup.ec.europa.eu/software/page/eupl
 * It is bundled with this package in the file LICENSE.txt
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Licence is distributed on an as is basis,
 * without warranties or conditions of any kind, either express or implied.
 * Check the Licence for the specific language governing permissions
 * and limitations under the License.
 *
 * @author   Simply.IN Sp. z o.o.
 * @copyright 2024-2025 Simply.IN Sp. z o.o.
 * @license   https://joinup.ec.europa.eu/software/page/eupl
 */

declare(strict_types=1);

namespace SimplyIn\Front;

use Configuration;

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

/**
 * The merchant's two brand colours, read and validated in one place.
 *
 * These values are merchant-entered and reach both a CSS custom property and a `style` attribute.
 * Escaping keeps such an attribute structurally intact but still admits arbitrary declarations
 * inside it, so the values are validated as hex colours and fall back to the product defaults when
 * they are anything else.
 *
 * Read through here rather than inline at each surface, because the guarantee is only worth
 * anything if it is the same everywhere: the reads were previously spread across the front-end
 * payload, the confirmation surface and the settings screen, each with its own copy of the default
 * and none of them validating. One unguarded reader is enough to put an unvalidated value on a page.
 */
final class BrandColors
{
    /** Product defaults, matching what a fresh install stores. */
    public const DEFAULT_ACCENT = '#2d40f6';

    public const DEFAULT_FONT = '#000000';

    public static function accent(): string
    {
        return self::read('SIMPLYIN_ACCENT_COLOR', self::DEFAULT_ACCENT);
    }

    public static function font(): string
    {
        return self::read('SIMPLYIN_FONT_COLOR', self::DEFAULT_FONT);
    }

    private static function read(string $key, string $default): string
    {
        $value = Configuration::get($key);

        // Three- and six-digit hex only. Anything else - a named colour, a gradient, a stray
        // semicolon carrying a second declaration - is not a colour we are willing to emit.
        return (is_string($value) && preg_match('/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/', $value) === 1)
            ? $value
            : $default;
    }
}
