<?php $s = $stats ?? []; ?>

<?php if (!($lgIdx ?? null)): ?>
<div class="border border-orange-300 bg-orange-50 p-4 text-sm text-orange-700">
  작업할 지자체가 선택되지 않았습니다. 상단에서 지자체를 선택해 주세요.
</div>
<?php else: ?>

<?php if (! empty($s['stats_unavailable'])): ?>
<div class="border border-amber-300 bg-amber-50 p-4 text-sm text-amber-900 mb-4">
  발주·판매·재고·불출 통계 테이블이 아직 없거나 조회에 실패했습니다. MySQL에서
  <code class="text-xs bg-white px-1 rounded">writable/database/order_tables.sql</code>과
  <code class="text-xs bg-white px-1 rounded">writable/database/sales_tables.sql</code>을
  <code class="text-xs bg-white px-1 rounded">jongryangje_dev</code> DB에 실행해 주세요.
</div>
<?php endif; ?>

<!-- 통계 카드 -->
<div class="grid grid-cols-2 md:grid-cols-4 gap-3 mb-4">
  <div class="border border-gray-300 rounded-lg p-4 bg-white">
    <div class="text-xs text-gray-500">총 발주 건수</div>
    <div class="text-2xl font-bold text-blue-700"><?= number_format($s['order_count'] ?? 0) ?></div>
    <div class="text-xs text-gray-400 mt-1">금액: <?= number_format($s['order_amount'] ?? 0) ?>원</div>
  </div>
  <div class="border border-gray-300 rounded-lg p-4 bg-white">
    <div class="text-xs text-gray-500">총 판매 건수</div>
    <div class="text-2xl font-bold text-green-700"><?= number_format($s['sale_count'] ?? 0) ?></div>
    <div class="text-xs text-gray-400 mt-1">금액: <?= number_format($s['sale_amount'] ?? 0) ?>원</div>
  </div>
  <div class="border border-gray-300 rounded-lg p-4 bg-white">
    <div class="text-xs text-gray-500">재고 품목 수</div>
    <div class="text-2xl font-bold text-purple-700"><?= number_format($s['inventory_count'] ?? 0) ?></div>
    <div class="text-xs text-gray-400 mt-1">현재 재고가 있는 봉투 품목</div>
  </div>
  <div class="border border-gray-300 rounded-lg p-4 bg-white">
    <div class="text-xs text-gray-500">이번 달 불출</div>
    <div class="text-2xl font-bold text-orange-700"><?= number_format($s['issue_count_month'] ?? 0) ?></div>
    <div class="text-xs text-gray-400 mt-1"><?= date('Y년 n월') ?> 무료용 불출</div>
  </div>
</div>

<!-- 최근 내역 -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
  <!-- 최근 발주 -->
  <div>
    <div class="flex items-center justify-between mb-1">
      <h3 class="text-sm font-bold text-gray-700">최근 발주 5건</h3>
      <a href="<?= base_url('bag/bag-orders') ?>" class="text-xs text-blue-600 hover:underline">전체보기</a>
    </div>
    <div class="border border-gray-300 rounded-lg p-4 overflow-auto">
      <table class="w-full data-table">
        <thead>
          <tr>
            <th class="text-center">LOT번호</th>
            <th class="text-center">발주일</th>
            <th class="text-center">상태</th>
          </tr>
        </thead>
        <tbody class="text-center">
          <?php
            $statusMap = ['normal' => '정상', 'cancelled' => '취소', 'deleted' => '삭제'];
            foreach (($s['recent_orders'] ?? []) as $order):
          ?>
          <tr>
            <td class="font-mono text-sm">
              <a href="<?= base_url('bag/bag-orders/detail/' . (int) $order->bo_idx) ?>" class="text-blue-600 hover:underline"><?= esc($order->bo_lot_no) ?></a>
            </td>
            <td><?= esc($order->bo_order_date) ?></td>
            <td>
              <?php
                $stClass = match($order->bo_status) {
                    'cancelled' => 'text-red-600',
                    'deleted'   => 'text-gray-400',
                    default     => 'text-green-600',
                };
              ?>
              <span class="<?= $stClass ?>"><?= esc($statusMap[$order->bo_status] ?? $order->bo_status) ?></span>
            </td>
          </tr>
          <?php endforeach; ?>
          <?php if (empty($s['recent_orders'])): ?>
          <tr><td colspan="3" class="text-gray-400 py-3">발주 내역이 없습니다.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <!-- 최근 판매 -->
  <div>
    <div class="flex items-center justify-between mb-1">
      <h3 class="text-sm font-bold text-gray-700">최근 판매 5건</h3>
      <a href="<?= base_url('bag/bag-sales') ?>" class="text-xs text-blue-600 hover:underline">전체보기</a>
    </div>
    <div class="border border-gray-300 rounded-lg p-4 overflow-auto">
      <table class="w-full data-table">
        <thead>
          <tr>
            <th class="text-left pl-2">판매소</th>
            <th class="text-left pl-2">봉투명</th>
            <th class="text-right">수량</th>
            <th class="text-right">금액</th>
            <th class="text-center">구분</th>
          </tr>
        </thead>
        <tbody class="text-right">
          <?php
            $typeMap = ['sale' => '판매', 'return' => '반품', 'cancel' => '취소'];
            foreach (($s['recent_sales'] ?? []) as $sale):
          ?>
          <tr>
            <td class="text-left pl-2"><?= esc($sale->bs_ds_name) ?></td>
            <td class="text-left pl-2"><?= esc($sale->bs_bag_name) ?></td>
            <td><?= number_format(abs((int) $sale->bs_qty)) ?></td>
            <td><?= number_format((int) $sale->bs_amount) ?></td>
            <td class="text-center"><?= esc($typeMap[$sale->bs_type] ?? $sale->bs_type) ?></td>
          </tr>
          <?php endforeach; ?>
          <?php if (empty($s['recent_sales'])): ?>
          <tr><td colspan="5" class="text-center text-gray-400 py-3">판매 내역이 없습니다.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php endif; ?>
