<?php
$saleDate = (string) ($saleDate ?? date('Y-m-d'));
$shops = is_array($shops ?? null) ? $shops : [];
$sales = is_array($sales ?? null) ? $sales : [];
$canCancel = (bool) ($canCancel ?? false);
$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="cancel-form" action="<?= base_url('bag/sale/designated-cancel/submit') ?>" method="POST" class="flex flex-wrap items-end gap-2">
    <?= csrf_field() ?>
    <input type="hidden" name="sale_date" value="<?= esc($saleDate) ?>"/>
    <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="sale-date" value="<?= esc($saleDate) ?>" class="border border-gray-300 rounded px-2 py-1.5 text-sm w-44"/>
    </div>
    <button type="submit" class="bg-btn-exit text-white px-4 py-1.5 rounded-sm text-sm shadow hover:opacity-90" <?= $canCancel ? '' : 'disabled' ?>>취소</button>
    <?php if (! $canCancel): ?>
      <span class="text-xs text-orange-600">과거 일자는 조회만 가능합니다. (취소 불가)</span>
    <?php endif; ?>
  </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="w-14 text-center">번호</th>
              <th class="text-left">지정판매소</th>
            </tr>
          </thead>
          <tbody id="shop-list-body">
            <?php if ($shops !== []): ?>
              <?php foreach ($shops as $idx => $s): ?>
                <tr class="shop-row cursor-pointer hover:bg-blue-50" data-ds-idx="<?= esc((string) ($s['bssc_ds_idx'] ?? 0), 'attr') ?>">
                  <td class="text-center"><?= $idx + 1 ?></td>
                  <td class="text-left pl-2"><?= esc((string) ($s['ds_name'] ?? ('판매소#' . (string) ($s['bssc_ds_idx'] ?? 0)))) ?></td>
                </tr>
              <?php endforeach; ?>
            <?php else: ?>
              <tr><td colspan="2" 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>
            <tr class="font-semibold bg-gray-50">
              <td colspan="4" class="text-right px-2 py-1">총 판매액 - 총 취소액</td>
              <td class="text-right px-2 py-1" id="sum-net-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>

  <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>
      지정판매소 <strong>판매 취소</strong> 화면 테스트를 위해, 위에서 선택한 <strong>판매일자</strong>(<code class="bg-amber-100 px-1 rounded"><?= esc($saleDate) ?></code>)에
      <code class="bg-amber-100 px-1 rounded">bssc_regdate</code>가 해당 일자이고 상태가 <strong>판매(sold)</strong>인 스캔 코드를 표시합니다(최대 500건).
      운영에는 불필요하므로 <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 saleDate = <?= json_encode($saleDate, JSON_UNESCAPED_UNICODE) ?>;
  const canCancel = <?= $canCancel ? 'true' : 'false' ?>;
  const sales = <?= json_encode($sales, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
  const nf = (n) => new Intl.NumberFormat('ko-KR').format(n || 0);

  const saleDateInput = document.getElementById('sale-date');
  const itemListBody = document.getElementById('item-list-body');
  const codeListBody = document.getElementById('code-list-body');
  const selectedCodesInput = document.getElementById('selected-codes-json');
  const cancelForm = document.getElementById('cancel-form');

  let currentDsIdx = null;
  const selectedCodeSet = new Set();
  const selectedItemSet = new Set();

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

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

  function renderSums(items) {
    let sumSale = 0;
    let sumCancel = 0;
    items.forEach((it) => {
      sumSale += it.sale_amount;
      sumCancel += it.cancel_amount;
    });
    document.getElementById('sum-sale-amount').textContent = nf(sumSale);
    document.getElementById('sum-cancel-amount').textContent = nf(sumCancel);
    document.getElementById('sum-net-amount').textContent = nf(sumSale - sumCancel);
  }

  function renderItems() {
    if (!currentDsIdx) {
      itemListBody.innerHTML = '<tr><td colspan="5" class="text-center text-gray-400 py-6">판매소를 선택해 주세요.</td></tr>';
      renderSums([]);
      return;
    }

    const items = rowsByItem();
    if (items.length === 0) {
      itemListBody.innerHTML = '<tr><td colspan="5" class="text-center text-gray-400 py-6">판매 품목이 없습니다.</td></tr>';
      renderSums([]);
      return;
    }

    itemListBody.innerHTML = items.map((it) => {
      const key = String(it.bag_code || '');
      const checked = selectedItemSet.has(key) ? 'checked' : '';
      const disabled = canCancel ? '' : 'disabled';
      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}" ${checked} ${disabled}></td>
          <td class="text-right pr-2">${nf(it.cancel_amount)}</td>
        </tr>
      `;
    }).join('');
    renderSums(items);
  }

  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 rows = rowsByShop().filter((r) => selectedItemSet.has(String(r.bag_code || '')));
    if (rows.length === 0) {
      codeListBody.innerHTML = '<tr><td colspan="5" class="text-center text-gray-400 py-6">봉투 코드가 없습니다.</td></tr>';
      return;
    }
    codeListBody.innerHTML = rows.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 syncSelectedCodesField() {
    selectedCodesInput.value = JSON.stringify(Array.from(selectedCodeSet));
  }

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

  document.getElementById('shop-list-body')?.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();
    syncSelectedCodesField();
  });

  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();
    syncSelectedCodesField();
  });

  saleDateInput?.addEventListener('change', () => {
    const val = saleDateInput.value || '';
    if (!val) return;
    location.href = `<?= base_url('bag/sale/designated-cancel') ?>?sale_date=${encodeURIComponent(val)}`;
  });

  cancelForm?.addEventListener('submit', (e) => {
    if (!canCancel) {
      e.preventDefault();
      alert('과거 판매일자는 취소 처리할 수 없습니다.');
      return;
    }
    if (selectedCodeSet.size === 0) {
      e.preventDefault();
      alert('취소할 품목/봉투코드를 선택해 주세요.');
      return;
    }
    if (!confirm('선택한 품목을 취소 처리 하시겠습니까?')) {
      e.preventDefault();
      return;
    }
    syncSelectedCodesField();
  });

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

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