<?php
$year = (int) ($year ?? (int) date('Y'));
$queried = (bool) ($queried ?? false);
$filters = is_array($filters ?? null) ? $filters : [];
$report = is_array($report ?? null) ? $report : [];
$lgName = (string) ($lgName ?? '');
$rows = is_array($report['rows'] ?? null) ? $report['rows'] : [];
$months = is_array($report['months'] ?? null) ? $report['months'] : range(1, 12);
$prevYear = (int) ($report['prevYear'] ?? $year - 1);
$printExtra = [
    $lgName !== '' ? $lgName : '',
    '(단위: 매, 원) ' . $year . '년',
];
?>
<?= view('components/print_header', ['printTitle' => '전년대비 판매 통계분석', '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">전년 대비 판매 분석</span>
    <div class="flex 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">인쇄</button>
      <a href="<?= base_url('dashboard') ?>" class="border border-gray-400 text-gray-700 px-3 py-1 rounded-sm text-sm">종료</a>
    </div>
  </div>
</section>

<section class="p-2 bg-white border-b border-gray-200 no-print text-sm">
  <form method="get" action="<?= site_url('bag/analytics/year-over-year') ?>" class="flex flex-wrap items-end gap-3">
    <input type="hidden" name="search" value="1"/>
    <div>
      <label class="block text-gray-600 mb-0.5">조회년도</label>
      <input type="number" name="year" value="<?= (int) $year ?>" min="2000" max="2100" class="border border-gray-300 rounded px-2 py-1 w-24"/>
    </div>
    <button type="submit" class="bg-btn-search text-white px-4 py-1 rounded-sm">조회</button>
  </form>
</section>


<div class="m-2 border border-gray-300 rounded-lg p-4 overflow-auto">
  <p class="text-center text-sm font-bold py-2 bg-gray-50 border-b">전년대비 판매 통계분석</p>
  <p class="text-xs text-gray-500 px-2 py-1 border-b">(단위: 매, 원) · <strong>판매(sale)</strong> 수량·금액만 집계합니다(반품·취소 제외). 증감은 전년·당해 판매량(또는 금액) 차이입니다.</p>
  <table class="w-full data-table text-xs">
    <thead>
      <tr>
        <th rowspan="2" class="w-32">품목</th>
        <th rowspan="2" class="w-14 text-center">구분</th>
        <th rowspan="2" class="w-12 text-center">년도</th>
        <th rowspan="2" class="w-16 text-right">계</th>
        <?php foreach ($months as $mo): ?>
        <th class="w-14 text-right"><?= (int) $mo ?>월</th>
        <?php endforeach; ?>
      </tr>
    </thead>
    <tbody class="text-right">
      <?php if ($queried && $rows === []): ?>
      <tr><td colspan="<?= 4 + count($months) ?>" class="text-center text-gray-500 py-6">해당 자료가 없습니다.</td></tr>
      <?php endif; ?>
      <?php
        $byProduct = [];
        foreach ($rows as $block) {
            $code = (string) ($block['bag_code'] ?? '');
            if (! isset($byProduct[$code])) {
                $byProduct[$code] = ['name' => (string) ($block['bag_name'] ?? ''), 'blocks' => []];
            }
            $byProduct[$code]['blocks'][] = $block;
        }
        foreach ($byProduct as $product):
          $productRowspan = 0;
          foreach ($product['blocks'] as $b) {
              $productRowspan += count($b['lines'] ?? []);
          }
          $printedProduct = false;
          foreach ($product['blocks'] as $block):
            $sectionRows = count($block['lines'] ?? []);
            $sectionPrinted = false;
            foreach ($block['lines'] ?? [] as $line):
      ?>
      <tr>
        <?php if (! $printedProduct): ?>
        <td class="text-left pl-2 font-medium" rowspan="<?= (int) $productRowspan ?>"><?= esc($product['name']) ?></td>
        <?php $printedProduct = true; endif; ?>
        <?php if (! $sectionPrinted): ?>
        <td class="text-center" rowspan="<?= (int) $sectionRows ?>"><?= esc((string) ($block['section'] ?? '')) ?></td>
        <?php $sectionPrinted = true; endif; ?>
        <td class="text-center"><?= esc((string) ($line['label'] ?? '')) ?></td>
        <td class="tabular-nums font-semibold"><?= number_format((int) ($line['total'] ?? 0)) ?></td>
        <?php foreach ($months as $mo): ?>
        <td class="tabular-nums <?= ($line['label'] ?? '') === '증감' && (int) (($line['months'][$mo] ?? 0)) < 0 ? 'text-red-600' : '' ?>">
          <?= number_format((int) (($line['months'][$mo] ?? 0))) ?>
        </td>
        <?php endforeach; ?>
      </tr>
      <?php
            endforeach;
          endforeach;
        endforeach;
      ?>
    </tbody>
  </table>
</div>
