<?php
$barcode = (string) ($barcode ?? '');
$lotNo = (string) ($lotNo ?? '');
$result = is_array($result ?? null) ? $result : [];
$queried = (bool) ($queried ?? false);

$ok = (bool) ($result['ok'] ?? false);
$message = (string) ($result['message'] ?? '');
$rows = is_array($result['rows'] ?? null) ? $result['rows'] : [];
$unit = (string) ($result['unit'] ?? '');
$bagName = (string) ($result['bag_name'] ?? '');
$bagCode = (string) ($result['bag_code'] ?? '');
$lotLabel = (string) ($result['lot_no'] ?? $lotNo);
$qtyBox = (int) ($result['qty_box'] ?? 0);
$qtyPack = (int) ($result['qty_pack'] ?? 0);
$qtySheet = (int) ($result['qty_sheet'] ?? 0);
$testSamples = is_array($testSamples ?? null) ? $testSamples : [];

$printExtra = [];
if ($queried && $barcode !== '') {
    $printExtra[] = '봉투번호(바코드): ' . $barcode;
}
if ($bagName !== '' || $bagCode !== '') {
    $printExtra[] = '품목: ' . trim($bagName . ($bagCode !== '' ? ' (' . $bagCode . ')' : ''));
}
?>
<?= view('components/print_header', [
    'printTitle'      => 'LOT 수불 조회',
    'printExtraLines' => $printExtra,
]) ?>

<section class="border-b border-gray-300 p-2 shrink-0 bg-control-panel no-print">
  <div class="flex flex-wrap items-center justify-between gap-y-2">
    <span class="text-sm font-bold text-gray-700">LOT 수불 조회</span>
    <div class="flex flex-wrap items-center gap-2">
      <button type="button" onclick="window.print()" class="border border-btn-print-border text-gray-600 px-3 py-1 rounded-sm text-sm hover:bg-gray-50">인쇄</button>
      <a href="<?= base_url('dashboard') ?>" class="border border-gray-400 text-gray-700 px-3 py-1 rounded-sm text-sm hover:bg-gray-50">종료</a>
    </div>
  </div>
</section>

<section class="p-2 bg-white border-b border-gray-200 no-print text-sm">
  <form method="get" action="<?= mgmt_url('reports/lot-flow') ?>" class="flex flex-wrap items-end gap-x-4 gap-y-2">
    <input type="hidden" name="search" value="1"/>
    <div class="flex flex-wrap items-center gap-2">
      <label class="font-bold text-gray-700 whitespace-nowrap">봉투번호</label>
      <input type="text" name="barcode" id="lot-flow-barcode-input" value="<?= esc($barcode) ?>"
             placeholder="바코드·팩·박스·낱장 코드 입력"
             class="border border-gray-300 rounded px-2 py-1 w-80 font-mono text-sm" autocomplete="off"/>
      <span class="text-gray-500 text-xs">(바코드 스캔 = 번호 직접 입력)</span>
    </div>
    <button type="submit" class="bg-btn-search text-white px-4 py-1 rounded-sm">조회</button>
  </form>
  <p class="text-xs text-gray-500 mt-1">
    낱장 번호 조회 시 <strong>해당 장(바코드)의 판매·반품</strong>만 표시합니다. 팩·박스·LOT 조회는 해당 단위 이력입니다.
  </p>
</section>

<?php if ($queried && ! $ok && $message !== ''): ?>
<div class="m-2 p-3 border border-amber-300 bg-amber-50 text-sm text-amber-900 no-print">
  <?= esc($message) ?>
</div>
<?php endif; ?>

<?php if (! $queried): ?>
<div class="m-2 p-3 border border-blue-200 bg-blue-50 text-sm text-blue-900 no-print">
  봉투번호(바코드)를 입력한 뒤 <strong>조회</strong>를 눌러 주세요.
</div>
<?php endif; ?>

<section class="mx-2 mb-2 border border-amber-400 bg-amber-50/80 rounded-sm no-print" id="lot-flow-test-samples">
  <div class="px-3 py-2 border-b border-amber-300 bg-amber-100/80">
    <strong class="text-amber-950 text-sm">[개발용 임시] 등록·조회 가능 봉투번호 샘플</strong>
    <span class="text-xs text-amber-800 ml-2">행 클릭 → 봉투번호 입력 후 조회 · 현재 지자체 DB 기준</span>
  </div>
  <div class="overflow-auto max-h-48">
    <table class="w-full text-xs data-table">
      <thead>
        <tr>
          <th class="w-14 text-center">구분</th>
          <th>봉투번호(입력값)</th>
          <th class="w-28">품목</th>
          <th class="w-24">LOT</th>
          <th class="w-14 text-center">상태</th>
          <th class="w-32">비고</th>
        </tr>
      </thead>
      <tbody>
        <?php if ($testSamples === []): ?>
        <tr>
          <td colspan="6" class="text-center text-gray-500 py-4">
            <code>bag_receiving_pack_code</code> 데이터가 없습니다. 입고 처리 후 표시됩니다.
          </td>
        </tr>
        <?php endif; ?>
        <?php foreach ($testSamples as $sample): ?>
        <tr class="lot-flow-sample-row cursor-pointer hover:bg-amber-100"
            data-code="<?= esc((string) ($sample['code'] ?? ''), 'attr') ?>"
            title="클릭하여 조회">
          <td class="text-center"><?= esc((string) ($sample['kind'] ?? '')) ?></td>
          <td class="font-mono text-left pl-2 break-all"><?= esc((string) ($sample['code'] ?? '')) ?></td>
          <td class="text-left pl-1 truncate max-w-[7rem]" title="<?= esc((string) ($sample['bag_name'] ?? ''), 'attr') ?>">
            <?= esc((string) ($sample['bag_name'] ?? '')) ?>
          </td>
          <td class="font-mono text-left pl-1 truncate max-w-[6rem]"><?= esc((string) ($sample['lot_no'] ?? '')) ?></td>
          <td class="text-center"><?= esc((string) ($sample['state'] ?? '')) ?></td>
          <td class="text-gray-600 pl-1"><?= esc((string) ($sample['hint'] ?? '')) ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</section>

<div class="lot-flow-layout m-2 flex flex-col lg:flex-row gap-3 min-h-[320px]">
  <!-- 좌: 품목·단위 요약 (레거시 BOX/PACK/낱장) -->
  <div class="lot-flow-summary border border-gray-300 rounded-lg bg-gray-50 p-3 lg:w-64 shrink-0">
    <h3 class="text-sm font-bold text-gray-700 mb-2">봉투 정보</h3>
    <?php if ($ok): ?>
    <dl class="text-sm space-y-1.5">
      <div><dt class="text-gray-500 inline">품목</dt>
        <dd class="font-medium"><?= esc($bagName !== '' ? $bagName : '-') ?></dd></div>
      <?php if ($bagCode !== ''): ?>
      <div><dt class="text-gray-500 inline">코드</dt>
        <dd class="font-mono text-xs"><?= esc($bagCode) ?></dd></div>
      <?php endif; ?>
      <?php if ($lotLabel !== ''): ?>
      <div><dt class="text-gray-500 inline">LOT</dt>
        <dd class="font-mono text-xs break-all"><?= esc($lotLabel) ?></dd></div>
      <?php endif; ?>
      <div><dt class="text-gray-500 inline">봉투번호</dt>
        <dd class="font-mono text-xs break-all"><?= esc($barcode !== '' ? $barcode : '-') ?></dd></div>
      <?php if ($unit !== ''): ?>
      <div><dt class="text-gray-500 inline">조회단위</dt>
        <dd><?= esc($unit) ?></dd></div>
      <?php endif; ?>
    </dl>
    <div class="grid grid-cols-3 gap-2 mt-4 text-center text-xs">
      <div class="border border-gray-300 bg-white rounded p-2">
        <div class="text-gray-500 font-bold">BOX</div>
        <div class="text-lg font-semibold tabular-nums"><?= $qtyBox > 0 ? number_format($qtyBox) : '—' ?></div>
      </div>
      <div class="border border-gray-300 bg-white rounded p-2">
        <div class="text-gray-500 font-bold">PACK</div>
        <div class="text-lg font-semibold tabular-nums"><?= $qtyPack > 0 ? number_format($qtyPack) : '—' ?></div>
      </div>
      <div class="border border-gray-300 bg-white rounded p-2">
        <div class="text-gray-500 font-bold">낱장</div>
        <div class="text-lg font-semibold tabular-nums"><?= $qtySheet > 0 ? number_format($qtySheet) : '—' ?></div>
      </div>
    </div>
    <?php elseif ($queried): ?>
    <p class="text-sm text-gray-500">조회 결과 없음</p>
    <?php else: ?>
    <p class="text-sm text-gray-400">조회 후 표시</p>
    <?php endif; ?>
  </div>

  <!-- 우: LOT 수불 현황 -->
  <div class="lot-flow-table-wrap flex-1 border border-gray-300 rounded-lg flex flex-col min-w-0">
    <div class="bg-gray-100 border-b border-gray-300 px-3 py-1.5">
      <span class="text-sm font-bold text-gray-700">LOT 수불 현황</span>
    </div>
    <div class="overflow-auto flex-1">
      <table class="w-full data-table text-sm">
        <thead>
          <tr>
            <th class="w-28 text-center">일자</th>
            <th>입출고처</th>
            <th class="w-24 text-center">구분</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($queried && $ok && $rows === []): ?>
          <tr>
            <td colspan="3" class="text-center text-gray-500 py-8">수불 이력이 없습니다.</td>
          </tr>
          <?php endif; ?>
          <?php if (! $queried): ?>
          <tr>
            <td colspan="3" class="text-center text-gray-400 py-8">봉투번호 입력 후 조회</td>
          </tr>
          <?php endif; ?>
          <?php foreach ($rows as $row): ?>
          <tr>
            <td class="text-center"><?= esc((string) ($row['flow_date'] ?? '')) ?></td>
            <td class="text-left pl-2"><?= esc((string) ($row['counterparty'] ?? '')) ?></td>
            <td class="text-center"><?= esc((string) ($row['flow_type'] ?? '')) ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<script>
(function () {
  const input = document.getElementById('lot-flow-barcode-input');
  const form = input?.closest('form');
  document.querySelectorAll('.lot-flow-sample-row').forEach((row) => {
    row.addEventListener('click', () => {
      const code = row.getAttribute('data-code') || '';
      if (!input || !form || code === '') return;
      input.value = code;
      form.submit();
    });
  });
})();
</script>

<style>
@media print {
  .no-print { display: none !important; }
  #lot-flow-test-samples { display: none !important; }
  .lot-flow-layout { margin: 0; flex-direction: row; }
}
</style>
