<?php

declare(strict_types=1);

namespace PpPhp\Plugins;

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

/**
 * A three-state select (All / Yes / No) to filter a boolean column. The values it
 * submits are configurable so they match however the column stores true/false
 * (1/0 by default), and the current selection is preserved from the query string.
 */
class BooleanFilter implements FilterPlugin
{
    use PluginSupport;

    public static function id(): string { return 'BooleanFilter'; }
    public static function label(): string { return 'Yes / No Filter'; }
    public static function version(): string { return '1.0.0'; }
    public static function description(): string { return 'All/Yes/No dropdown for a boolean column, with configurable stored values.'; }

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

        $trueVal  = (string) ($settings['trueValue'] ?? '1');
        $falseVal = (string) ($settings['falseValue'] ?? '0');
        $allLabel = ($settings['allLabel'] ?? '') !== '' ? (string) $settings['allLabel'] : 'All';
        $tLabel   = ($settings['trueLabel'] ?? '') !== '' ? (string) $settings['trueLabel'] : 'Yes';
        $fLabel   = ($settings['falseLabel'] ?? '') !== '' ? (string) $settings['falseLabel'] : 'No';

        $opt = function (string $val, string $label) use ($cur): string {
            $sel = $val === $cur ? ' selected' : '';
            return '<option value="' . self::e($val) . '"' . $sel . '>' . self::e($label) . '</option>';
        };

        return '<select name="' . self::e($name) . '" class="ppd-grid-search pp-input">'
            . $opt('', $allLabel)
            . $opt($trueVal, $tLabel)
            . $opt($falseVal, $fLabel)
            . '</select>';
    }

    public static function settingsSchema(): array
    {
        return [
            ['key' => 'trueValue',  'type' => 'text', 'label' => 'Stored "true" value', 'default' => '1', 'hint' => 'e.g. 1, yes, true.'],
            ['key' => 'falseValue', 'type' => 'text', 'label' => 'Stored "false" value', 'default' => '0', 'hint' => 'e.g. 0, no, false.'],
            ['key' => 'trueLabel',  'type' => 'text', 'label' => '"True" label', 'default' => 'Yes'],
            ['key' => 'falseLabel', 'type' => 'text', 'label' => '"False" label', 'default' => 'No'],
            ['key' => 'allLabel',   'type' => 'text', 'label' => '"All" label', 'default' => 'All'],
        ];
    }

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