<?php

declare(strict_types=1);

namespace PpPhp\Plugins;

use PpPhp\Core\FilterPlugin;
use PpPhp\Core\PluginSupport;

/**
 * Min/max numeric range filter. Submits as f[column][min] / f[column][max] so the
 * generated list query applies col >= ? / col <= ? (open-ended if one side is
 * blank). Preserves the current values.
 */
class NumberRange implements FilterPlugin
{
    use PluginSupport;

    public static function id(): string { return 'NumberRange'; }
    public static function label(): string { return 'Number Range'; }
    public static function version(): string { return '1.2.0'; }
    public static function description(): string { return 'Filter a numeric column by a min/max range (either side optional).'; }

    public static function render(string $fieldName, array $settings): string
    {
        $col = preg_replace('/[^A-Za-z0-9_]/', '', $fieldName);
        $minVal = self::e($_GET['f'][$col]['min'] ?? '');
        $maxVal = self::e($_GET['f'][$col]['max'] ?? '');
        $step = trim((string) ($settings['step'] ?? ''));
        $stepAttr = $step !== '' ? ' step="' . self::e($step) . '"' : '';

        return '<span class="pp-numrange">'
            . '<input type="number" name="f[' . self::e($col) . '][min]" value="' . $minVal . '"' . $stepAttr . ' class="ppd-grid-search pp-input" placeholder="Min" inputmode="decimal">'
            . '<span class="pp-numrange-sep">–</span>'
            . '<input type="number" name="f[' . self::e($col) . '][max]" value="' . $maxVal . '"' . $stepAttr . ' class="ppd-grid-search pp-input" placeholder="Max" inputmode="decimal">'
            . '</span>';
    }

    public static function settingsSchema(): array
    {
        return [['key' => 'step', 'type' => 'text', 'label' => 'Step', 'default' => '', 'hint' => 'Optional numeric step, e.g. 0.01.']];
    }

    public static function assets(): array { return ['js' => [], 'css' => []]; }
}
