<?php
$devSoldScans = is_array($devSoldScans ?? null) ? $devSoldScans : [];
?>
<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-3 mt-2 bg-white space-y-3">
  <form id="return-save-form" action="<?= base_url('bag/sale/designated-return/save') ?>" method="POST">
    <?= csrf_field() ?>
    <input type="hidden" name="ds_idx" id="save-ds-idx" value=""/>
    <input type="hidden" name="scans_json" id="save-scans-json" value="[]"/>

    <div class="flex flex-wrap items-end gap-2">
      <div class="relative">
        <label class="block text-xs font-bold text-gray-700 mb-1">판매소 검색</label>
        <input id="shop-search" type="text" class="border border-gray-300 rounded px-2 py-1.5 text-sm w-[36rem] max-w-full" placeholder="코드/상호/대표자/전화/주소"/>
        <div id="shop-search-suggest" class="hidden absolute left-0 top-full mt-1 w-[36rem] max-w-full max-h-56 overflow-auto border border-gray-300 rounded-lg bg-white shadow-lg z-20"></div>
      </div>
      <div>
        <label class="block text-xs font-bold text-gray-700 mb-1">봉투코드 입력</label>
        <input id="barcode-input" type="text" class="border border-gray-300 rounded px-2 py-1.5 text-sm w-80" placeholder="박스/팩/낱장 바코드"/>
      </div>
      <button type="submit" class="bg-btn-search text-white px-4 py-1.5 rounded-sm text-sm shadow hover:opacity-90">반품 저장</button>
    </div>
  </form>

  <div id="scan-message" class="text-sm text-gray-600"></div>

  <div class="grid grid-cols-1 xl:grid-cols-2 gap-3">
    <section class="border border-gray-300 rounded-lg overflow-hidden">
      <div class="px-3 py-2 border-b bg-gray-50 text-sm font-semibold text-gray-700">지정판매소 정보</div>
      <table class="w-full text-sm">
        <tr><th class="text-left px-3 py-1.5 w-28">판매소 코드</th><td id="shop-info-code" class="px-3 py-1.5">-</td></tr>
        <tr><th class="text-left px-3 py-1.5">상호</th><td id="shop-info-name" class="px-3 py-1.5">-</td></tr>
        <tr><th class="text-left px-3 py-1.5">대표자명</th><td id="shop-info-rep" class="px-3 py-1.5">-</td></tr>
        <tr><th class="text-left px-3 py-1.5">대표전화</th><td id="shop-info-tel" class="px-3 py-1.5">-</td></tr>
        <tr><th class="text-left px-3 py-1.5">주소</th><td id="shop-info-addr" class="px-3 py-1.5">-</td></tr>
      </table>
    </section>

    <section class="border border-gray-300 rounded-lg overflow-hidden">
      <div class="px-3 py-2 border-b bg-gray-50 text-sm font-semibold text-gray-700">반품 리스트</div>
      <div class="max-h-64 overflow-auto">
        <table class="w-full data-table text-sm">
          <thead>
            <tr>
              <th class="w-14 text-center">선택</th>
              <th class="text-left">봉투 종류</th>
              <th class="w-20 text-right">수량</th>
              <th class="w-20 text-right">단가</th>
              <th class="w-24 text-right">금액</th>
              <th class="w-16 text-center">제거</th>
            </tr>
          </thead>
          <tbody id="return-list-body">
            <tr><td colspan="6" class="text-center text-gray-400 py-6">판매소를 선택하고 바코드를 스캔해 주세요.</td></tr>
          </tbody>
          <tfoot>
            <tr class="font-semibold bg-gray-50">
              <td colspan="2" 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">-</td>
              <td class="text-right px-2 py-1" id="sum-amount">0</td>
              <td class="px-2 py-1"></td>
            </tr>
          </tfoot>
        </table>
      </div>
    </section>
  </div>

  <section class="border border-gray-300 rounded-lg overflow-hidden">
    <div class="px-3 py-2 border-b bg-gray-50 text-sm font-semibold text-gray-700">반품 봉투 코드</div>
    <div class="max-h-72 overflow-auto">
      <table class="w-full data-table text-sm">
        <thead>
          <tr>
            <th class="text-left">봉투 종류</th>
            <th class="w-36 text-center">봉투 코드</th>
            <th class="w-16 text-right">수량</th>
            <th class="w-20 text-right">금액</th>
          </tr>
        </thead>
        <tbody id="return-code-body">
          <tr><td colspan="4" class="text-center text-gray-400 py-6">품목을 선택해 주세요.</td></tr>
        </tbody>
      </table>
    </div>
  </section>

  <section class="border border-amber-400 bg-amber-50/50 p-3 mt-3 rounded-sm">
    <p class="text-xs text-amber-900 mb-2 leading-relaxed">
      <strong class="text-amber-950">[개발용 임시 표]</strong>
      반품 스캔 테스트를 위해, 현재 지자체에서 <code class="bg-amber-100 px-1 rounded">bag_sale_scan_code</code> 상태가
      <strong>판매(sold)</strong>인 봉투 바코드 일부(최대 200건, 최근 등록순)를 표시합니다.
      운영 화면에는 포함되지 않아야 하므로 <strong>개발이 끝나면 이 블록 전체를 제거</strong>해 주세요.
    </p>
    <div class="max-h-56 overflow-auto border border-amber-300 bg-white">
      <table class="w-full data-table text-xs">
        <thead>
          <tr>
            <th class="text-left">지정판매소</th>
            <th class="w-14 text-center">주문</th>
            <th class="text-left">봉투 종류</th>
            <th class="w-40 text-center">봉투 바코드</th>
            <th class="w-14 text-center">포장</th>
            <th class="w-12 text-right">수량</th>
            <th class="w-16 text-center">상태</th>
            <th class="w-36 text-center">등록일시</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($devSoldScans === []): ?>
            <tr><td colspan="8" class="text-center text-gray-400 py-4">판매(sold) 상태인 스캔 코드가 없습니다.</td></tr>
          <?php else: ?>
            <?php foreach ($devSoldScans as $r): ?>
              <tr>
                <td class="text-left pl-1"><?= esc(trim((string) ($r['ds_name'] ?? '')) !== '' ? (string) $r['ds_name'] : ('판매소#' . (string) ($r['bssc_ds_idx'] ?? '0'))) ?></td>
                <td class="text-center"><?= esc((string) ($r['bssc_so_idx'] ?? '')) ?></td>
                <td class="text-left pl-1"><?= esc((string) ($r['bssc_bag_code'] ?? '')) ?> <?= esc((string) ($r['bssc_bag_name'] ?? '')) ?></td>
                <td class="text-center font-mono"><?= esc((string) ($r['bssc_code'] ?? '')) ?></td>
                <td class="text-center"><?= esc((string) ($r['bssc_unit'] ?? '')) ?></td>
                <td class="text-right pr-1"><?= esc((string) ($r['bssc_qty'] ?? '0')) ?></td>
                <td class="text-center"><?= esc((string) ($r['bssc_state'] ?? '')) ?></td>
                <td class="text-center"><?= esc((string) ($r['bssc_regdate'] ?? '')) ?></td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </section>
</div>

<script>
(() => {
  const shops = <?= json_encode(array_map(static function ($s): array {
      return [
          'ds_idx' => (int) ($s->ds_idx ?? 0),
          'ds_shop_no' => (string) ($s->ds_shop_no ?? ''),
          'ds_name' => (string) ($s->ds_name ?? ''),
          'ds_rep_name' => (string) ($s->ds_rep_name ?? ''),
          'ds_tel' => (string) ($s->ds_tel ?? ''),
          'ds_addr' => trim((string) ($s->ds_addr ?? '') . ' ' . (string) ($s->ds_addr_detail ?? '')),
      ];
  }, $shops ?? []), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
  const scanApi = '<?= base_url('bag/sale/designated-return/scan') ?>';
  const csrfName = '<?= csrf_token() ?>';
  const csrfHash = '<?= csrf_hash() ?>';

  const shopSearch = document.getElementById('shop-search');
  const shopSuggest = document.getElementById('shop-search-suggest');
  const barcodeInput = document.getElementById('barcode-input');
  const returnListBody = document.getElementById('return-list-body');
  const returnCodeBody = document.getElementById('return-code-body');
  const saveForm = document.getElementById('return-save-form');
  const saveDsIdx = document.getElementById('save-ds-idx');
  const saveScansJson = document.getElementById('save-scans-json');
  const scanMessage = document.getElementById('scan-message');

  const nf = (n) => new Intl.NumberFormat('ko-KR').format(n || 0);
  let selectedShop = null;
  let selectedBagCode = '';
  const scannedRows = [];

  function mergedShopText(shop) {
    return [shop.ds_shop_no, shop.ds_name, shop.ds_rep_name, shop.ds_tel, shop.ds_addr].filter(Boolean).join(' ');
  }

  function setMessage(msg, isError = false) {
    scanMessage.textContent = msg || '';
    scanMessage.className = isError ? 'text-sm text-red-600' : 'text-sm text-emerald-700';
  }

  function updateShopInfo(shop) {
    document.getElementById('shop-info-code').textContent = shop?.ds_shop_no || '-';
    document.getElementById('shop-info-name').textContent = shop?.ds_name || '-';
    document.getElementById('shop-info-rep').textContent = shop?.ds_rep_name || '-';
    document.getElementById('shop-info-tel').textContent = shop?.ds_tel || '-';
    document.getElementById('shop-info-addr').textContent = shop?.ds_addr || '-';
  }

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

  function renderSuggest(query) {
    if (!shopSuggest) return;
    const q = String(query || '').trim().toLowerCase();
    const matched = (q ? shops.filter((s) => mergedShopText(s).toLowerCase().includes(q)) : shops).slice(0, 30);
    if (matched.length === 0) {
      hideSuggest();
      return;
    }
    shopSuggest.innerHTML = matched.map((s) => `
      <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-ds-idx="${s.ds_idx}">
        ${mergedShopText(s)}
      </button>
    `).join('');
    shopSuggest.classList.remove('hidden');
  }

  function aggregateByBag() {
    const map = new Map();
    scannedRows.forEach((r) => {
      const key = String(r.bag_code || '');
      if (!map.has(key)) {
        map.set(key, {
          bag_code: key,
          bag_name: String(r.bag_name || ''),
          unit_price: Number(r.unit_price || 0),
          qty: 0,
          amount: 0,
        });
      }
      const item = map.get(key);
      item.qty += Number(r.qty || 0);
      item.amount += Number(r.amount || 0);
    });
    return Array.from(map.values());
  }

  function renderReturnList() {
    const rows = aggregateByBag();
    if (rows.length === 0) {
      returnListBody.innerHTML = '<tr><td colspan="6" class="text-center text-gray-400 py-6">판매소를 선택하고 바코드를 스캔해 주세요.</td></tr>';
      document.getElementById('sum-qty').textContent = '0';
      document.getElementById('sum-amount').textContent = '0';
      return;
    }
    returnListBody.innerHTML = rows.map((r) => `
      <tr>
        <td class="text-center"><input type="radio" name="pick-return-bag" value="${r.bag_code}" ${selectedBagCode === r.bag_code ? 'checked' : ''}></td>
        <td class="text-left pl-2">${r.bag_code} ${r.bag_name || ''}</td>
        <td class="text-right pr-2">${nf(r.qty)}</td>
        <td class="text-right pr-2">${nf(r.unit_price)}</td>
        <td class="text-right pr-2">${nf(r.amount)}</td>
        <td class="text-center"><button type="button" class="btn-remove-bag text-red-600 hover:underline text-xs" data-bag-code="${r.bag_code}">제거</button></td>
      </tr>
    `).join('');
    const sumQty = rows.reduce((s, r) => s + Number(r.qty || 0), 0);
    const sumAmount = rows.reduce((s, r) => s + Number(r.amount || 0), 0);
    document.getElementById('sum-qty').textContent = nf(sumQty);
    document.getElementById('sum-amount').textContent = nf(sumAmount);
  }

  function renderCodeTable() {
    if (!selectedBagCode) {
      returnCodeBody.innerHTML = '<tr><td colspan="4" class="text-center text-gray-400 py-6">품목을 선택해 주세요.</td></tr>';
      return;
    }
    const rows = scannedRows.filter((r) => String(r.bag_code || '') === selectedBagCode);
    if (rows.length === 0) {
      returnCodeBody.innerHTML = '<tr><td colspan="4" class="text-center text-gray-400 py-6">반품 봉투 코드가 없습니다.</td></tr>';
      return;
    }
    returnCodeBody.innerHTML = rows.map((r) => `
      <tr>
        <td class="text-left pl-2">${r.bag_code || ''} ${r.bag_name || ''}</td>
        <td class="text-center">${r.code || ''}</td>
        <td class="text-right pr-2">${nf(r.qty)}</td>
        <td class="text-right pr-2">${nf(r.amount)}</td>
      </tr>
    `).join('');
  }

  function removeScannedByBagCode(bagCode) {
    if (!bagCode) return;
    for (let i = scannedRows.length - 1; i >= 0; i -= 1) {
      if (String(scannedRows[i].bag_code || '') === bagCode) scannedRows.splice(i, 1);
    }
    if (selectedBagCode === bagCode) selectedBagCode = '';
    saveScansJson.value = JSON.stringify(scannedRows);
  }

  function applyResolvedShopFromScan(data) {
    const dsIdx = Number(data.ds_idx || 0);
    if (!dsIdx) return;
    let shop = shops.find((s) => Number(s.ds_idx) === dsIdx) || null;
    if (!shop) {
      shop = {
        ds_idx: dsIdx,
        ds_shop_no: String(data.ds_shop_no || ''),
        ds_name: String(data.ds_name || ''),
        ds_rep_name: String(data.ds_rep_name || ''),
        ds_tel: String(data.ds_tel || ''),
        ds_addr: String(data.ds_addr || ''),
      };
    }
    const prevIdx = selectedShop ? Number(selectedShop.ds_idx) : 0;
    if (prevIdx && prevIdx !== dsIdx && scannedRows.length > 0) {
      scannedRows.length = 0;
      saveScansJson.value = '[]';
      selectedBagCode = '';
      setMessage('바코드에 해당하는 지정판매소로 변경되어 이전 스캔 목록은 초기화되었습니다.', false);
    }
    selectedShop = shop;
    shopSearch.value = mergedShopText(shop);
    saveDsIdx.value = String(dsIdx);
    updateShopInfo(shop);
  }

  async function submitScan() {
    const code = (barcodeInput.value || '').trim();
    if (!code) return;
    if (scannedRows.some((r) => String(r.code || '') === code)) {
      setMessage('이미 스캔한 바코드입니다.', true);
      barcodeInput.value = '';
      return;
    }

    const payload = new URLSearchParams();
    payload.set(csrfName, csrfHash);
    payload.set('ds_idx', selectedShop ? String(selectedShop.ds_idx) : '0');
    payload.set('barcode', code);

    const res = await fetch(scanApi, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
      body: payload.toString(),
    });
    const data = await res.json();
    if (!data.ok) {
      setMessage(data.message || '스캔 실패', true);
      return;
    }

    applyResolvedShopFromScan(data);

    scannedRows.push({
      code: data.code,
      bag_code: data.bag_code,
      bag_name: data.bag_name,
      qty: Number(data.qty || 0),
      unit: data.unit || '',
      unit_price: Number(data.unit_price || 0),
      amount: Number(data.amount || 0),
      so_idx: Number(data.so_idx || 0),
    });
    saveScansJson.value = JSON.stringify(scannedRows);
    barcodeInput.value = '';
    if (!selectedBagCode) selectedBagCode = String(data.bag_code || '');
    setMessage(`반품 코드 등록: ${data.code} / 수량 ${nf(data.qty)}`);
    renderReturnList();
    renderCodeTable();
  }

  shopSearch?.addEventListener('input', (e) => renderSuggest(e.target.value || ''));
  shopSearch?.addEventListener('focus', (e) => renderSuggest(e.target.value || ''));
  shopSearch?.addEventListener('click', (e) => renderSuggest(e.target.value || ''));

  shopSuggest?.addEventListener('click', (e) => {
    const btn = e.target.closest('.shop-suggest-item');
    if (!btn) return;
    const dsIdx = Number(btn.dataset.dsIdx || 0);
    const shop = shops.find((s) => Number(s.ds_idx) === dsIdx) || null;
    if (!shop) return;
    selectedShop = shop;
    shopSearch.value = mergedShopText(shop);
    saveDsIdx.value = String(shop.ds_idx);
    selectedBagCode = '';
    scannedRows.length = 0;
    saveScansJson.value = '[]';
    updateShopInfo(shop);
    renderReturnList();
    renderCodeTable();
    setMessage('');
    hideSuggest();
  });

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

  barcodeInput?.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      submitScan();
    }
  });

  returnListBody?.addEventListener('change', (e) => {
    const radio = e.target.closest('input[name="pick-return-bag"]');
    if (!radio) return;
    selectedBagCode = radio.value || '';
    renderCodeTable();
  });

  returnListBody?.addEventListener('click', (e) => {
    const btn = e.target.closest('.btn-remove-bag');
    if (!btn) return;
    const bagCode = String(btn.dataset.bagCode || '');
    if (!bagCode) return;
    if (!confirm(`'${bagCode}' 봉투종류의 스캔 내역을 모두 제거할까요?`)) return;
    removeScannedByBagCode(bagCode);
    renderReturnList();
    renderCodeTable();
    setMessage(`반품 리스트에서 ${bagCode} 봉투종류를 제거했습니다.`);
  });

  saveForm?.addEventListener('submit', (e) => {
    if (!selectedShop) {
      e.preventDefault();
      alert('판매소를 선택해 주세요.');
      return;
    }
    if (scannedRows.length === 0) {
      e.preventDefault();
      alert('반품할 바코드를 스캔해 주세요.');
      return;
    }
  });

  renderReturnList();
  renderCodeTable();
})();
</script>

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