<?php
// components/Form/OrderStatusMultiple.php
namespace Components\Form;

class OrderStatusMultiple extends BaseField {
    /**
     * Return associative array of order status options id => label
     * Delegates to DataRegistry FormDataProvider to centralize live/dev handling.
     */
    public static function getOptions(): array {
        try {
            $opts = \Components\Data\DataRegistry::form()->orderStatuses();
            if (is_array($opts) && !empty($opts)) {
                // Ensure string keys & values
                $out = [];
                foreach ($opts as $k => $v) {
                    $out[(string)$k] = (string)$v;
                }
                return $out;
            }
        } catch (\Throwable $e) {
             return ['errror' => 'error'];
        }
        return [];
    }

    /**
     * Render a list of checkboxes for selecting multiple order statuses
     */
    public static function render(string $name, string $label, $value = [], array $opts = []): string {
        $errors = $opts['errors'] ?? [];
        $help = $opts['help'] ?? '';
        // For checkbox groups, avoid binding a single x-model to all inputs
        $extra = '';

        // Normalize current value to array of strings
        if (is_string($value)) {
            // accept comma separated values
            $value = array_filter($value === '' ? [] : array_map('trim', explode(',', $value)), 'strlen');
        }
        $selected = array_map('strval', is_array($value) ? $value : []);

        $nameEsc = self::h($name);
        $labelEsc = self::h($label);

        $options = self::getOptions();
        $count = count($options);
        $scrollClass = $count > 5 ? ' max-h-48 overflow-y-auto pr-1' : '';

        $checkboxes = '';
        foreach ($options as $id => $text) {
            $idAttr = self::h(preg_replace('/[^a-zA-Z0-9_-]+/', '-', $name . '-' . $id));
            $checked = in_array((string)$id, $selected, true) ? ' checked' : '';
            $valueEsc = self::h((string)$id);
            $textEsc = self::h($text);
            $checkboxes .= <<<HTML
<div class="flex items-center gap-2 py-1">
  <input id="{$idAttr}" type="checkbox" name="{$nameEsc}[]" value="{$valueEsc}" class="rounded border-gray-300 text-brand focus:ring-brand" {$extra}{$checked}/>
  <label for="{$idAttr}" class="text-sm text-gray-700">{$textEsc}</label>
</div>
HTML;
        }

        $helpHtml = self::helpHtml($help);
        $errorHtml = self::errorsHtml($errors);
        $badge = $opts['label_badge_html'] ?? '';

        return <<<HTML
<label class="block">
  <span class="text-sm text-gray-700">{$labelEsc}{$badge}</span>
  <div class="mt-1 rounded border border-gray-200 p-2{$scrollClass}">
    {$checkboxes}
  </div>
  {$helpHtml}
  {$errorHtml}
</label>
HTML;
    }
}
