<?php
$startDate = (string) ($startDate ?? date('Y-m-01'));
$endDate = (string) ($endDate ?? date('Y-m-d'));
$ioType = (string) ($ioType ?? 'out');
$result = is_array($result ?? null) ? $result : (array) ($result ?? []);
$queried = (bool) ($queried ?? false);
$exportParams = $queried ? array_filter([
    'search'     => '1',
    'start_date' => $startDate,
    'end_date'   => $endDate,
    'io_type'    => $ioType,
], static fn ($v) => $v !== null && $v !== '') : [];
$excelUrl = $exportParams !== []
    ? mgmt_url('reports/returns/export') . '?' . http_build_query($exportParams)
    : '';

$fmtKrDate = static function (string $ymd): string {
    $ts = strtotime($ymd);

    return $ts ? date('Y년 m월 d일', $ts) : $ymd;
};

$ioLabel = $ioType === 'in' ? '입고' : '출고';
$periodLabel = $fmtKrDate($startDate) . ' ~ ' . $fmtKrDate($endDate);
$printExtraLines = [
    '조회기간: ' . $periodLabel,
    '입출고 구분: ' . $ioLabel,
    '(단위: 매)',
];

$typeLabel = static function (string $bsType): string {
    return match ($bsType) {
        'return'  => '반품',
        'dispose' => '파기',
        'cancel'  => '파기',
        default   => $bsType,
    };
};

$kindLabel = static function (object $row): string {
    $name = trim((string) ($row->bs_bag_name ?? ''));
    if ($name !== '') {
        return $name;
    }
    $code = trim((string) ($row->bs_bag_code ?? ''));

    return $code !== '' ? $code : '-';
};

$totalQty = 0;
foreach ($result as $row) {
    $totalQty += (int) ($row->qty ?? 0);
}

$tipPage = "지정판매소 반품·물류 입고분 파기 내역을 기간·입출고 구분으로 조회합니다.\n"
    . "· 출고: 지정판매소 반품 등록 화면에서 처리된 반품\n"
    . "· 입고: 물류 창고 입고분 파기 처리 내역\n"
    . "조회 후 표·엑셀·인쇄에 반영됩니다.";
?>
<?= view('components/print_header', [
    'printTitle'      => '반품 / 파기 현황',
    'printExtraLines' => $printExtraLines,
]) ?>

<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 inline-flex items-center gap-1">
      반품/파기 현황
      <?= view('components/field_tooltip', ['text' => $tipPage, 'placement' => 'below']) ?>
    </span>
    <div class="flex flex-wrap items-center gap-2">
      <?php if ($excelUrl !== ''): ?>
      <a href="<?= esc($excelUrl, 'attr') ?>" target="_blank" rel="noopener noreferrer"
         class="bg-green-700 text-white px-3 py-1 rounded-sm text-sm hover:bg-green-800">엑셀저장</a>
      <?php else: ?>
      <span class="bg-gray-300 text-gray-600 px-3 py-1 rounded-sm text-sm cursor-not-allowed" title="조회 후 이용">엑셀저장</span>
      <?php endif; ?>
      <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">
  <form method="get" action="<?= mgmt_url('reports/returns') ?>" class="flex flex-wrap items-end gap-x-4 gap-y-2 text-sm">
    <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="date" name="start_date" value="<?= esc($startDate) ?>" class="border border-gray-300 rounded px-2 py-1" required/>
      <span>~</span>
      <input type="date" name="end_date" value="<?= esc($endDate) ?>" class="border border-gray-300 rounded px-2 py-1" required/>
    </div>

    <div class="flex flex-wrap items-center gap-3">
      <span class="font-bold text-gray-700 whitespace-nowrap">입출고 구분</span>
      <label class="inline-flex items-center gap-1">
        <input type="radio" name="io_type" value="in" <?= $ioType === 'in' ? 'checked' : '' ?>/>
        입고
      </label>
      <label class="inline-flex items-center gap-1">
        <input type="radio" name="io_type" value="out" <?= $ioType === 'out' ? 'checked' : '' ?>/>
        출고
      </label>
    </div>

    <button type="submit" class="bg-btn-search text-white px-4 py-1 rounded-sm">조회</button>
  </form>
</section>

<?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; ?>

<div class="border border-gray-300 rounded-lg p-4 overflow-auto m-2 print:m-0">
  <table class="w-full data-table text-sm">
    <thead>
      <tr>
        <th class="w-28 text-center">일자</th>
        <th>반품처</th>
        <th>종류</th>
        <th class="w-24 text-right">수량</th>
        <th class="w-20 text-center">구분</th>
      </tr>
    </thead>
    <tbody>
      <?php if ($queried && $result === []): ?>
      <tr>
        <td colspan="5" class="text-center text-gray-500 py-8">해당 자료가 없습니다.</td>
      </tr>
      <?php endif; ?>
      <?php foreach ($result as $row): ?>
      <tr>
        <td class="text-center"><?= esc((string) $row->bs_sale_date) ?></td>
        <td class="text-left pl-2"><?= esc((string) ($row->bs_ds_name ?? '')) ?></td>
        <td class="text-left pl-2"><?= esc($kindLabel($row)) ?></td>
        <td class="text-right pr-2 tabular-nums"><?= number_format((int) ($row->qty ?? 0)) ?></td>
        <td class="text-center"><?= esc($typeLabel((string) ($row->bs_type ?? ''))) ?></td>
      </tr>
      <?php endforeach; ?>
      <?php if ($queried && $result !== []): ?>
      <tr class="font-bold bg-gray-100">
        <td colspan="3" class="text-center">합계</td>
        <td class="text-right pr-2 tabular-nums"><?= number_format($totalQty) ?></td>
        <td></td>
      </tr>
      <?php endif; ?>
    </tbody>
  </table>
</div>

<style>
.field-tip { position: relative; display: inline-flex; vertical-align: middle; }
.field-tip-btn {
  display: inline-flex; align-items: center; justify-content: center;
  width: 14px; height: 14px; font-size: 10px; font-weight: 700; line-height: 1;
  color: #6b7280; background: #f3f4f6; border: 1px solid #d1d5db; border-radius: 50%;
  cursor: help; user-select: none;
}
.field-tip-btn:hover, .field-tip-btn:focus { color: #1d4ed8; border-color: #93c5fd; background: #eff6ff; outline: none; }
.field-tip-panel {
  position: absolute; z-index: 60; left: 50%; transform: translateX(-50%);
  bottom: calc(100% + 6px); width: max-content; max-width: 280px;
  padding: 0.35rem 0.5rem; border-radius: 4px;
  background: #1f2937; color: #f9fafb; font-size: 11px; font-weight: 500; line-height: 1.35;
  text-align: left; white-space: pre-line; box-shadow: 0 2px 8px rgba(0,0,0,.15);
  opacity: 0; visibility: hidden; pointer-events: none; transition: opacity .12s, visibility .12s;
}
.field-tip--below .field-tip-panel { bottom: auto; top: calc(100% + 6px); }
.field-tip:hover .field-tip-panel,
.field-tip:focus-within .field-tip-panel { opacity: 1; visibility: visible; }

@media print {
  .no-print { display: none !important; }
}
</style>
