<?php

namespace DZ\ImageShield\Option;

use XF;
use XF\Entity\Option;
use XF\Option\AbstractOption;

/**
 * Option handler for stamp configuration.
 * Handles rendering and validation of stamp source, text, and design settings.
 */
class Stamp extends AbstractOption
{
    /**
     * Render the option template.
     */
    public static function renderOption(Option $option, array $htmlParams): string
    {
        return self::getTemplate(
            'admin:dz_imageshield_option_stamp',
            $option,
            $htmlParams
        );
    }

    /**
     * Verify and normalize the option value before saving.
     */
    public static function verifyOption(array &$value, Option $option, string $optionId): bool
    {
        // Normalize source
        if (!isset($value['source']) || !in_array($value['source'], ['text', 'graphic'], true)) {
            $value['source'] = 'text';
        }

        // Normalize text
        $value['text'] = trim($value['text'] ?? '');

        // Normalize design settings
        if (!isset($value['design']) || !is_array($value['design'])) {
            $value['design'] = [];
        }

        $value['design']['size'] = max(8, min(200, (int) ($value['design']['size'] ?? 15)));
        $value['design']['foreground'] = self::normalizeColor($value['design']['foreground'] ?? '#ffffff');
        $value['design']['background'] = self::normalizeColor($value['design']['background'] ?? '#000000');
        $value['design']['font'] = trim($value['design']['font'] ?? '');

        return true;
    }

    /**
     * Normalize hex color value.
     */
    protected static function normalizeColor(string $color): string
    {
        $color = trim($color);
        if (empty($color)) {
            return '#000000';
        }

        // Add # if missing
        if ($color[0] !== '#') {
            $color = '#' . $color;
        }

        // Validate hex format
        if (!preg_match('/^#[0-9A-Fa-f]{6}$/', $color)) {
            return '#000000';
        }

        return strtolower($color);
    }
}
