<?php
declare(strict_types=1);

/** @var string $startDate */
/** @var string $endDate */
/** @var string $zoneCode */
/** @var string $bagCode */
/** @var string $catFilter */
/** @var string $metric */
/** @var list<string> $zoneOptions */
/** @var array<string, string> $bagOptions */
/** @var array<string, string> $catLabels */
/** @var list<array<string, mixed>> $reportRows */
/** @var list<float> $grandMonths */
/** @var float $grandTotal */
/** @var string $lgName */
/** @var string $zoneLabel */
/** @var string $bagLabel */
/** @var string $catLabelFilter */
/** @var string $metricLabel */
/** @var list<string> $printExtraLines */

$isAmt = ($metric ?? 'qty') === 'amt';
$fmtVal = static function (float $v) use ($isAmt): string {
    return number_format((int) round($v));
};

$exportParams = array_merge([
    'start_date' => $startDate ?? '',
    'end_date' => $endDate ?? '',
    'metric' => ($metric ?? 'qty') === 'amt' ? 'amt' : 'qty',
    'export' => '1',
], array_filter([
    'zone_code' => (string) ($zoneCode ?? ''),
    'bag_code' => (string) ($bagCode ?? ''),
    'cat' => (string) ($catFilter ?? ''),
], static fn ($v): bool => $v !== '' && $v !== null));

$excelUrl = mgmt_url('reports/shop-sales?' . http_build_query($exportParams));
$colCount = 16;
?>
<?= 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>
  <p class="text-xs text-gray-500 mt-2">
    <?php if ($isAmt): ?>
      금액은 조회기간 내 판매(sale) 건의 판매금액을 거래 월별로 합산합니다(반품·취소는 제외).
    <?php else: ?>
      수량은 반품·판매취소를 연초부터 판매와 품목별 선입선출로 맞추고, 반품취소는 원복합니다. 조회에 포함되지 않은 달의 수치는 조회 구간의 첫 달에 합쳐 집계됩니다.
    <?php endif; ?>
  </p>
</section>

<section class="p-3 bg-white border-b border-gray-200 no-print">
  <form method="GET" action="<?= mgmt_url('reports/shop-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="zone_code" class="border border-gray-300 rounded px-2 py-1 text-sm min-w-[8rem] max-w-[16rem]">
        <option value="">전체</option>
        <?php foreach ($zoneOptions ?? [] as $z): ?>
          <option value="<?= esc($z, 'attr') ?>" <?= ($zoneCode ?? '') === $z ? 'selected' : '' ?>><?= esc($z) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div>
      <label class="block text-gray-600 mb-0.5">봉투 종류</label>
      <select name="bag_code" class="border border-gray-300 rounded px-2 py-1 text-sm min-w-[10rem] max-w-[20rem]">
        <option value="">전체</option>
        <?php foreach (($bagOptions ?? []) as $bc => $bn): ?>
          <option value="<?= esc((string) $bc, 'attr') ?>" <?= ($bagCode ?? '') === (string) $bc ? 'selected' : '' ?>>
            <?= esc(trim((string) $bc . (($bn ?? '') !== '' ? ' · ' . $bn : ''))) ?>
          </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-[9rem]">
        <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>
    <fieldset class="border border-gray-200 rounded px-2 py-1">
      <legend class="text-xs text-gray-600 px-1">집계 대상</legend>
      <label class="inline-flex items-center gap-1 mr-3 cursor-pointer">
        <input type="radio" name="metric" value="qty" <?= ! $isAmt ? 'checked' : '' ?>/>
        <span>수량</span>
      </label>
      <label class="inline-flex items-center gap-1 cursor-pointer">
        <input type="radio" name="metric" value="amt" <?= $isAmt ? 'checked' : '' ?>/>
        <span>금액</span>
      </label>
    </fieldset>
    <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 shop-sales-report-section">
  <style>
    @media print {
      @page {
        size: A4 landscape;
        margin: 5mm 6mm;
      }
      .shop-sales-report-section { padding: 0 !important; }
      .shop-sales-scroll-wrap {
        overflow: visible !important;
        border: 1px solid #333 !important;
      }
      #shop-sales-table {
        font-size: 7pt !important;
        width: 100% !important;
        table-layout: fixed !important;
      }
      #shop-sales-table th,
      #shop-sales-table td {
        min-width: 0 !important;
        padding: 1px 2px !important;
        white-space: normal !important;
        word-break: break-word;
        overflow-wrap: anywhere;
        line-height: 1.12;
        vertical-align: top;
      }
      #shop-sales-table th { font-size: 6.5pt !important; }
    }
    @media screen {
      #shop-sales-table td.num-cell { white-space: nowrap; }
    }
  </style>
  <div class="mb-2 text-center no-print">
    <h1 class="text-lg font-bold m-0">지정 판매소별 판매현황</h1>
    <p class="text-sm text-gray-700 m-1"><?= esc(trim(($lgName ?? '') . ' · ' . ($startDate ?? '') . ' ~ ' . ($endDate ?? '') . ' · 읍면동: ' . ($zoneLabel ?? '') . ' · 집계: ' . ($metricLabel ?? ''))) ?></p>
    <p class="text-xs text-gray-500 m-0"><?= $isAmt ? '(단위: 원)' : '(단위: 매)' ?></p>
  </div>

  <div class="shop-sales-scroll-wrap border border-gray-300 rounded-lg p-4 overflow-x-auto">
    <table class="w-full data-table text-xs" id="shop-sales-table">
      <colgroup>
        <col style="width: 14%;"/>
        <col style="width: 7%;"/>
        <col style="width: 16%;"/>
        <col style="width: 6%;"/>
        <?php for ($i = 0; $i < 12; $i++): ?>
        <col style="width: <?= esc((string) round(57 / 12, 2), 'attr') ?>%;"/>
        <?php endfor; ?>
      </colgroup>
      <thead>
        <tr>
          <th class="text-left pl-2">지정판매소</th>
          <th class="text-center">대표자명</th>
          <th class="text-left pl-1">주소</th>
          <th class="text-right">합계</th>
          <?php for ($m = 1; $m <= 12; $m++): ?>
            <th class="text-right"><?= $m ?>월</th>
          <?php endfor; ?>
        </tr>
      </thead>
      <tbody class="text-right">
        <?php foreach ($reportRows ?? [] as $rw): ?>
          <tr>
            <td class="text-left pl-2 font-medium"><?= esc((string) ($rw['name'] ?? '')) ?></td>
            <td class="text-center"><?= esc((string) ($rw['rep'] ?? '')) ?></td>
            <td class="text-left pl-1"><?= esc((string) ($rw['address'] ?? '')) ?></td>
            <td class="num-cell tabular-nums"><?= $fmtVal((float) ($rw['total'] ?? 0)) ?></td>
            <?php foreach (($rw['months'] ?? []) as $mv): ?>
              <td class="num-cell tabular-nums"><?= $fmtVal((float) $mv) ?></td>
            <?php endforeach; ?>
          </tr>
        <?php endforeach; ?>
        <?php if (($reportRows ?? []) === []): ?>
          <tr>
            <td colspan="<?= (int) $colCount ?>" class="text-center text-gray-400 py-6">조회된 데이터가 없습니다.</td>
          </tr>
        <?php else: ?>
          <tr class="bg-gray-100 font-bold">
            <td colspan="3" class="text-center">전체 합계</td>
            <td class="num-cell tabular-nums"><?= $fmtVal((float) ($grandTotal ?? 0)) ?></td>
            <?php foreach (($grandMonths ?? []) as $gm): ?>
              <td class="num-cell tabular-nums"><?= $fmtVal((float) $gm) ?></td>
            <?php endforeach; ?>
          </tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</section>
<script>
(function () {
  const metric = <?= json_encode($isAmt ? 'amt' : 'qty', JSON_THROW_ON_ERROR) ?>;
  const start = <?= json_encode((string) ($startDate ?? ''), JSON_THROW_ON_ERROR) ?>;
  const end = <?= json_encode((string) ($endDate ?? ''), JSON_THROW_ON_ERROR) ?>;
  let savedTitle = document.title;
  function stamp() {
    const d = new Date();
    const p = (n) => String(n).padStart(2, '0');
    return d.getFullYear() + p(d.getMonth() + 1) + p(d.getDate()) + '_' + p(d.getHours()) + p(d.getMinutes()) + p(d.getSeconds());
  }
  window.addEventListener('beforeprint', function () {
    savedTitle = document.title;
    document.title = '지정판매소별판매현황_' + metric + '_' + start + '_' + end + '_' + stamp();
  });
  window.addEventListener('afterprint', function () {
    document.title = savedTitle;
  });
})();
</script>
