<?php

use App\Models\Cloudflare\ZoneModel;

function getFieldLabel_ZoneHelper(string $field, array $viewDatas, array $extras = []): string
{
    switch ($field) {
        case ZoneModel::PARENT:
            $extras = [...$extras, "class" => 'text-danger'];
            break;
        default:
            if (strpos($viewDatas['field_rules'][$field], 'required') !== false) {
                $extras = [...$extras, "class" => 'text-danger'];
            }
            break;
    }
    return form_label(lang("{$viewDatas['class_path']}.label.{$field}"), $field, $extras);
}
//header.php에서 getFieldForm_Helper사용
function getFieldForm_ZoneHelper(string $field, mixed $value, array $viewDatas, array $extras = []): string
{
    $value = $value ?: DEFAULTS['EMPTY'];
    switch ($field) {
        case ZoneModel::PARENT:
            $form = form_dropdown($field, [
                "" => lang($viewDatas['class_path'] . '.label.' . $field) . ' 선택',
                ...$viewDatas['field_options'][$field]
            ], isset($viewDatas[ZoneModel::PARENT]) ? $viewDatas[ZoneModel::PARENT] : $value, [...$extras, 'class' => "select-field"]);
            // // return form_multiselect($field, $field_options[$field], is_array($value) ? [...$value] : [$value], [$extras]);
            // foreach ($viewDatas['field_options'][$field] as $key => $label) {
            //   $checkboxs[] = form_checkbox("{$field}[]", $key, in_array($key, explode(DEFAULTS["DELIMITER_ROLE"], $value))) . $label;
            // }
            // return implode("&nbsp;", $checkboxs);
            break;
        case ZoneModel::TITLE:
            $form = form_input($field, $value, ["placeholder" => "예)exmaple.com", "style" => "width:100%; ::placeholder{color:silver; opacity: 1;}"]);
            break;
        case 'domains':
            $form = form_textarea($field, $value, ['class' => 'editor', 'rows' => '5']);
            break;
        case 'hosts':
            $form = form_textarea($field, $value == DEFAULTS['EMPTY'] ? "@\n*\nm\nwww" : $value, ['class' => 'editor', 'rows' => '5']);
            break;
        case 'content':
            $form = form_input($field, $value, ["placeholder" => "예)123.123.123.123", "style" => "width:200px; ::placeholder{color:silver; opacity: 1;}"]);
            break;
        case "development_mode":
        case "ipv6":
        case "security_level":
        case 'status':
            $form = form_dropdown($field, [
                "" => lang($viewDatas['class_path'] . '.label.' . $field) . ' 선택',
                ...$viewDatas['field_options'][$field]
            ], $value, $extras);
            break;
        case 'type':    //A,AAA...
        case 'proxied': //CDN사용여부
            $form = form_dropdown($field, [
                "" => lang('Admin/Cloudflare/Record.label.' . $field) . ' 선택',
                ...$viewDatas['field_options'][$field]
            ], $value, $extras);
            break;
        case 'updated_at':
        case 'created_at':
            $form = form_input($field, $value, ['class' => 'calender']);
            break;
        default:
            $form = form_input($field, $value, ["style" => "width:100%;"]);
            break;
    }
    return $form;
} //
function getFieldView_ZoneHelper(string $field, array $viewDatas, array $extras = [])
{
    $value = $viewDatas['entity']->$field ?: DEFAULTS['EMPTY'];
    switch ($field) {
        case ZoneModel::PARENT:
            if ($viewDatas['old_account'] === $viewDatas['entity']->getParent()) {
                $value = "";
            } else {
                $value = anchor(
                    base_url() . strtolower($viewDatas['root']) . "account/reload/"  . $viewDatas['entity']->getParent(),
                    ICONS["RELOAD"],
                    [
                        "class" => "btn btn-sm btn-primary btn-circle",
                        "target" => "_self"
                    ]
                ) . " <span class=\"label_accounts\">" .
                    preg_replace("/(\w+)@(.+)/", "$1", $viewDatas['field_options'][$field][$value])
                    . "</span>";
            }
            break;
        case ZoneModel::TITLE:
            $value = anchor(
                current_url() . '/reload/' . $viewDatas['entity']->getPK(),
                ICONS["RELOAD"],
                [
                    "class" => "btn btn-sm btn-primary btn-circle",
                    "target" => "_self"
                ]
            ) . " " .
                anchor(
                    base_url() . strtolower($viewDatas['root']) . "record?zone_uid="   . $viewDatas['entity']->getPK(),
                    ICONS["FLAG"],
                    [
                        "class" => "btn btn-sm btn-primary btn-circle",
                        "target" => "_self"
                    ]
                ) . " <span class=\"label_zones\">{$value}</span>";
            break;
        case 'name_servers':
        case 'original_name_servers':
            $value = str_replace(",", "<BR>", $value);
            break;
        case 'category_uid':
            foreach (array_values($viewDatas['field_options'][$field]) as $category_2depths) {
                foreach ($category_2depths as $key => $depth) {
                    if ($key == $depth) {
                        $value = $depth;
                    }
                }
            }
            break;
        case 'cost':
        case 'price':
        case 'sale':
            $value = number_format(!$value ? 0 : $value) . "원";
            break;
        case 'updated_at':
        case 'created_at':
            $value = $value ? date("Y-m-d", strtotime($value)) : "";
            break;
        default:
            if (in_array($field, $viewDatas['filter_fields']) && $value) {
                $extras["onChange"] = sprintf(
                    'location.href="%s/toggle/%s/%s?%s="+this.options[this.selectedIndex].value',
                    current_url(),
                    $viewDatas['entity']->getPK(),
                    $field,
                    $field
                );
                $value = getFieldForm_ZoneHelper($field, $viewDatas['entity']->$field, $viewDatas, $extras);
            }
            break;
    }
    return $value;
} //
function getListLabel_ZoneHelper(string $field, array $viewDatas, array $extras = []): string
{
    $label = getFieldLabel_ZoneHelper($field, $viewDatas, $extras);
    if ($field == $viewDatas['order_field']) {
        $label .= $viewDatas['order_value'] == 'ASC' ? ICONS["UP"] : ICONS["DOWN"];
    }
    $order_value = $viewDatas['order_value'] == 'DESC' ? "ASC" : "DESC";
    $viewDatas['uri']->addQuery('order_field', $field);
    $viewDatas['uri']->addQuery('order_value', $order_value);
    $label = anchor((string)$viewDatas['uri'], $label);
    switch ($field) {
        case ZoneModel::PARENT:
            break;
        case ZoneModel::TITLE:
            $label .= "<button onClick=\"getElementsByClassNameCopyToClipboard('label_zones'); return false;\" class=\"btn btn-sm btn-danger btn-circle\">Copy Domains</buttion>";
            break;
    }
    return sprintf("<th %s>%s</th>", implode(" ", $extras), $label);
}
function getListButtonLabel_ZoneHelper(string $action, string $label, array $viewDatas, array $extras = []): string
{
    switch ($action) {
        case 'create':
            switch ($viewDatas['action_form']) {
                case FORMS['MODAL']:
                    $value = form_label(
                        $label,
                        "",
                        [
                            "data-src" => $viewDatas['list_action_url'],
                            "data-bs-toggle" => "modal",
                            "data-bs-target" => "#index_action_form",
                            ...$extras
                        ]
                    );
                    break;
                case FORMS['IFRAME']:
                    $value = "";
                    break;
                default:
                    $value = anchor($viewDatas['list_action_url'], $label, $extras);
                    break;
            }
            break;
        case 'modify':
            switch ($viewDatas['action_form']) {
                case FORMS['MODAL']:
                    $value = form_label(
                        $label,
                        "",
                        [
                            "data-src" => $viewDatas['list_action_url'],
                            "data-bs-toggle" => "modal",
                            "data-bs-target" => "#index_action_form",
                            ...$extras
                        ]
                    );
                    break;
                case FORMS['IFRAME']:
                    $value = form_label($label, "", [
                        "onClick" => "changeIframe_src('{$viewDatas['list_action_url']}')",
                        ...$extras
                    ]);
                    break;
                default:
                    $value = anchor($viewDatas['list_action_url'], $label, $extras);
                    break;
            }
            break;
        default:
            break;
    }
    return $value;
}
function getListButton_ZoneHelper(string $action, array $viewDatas, array $extras = []): string
{
    switch ($action) {
        case 'create':
            $viewDatas['list_action_url'] = current_url() . '/' . $action . '?' . $viewDatas['uri']->getQuery(['only' => ZoneModel::PARENT]);
            $extras = ["class" => "btn btn-outline btn-primary btn-circle", "target" => "_self", ...$extras];
            $action = getListButtonLabel_ZoneHelper($action, '입력',  $viewDatas, $extras);
            break;
        case 'sync':
            $checkbox = form_checkbox([
                "id" => "checkbox_uid_{$viewDatas['entity']->getPK()}",
                "name" => "batchjob_uids[]",
                "value" => $viewDatas['entity']->getPK(),
                "class" => "batchjobuids_checkboxs"
            ]);
            $viewDatas['list_action_url'] = current_url() . '/' . $action . '/' . $viewDatas['entity']->getPK();
            $action = $checkbox . anchor($viewDatas['list_action_url'], $viewDatas['cnt'], $extras);
            break;
        case 'delete':
            $viewDatas['list_action_url'] = current_url() . '/' . $action . '/' . $viewDatas['entity']->getPK();
            $extras = ["class" => "btn btn-sm btn-danger btn-circle", "target" => "_self", ...$extras];
            $action = anchor($viewDatas['list_action_url'], ICONS['DELETE'], $extras);
            break;
    }
    return $action;
}
