<?php
namespace PpPhp\Plugins;
use PpPhp\Core\FilterPlugin;
use PpPhp\Core\Designer\FieldControl\LookupOptions;

/**
 * Dropdown filter — a styled select for the list-page filter panel with
 * options from a manual list or a database-table lookup (with WHERE
 * condition). Submits as f[field] so it plugs into the existing
 * contains/equals filter query.
 */
class DropdownFilter implements FilterPlugin
{
    private const COLORS = ['primary', 'info', 'success', 'warning', 'danger', 'secondary', 'dark'];

    public static function id(): string { return 'DropdownFilter'; }
    public static function label(): string { return 'Lookup Dropdown Filter'; }
    public static function version(): string { return '1.0.0'; }
    public static function description(): string { return 'A dropdown of column values to filter the list.'; }

    public static function render(string $fieldName, array $settings): string
    {
        $color = (string) ($settings['color'] ?? 'secondary'); if (!in_array($color, self::COLORS, true)) $color = 'secondary';
        $variant = (string) ($settings['variant'] ?? 'outline');
        $allLabel = (string) ($settings['allLabel'] ?? '— All —');

        $cls = 'pp-b2 pp-dd is-block pp-bc-' . $color . ' pp-bz-sm'
            . ($variant === 'solid' ? '' : ($variant === 'light' ? ' is-light' : ' is-outline'));

        // Persist the currently-applied filter value (sticky across submits).
        $current = (string) ($_GET['f'][$fieldName] ?? '');
        $opts = '<option value="">' . htmlspecialchars($allLabel) . '</option>';
        foreach (LookupOptions::resolve($settings) as $val => $label) {
            $sel = ($current !== '' && $current === (string) $val) ? ' selected' : '';
            $opts .= '<option value="' . htmlspecialchars((string) $val) . '"' . $sel . '>' . htmlspecialchars((string) $label) . '</option>';
        }

        return '<div class="' . $cls . '"><select name="f[' . $fieldName . ']">' . $opts . '</select><i class="bi bi-chevron-down"></i></div>';
    }

    public static function settingsSchema(): array
    {
        return array_merge([
            ['key' => 'variant', 'label' => 'Variant', 'type' => 'select', 'options' => ['outline', 'solid', 'light'], 'default' => 'outline'],
            ['key' => 'color', 'label' => 'Color', 'type' => 'select', 'options' => self::COLORS, 'default' => 'secondary'],
            ['key' => 'allLabel', 'label' => '"All" label', 'type' => 'text', 'default' => '— All —'],
        ], LookupOptions::schema());
    }

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