<?php

use App\Models\Cloudflare\RecordModel;
use App\Models\Cloudflare\ZoneModel;

function getFieldLabel_RecordHelper(string $field, array $viewDatas, array $extras = []): string
{
    switch ($field) {
        case RecordModel::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_RecordHelper(string $field, mixed $value, array $viewDatas, array $extras = []): string
{
    $value = $value ?: DEFAULTS['EMPTY'];
    switch ($field) {
        case RecordModel::PARENT:
            $form = form_dropdown(
                $field,
                [
                    "" => lang($viewDatas['class_path'] . '.label.' . $field) . ' 선택',
                    ...$viewDatas['field_options'][$field]
                ],
                isset($viewDatas[RecordModel::PARENT]) ? $viewDatas[RecordModel::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 RecordModel::TITLE: //host
            $form = form_input($field, $value, ["placeholder" => "예)www.example.com", "style" => "width:200px; ::placeholder{color:silver; opacity: 1;}"]);
            break;
        case 'hosts':
            $form = form_textarea($field, html_entity_decode($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 "type":
        case "fixed":
        case "locked":
        case "proxied":
        case "proxiable":
            $form = form_dropdown($field, [
                "" => lang($viewDatas['class_path'] . '.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_RecordHelper(string $field, array $viewDatas, array $extras = [])
{
    $value = $viewDatas['entity']->$field ?: DEFAULTS['EMPTY'];
    switch ($field) {
        case RecordModel::PARENT:
            if ($viewDatas['old_zone'] === $viewDatas['entity']->getParent()) {
                $value = "";
            } else {
                $value = anchor(
                    base_url() . strtolower($viewDatas['root']) . 'zone/reload/' . $viewDatas['entity']->getParent(),
                    ICONS["RELOAD"],
                    [
                        "class" => "btn btn-sm btn-primary btn-circle",
                        "target" => "_self"
                    ]
                ) . " " . "<span class=\"label_zones\">{$viewDatas['field_options'][$field][$value]}</span>";
            }
            break;
        case RecordModel::TITLE:
            $url =  sprintf("%s/toggle/%s?fixed=%s", current_url(), $viewDatas['entity']->getPK(), $viewDatas['entity']->fixed == 'on' ? "off" : "on");
            $value = sprintf("%s%s", $viewDatas['entity']->fixed == 'on' ? ICONS['LOCK'] : "", $value);
            $value = anchor($url, $value, ["target" => "_self"]);
            break;
        case 'content':
            $value = sprintf(
                "<span class=\"short-text\" data-bs-toggle=\"tooltip\" data-bs-placement=\"top\" title=\"%s\">%s</span>",
                $value,
                mb_strlen($value) > 40 ? mb_substr($value, 0, 40) . '...' : $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_RecordHelper($field, $viewDatas['entity']->$field, $viewDatas, $extras);
            }
            break;
    }
    return $value;
} //

function getListLabel_RecordHelper(string $field, array $viewDatas, array $extras = []): string
{
    $label = getFieldLabel_RecordHelper($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 RecordModel::PARENT:
            $label .= "<button onClick=\"getElementsByClassNameCopyToClipboard('label_zones'); return false;\" class=\"btn btn-sm btn-danger btn-circle\">Copy Domains</buttion>";
            break;
        case RecordModel::TITLE:
            $label .= "<button onClick=\"getElementsByClassNameCopyToClipboard('label_hosts'); return false;\" class=\"btn btn-sm btn-danger btn-circle\">Copy Hosts</buttion>";
            break;
    }
    return sprintf("<th %s>%s</th>", implode(" ", $extras), $label);
}
function getListButtonLabel_RecordHelper(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_RecordHelper(string $action, array $viewDatas, array $extras = []): string
{
    switch ($action) {
        case 'create':
            $viewDatas['list_action_url'] = current_url() . '/' . $action . '?' . $viewDatas['uri']->getQuery(['only' => RecordModel::PARENT]);
            $extras = ["class" => "btn btn-outline btn-primary btn-circle", "target" => "_self", ...$extras];
            $action = getListButtonLabel_RecordHelper($action, '입력',  $viewDatas, $extras);
            break;
        case 'sync':
            $checkbox = "";
            if ($viewDatas['entity']->type == "A" && $viewDatas['entity']->fixed != 'on')
                $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;
}
