<section class="border-b border-gray-300 p-2 shrink-0 bg-control-panel">
  <span class="text-sm font-bold text-gray-700">지정판매소 등록</span>
</section>
<div class="border border-gray-300 rounded-lg p-4 mt-2 bg-white max-w-3xl">
  <form id="designated-shop-create-form" action="<?= mgmt_url('designated-shops/store') ?>" method="POST" class="space-y-4">
    <?= csrf_field() ?>

    <?php if (! empty($localGovs)): ?>
    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">지자체 <span class="text-red-500">*</span></label>
      <select class="border border-gray-300 rounded px-3 py-1.5 text-sm w-60" name="ds_lg_idx" required>
        <option value="">선택</option>
        <?php foreach ($localGovs as $lg): ?>
        <option value="<?= esc($lg->lg_idx) ?>" <?= (string) old('ds_lg_idx') === (string) $lg->lg_idx ? 'selected' : '' ?>>
          <?= esc($lg->lg_name) ?> (<?= esc($lg->lg_code) ?>)
        </option>
        <?php endforeach; ?>
      </select>
    </div>
    <?php elseif (! empty($currentLg)): ?>
    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">지자체</label>
      <div class="text-sm">
        <span class="font-semibold"><?= esc($currentLg->lg_name) ?></span>
        <span class="text-gray-500 ml-2">(<?= esc($currentLg->lg_code) ?>)</span>
        <span class="text-gray-500 ml-1"><?= esc(trim((string) ($currentLg->lg_sido ?? '') . ' ' . (string) ($currentLg->lg_gugun ?? ''))) ?></span>
      </div>
      <input type="hidden" name="ds_lg_idx" value="<?= esc($currentLg->lg_idx) ?>"/>
    </div>
    <?php endif; ?>

    <input type="hidden" name="addr_search_sido" id="addr_search_sido" value="<?= esc((string) old('addr_search_sido', '')) ?>"/>
    <input type="hidden" name="addr_search_sigungu" id="addr_search_sigungu" value="<?= esc((string) old('addr_search_sigungu', '')) ?>"/>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">판매소번호</label>
      <div class="text-sm text-gray-600">등록 시 자동 부여 (주소 기준 기본코드 B·C·D 조합 + 일련번호 3자리)</div>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">상호명 <span class="text-red-500">*</span></label>
      <input class="border border-gray-300 rounded px-3 py-1.5 text-sm w-72" name="ds_name" type="text" value="<?= esc(old('ds_name')) ?>" required/>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">사업자번호 <span class="text-red-500">*</span></label>
      <input class="border border-gray-300 rounded px-3 py-1.5 text-sm w-48" name="ds_biz_no" type="text" value="<?= esc(old('ds_biz_no')) ?>" required/>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">대표자명 <span class="text-red-500">*</span></label>
      <input class="border border-gray-300 rounded px-3 py-1.5 text-sm w-48" name="ds_rep_name" type="text" value="<?= esc(old('ds_rep_name')) ?>" required/>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">업태</label>
      <input class="border border-gray-300 rounded px-3 py-1.5 text-sm w-48" name="ds_biz_type" type="text" value="<?= esc(old('ds_biz_type')) ?>"/>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">업종</label>
      <input class="border border-gray-300 rounded px-3 py-1.5 text-sm w-48" name="ds_biz_kind" type="text" value="<?= esc(old('ds_biz_kind')) ?>"/>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">가상계좌(은행)</label>
      <input class="border border-gray-300 rounded px-3 py-1.5 text-sm w-48" name="ds_va_bank" type="text" value="<?= esc(old('ds_va_bank')) ?>" placeholder="예: 농협"/>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">계좌번호</label>
      <input class="border border-gray-300 rounded px-3 py-1.5 text-sm w-60" name="ds_va_account" type="text" value="<?= esc(old('ds_va_account')) ?>"/>
    </div>

    <div class="flex flex-wrap items-start gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28 pt-1.5">주소</label>
      <p class="text-xs text-gray-600 max-w-lg leading-relaxed">우편번호 옆 <strong>주소 검색</strong>으로만 지정합니다(직접 입력 불가). <strong>지도</strong>는 카카오맵에서 현재 입력된 주소를 검색해 엽니다. 관할이 아니면 검색 직후 안내 후 반영되지 않습니다. 동·호 등은 아래 <strong>상세주소</strong>에 입력하세요.</p>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">우편번호</label>
      <input class="border border-gray-300 rounded px-3 py-1.5 text-sm w-32 bg-gray-100 text-gray-800 cursor-not-allowed" name="ds_zip" id="ds_zip" type="text" value="<?= esc(old('ds_zip')) ?>" maxlength="10" autocomplete="postal-code" readonly tabindex="-1"/>
      <button type="button" id="btn-ds-kakao-postcode" class="no-print border border-btn-print-border text-gray-700 px-3 py-1.5 rounded-sm text-sm hover:bg-gray-50 transition shrink-0">주소 검색</button>
      <?= view('components/kakao_map_link_button', ['buttonId' => 'btn-ds-kakao-map-create']) ?>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">도로명주소</label>
      <input class="border border-gray-300 rounded px-3 py-1.5 text-sm w-96 max-w-full bg-gray-100 text-gray-800 cursor-not-allowed" name="ds_addr" id="ds_addr" type="text" value="<?= esc(old('ds_addr')) ?>" readonly tabindex="-1"/>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">지번주소</label>
      <input class="border border-gray-300 rounded px-3 py-1.5 text-sm w-96 max-w-full bg-gray-100 text-gray-800 cursor-not-allowed" name="ds_addr_jibun" id="ds_addr_jibun" type="text" value="<?= esc(old('ds_addr_jibun')) ?>" readonly tabindex="-1"/>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">상세주소</label>
      <input class="border border-gray-300 rounded px-3 py-1.5 text-sm w-96 max-w-full" name="ds_addr_detail" id="ds_addr_detail" type="text" value="<?= esc(old('ds_addr_detail')) ?>" maxlength="200" placeholder="동·호수·층 등"/>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">일반전화</label>
      <input class="border border-gray-300 rounded px-3 py-1.5 text-sm w-48" name="ds_tel" type="text" value="<?= esc(old('ds_tel')) ?>"/>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">대표 휴대전화</label>
      <input class="border border-gray-300 rounded px-3 py-1.5 text-sm w-48" name="ds_rep_phone" type="text" value="<?= esc(old('ds_rep_phone')) ?>"/>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">이메일</label>
      <input class="border border-gray-300 rounded px-3 py-1.5 text-sm w-60" name="ds_email" type="email" value="<?= esc(old('ds_email')) ?>"/>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">구·군(동코드)</label>
      <input type="text" id="ds_dong_display" class="border border-gray-300 rounded px-3 py-1.5 text-sm w-60 bg-gray-100 text-gray-800 cursor-not-allowed" value="" readonly tabindex="-1" placeholder="주소 검색 시 자동 표시"/>
      <span id="ds_dong_hint" class="text-xs text-gray-500">주소를 검색하면 해당 동코드가 표시됩니다.</span>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">구역</label>
      <input class="border border-gray-300 rounded px-3 py-1.5 text-sm w-72" name="ds_zone_code" type="text" value="<?= esc(old('ds_zone_code')) ?>"/>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">종사업장번호</label>
      <input class="border border-gray-300 rounded px-3 py-1.5 text-sm w-48" name="ds_branch_no" type="text" value="<?= esc(old('ds_branch_no')) ?>"/>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">지정일자</label>
      <input class="border border-gray-300 rounded px-3 py-1.5 text-sm w-40" name="ds_designated_at" type="date" value="<?= esc(old('ds_designated_at')) ?>"/>
    </div>

    <div class="flex flex-wrap items-center gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28">변경일자</label>
      <input class="border border-gray-300 rounded px-3 py-1.5 text-sm w-40" name="ds_state_changed_at" type="date" value="<?= esc(old('ds_state_changed_at')) ?>"/>
    </div>

    <div class="flex flex-wrap items-start gap-2">
      <label class="block text-sm font-bold text-gray-700 w-28 pt-1.5">변경사유</label>
      <textarea class="border border-gray-300 rounded px-3 py-1.5 text-sm w-96 min-h-[4rem]" name="ds_change_reason" rows="3"><?= esc(old('ds_change_reason')) ?></textarea>
    </div>

    <div class="flex gap-2 pt-2">
      <button type="submit" class="bg-btn-search text-white px-4 py-1.5 rounded-sm text-sm shadow hover:opacity-90 transition">등록</button>
      <a href="<?= mgmt_url('designated-shops') ?>" class="bg-white text-black border border-btn-print-border px-4 py-1.5 rounded-sm text-sm shadow hover:bg-gray-50 transition">목록</a>
    </div>
  </form>
</div>

<?= view('components/kakao_map_modal', ['kakaoJavascriptKey' => $kakaoJavascriptKey ?? '']) ?>

<?= view('components/kakao_address_search', [
    'buttonId'         => 'btn-ds-kakao-postcode',
    'zipName'          => 'ds_zip',
    'roadName'         => 'ds_addr',
    'jibunName'        => 'ds_addr_jibun',
    'sidoFieldName'    => 'addr_search_sido',
    'sigunguFieldName' => 'addr_search_sigungu',
    'tenantScope'      => $addrTenantScope ?? ['lg_sido' => '', 'lg_gugun' => ''],
    'roadBaseOnly'     => true,
    'detailFieldName'  => 'ds_addr_detail',
]) ?>

<script>
(function () {
  var form = document.getElementById('designated-shop-create-form');
  if (!form) return;
  var display = document.getElementById('ds_dong_display');
  var hint = document.getElementById('ds_dong_hint');
  var endpoint = new URL('<?= mgmt_url('designated-shops/resolve-address-codes') ?>', window.location.href).pathname;
  var csrfName = '<?= csrf_token() ?>';

  function setHint(msg, isError) {
    if (!hint) return;
    hint.textContent = msg;
    hint.className = 'text-xs ' + (isError ? 'text-red-600' : 'text-gray-500');
  }

  // 주소 검색 완료 시 서버에서 동코드 조회 → 표시
  form.addEventListener('kakao-address-selected', function () {
    if (display) display.value = '';
    setHint('동코드 조회 중…', false);

    var body = new URLSearchParams();
    body.set('addr_search_sido', (form.querySelector('[name="addr_search_sido"]') || {}).value || '');
    body.set('addr_search_sigungu', (form.querySelector('[name="addr_search_sigungu"]') || {}).value || '');
    body.set('ds_addr', (form.querySelector('[name="ds_addr"]') || {}).value || '');
    body.set('ds_addr_jibun', (form.querySelector('[name="ds_addr_jibun"]') || {}).value || '');
    body.set('ds_zip', (form.querySelector('[name="ds_zip"]') || {}).value || '');
    var csrfEl = form.querySelector('[name="' + csrfName + '"]');
    if (csrfEl) body.set(csrfName, csrfEl.value);

    fetch(endpoint, {
      method: 'POST',
      headers: { 'X-Requested-With': 'XMLHttpRequest' },
      body: body
    })
      .then(function (r) { return r.json(); })
      .then(function (d) {
        if (d && d.ok) {
          if (display) display.value = d.dong_code + (d.dong_name ? ' (' + d.dong_name + ')' : '');
          setHint('등록 시 판매소번호에 이 동코드가 반영됩니다.', false);
        } else {
          setHint((d && d.error) ? d.error : '동코드를 조회하지 못했습니다.', true);
        }
      })
      .catch(function () {
        setHint('동코드 조회 중 오류가 발생했습니다.', true);
      });
  });
})();
</script>

