<?php
$returnDate = (string) ($returnDate ?? date('Y-m-d'));
$shops = is_array($shops ?? null) ? $shops : [];
$returns = is_array($returns ?? null) ? $returns : [];
?>

<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-cancel-form" action="<?= base_url('bag/sale/designated-return-cancel/save') ?>" method="POST" class="flex flex-wrap items-end gap-2">
    <?= csrf_field() ?>
    <input type="hidden" name="return_date" id="return-date-hidden" value="<?= esc($returnDate) ?>"/>
    <input type="hidden" name="selected_codes_json" id="selected-codes-json" value="[]"/>
    <div>
      <label class="block text-xs font-bold text-gray-700 mb-1">반품 일자</label>
      <input type="date" id="return-date" value="<?= esc($returnDate) ?>" class="border border-gray-300 rounded px-2 py-1.5 text-sm w-44"/>
    </div>
    <button type="button" id="btn-search" class="bg-btn-search text-white px-4 py-1.5 rounded-sm text-sm shadow hover:opacity-90">조회</button>
    <button type="submit" class="bg-btn-exit text-white px-4 py-1.5 rounded-sm text-sm shadow hover:opacity-90">반품 취소 저장</button>
  </form>

  <div class="grid grid-cols-1 xl:grid-cols-5 gap-3">
    <section class="xl:col-span-2 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="text-left">지정판매소 상호명</th>
              <th class="w-24 text-center">대표자명</th>
              <th class="w-28 text-center">반품일자</th>
            </tr>
          </thead>
          <tbody id="shop-list-body">
            <?php if ($shops !== []): ?>
              <?php foreach ($shops as $s): ?>
                <tr class="shop-row cursor-pointer hover:bg-blue-50" data-ds-idx="<?= esc((string) ($s['brsc_ds_idx'] ?? 0), 'attr') ?>">
                  <td class="text-left pl-2"><?= esc((string) ($s['ds_name'] ?? ('판매소#' . (string) ($s['brsc_ds_idx'] ?? 0)))) ?></td>
                  <td class="text-center"><?= esc((string) ($s['ds_rep_name'] ?? '-')) ?></td>
                  <td class="text-center"><?= esc((string) ($s['brsc_return_date'] ?? $returnDate)) ?></td>
                </tr>
              <?php endforeach; ?>
            <?php else: ?>
              <tr><td colspan="3" class="text-center text-gray-400 py-6">조회된 반품 데이터가 없습니다.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </section>

    <section class="xl:col-span-3 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="text-left">품목</th>
              <th class="w-20 text-right">단가</th>
              <th class="w-24 text-right">판매액</th>
              <th class="w-14 text-center">취소</th>
              <th class="w-24 text-right">취소액</th>
            </tr>
          </thead>
          <tbody id="item-list-body">
            <tr><td colspan="5" 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-sale-amount">0</td>
              <td class="text-center px-2 py-1">-</td>
              <td class="text-right px-2 py-1" id="sum-cancel-amount">0</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>
            <th class="w-24 text-right">금액</th>
          </tr>
        </thead>
        <tbody id="code-list-body">
          <tr><td colspan="5" class="text-center text-gray-400 py-6">반품 리스트에서 취소할 품목(취소 컬럼)을 선택해 주세요.</td></tr>
        </tbody>
      </table>
    </div>
  </section>
</div>

<script>
(() => {
  const rows = <?= json_encode($returns, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
  const nf = (n) => new Intl.NumberFormat('ko-KR').format(n || 0);
  const shopListBody = document.getElementById('shop-list-body');
  const itemListBody = document.getElementById('item-list-body');
  const codeListBody = document.getElementById('code-list-body');
  const selectedCodesInput = document.getElementById('selected-codes-json');
  const returnDateInput = document.getElementById('return-date');
  const returnDateHidden = document.getElementById('return-date-hidden');
  const selectedCodeSet = new Set();
  const selectedItemSet = new Set();
  let currentDsIdx = null;

  function rowsByShop() {
    return rows.filter((r) => Number(r.ds_idx) === Number(currentDsIdx));
  }

  function rowsByItem() {
    const map = new Map();
    rowsByShop().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), sale_amount: 0, cancel_amount: 0 });
      }
      const item = map.get(key);
      item.sale_amount += Number(r.amount || 0);
      if (selectedCodeSet.has(String(r.code || ''))) item.cancel_amount += Number(r.amount || 0);
    });
    return Array.from(map.values());
  }

  function syncHidden() {
    selectedCodesInput.value = JSON.stringify(Array.from(selectedCodeSet));
    returnDateHidden.value = returnDateInput.value || '';
  }

  function renderItems() {
    if (!currentDsIdx) {
      itemListBody.innerHTML = '<tr><td colspan="5" class="text-center text-gray-400 py-6">지정판매소를 선택해 주세요.</td></tr>';
      document.getElementById('sum-sale-amount').textContent = '0';
      document.getElementById('sum-cancel-amount').textContent = '0';
      return;
    }
    const items = rowsByItem();
    if (items.length === 0) {
      itemListBody.innerHTML = '<tr><td colspan="5" class="text-center text-gray-400 py-6">반품 품목이 없습니다.</td></tr>';
      document.getElementById('sum-sale-amount').textContent = '0';
      document.getElementById('sum-cancel-amount').textContent = '0';
      return;
    }
    itemListBody.innerHTML = items.map((it) => {
      const key = String(it.bag_code || '');
      return `
        <tr>
          <td class="text-left pl-2">${key} ${it.bag_name || ''}</td>
          <td class="text-right pr-2">${nf(it.unit_price)}</td>
          <td class="text-right pr-2">${nf(it.sale_amount)}</td>
          <td class="text-center"><input type="checkbox" class="item-cancel-check" data-bag-code="${key}" ${selectedItemSet.has(key) ? 'checked' : ''}></td>
          <td class="text-right pr-2">${nf(it.cancel_amount)}</td>
        </tr>
      `;
    }).join('');
    const sumSale = items.reduce((s, it) => s + Number(it.sale_amount || 0), 0);
    const sumCancel = items.reduce((s, it) => s + Number(it.cancel_amount || 0), 0);
    document.getElementById('sum-sale-amount').textContent = nf(sumSale);
    document.getElementById('sum-cancel-amount').textContent = nf(sumCancel);
  }

  function renderCodes() {
    if (!currentDsIdx || selectedItemSet.size === 0) {
      codeListBody.innerHTML = '<tr><td colspan="5" class="text-center text-gray-400 py-6">반품 리스트에서 취소할 품목(취소 컬럼)을 선택해 주세요.</td></tr>';
      return;
    }
    const targetRows = rowsByShop().filter((r) => selectedItemSet.has(String(r.bag_code || '')));
    if (targetRows.length === 0) {
      codeListBody.innerHTML = '<tr><td colspan="5" class="text-center text-gray-400 py-6">반품 코드가 없습니다.</td></tr>';
      return;
    }
    codeListBody.innerHTML = targetRows.map((r) => `
      <tr>
        <td class="text-left pl-2">${r.bag_code || ''} ${r.bag_name || ''}</td>
        <td class="text-center">${String(r.code || '')}</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>
      </tr>
    `).join('');
  }

  function toggleItemCodes(bagCode, checked) {
    rowsByShop().forEach((r) => {
      if (String(r.bag_code || '') !== bagCode) return;
      const code = String(r.code || '');
      if (!code) return;
      if (checked) selectedCodeSet.add(code); else selectedCodeSet.delete(code);
    });
  }

  document.getElementById('btn-search')?.addEventListener('click', () => {
    const val = returnDateInput.value || '';
    if (!val) return;
    location.href = `<?= base_url('bag/sale/designated-return-cancel') ?>?return_date=${encodeURIComponent(val)}`;
  });

  shopListBody?.addEventListener('click', (e) => {
    const tr = e.target.closest('.shop-row');
    if (!tr) return;
    document.querySelectorAll('.shop-row').forEach((row) => row.classList.remove('bg-blue-100'));
    tr.classList.add('bg-blue-100');
    currentDsIdx = Number(tr.dataset.dsIdx || 0) || null;
    selectedCodeSet.clear();
    selectedItemSet.clear();
    renderItems();
    renderCodes();
    syncHidden();
  });

  itemListBody?.addEventListener('change', (e) => {
    const itemCheck = e.target.closest('.item-cancel-check');
    if (!itemCheck) return;
    const bagCode = String(itemCheck.dataset.bagCode || '');
    if (itemCheck.checked) selectedItemSet.add(bagCode); else selectedItemSet.delete(bagCode);
    toggleItemCodes(bagCode, itemCheck.checked);
    renderItems();
    renderCodes();
    syncHidden();
  });

  document.getElementById('return-cancel-form')?.addEventListener('submit', (e) => {
    syncHidden();
    if ((returnDateHidden.value || '') === '') {
      e.preventDefault();
      alert('반품 일자를 선택해 주세요.');
      return;
    }
    if (selectedCodeSet.size === 0) {
      e.preventDefault();
      alert('반품 취소할 품목/봉투코드를 선택해 주세요.');
      return;
    }
    if (!confirm('선택한 반품 품목을 취소 처리 하시겠습니까?')) {
      e.preventDefault();
    }
  });

  const firstShop = document.querySelector('.shop-row');
  if (firstShop) {
    firstShop.classList.add('bg-blue-100');
    currentDsIdx = Number(firstShop.dataset.dsIdx || 0) || null;
    renderItems();
    renderCodes();
    syncHidden();
  }
})();
</script>

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