<?php

use App\Models\MapurlModel;

function getFieldLabel_MapurlHelper(string $field, array $viewDatas, array $extras = []): string
{
    switch ($field) {
        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_MapurlHelper(string $field, mixed $value, array $viewDatas, array $extras = []): string
{
    $value = $value ?: DEFAULTS['EMPTY'];
    switch ($field) {
        case MapurlModel::TITLE:
            $form = form_input($field, $value, ["placeholder" => "예)http://old.example.com", "style" => "width:100%; ::placeholder{color:silver; opacity: 1;}"]);
            break;
        case 'newurl':
            $form = form_input($field, $value, ["placeholder" => "예)https://new.example.com", "style" => "width:100%; ::placeholder{color:silver; opacity: 1;}"]);
            break;
        case 'status':
            $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_MapurlHelper(string $field, array $viewDatas, array $extras = [])
{
    $value = $viewDatas['entity']->$field ?: DEFAULTS['EMPTY'];
    switch ($field) {
        case MapurlModel::TITLE:
            // $value = anchor(
            //     current_url() . '/view/' . $viewDatas['entity']->getPK(),
            //     $value,
            //     [
            //         "target" => "_self",
            //     ]
            // );
            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 '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_MapurlHelper($field, $viewDatas['entity']->$field, $viewDatas, $extras);
            }
            break;
    }
    return $value;
} //
function getListLabel_MapurlHelper(string $field, array $viewDatas, array $extras = []): string
{
    $label = getFieldLabel_MapurlHelper($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 MapurlModel::TITLE:
            break;
    }
    return sprintf("<th %s>%s</th>", implode(" ", $extras), $label);
}
function getListButtonLabel_MapurlHelper(string $action, string $label, array $viewDatas, array $extras = []): string
{
    switch ($viewDatas['action_form']) {
        case FORMS['MODAL']:
            $label = form_label(
                $label,
                "",
                [
                    "data-src" => $viewDatas['list_action_url'],
                    "data-bs-toggle" => "modal",
                    "data-bs-target" => "#index_action_form",
                    ...$extras
                ]
            );
            break;
        case FORMS['IFRAME']:
            if ($action == 'create') {
                $label = form_label($label, "", [
                    "onClick" => "changeIframe_src('{$viewDatas['list_action_url']}')",
                    ...$extras,
                ]);
            } else {
                $label = "";
            }
            break;
        default:
            $label = anchor($viewDatas['list_action_url'], $label, $extras);
            break;
    }
    return $label;
}
function getListButton_MapurlHelper(string $action, array $viewDatas, array $extras = []): string
{
    switch ($action) {
        case 'create':
            $viewDatas['list_action_url'] = current_url() . '/' . $action;
            $extras = ["class" => "btn btn-outline btn-primary btn-circle", "target" => "_self", ...$extras];
            $action = getListButtonLabel_MapurlHelper($action, '입력',  $viewDatas, $extras);
            break;
        case 'modify':
            $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 . getListButtonLabel_MapurlHelper($action, $viewDatas['cnt'], $viewDatas, $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;
}
function getRemapPage_MapurlHelper(array $viewDatas): string
{
    $urls = [];
    foreach ($viewDatas['entitys'] as $viewDatas['entity']) {
        //한글을 포함하고 있는지 체크 HTTP 나 HTTPS 와 도메인 분리해서 한글도메인을 Punycode로 변환
        if (preg_match("/[\xE0-\xFF][\x80-\xFF][\x80-\xFF]/", $viewDatas['entity']->oldurl)) {
            preg_match("/^(https?:\/\/)(.*)/", $viewDatas['entity']->oldurl, $matches);
            $oldurl = $matches[1] . idn_to_ascii($matches[2]);
        } else {
            $oldurl = trim($viewDatas['entity']->oldurl);
        }
        $urls[] = sprintf(
            "case '%s': window.location.href='%s'; break;",
            $oldurl,
            trim($viewDatas['entity']->newurl)
        );
    }
    return sprintf("
    switch (window.location.origin) {
        %s
        default: 
            alert(window.location.origin + ' 지정되지 않은 URL입니다'); 
            history.go(-1); 
            break; 
        }     
    ", implode("\n", $urls));
}
