<?= $this->extend(LAYOUTS[$viewDatas['layout']]['path']) ?>
<?= $this->section('content') ?>
<?php if ($error = session('error')): echo $viewDatas['helper']->alert($error) ?><?php endif ?>
<div id="container" class="content">
  <div class="form_top"><?= $this->include("templates/{$viewDatas['layout']}/form_content_top"); ?></div>
  <?= form_open(current_url(), $viewDatas['forms']['attributes'], $viewDatas['forms']['hiddens']) ?>
  <div class="action_form">
    <table class="table table-bordered">
      <?php foreach ($viewDatas['control']['form_fields'] as $field): ?>
        <tr>
          <th nowrap class="text-end"><?= $viewDatas['helper']->getFieldLabel($field, lang("{$viewDatas['class_path']}.label.{$field}"), $viewDatas) ?></th>
          <td nowrap class="text-start">
            <?= $viewDatas['helper']->getFieldForm($field, old($field) ?? ($viewDatas['control']['filter_values'][$field] ?? null), $viewDatas) ?>
            <span><?= validation_show_error($field); ?></span>
          </td>
        </tr>
      <?php endforeach; ?>
    </table>
    <div class="text-center"><?= form_submit('', '입력', array("class" => "btn btn-outline btn-primary")); ?></div>
    <?= form_close(); ?>
  </div>
  <div class="form_bottom"><?= $this->include("templates/{$viewDatas['layout']}/form_content_bottom"); ?></div>
</div>
<script>
  document.addEventListener('DOMContentLoaded', function() {
    if (document.querySelector('#domain')) {
      const domainSelecor = document.querySelector('#domain')
      const errorBox = document.getElementById('domain-errors');

      const tagify = new Tagify(domainSelecor, {
        enforceWhitelist: false,
        whitelist: [],
        duplicates: false,
        delimiters: ", ",
        pattern: /[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z0-9\&\.\/\?\:@\-_=#])*/ // 도메인주소 패턴
      });
      // ✅ 패턴이 맞지 않을 때
      tagify.on('invalid', e => {
        const value = e.detail.data.value;
        errorBox.innerText = `"${value}" 은(는) 유효한 도메인 형식이 아닙니다. 예: domain.co.kr`;
      });
      // ✅ 서버에서 존재 여부 확인
      tagify.on('add', async e => {
        const domain = e.detail.data.value;
        const res = await fetch('/admin/equipment/part/domain/confirm', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            domain
          })
        });
        const results = await res.json();
        // 이미 존재하는 도메인인지 확인 결과처리
        if (exists = results.exists === true || results.exists === 'true') {
          tagify.removeTag(domain);
          errorBox.innerText = results.message;
        }
      });
    }
  });
</script>
<?= $this->endSection() ?>