<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">
  <?php /* success·error 플래시는 레이아웃(embed/portal)에서 한 번만 표시 — 중복 방지. (검증 errors 목록만 여기서 표시) */ ?>
  <?php $flashErrors = session()->getFlashdata('errors'); ?>
  <?php if (is_array($flashErrors) && $flashErrors !== []): ?>
    <div class="mb-3 border border-red-300 bg-red-50 text-red-700 px-3 py-2 rounded-sm text-sm">
      <ul class="list-disc list-inside">
        <?php foreach ($flashErrors as $err): ?>
          <li><?= esc((string) $err) ?></li>
        <?php endforeach; ?>
      </ul>
    </div>
  <?php endif; ?>
  <form action="<?= base_url('bag/shop-order/store') ?>" method="POST" class="space-y-4" id="phone-order-form">
    <?= csrf_field() ?>
    <input type="hidden" name="return_to" value="bag/order/phone"/>

    <input type="hidden" name="so_delivery_date" value="<?= esc(date('Y-m-d', strtotime('+1 day'))) ?>"/>

    <div class="grid grid-cols-1 xl:grid-cols-3 gap-4 items-start">
      <!-- 좌측(좁게): 판매소 선택 → 접수정보 → 지정판매소 정보(+결제/가상계좌) -->
      <div id="phone-left-col" class="xl:col-span-1 space-y-3">
        <div>
          <label class="block text-sm font-bold text-gray-700 mb-1">판매소 검색</label>
          <div class="relative">
            <input id="shop-search" class="border border-gray-300 rounded px-3 py-1.5 text-sm w-full" type="text" autocomplete="off" placeholder="코드/사업자번호/대표자명/상호/전화/주소"/>
            <div id="shop-search-suggest" class="hidden absolute left-0 top-full mt-1 w-[28rem] max-w-[90vw] max-h-72 overflow-auto border border-gray-300 rounded-lg bg-white shadow-lg z-30"></div>
          </div>
        </div>

        <div>
          <label class="block text-sm font-bold text-gray-700 mb-1">판매소 선택 <span class="text-red-500">*</span></label>
          <select id="shop-select" class="border border-gray-300 rounded px-3 py-1.5 text-sm w-full" name="so_ds_idx" required>
            <option value="">선택</option>
            <?php foreach ($shops as $shop): ?>
              <option
                value="<?= esc($shop->ds_idx) ?>"
                data-shop-no="<?= esc((string) ($shop->ds_shop_no ?? '')) ?>"
                data-biz-no="<?= esc((string) ($shop->ds_biz_no ?? '')) ?>"
                data-name="<?= esc((string) ($shop->ds_name ?? '')) ?>"
                data-rep-name="<?= esc((string) ($shop->ds_rep_name ?? '')) ?>"
                data-tel="<?= esc((string) ($shop->ds_tel ?? '')) ?>"
                data-rep-phone="<?= esc((string) ($shop->ds_rep_phone ?? '')) ?>"
                data-address="<?= esc(trim((string) ($shop->ds_addr ?? '') . ' ' . (string) ($shop->ds_addr_detail ?? ''))) ?>"
                data-va-bank="<?= esc((string) ($shop->ds_va_bank ?? '')) ?>"
                data-va-account="<?= esc((string) ($shop->ds_va_account ?? '')) ?>"
              >
                <?= esc(($shop->ds_shop_no ? '[' . $shop->ds_shop_no . '] ' : '') . $shop->ds_name) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="border border-gray-300 rounded-lg p-2 bg-gray-50">
          <div class="text-sm font-bold text-gray-700 mb-2">접수 정보</div>
          <table class="w-full text-sm">
            <tr><th class="text-left w-28 py-1">접수번호</th><td class="py-1 text-gray-800 font-semibold"><?= esc((string) ($receiptNo ?? 1)) ?></td></tr>
            <tr><th class="text-left py-1">접수일</th><td class="py-1 text-gray-700"><?= esc(date('Y-m-d')) ?></td></tr>
            <tr><th class="text-left py-1">배달일</th><td class="py-1 text-gray-700"><?= esc(date('Y-m-d', strtotime('+1 day'))) ?> (자동)</td></tr>
            <tr><th class="text-left py-1">담당자</th><td class="py-1 text-gray-700"><?= esc((string) (session()->get('mb_name') ?? '담당자')) ?></td></tr>
          </table>
        </div>

        <div class="border border-gray-300 rounded-lg p-2 bg-gray-50">
          <div class="text-sm font-bold text-gray-700 mb-2">지정판매소 정보</div>
          <table class="w-full text-sm">
            <tr><th class="text-left w-28 py-1">코드</th><td id="shop-info-code" class="py-1 text-gray-700">-</td></tr>
            <tr><th class="text-left py-1">사업자번호</th><td id="shop-info-biz" class="py-1 text-gray-700">-</td></tr>
            <tr><th class="text-left py-1">대표자명</th><td id="shop-info-rep" class="py-1 text-gray-700">-</td></tr>
            <tr><th class="text-left py-1">상호명</th><td id="shop-info-name" class="py-1 text-gray-700">-</td></tr>
            <tr><th class="text-left py-1">전화번호</th><td id="shop-info-tel" class="py-1 text-gray-700">-</td></tr>
            <tr><th class="text-left py-1">주소</th><td id="shop-info-addr" class="py-1 text-gray-700">-</td></tr>
          </table>
          <div class="mt-3 pt-3 border-t border-gray-200">
            <div class="text-sm font-bold text-gray-700 mb-2">결제/가상계좌</div>
            <div class="flex flex-wrap items-center gap-2 mb-2">
              <label class="block text-sm font-bold text-gray-700 w-24">결제구분 <span class="text-red-500">*</span></label>
              <select id="payment-type" class="border border-gray-300 rounded px-3 py-1.5 text-sm w-40" name="so_payment_type" required>
                <option value="">선택</option>
                <option value="이체">이체</option>
                <option value="가상계좌" selected>가상계좌</option>
              </select>
              <span id="payment-guide" class="text-xs text-gray-500"></span>
            </div>
            <div class="text-sm">
              <span class="font-semibold text-gray-700">가상계좌:</span>
              <span id="shop-info-va" class="text-gray-700">-</span>
            </div>
          </div>
        </div>
      </div><!-- /좌측 컬럼 -->

<?php
// 일괄표: 봉투코드를 카테고리(일반용·재사용·음식물 스티커·대형폐기물 스티커)로 묶어
// 봉투류는 리터 오름차순, 폐기물 스티커는 금액 오름차순으로 정렬한다.
$catOf = static function (string $name): ?array {
    if (mb_strpos($name, '일반용') === 0)        { return [1, '일반용', 'liter']; }
    if (mb_strpos($name, '재사용') === 0)        { return [2, '재사용', 'liter']; }
    if (mb_strpos($name, '음식물 스티커') === 0) { return [3, '음식물 스티커', 'liter']; }
    if (mb_strpos($name, '폐기물 스티커') === 0) { return [4, '대형폐기물 스티커', 'amount']; }
    return null;
};
$orderGroups = [];
foreach (($bagCodes ?? []) as $cd) {
    $name = (string) ($cd->cd_name ?? '');
    $cat  = $catOf($name);
    if ($cat === null) { continue; }
    $code  = (string) $cd->cd_code;
    $price = $priceMap[$code] ?? null;
    $unit  = $unitMap[$code] ?? null;
    if ($cat[2] === 'amount') {
        preg_match('/([\d,]+)\s*원/u', $name, $m);
        $sortVal = (int) str_replace(',', '', $m[1] ?? '0');
    } else {
        preg_match('/(\d+)\s*[lL]/u', $name, $m);
        $sortVal = (int) ($m[1] ?? 0);
    }
    $orderGroups[$cat[0]]['label']  = $cat[1];
    $orderGroups[$cat[0]]['rows'][] = [
        'code'  => $code,
        'name'  => $name,
        'price' => (int) ($price->bp_consumer ?? 0),
        'box'   => (int) ($unit->pu_total_per_box ?? 0),
        'pack'  => (int) ($unit->pu_pack_per_sheet ?? 0),
        'sort'  => $sortVal,
    ];
}
ksort($orderGroups);
foreach ($orderGroups as &$g) {
    usort($g['rows'], static fn ($a, $b) => $a['sort'] <=> $b['sort']);
}
unset($g);
?>
      <!-- 우측(넓게): 전화 주문접수표(일괄) — 최상단부터, 좌측 컬럼 높이에 맞춤 -->
      <div id="phone-right-col" class="xl:col-span-2 flex flex-col">
        <label class="block text-sm font-bold text-gray-700 mb-2">전화 주문접수표 (일괄)</label>
      <style>
        /* 그룹 헤더(rowspan/colspan) 경계선이 단가까지 이어지는 현상 방지 — 헤더 맨 아래 한 줄만 */
        /* table-layout: fixed — 판매수량 입력 시 숫자 자릿수 변화로 열 너비가 흔들리는 현상 방지 */
        table.phone-batch-table { border-collapse: separate; border-spacing: 0; table-layout: fixed; }
        table.phone-batch-table thead th { border-bottom: 0; }
        table.phone-batch-table thead tr:last-child th { border-bottom: 1px solid #e5e7eb; }   /* 수량/금액 등 하위 헤더 */
        table.phone-batch-table thead tr:first-child th[rowspan] { border-bottom: 1px solid #e5e7eb; } /* 구분·봉투종류·단가 */
        table.phone-batch-table tbody td { border-bottom: 1px solid #f1f3f5; }
        /* 행·열 간격 축소 — 한 화면에 전체 품목이 보이도록 (피드백 #13) */
        table.phone-batch-table th, table.phone-batch-table td { padding: 0.2rem 0.35rem; }
        table.phone-batch-table .item-qty-input { padding-top: 0.1rem; padding-bottom: 0.1rem; }
        /* 스크롤 시 2행 그룹 헤더 + 합계 행 고정. --hdr-row1-h는 JS가 첫 헤더행 높이로 설정.
           표 높이는 JS가 좌측 컬럼 높이에 맞춰 우측 컬럼에 지정하고, 래퍼(flex-1)가 그 높이를 채운다. */
        table.phone-batch-table thead th { position: sticky; z-index: 3; background: #f3f4f6; }
        table.phone-batch-table thead tr:first-child th { top: 0; }
        table.phone-batch-table thead tr:last-child th { top: var(--hdr-row1-h, 1.6rem); }
        table.phone-batch-table tfoot td { position: sticky; bottom: 0; z-index: 2; background: #f9fafb; box-shadow: inset 0 1px 0 #e5e7eb; }
      </style>
      <div class="phone-batch-wrap flex-1 min-h-0 border border-gray-300 rounded-lg overflow-auto">
        <table class="w-full data-table text-sm phone-batch-table">
          <colgroup>
            <col style="width:8rem"/>     <!-- 구분: 최장 라벨("대형폐기물 스티커") 기준 고정폭 -->
            <col style="width:11rem"/>    <!-- 봉투종류: 최장 품목명(예: "폐기물 스티커 10,000원") 기준 고정폭.
                                                width:auto는 화면이 좁거나 텍스트 확대 시 0으로 찌부러질 수 있어 사용 안 함. -->
            <col style="width:4rem"/>     <!-- Pack 수량 -->
            <col style="width:5.5rem"/>   <!-- Pack 금액 -->
            <col style="width:4rem"/>     <!-- Box 수량 -->
            <col style="width:5.5rem"/>   <!-- Box 금액 -->
            <col style="width:5rem"/>     <!-- 단가 -->
            <col style="width:6rem"/>     <!-- 판매수량 -->
            <col style="width:6rem"/>     <!-- 금액 -->
            <col style="width:3rem"/>     <!-- B -->
            <col style="width:3rem"/>     <!-- P -->
            <col style="width:3rem"/>     <!-- E -->
          </colgroup>
          <thead>
            <tr>
              <th class="text-center" rowspan="2">구분</th>
              <th rowspan="2">봉투종류</th>
              <th class="text-center" colspan="2">Pack</th>
              <th class="text-center" colspan="2">Box</th>
              <th class="text-right" rowspan="2">단가</th>
              <th class="text-center" colspan="2">주문내용</th>
              <th class="text-center" colspan="3">포장</th>
            </tr>
            <tr>
              <th class="text-right">수량</th>
              <th class="text-right">금액</th>
              <th class="text-right">수량</th>
              <th class="text-right">금액</th>
              <th class="text-right">판매수량</th>
              <th class="text-right">금액</th>
              <th class="text-center">B</th>
              <th class="text-center">P</th>
              <th class="text-center">E</th>
            </tr>
          </thead>
          <tbody id="order-rows">
            <?php if (empty($orderGroups)): ?>
              <tr><td colspan="12" class="text-center text-gray-400 py-6">등록된 봉투 품목이 없습니다.</td></tr>
            <?php else: ?>
              <?php foreach ($orderGroups as $g): ?>
                <?php $rc = count($g['rows']); $firstRow = true; ?>
                <?php foreach ($g['rows'] as $r): ?>
                  <?php $boxPrice = $r['box'] * $r['price']; $packPrice = $r['pack'] * $r['price']; ?>
                  <tr class="order-row" data-unit-price="<?= esc((string) $r['price'], 'attr') ?>" data-box-sheets="<?= esc((string) $r['box'], 'attr') ?>" data-pack-sheets="<?= esc((string) $r['pack'], 'attr') ?>">
                    <?php if ($firstRow): ?>
                    <td class="text-center align-top font-semibold text-gray-700" rowspan="<?= (int) $rc ?>"><?= esc($g['label']) ?></td>
                    <?php endif; ?>
                    <td class="text-left pl-2"><?= esc($r['name']) ?><input type="hidden" name="item_bag_code[]" value="<?= esc($r['code'], 'attr') ?>"/></td>
                    <td class="text-right px-2"><?= number_format($r['pack']) ?></td>
                    <td class="text-right px-2"><?= number_format($packPrice) ?></td>
                    <td class="text-right px-2"><?= number_format($r['box']) ?></td>
                    <td class="text-right px-2"><?= number_format($boxPrice) ?></td>
                    <td class="text-right px-2"><?= number_format($r['price']) ?></td>
                    <td><input class="border border-gray-300 rounded px-2 py-1 text-sm w-full text-right item-qty-input" name="item_qty[]" type="number" min="0" value="0"/></td>
                    <td class="text-right px-2 item-amount-cell">0</td>
                    <td class="text-center item-box-cell">0</td>
                    <td class="text-center item-pack-cell">0</td>
                    <td class="text-center item-sheet-cell">0</td>
                  </tr>
                  <?php $firstRow = false; ?>
                <?php endforeach; ?>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
          <tfoot>
            <tr class="font-semibold bg-gray-50">
              <td colspan="7" class="text-right px-2 py-1">합계</td>
              <td class="text-right px-2 py-1" id="sum-qty">0</td>
              <td class="text-right px-2 py-1" id="sum-amount">0</td>
              <td class="text-center px-2 py-1" id="sum-box">0</td>
              <td class="text-center px-2 py-1" id="sum-pack">0</td>
              <td class="text-center px-2 py-1" id="sum-sheet">0</td>
            </tr>
          </tfoot>
        </table>
      </div>
      </div><!-- /우측 컬럼 -->
    </div><!-- /2열 그리드 -->

    <div class="flex gap-2 pt-2">
      <button type="submit" class="bg-btn-search text-white px-6 py-1.5 rounded-sm text-sm shadow hover:opacity-90 transition">저장</button>
      <a href="<?= base_url('bag/sales') ?>" class="bg-gray-200 text-gray-700 px-6 py-1.5 rounded-sm text-sm hover:bg-gray-300 transition">취소</a>
    </div>
  </form>
</div>


<script>
(() => {
  const shopSearch = document.getElementById('shop-search');
  const shopSelect = document.getElementById('shop-select');
  const shopSuggest = document.getElementById('shop-search-suggest');
  const paymentType = document.getElementById('payment-type');
  const paymentGuide = document.getElementById('payment-guide');
  const orderRows = document.getElementById('order-rows');
  const form = document.getElementById('phone-order-form');

  const nf = (n) => new Intl.NumberFormat('ko-KR').format(n || 0);

  function updateShopInfo() {
    const opt = shopSelect.options[shopSelect.selectedIndex];
    const bank = opt?.dataset?.vaBank || '';
    const account = opt?.dataset?.vaAccount || '';
    const va = bank || account ? [bank, account].filter(Boolean).join(' ') : '-';

    document.getElementById('shop-info-code').textContent = opt?.dataset?.shopNo || '-';
    document.getElementById('shop-info-biz').textContent = opt?.dataset?.bizNo || '-';
    document.getElementById('shop-info-rep').textContent = opt?.dataset?.repName || '-';
    document.getElementById('shop-info-name').textContent = opt?.dataset?.name || '-';
    document.getElementById('shop-info-tel').textContent = opt?.dataset?.tel || opt?.dataset?.repPhone || '-';
    document.getElementById('shop-info-addr').textContent = opt?.dataset?.address || '-';
    document.getElementById('shop-info-va').textContent = va;
    paymentGuide.textContent = paymentType.value === '가상계좌' ? ('안내 계좌: ' + va) : '';
  }

  function shopMergedText(opt) {
    return [
      opt.dataset.shopNo || '',
      opt.dataset.bizNo || '',
      opt.dataset.repName || '',
      opt.dataset.name || '',
      opt.dataset.tel || '',
      opt.dataset.address || '',
    ].filter(Boolean).join(' ');
  }

  function matchShopByKeyword(keyword) {
    const q = (keyword || '').trim().toLowerCase();
    if (!q) return;
    for (let i = 0; i < shopSelect.options.length; i++) {
      const opt = shopSelect.options[i];
      if (!opt.value) continue;
      const merged = (shopMergedText(opt) + ' ' + (opt.text || '')).toLowerCase();
      if (merged.includes(q)) {
        shopSelect.selectedIndex = i;
        updateShopInfo();
        return;
      }
    }
  }

  function hideSuggest() {
    if (!shopSuggest) return;
    shopSuggest.classList.add('hidden');
    shopSuggest.innerHTML = '';
  }

  function renderSuggest(query) {
    if (!shopSuggest || !shopSelect) return;
    const q = (query || '').trim().toLowerCase();
    const matched = [];
    for (let i = 0; i < shopSelect.options.length; i++) {
      const opt = shopSelect.options[i];
      if (!opt.value) continue;
      const merged = shopMergedText(opt);
      if (!q || merged.toLowerCase().includes(q)) {
        matched.push({ index: i, label: merged });
      }
      if (matched.length >= 50) break;
    }
    if (matched.length === 0) {
      hideSuggest();
      return;
    }
    shopSuggest.innerHTML = matched.map((m) => `
      <button type="button" class="shop-suggest-item w-full text-left px-2 py-1.5 hover:bg-blue-50 text-xs border-b border-gray-100 whitespace-normal break-all" data-index="${m.index}">${m.label}</button>
    `).join('');
    shopSuggest.classList.remove('hidden');
  }

  function calcRow(row) {
    const qtyInput = row.querySelector('.item-qty-input');
    const qty = parseInt(qtyInput.value || '0', 10) || 0;
    const unitPrice = parseInt(row.dataset.unitPrice || '0', 10) || 0;
    const boxSheets = parseInt(row.dataset.boxSheets || '0', 10) || 0;
    const packSheets = parseInt(row.dataset.packSheets || '0', 10) || 0;

    let box = 0;
    let pack = 0;
    let sheet = qty;
    if (boxSheets > 0) {
      box = Math.floor(qty / boxSheets);
      const remain = qty % boxSheets;
      if (packSheets > 0) {
        pack = Math.floor(remain / packSheets);
        sheet = remain % packSheets;
      } else {
        sheet = remain;
      }
    } else if (packSheets > 0) {
      pack = Math.floor(qty / packSheets);
      sheet = qty % packSheets;
    }

    const amount = unitPrice * qty;
    row.querySelector('.item-amount-cell').textContent = nf(amount);
    row.querySelector('.item-box-cell').textContent = box ? nf(box) : '';
    row.querySelector('.item-pack-cell').textContent = pack ? nf(pack) : '';
    row.querySelector('.item-sheet-cell').textContent = sheet ? nf(sheet) : '';

    return { qty, amount, box, pack, sheet };
  }

  function recalcAllRows() {
    let sumQty = 0, sumAmount = 0, sumBox = 0, sumPack = 0, sumSheet = 0;
    document.querySelectorAll('.order-row').forEach((row) => {
      const r = calcRow(row);
      sumQty += r.qty;
      sumAmount += r.amount;
      sumBox += r.box;
      sumPack += r.pack;
      sumSheet += r.sheet;
    });
    document.getElementById('sum-qty').textContent = nf(sumQty);
    document.getElementById('sum-amount').textContent = nf(sumAmount);
    document.getElementById('sum-box').textContent = nf(sumBox);
    document.getElementById('sum-pack').textContent = nf(sumPack);
    document.getElementById('sum-sheet').textContent = nf(sumSheet);
  }

  function clearSearchInputOnly() {
    if (shopSearch) shopSearch.value = '';
  }

  // 판매소 검색 input을 다시 누르면(또는 포커스를 다시 받으면) 검색 input 텍스트만 비운다.
  // 기존에 선택된 판매소 정보(셀렉트, 지정판매소 정보, 가상계좌 등)는 그대로 유지한다.
  shopSearch?.addEventListener('focus', () => {
    if (shopSelect && shopSelect.value) clearSearchInputOnly();
    renderSuggest('');
  });
  shopSearch?.addEventListener('mousedown', () => {
    if (shopSelect && shopSelect.value) clearSearchInputOnly();
  });
  shopSearch?.addEventListener('click', () => renderSuggest(shopSearch.value || ''));
  shopSearch?.addEventListener('input', (e) => renderSuggest(e.target.value || ''));

  shopSuggest?.addEventListener('mousedown', (e) => {
    const btn = e.target.closest('.shop-suggest-item');
    if (!btn) return;
    e.preventDefault();
    const idx = Number(btn.dataset.index || -1);
    if (!Number.isInteger(idx) || idx < 0 || idx >= shopSelect.options.length) return;
    shopSelect.selectedIndex = idx;
    const opt = shopSelect.options[idx];
    shopSearch.value = shopMergedText(opt);
    updateShopInfo();
    hideSuggest();
  });

  document.addEventListener('click', (e) => {
    if (!shopSuggest || !shopSearch) return;
    if (e.target === shopSearch || shopSuggest.contains(e.target)) return;
    hideSuggest();
  });

  shopSearch?.addEventListener('change', (e) => matchShopByKeyword(e.target.value));
  shopSearch?.addEventListener('blur', () => {
    // 자동완성 클릭이 우선되도록 약간 지연.
    setTimeout(() => {
      matchShopByKeyword(shopSearch.value || '');
    }, 150);
  });
  shopSelect?.addEventListener('change', updateShopInfo);
  paymentType?.addEventListener('change', updateShopInfo);

  orderRows?.addEventListener('input', function (e) {
    if (e.target.closest('.item-qty-input')) {
      recalcAllRows();
    }
  });

  // 판매수량 입력 중 엔터키 → 다음 봉투 종류의 수량 입력칸으로 이동
  orderRows?.addEventListener('keydown', function (e) {
    if (e.key !== 'Enter' || !e.target.classList.contains('item-qty-input')) return;
    e.preventDefault();
    const inputs = Array.from(orderRows.querySelectorAll('.item-qty-input'));
    const next = inputs[inputs.indexOf(e.target) + 1];
    if (next) { next.focus(); next.select(); }
  });

  form?.addEventListener('submit', function (e) {
    let hasItem = false;
    document.querySelectorAll('.order-row').forEach((row) => {
      const qty = parseInt(row.querySelector('.item-qty-input').value || '0', 10) || 0;
      if (qty > 0) hasItem = true;
    });
    if (!hasItem) {
      e.preventDefault();
      alert('주문 수량을 1개 이상 입력해 주세요.');
    }
  });

  updateShopInfo();
  recalcAllRows();

  // 스크롤 시 두 번째 헤더행이 첫 번째 헤더행 바로 아래에 붙도록 오프셋 계산.
  // offsetHeight는 화면 zoom(텍스트 크기)과 무관한 레이아웃 px라 배율이 바뀌어도 정확하다.
  (function () {
    const tbl = document.querySelector('table.phone-batch-table');
    if (!tbl) return;
    const r1 = tbl.querySelector('thead tr:first-child');
    function setHeaderOffset() {
      if (r1) tbl.style.setProperty('--hdr-row1-h', r1.offsetHeight + 'px');
    }
    setHeaderOffset();
    window.addEventListener('resize', setHeaderOffset);
    window.addEventListener('storage', function (e) { if (e.key === 'jrj_font_scale') setHeaderOffset(); });
  })();

  // 전화 주문접수표(우측 컬럼) 높이를 좌측 컬럼(지정판매소 정보 하단까지)에 맞춘다.
  // offsetHeight/offsetTop은 zoom과 무관한 레이아웃 px라 배율이 바뀌어도 정확하다.
  (function () {
    const leftCol = document.getElementById('phone-left-col');
    const rightCol = document.getElementById('phone-right-col');
    if (!leftCol || !rightCol) return;
    function syncTableHeight() {
      // 2열(나란히)일 때만 높이 맞춤. 1열로 쌓이면 자동 높이로 둔다.
      const sideBySide = Math.abs(leftCol.offsetTop - rightCol.offsetTop) < 4;
      rightCol.style.height = sideBySide ? (leftCol.offsetHeight + 'px') : '';
    }
    syncTableHeight();
    window.addEventListener('resize', syncTableHeight);
    window.addEventListener('storage', function (e) { if (e.key === 'jrj_font_scale') syncTableHeight(); });
    if ('ResizeObserver' in window) { new ResizeObserver(syncTableHeight).observe(leftCol); }
  })();
})();
</script>

<?= view('bag/_dev_all_sales_panel') ?>
