<?php

namespace App\Helpers;

use App\Models\UserModel;

class UserHelper extends CommonHelper
{
    public function __construct()
    {
        parent::__construct();
    }
    public function getFieldForm(string $field, mixed $value, array $viewDatas, array $extras = []): string
    {
        $value = $value ?: DEFAULTS['EMPTY'];
        switch ($field) {
            case 'id':
            case UserModel::TITLE:
                $form = form_input($field, $value, $extras);
                break;
            case 'passwd':
            case 'confirmpassword':
                $form = form_password($field, "", ["autocomplete" => $field, ...$extras]);
                break;
            case 'email':
                $form = form_input($field, $value, ["placeholder" => "예)test@example.com", ...$extras]);
                break;
            case 'mobile':
                $form = form_input($field, $value, ["placeholder" => "예)010-0010-0010", ...$extras]);
                break;
            case 'role':
                if (in_array($viewDatas['action'], ['create', 'modify'])) {
                    $forms = [];
                    foreach ($viewDatas['field_options'][$field] as $key => $label) {
                        $values = is_array($value) ? $value : explode(DEFAULTS["DELIMITER_ROLE"], $value);
                        $forms[] = form_checkbox(
                            "{$field}[]",
                            $key,
                            in_array($key, $values)
                        ) . $label;
                    }
                    $form = implode(" ", $forms);
                } else {
                    $form = form_dropdown(
                        $field,
                        [
                            "" => lang($viewDatas['class_path'] . '.label.' . $field) . ' 선택',
                            ...$viewDatas['field_options'][$field]
                        ],
                        $value,
                        $extras
                    );
                }
                break;
            default:
                $form = parent::getFieldForm($field, $value, $viewDatas, $extras);
                break;
        }
        return $form;
    } //
    public function getFieldView(string $field, array $viewDatas, array $extras = []): string
    {
        $value = $viewDatas['entity']->$field ?: DEFAULTS['EMPTY'];
        switch ($field) {
            case 'role':
                $roles = [];
                foreach (explode(DEFAULTS["DELIMITER_ROLE"], $value) as $key) {
                    $roles[] = $viewDatas['field_options'][$field][$key];
                }
                $value = implode(" , ", $roles);
                break;
            default:
                $value = parent::getFieldView($field, $viewDatas, $extras);
                break;
        }
        return $value;
    } //
}
