<?php
declare(strict_types=1);

/** @var list<array<string,mixed>> $lines */
/** @var string $startDate */
/** @var string $endDate */
/** @var int $saIdx */
/** @var string $catFilter */
/** @var string $mode */
/** @var list<object> $agencies */
/** @var array<string,string> $catLabels */
/** @var bool $hasBsFee */
/** @var string $lgName */
/** @var string $agencyLabel */
/** @var string $catLabelFilter */
/** @var list<string> $printExtraLines */

$byDaily = ($mode ?? 'daily') === 'daily';

$exportParams = array_filter([
    'start_date' => $startDate ?? '',
    'end_date' => $endDate ?? '',
    'sa_idx' => (int) ($saIdx ?? 0),
    'cat' => (string) ($catFilter ?? ''),
    'mode' => $byDaily ? '' : 'period',
    'export' => '1',
], static fn ($v): bool => $v !== '' && $v !== null);
$excelUrl = mgmt_url('reports/period-sales?' . http_build_query($exportParams));

$fmtFee = static function (float $v) use ($hasBsFee): string {
    if (! $hasBsFee) {
        return '—';
    }

    return number_format((int) round($v));
};

$rowClass = static function (string $kind): string {
    return match ($kind) {
        'day_sub_all' => 'bg-gray-100 font-semibold',
        'day_sub_bag' => 'bg-sky-50 font-semibold text-sky-900',
        'day_sub_fs' => 'bg-violet-50 font-semibold text-violet-900',
        'foot_all' => 'bg-red-50 font-bold text-red-700',
        'foot_bag' => 'bg-blue-50 font-bold text-blue-700',
        'foot_fs' => 'bg-purple-50 font-bold text-purple-800',
        default => '',
    };
};
?>
<?= 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">기간별 판매현황</span>
    <div class="flex flex-wrap 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 transition">인쇄</button>
      <a href="<?= esc($excelUrl, 'attr') ?>" class="inline-flex items-center border border-green-600 text-green-700 px-3 py-1 rounded-sm text-sm hover:bg-green-50 transition">엑셀저장</a>
    </div>
  </div>
</section>

<section class="p-3 bg-white border-b border-gray-200 no-print">
  <form method="GET" action="<?= mgmt_url('reports/period-sales') ?>" class="flex flex-wrap items-end gap-3 text-sm">
    <div>
      <label class="block text-gray-600 mb-0.5">시작일</label>
      <input type="date" name="start_date" value="<?= esc($startDate ?? '') ?>" class="border border-gray-300 rounded px-2 py-1 text-sm"/>
    </div>
    <div>
      <label class="block text-gray-600 mb-0.5">종료일</label>
      <input type="date" name="end_date" value="<?= esc($endDate ?? '') ?>" class="border border-gray-300 rounded px-2 py-1 text-sm"/>
    </div>
    <div>
      <label class="block text-gray-600 mb-0.5">대행소</label>
      <select name="sa_idx" class="border border-gray-300 rounded px-2 py-1 text-sm min-w-[12rem] max-w-[20rem]">
        <option value="0">전체</option>
        <?php foreach ($agencies ?? [] as $agency): ?>
          <?php $aid = (int) ($agency->sa_idx ?? 0); ?>
          <option value="<?= esc((string) $aid) ?>" <?= (int) ($saIdx ?? 0) === $aid ? 'selected' : '' ?>>
            <?= esc(trim((string) ($agency->sa_name ?? ''))) ?>
          </option>
        <?php endforeach; ?>
      </select>
    </div>
    <div>
      <label class="block text-gray-600 mb-0.5">구분</label>
      <select name="cat" class="border border-gray-300 rounded px-2 py-1 text-sm min-w-[10rem]">
        <option value="" <?= ($catFilter ?? '') === '' ? 'selected' : '' ?>>전체</option>
        <?php foreach (($catLabels ?? []) as $ck => $lab): ?>
          <option value="<?= esc($ck, 'attr') ?>" <?= ($catFilter ?? '') === $ck ? 'selected' : '' ?>><?= esc($lab) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div>
      <label class="block text-gray-600 mb-0.5">집계 방식</label>
      <select name="mode" class="border border-gray-300 rounded px-2 py-1 text-sm min-w-[9rem]">
        <option value="daily" <?= $byDaily ? 'selected' : '' ?>>일자별</option>
        <option value="period" <?= ! $byDaily ? 'selected' : '' ?>>기간별</option>
      </select>
    </div>
    <button type="submit" class="bg-btn-search text-white px-4 py-1.5 rounded-sm text-sm">조회</button>
  </form>
</section>

<section class="p-3 bg-white">
  <style>
    @media print {
      .period-sales-screen-title { display: none !important; }
    }
  </style>
  <div class="mb-2 text-center period-sales-screen-title no-print">
    <h1 class="text-lg font-bold m-0">기간별 판매현황<?= $byDaily ? ' [일집계]' : ' [기간집계]' ?></h1>
    <p class="text-sm text-gray-700 m-1"><?= esc(trim(($lgName ?? '') . ' · ' . ($startDate ?? '') . ' ~ ' . ($endDate ?? '') . ' · 대행소: ' . ($agencyLabel ?? '') . ' · 구분: ' . ($catLabelFilter ?? ''))) ?></p>
    <p class="text-xs text-gray-500 m-0">집계: <?= $byDaily ? '일자별' : '기간별' ?> · (단위: 매 / 원)</p>
  </div>

  <div class="border border-gray-300 rounded-lg p-4 overflow-auto">
    <table class="w-full data-table text-sm" id="period-sales-table">
      <thead>
        <tr>
          <?php if ($byDaily): ?>
            <th rowspan="2" class="align-middle whitespace-nowrap text-center">일자</th>
          <?php endif; ?>
          <th rowspan="2" class="align-middle text-left pl-2">품목</th>
          <th colspan="4" class="text-center border-l border-gray-300">판매</th>
          <th colspan="2" class="text-center border-l border-gray-300">반품</th>
          <th colspan="4" class="text-center border-l border-gray-300">계</th>
        </tr>
        <tr>
          <th class="text-right border-l border-gray-300">수량</th>
          <th class="text-right">판매금액</th>
          <th class="text-right">수수료</th>
          <th class="text-right">징수액</th>
          <th class="text-right border-l border-gray-300">수량</th>
          <th class="text-right">금액</th>
          <th class="text-right border-l border-gray-300">수량</th>
          <th class="text-right">판매금액</th>
          <th class="text-right">수수료</th>
          <th class="text-right">징수액</th>
        </tr>
      </thead>
      <tbody class="text-right">
        <?php
          $emptyColspan = $byDaily ? 12 : 11;
        ?>
        <?php foreach ($lines ?? [] as $ln): ?>
          <?php
            $kind = (string) ($ln['kind'] ?? 'data');
            $trCls = $rowClass($kind);
            $isData = $kind === 'data';
            $rs = (int) ($ln['ymd_rowspan'] ?? 0);
          ?>
          <tr class="<?= esc($trCls, 'attr') ?>">
            <?php if ($byDaily): ?>
              <?php if ($isData && $rs > 0): ?>
                <td rowspan="<?= $rs ?>" class="text-center align-top whitespace-nowrap tabular-nums pt-1"><?= esc((string) ($ln['ymd'] ?? '')) ?></td>
              <?php elseif (str_starts_with($kind, 'foot_')): ?>
                <td class="bg-inherit"></td>
              <?php endif; ?>
            <?php endif; ?>
            <td class="text-left pl-2"><?= esc((string) ($ln['name'] ?? '')) ?></td>
            <td class="border-l border-gray-200 tabular-nums"><?= number_format((int) ($ln['s_qty'] ?? 0)) ?></td>
            <td class="tabular-nums"><?= number_format((int) round((float) ($ln['s_amt'] ?? 0))) ?></td>
            <td class="tabular-nums"><?= $fmtFee((float) ($ln['s_fee'] ?? 0)) ?></td>
            <td class="tabular-nums"><?= number_format((int) round((float) ($ln['s_levy'] ?? 0))) ?></td>
            <td class="border-l border-gray-200 tabular-nums"><?= number_format((int) ($ln['r_qty'] ?? 0)) ?></td>
            <td class="tabular-nums"><?= number_format((int) round((float) ($ln['r_amt'] ?? 0))) ?></td>
            <td class="border-l border-gray-200 tabular-nums"><?= number_format((int) ($ln['t_qty'] ?? 0)) ?></td>
            <td class="tabular-nums"><?= number_format((int) round((float) ($ln['t_amt'] ?? 0))) ?></td>
            <td class="tabular-nums"><?= $fmtFee((float) ($ln['t_fee'] ?? 0)) ?></td>
            <td class="tabular-nums"><?= number_format((int) round((float) ($ln['t_levy'] ?? 0))) ?></td>
          </tr>
        <?php endforeach; ?>
        <?php if (($lines ?? []) === []): ?>
          <tr>
            <td colspan="<?= (int) $emptyColspan ?>" class="text-center text-gray-400 py-6">조회된 데이터가 없습니다.</td>
          </tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</section>
