<?php

declare(strict_types=1);

namespace PpPhp\Plugins;

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

/**
 * A dropdown of preset options that filters a column by exact match. Submits as
 * f[column] so the generated list query reads it, and preserves the current
 * selection.
 */
class SelectFilter implements FilterPlugin
{
    use PluginSupport;

    public static function id(): string { return 'SelectFilter'; }
    public static function label(): string { return 'Dropdown Filter'; }
    public static function version(): string { return '1.1.0'; }
    public static function description(): string { return 'A dropdown of preset options that filters a column by exact match.'; }

    public static function render(string $fieldName, array $settings): string
    {
        $col = preg_replace('/[^A-Za-z0-9_]/', '', $fieldName);
        $cur = (string) ($_GET['f'][$col] ?? '');

        if ((string) ($settings['source'] ?? 'manual') === 'distinct') {
            $items = self::distinctOptions($settings);
        } else {
            $items = preg_split('/\r\n|\r|\n|,/', (string) ($settings['options'] ?? '')) ?: [];
        }

        $html = '<select name="f[' . self::e($col) . ']" class="ppd-grid-search pp-input"><option value="">— All —</option>';
        $seen = [];
        foreach ($items as $o) {
            $o = trim((string) $o);
            if ($o === '' || isset($seen[$o])) continue;
            $seen[$o] = true;
            $sel = $o === $cur ? ' selected' : '';
            $html .= '<option value="' . self::e($o) . '"' . $sel . '>' . self::e($o) . '</option>';
        }
        return $html . '</select>';
    }

    public static function settingsSchema(): array
    {
        return [
            ['key' => 'source',  'type' => 'select', 'label' => 'Options from', 'options' => ['manual', 'distinct'], 'default' => 'manual', 'hint' => 'distinct = the column’s existing values, updated automatically.'],
            ['key' => 'options', 'type' => 'textarea', 'label' => 'Manual options', 'default' => '', 'hint' => 'One per line (or comma-separated). Used when “Options from” is manual.'],
        ];
    }

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