<?php

namespace App\Helpers\Support;

class HtmlRenderHelper
{
    /**
     *  Renders the HTML attributes of any element from an associative array.
     */
    public static function attrs(array $attrs = []): string
    {
        $out = ''; //HTML result
        foreach ($attrs as $k => $v) {
            if (is_bool($v)) { // Boolean Attrs
                if ($v) $out .= ' ' . e($k);
            } elseif ($v !== null) { // Common and Not-Empty Attrs
                $out .= ' ' . e($k) . '="' . e($v) . '"';
            }
        }

        return $out;
    }

    /**
     *  Renders the <option> choices for a <select>
     */
    public static function renderSelectOptions(array $optDef): string
    {
        // 1) Use Static Options
        if (!empty($optDef['static'])) {
            return collect($optDef['static'])->map(function ($o) {
                $attrs = [];
                return '<option' . self::attrs($attrs) . '>' . e($o['label'] ?? '') . '</option>';
            })->implode('');
        }

        // 2) Use filtered Collections
        $collection = collect($optDef['collection'] ?? []);
        if (!empty($optDef['where']) && is_array($optDef['where'])) {
            foreach ($optDef['where'] as $k => $v) {
                $collection = $collection->filter(fn($row) =>
                    isset($row->$k) ? $row->$k == $v : (is_array($row) && ($row[$k] ?? null) == $v)
                );
            }
        }

        //* Build Options
        $valueKey = $optDef['value_key'] ?? 'id';
        $labelKey = $optDef['label_key'] ?? 'name';

        $html = '';

        $html .= $collection->map(function ($row) use ($valueKey, $labelKey) {
            $value = is_array($row) ? ($row[$valueKey] ?? '') : ($row->$valueKey ?? '');
            $label = is_array($row) ? ($row[$labelKey] ?? '') : ($row->$labelKey ?? '');
            return '<option value="' . e($value) . '">' . e($label) . '</option>';
        })->implode('');

        return $html;
    }
}
