<?php
$baseYm = (string) ($baseYm ?? date('Y-m'));
$baseYmDot = str_replace('-', '.', $baseYm);
$trendBasis = (string) ($trendBasis ?? 'year_avg');
$deviationMin = (float) ($deviationMin ?? 0);
$queried = (bool) ($queried ?? false);
$filters = is_array($filters ?? null) ? $filters : [];
$rows = is_array($rows ?? null) ? $rows : [];
$agencies = is_array($filters['agencies'] ?? null) ? $filters['agencies'] : [];
$saIdx = (int) ($saIdx ?? 0);
$reportMeta = is_array($reportMeta ?? null) ? $reportMeta : [];
$shopCount = (int) ($reportMeta['shopCount'] ?? 0);
$monthSalesShops = (int) ($reportMeta['monthSalesShops'] ?? 0);
$error = (string) ($error ?? '');
$lgPickNotice = (string) ($lgPickNotice ?? '');
$prevAvgLabel = ($trendBasis ?? '') === 'month' ? '전년 동월' : '전년 평균';
?>
<?= view('components/print_header', [
    'printTitle'      => '월별 판매 추이 분석',
    'printExtraLines' => ['기준년월: ' . $baseYmDot, '(단위: 매)'],
]) ?>

<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/monthly-trend') ?>" 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="month" name="base_ym" value="<?= esc($baseYm) ?>" class="border border-gray-300 rounded px-2 py-1 min-w-[11rem] w-full max-w-[14rem]"/>
    </div>
    <div>
      <label class="block text-gray-600 mb-0.5">판매추이기준</label>
      <select name="trend_basis" class="border border-gray-300 rounded px-2 py-1 min-w-[12rem] w-full max-w-[16rem]">
        <option value="year_avg" <?= $trendBasis === 'year_avg' ? 'selected' : '' ?>>년 평균</option>
        <option value="month" <?= $trendBasis === 'month' ? 'selected' : '' ?>>동월(전년)</option>
      </select>
    </div>
    <div>
      <label class="block text-gray-600 mb-0.5">편차</label>
      <input type="number" name="deviation_min" value="<?= esc((string) $deviationMin) ?>" step="0.01" min="0" class="border border-gray-300 rounded px-2 py-1 w-28"/>
      <span class="text-gray-500">% 이상(절대값)</span>
    </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 min-w-[14rem] w-full max-w-[18rem]">
        <option value="0">전체</option>
        <?php foreach ($agencies as $agency): ?>
        <?php $aid = (int) ($agency->sa_idx ?? 0); ?>
        <option value="<?= $aid ?>" <?= $saIdx === $aid ? 'selected' : '' ?>><?= esc((string) ($agency->sa_name ?? '')) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <button type="submit" class="bg-btn-search text-white px-4 py-1 rounded-sm">조회</button>
  </form>
  <p class="text-xs text-gray-500 mt-1">(단위: 매) · <strong>판매(sale)</strong> 수량만 집계합니다(반품·취소 제외). <?= esc($prevAvgLabel) ?> 대비 기준월 편차를 표시합니다.</p>
</section>

<?php if ($error !== ''): ?>
<div class="m-2 p-3 border border-red-200 bg-red-50 text-sm text-red-800 no-print"><?= esc($error) ?></div>
<?php endif; ?>
<?php if ($lgPickNotice !== ''): ?>
<div class="m-2 p-3 border border-blue-200 bg-blue-50 text-sm text-blue-900 no-print"><?= esc($lgPickNotice) ?></div>
<?php endif; ?>

<?php if ($queried && $monthSalesShops === 0 && $shopCount > 0): ?>
<div class="m-2 p-3 border border-amber-200 bg-amber-50 text-sm text-amber-900 no-print">
  <strong><?= esc($baseYmDot) ?></strong> 기준월에 등록된 판매 실적이 없습니다.
  (지정판매소 <?= number_format($shopCount) ?>곳 · 해당 월 판매 <?= number_format($monthSalesShops) ?>곳)
  판매 데이터가 있는 월(예: 2026-05)로 기준년월을 바꿔 조회해 보세요.
</div>
<?php endif; ?>

<div class="m-2 border border-gray-300 rounded-lg overflow-hidden">
  <div class="bg-gray-100 px-3 py-1.5 text-sm font-bold border-b">월별 판매 추이 분석 조회 내역</div>
  <div class="overflow-auto max-h-[28rem]">
    <table class="w-full data-table text-sm">
      <thead>
        <tr>
          <th>대행소</th>
          <th class="w-24 text-center">판매소번호</th>
          <th>지정판매소</th>
          <th class="w-20 text-center">성명</th>
          <th class="w-20 text-right"><?= esc($prevAvgLabel) ?></th>
          <th class="w-20 text-right">월 판매량</th>
          <th class="w-20 text-right">평균 차</th>
          <th class="w-16 text-right">편차(%)</th>
          <th class="w-24 text-center">지정일자</th>
        </tr>
      </thead>
      <tbody>
        <?php if (! $queried): ?>
        <tr><td colspan="9" class="text-center text-gray-400 py-8">조회 조건 입력 후 조회</td></tr>
        <?php elseif ($rows === [] && $shopCount === 0): ?>
        <tr><td colspan="9" class="text-center text-gray-500 py-8">등록된 지정판매소가 없습니다.</td></tr>
        <?php elseif ($rows === []): ?>
        <tr><td colspan="9" class="text-center text-gray-500 py-8">편차 조건(|%|)에 맞는 자료가 없습니다. (0%이면 전체 표시)</td></tr>
        <?php endif; ?>
        <?php foreach ($rows as $row): ?>
        <tr>
          <td class="text-left pl-2"><?= esc((string) ($row['agency_name'] ?? '')) ?></td>
          <td class="text-center"><?= esc((string) ($row['shop_no'] ?? '')) ?></td>
          <td class="text-left pl-2"><?= esc((string) ($row['shop_name'] ?? '')) ?></td>
          <td class="text-center"><?= esc((string) ($row['rep_name'] ?? '')) ?></td>
          <td class="text-right tabular-nums"><?= number_format((int) ($row['prev_avg'] ?? 0)) ?></td>
          <td class="text-right tabular-nums"><?= number_format((int) ($row['monthly_qty'] ?? 0)) ?></td>
          <td class="text-right tabular-nums"><?= number_format((int) ($row['avg_diff'] ?? 0)) ?></td>
          <td class="text-right tabular-nums"><?= esc((string) ($row['deviation_pct'] ?? '0')) ?></td>
          <td class="text-center"><?= esc((string) ($row['designated_at'] ?? '')) ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
