<?php

namespace App\Helpers\Customer;

use RuntimeException;

class ClientHelper extends CustomerHelper
{
    public function __construct()
    {
        parent::__construct();
    }
    public function getFieldForm(string $field, mixed $value, array $viewDatas, array $extras = []): string
    {
        switch ($field) {
            case 'site':
                $forms = [];
                array_shift($viewDatas['formOptions'][$field]['options']);
                foreach ($viewDatas['formOptions'][$field]['options'] as $key => $label)
                    $forms[] = form_radio($field, $key, $key == $value, $extras) . $label;
                $form = implode(" ", $forms);
                break;
            case 'role':
                // 1) value가 배열이면 그대로, 문자열이면 CSV를 배열로 변환
                if (is_string($value)) {
                    $value = trim($value, " \t\n\r\0\x0B\"");
                    $value = ($value === '') ? [] : explode(DEFAULTS["DELIMITER_COMMA"], $value);
                } elseif (!is_array($value)) {
                    $value = [];
                }

                // 2) 정리
                $currentRoles = array_values(array_filter(
                    array_map(
                        fn($item) => strtolower(trim((string) ($item ?? ''), " \t\n\r\0\x0B\"")),
                        $value
                    )
                ));

                $form = '';
                array_shift($viewDatas['formOptions'][$field]['options']);
                foreach ($viewDatas['formOptions'][$field]['options'] as $key => $label) {
                    $checked = in_array(strtolower(trim((string) $key)), $currentRoles, true);
                    $form .= '<label class="me-3">';
                    $form .= form_checkbox('role[]', $key, $checked, ['id' => "role_{$key}", ...$extras]);
                    $form .= " {$label}";
                    $form .= '</label>';
                }
                // dd($form);
                break;
            default:
                $form = parent::getFieldForm($field, $value, $viewDatas, $extras);
                break;
        }
        return $form;
    } //
    public function getFieldView(string $field, mixed $value, array $viewDatas, array $extras = []): string|null
    {
        switch ($field) {
            case 'name':
                $value = "<a href=\"/admin/customer/client/detail/{$viewDatas['entity']->getPK()}\">" . $value . "</a>";
                break;
            case "email":
            case "phone":
                //역활이 보안관리자가 아니면 정보숨김
                $value = $this->getAuthContext()->isAccessRole([ROLE['USER']['SECURITY']]) ? parent::getFieldView($field, $value, $viewDatas, $extras) : "***********";
                break;
            case 'account_balance':
                $value = form_label(
                    number_format($value) . "원",
                    $field,
                    [
                        "data-src" => "/admin/customer/wallet/account?clientinfo_uid={$viewDatas['entity']->getPK()}&ActionTemplate=popup",
                        "data-bs-toggle" => "modal",
                        "data-bs-target" => "#modal_action_form",
                        "class" => "text-primary",
                        ...$extras,
                    ]
                );
                break;
            case 'coupon_balance':
                $value = form_label(
                    number_format($value) . "개",
                    $field,
                    [
                        "data-src" => "/admin/customer/wallet/coupon?clientinfo_uid={$viewDatas['entity']->getPK()}&ActionTemplate=popup",
                        "data-bs-toggle" => "modal",
                        "data-bs-target" => "#modal_action_form",
                        "class" => "text-primary",
                        ...$extras,
                    ]
                );
                break;
            case 'point_balance':
                $value = form_label(
                    number_format($value) . "점",
                    $field,
                    [
                        "data-src" => "/admin/customer/wallet/point?clientinfo_uid={$viewDatas['entity']->getPK()}&ActionTemplate=popup",
                        "data-bs-toggle" => "modal",
                        "data-bs-target" => "#modal_action_form",
                        "class" => "text-primary",
                        ...$extras,
                    ]
                );
                break;
            default:
                $value = parent::getFieldView($field, $value, $viewDatas, $extras);
                break;
        }
        if (is_array($value)) {
            throw new RuntimeException(static::class . "->" . __FUNCTION__ . "에서 오류발생:{$field}에 해당하는 Return 값이 배열형식입니다.\n" . var_export($value, true));
        }
        return $value;
    } //
    public function getListButton(string $action, string $label, array $viewDatas, array $extras = []): string
    {
        switch ($action) {
            case 'delete':
            case 'batchjob':
            case 'batchjob_delete':
                //역활이 보안관리자가 아니면 사용불가
                $action = $this->getAuthContext()->isAccessRole([ROLE['USER']['SECURITY']]) ? parent::getListButton($action, $label, $viewDatas, $extras) : "";
                break;
            case 'modify':
                //역활이 보안관리자가 아니면 수정불가
                $action = $this->getAuthContext()->isAccessRole([ROLE['USER']['SECURITY']]) ? parent::getListButton($action, $label, $viewDatas, $extras) : $label;
                break;
            case 'history':
                $action = form_label(
                    $label ? $label : ICONS['HISTORY'],
                    $action,
                    [
                        "data-src" => "/admin/customer/client/history?clientinfo_uid={$viewDatas['entity']->getPK()}",
                        "data-bs-toggle" => "modal",
                        "data-bs-target" => "#modal_action_form",
                        "class" => "btn btn-sm btn-primary form-label-sm",
                        ...$extras
                    ]
                );
                break;
            case 'coupon':
            case 'account':
            case 'point':
                $action = form_label(
                    $label,
                    $action,
                    [
                        "data-src" => "/admin/customer/wallet/{$action}?clientinfo_uid={$viewDatas['entity']->getPK()}&ActionTemplate=popup",
                        "data-bs-toggle" => "modal",
                        "data-bs-target" => "#modal_action_form",
                        "class" => "text-primary",
                        ...$extras
                    ]
                );
                break;
            case 'invoice':
                $action = form_label(
                    $label,
                    'payment_invoice',
                    [
                        "data-src" => "/admin/payment?clientinfo_uid={$viewDatas['entity']->getPK()}&ActionTemplate=popup",
                        "data-bs-toggle" => "modal",
                        "data-bs-target" => "#modal_action_form",
                        "class" => "text-primary form-label-sm",
                    ]
                );
                break;
            case 'addService':
                $action = form_label(
                    '서비스추가',
                    'create_service',
                    [
                        "data-src" => "/admin/customer/service/create?clientinfo_uid={$viewDatas['entity']->getPK()}",
                        "data-bs-toggle" => "modal",
                        "data-bs-target" => "#modal_action_form",
                        "class" => "btn btn-sm btn-primary form-label-sm",
                    ]
                );
                break;
            case 'unpaid':
                $action = "{$label} 0원";
                if (array_key_exists($viewDatas['entity']->getPK(), $viewDatas['unPaids'])) {
                    $action = form_label(
                        sprintf("%s건/%s원", $viewDatas['unPaids'][$viewDatas['entity']->getPK()]['cnt'], number_format($viewDatas['unPaids'][$viewDatas['entity']->getPK()]['amount'])),
                        'payment_unpaid',
                        [
                            "data-src" => "/admin/payment?clientinfo_uid={$viewDatas['entity']->getPK()}&status=unpaid&ActionTemplate=popup",
                            "data-bs-toggle" => "modal",
                            "data-bs-target" => "#modal_action_form",
                            "class" => "text-primary form-label-sm",
                        ]
                    );
                }
                break;
            default:
                $action = parent::getListButton($action, $label, $viewDatas, $extras);
                break;
        }
        return $action;
    }
}
