<?php

namespace DZ\ImageShield\Option;

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

/**
 * Option handler for layout configuration.
 * Handles rendering and validation of anchor, rotation, and dimension settings.
 */
class Layout extends AbstractOption
{
    /**
     * Render the option template.
     */
    public static function renderOption(Option $option, array $htmlParams): string
    {
        return self::getTemplate(
            'admin:dz_imageshield_option_layout',
            $option,
            $htmlParams
        );
    }

    /**
     * Verify and normalize the option value before saving.
     */
    public static function verifyOption(array &$value, Option $option, string $optionId): bool
    {
        // Valid anchor positions
        $validAnchors = [
            'corner_tl', 'edge_t', 'corner_tr',
            'edge_l', 'middle', 'edge_r',
            'corner_bl', 'edge_b', 'corner_br',
            'manual'
        ];

        // Valid rotation values
        $validRotations = ['none', 'tilt_left', 'tilt_right'];

        // Normalize anchor
        if (!isset($value['anchor']) || !in_array($value['anchor'], $validAnchors, true)) {
            $value['anchor'] = 'corner_br';
        }

        // Normalize rotation
        if (!isset($value['rotation']) || !in_array($value['rotation'], $validRotations, true)) {
            $value['rotation'] = 'none';
        }

        // Normalize dimensions
        $value['width'] = max(5, min(100, (int) ($value['width'] ?? 30)));
        $value['height'] = max(5, min(100, (int) ($value['height'] ?? 25)));

        // Normalize offsets
        $value['offsetX'] = max(0, min(100, (int) ($value['offsetX'] ?? 0)));
        $value['offsetY'] = max(0, min(100, (int) ($value['offsetY'] ?? 0)));

        return true;
    }
}
