<?php

declare(strict_types=1);

namespace PpPhp\Plugins;

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

/**
 * A checkbox list to filter a column by several values at once. Submits as
 * f[column][] so the generated list query applies WHERE column IN (…). The
 * current selection is preserved from the query string.
 */
class MultiSelectFilter implements FilterPlugin
{
    use PluginSupport;

    public static function id(): string { return 'MultiSelectFilter'; }
    public static function label(): string { return 'Multi-select Filter'; }
    public static function version(): string { return '1.0.0'; }
    public static function description(): string { return 'Filter a column by any of several checkbox values (matches WHERE IN).'; }

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

        $options = (string) ($settings['source'] ?? 'manual') === 'distinct'
            ? self::distinctOptions($settings)
            : self::optionList($settings['options'] ?? '');
        // De-dupe (distinct already is, but manual may repeat).
        $options = array_values(array_unique($options));
        if ($options === []) {
            return '<span class="pp-msf-empty ppd-grid-search">No options configured.</span>';
        }

        $rows = '';
        foreach ($options as $opt) {
            $checked = in_array($opt, $current, true) ? ' checked' : '';
            $rows .= '<label class="pp-msf-opt"><input type="checkbox" name="' . self::e($name) . '" value="' . self::e($opt) . '"' . $checked . '> ' . self::e($opt) . '</label>';
        }
        return '<span class="pp-msf">' . $rows . '</span>';
    }

    /** @return array<int,string> */
    private static function optionList(mixed $raw): array
    {
        $items = is_array($raw) ? $raw : (preg_split('/\r\n|\r|\n|,/', (string) $raw) ?: []);
        $out = [];
        foreach ($items as $i) { $i = trim((string) $i); if ($i !== '' && !in_array($i, $out, true)) $out[] = $i; }
        return $out;
    }

    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' => ['plugins/Filter/MultiSelectFilter/multiselect.css']];
    }
}
