<?php

namespace App\Helpers;

use App\Models\MapurlModel;

class MapurlHelper 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 MapurlModel::TITLE:
                $form = form_input($field, $value, ["placeholder" => "예)http://old.example.com", ...$extras]);
                break;
            case 'newurl':
                $form = form_input($field, $value, ["placeholder" => "예)http://new.example.com", ...$extras]);
                break;
            default:
                $form = parent::getFieldForm($field, $value, $viewDatas, $extras);
                break;
        }
        return $form;
    } //
    public function getRemapPage(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));
    }
}
