<?php

namespace App\Helpers;

class UserHelper extends CommonHelper
{
    public function __construct()
    {
        parent::__construct();
    }
    public function getFieldForm(string $field, mixed $value, array $viewDatas, array $extras = []): string
    {
        switch ($field) {
            case 'passwd':
            case 'confirmpassword':
                $extras['class'] = array_key_exists('class', $extras) ? $extras['class'] . ' form-control' : 'form-control';
                $extras['style'] = 'width:100%;';
                $form = form_password($field, "", $extras);
                break;
            case 'role':
                // ✅ value가 string이면 CSV -> array로 변환
                if (is_string($value)) {
                    $value = array_values(array_filter(array_map('trim', explode(',', $value))));
                } elseif ($value === null) {
                    $value = [];
                }

                // ✅ 현재 role 목록(소문자/trim 정규화)
                $currentRoles = is_array($value)
                    ? array_map('strtolower', array_map('trim', $value))
                    : [];

                $form = '';

                // Form페이지에서는 맨앞에것 제외하기 위함
                if (isset($viewDatas['formOptions'][$field]['options']) && is_array($viewDatas['formOptions'][$field]['options'])) {
                    $options = $viewDatas['formOptions'][$field]['options'];

                    // ✅ 원본을 건드리지 말고 복사본에서 shift (중요)
                    array_shift($options);

                    foreach ($options as $key => $label) {
                        $checked = in_array(strtolower(trim((string) $key)), $currentRoles, true);

                        $form .= '<label class="me-3">';
                        $form .= form_checkbox('role[]', (string) $key, $checked, ['id' => "role_{$key}", ...$extras]);
                        $form .= " {$label}";
                        $form .= '</label>';
                    }
                }
                break;
            default:
                $form = parent::getFieldForm($field, $value, $viewDatas, $extras);
                break;
        }
        return $form;
    } //
}
