<?= view('components/print_header', ['printTitle' => '년 판매 현황']) ?>
<section class="border-b border-gray-300 p-2 shrink-0 bg-control-panel">
  <div class="flex flex-wrap items-center justify-between gap-y-2">
    <span class="text-sm font-bold text-gray-700">년 판매 현황 (월별)</span>
    <button onclick="window.print()" class="no-print border border-btn-print-border text-gray-600 px-3 py-1 rounded-sm text-sm hover:bg-gray-50 transition">인쇄</button>
  </div>
</section>
<section class="p-2 bg-white border-b border-gray-200">
  <form method="GET" action="<?= base_url('admin/reports/yearly-sales') ?>" class="flex flex-wrap items-center gap-2">
    <label class="text-sm text-gray-600">연도</label>
    <select name="year" class="border border-gray-300 rounded px-2 py-1 text-sm">
      <?php for ($y = (int) date('Y'); $y >= 2020; $y--): ?>
      <option value="<?= $y ?>" <?= (int)($year ?? date('Y')) === $y ? 'selected' : '' ?>><?= $y ?>년</option>
      <?php endfor; ?>
    </select>
    <button type="submit" class="bg-btn-search text-white px-4 py-1 rounded-sm text-sm">조회</button>
  </form>
</section>
<div class="border border-gray-300 overflow-auto mt-2">
  <table class="w-full data-table">
    <thead>
      <tr>
        <th>봉투코드</th>
        <th>봉투명</th>
        <th>1월</th><th>2월</th><th>3월</th><th>4월</th><th>5월</th><th>6월</th>
        <th>7월</th><th>8월</th><th>9월</th><th>10월</th><th>11월</th><th>12월</th>
        <th class="bg-gray-100">합계</th>
      </tr>
    </thead>
    <tbody class="text-right">
      <?php
        $grandTotal = array_fill(1, 13, 0); // 1~12 + 13=total
        foreach ($result as $row):
      ?>
      <tr>
        <td class="text-center font-mono"><?= esc($row->bs_bag_code) ?></td>
        <td class="text-left pl-2"><?= esc($row->bs_bag_name) ?></td>
        <?php for ($m = 1; $m <= 12; $m++):
          $key = 'm' . sprintf('%02d', $m);
          $val = (int) $row->$key;
          $grandTotal[$m] += $val;
        ?>
        <td><?= $val > 0 ? number_format($val) : '-' ?></td>
        <?php endfor; ?>
        <?php $grandTotal[13] += (int) $row->total; ?>
        <td class="font-bold bg-gray-50"><?= number_format((int) $row->total) ?></td>
      </tr>
      <?php endforeach; ?>
      <?php if (empty($result)): ?>
      <tr><td colspan="15" class="text-center text-gray-400 py-4">조회된 데이터가 없습니다.</td></tr>
      <?php else: ?>
      <tr class="font-bold bg-gray-100">
        <td colspan="2" class="text-center">합계</td>
        <?php for ($m = 1; $m <= 12; $m++): ?>
        <td><?= $grandTotal[$m] > 0 ? number_format($grandTotal[$m]) : '-' ?></td>
        <?php endfor; ?>
        <td class="bg-gray-200"><?= number_format($grandTotal[13]) ?></td>
      </tr>
      <?php endif; ?>
    </tbody>
  </table>
</div>
