<?php
$orders = is_array($orders ?? null) ? $orders : [];
$companyMap = is_array($companyMap ?? null) ? $companyMap : [];
$itemSummary = is_array($itemSummary ?? null) ? $itemSummary : [];
$companies = is_array($companies ?? null) ? $companies : [];
$startMonthValue = (string) ($startMonth ?? date('Y-m'));
$endMonthValue = (string) ($endMonth ?? date('Y-m'));
$baseYear = (int) date('Y');
if (preg_match('/^(\d{4})-\d{2}$/', $startMonthValue, $sm)) {
  $baseYear = (int) $sm[1];
} elseif (preg_match('/^(\d{4})-\d{2}$/', $endMonthValue, $em)) {
  $baseYear = (int) $em[1];
}
$monthOptionValues = [];
for ($year = $baseYear - 2; $year <= $baseYear + 2; $year++) {
  for ($m = 1; $m <= 12; $m++) {
    $monthValue = sprintf('%04d-%02d', $year, $m);
    $monthOptionValues[] = ['value' => $monthValue, 'label' => $year . '년 ' . $m . '월'];
  }
}
?>

<section class="border-b border-gray-300 p-2 shrink-0 bg-control-panel">
  <span class="text-sm font-bold text-gray-700">LOT-No 디스켓 불출</span>
</section>

<section class="border border-gray-300 rounded-lg p-2 mt-2 bg-white">
  <form method="get" class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-6 gap-2 text-sm">
    <div class="flex items-center gap-2 min-w-0">
      <label class="font-bold text-gray-700 whitespace-nowrap shrink-0">시작월</label>
      <select id="start_month" name="start_month" class="border border-gray-300 rounded px-2 py-1 w-full min-w-0">
        <?php foreach ($monthOptionValues as $opt): ?>
        <option value="<?= esc($opt['value']) ?>" <?= $opt['value'] === $startMonthValue ? 'selected' : '' ?>><?= esc($opt['label']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="flex items-center gap-2 min-w-0">
      <label class="font-bold text-gray-700 whitespace-nowrap shrink-0">종료월</label>
      <select id="end_month" name="end_month" class="border border-gray-300 rounded px-2 py-1 w-full min-w-0">
        <?php foreach ($monthOptionValues as $opt): ?>
        <option value="<?= esc($opt['value']) ?>" <?= $opt['value'] === $endMonthValue ? 'selected' : '' ?>><?= esc($opt['label']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="flex items-center gap-2 min-w-0 xl:col-span-2">
      <label class="font-bold text-gray-700 whitespace-nowrap shrink-0">LOT-No</label>
      <input type="text" name="lot_no" value="<?= esc((string) ($lotNo ?? '')) ?>" placeholder="예: ZLCH2M" class="border border-gray-300 rounded px-2 py-1 w-full min-w-0" />
    </div>
    <div class="flex items-center gap-2 min-w-0">
      <label class="font-bold text-gray-700 whitespace-nowrap shrink-0">제작업체</label>
      <select name="company_idx" class="border border-gray-300 rounded px-2 py-1 w-full min-w-0">
        <option value="0">전체</option>
        <?php foreach ($companies as $company): ?>
        <?php $cpIdx = (int) ($company->cp_idx ?? 0); ?>
        <option value="<?= $cpIdx ?>" <?= (int) ($companyIdx ?? 0) === $cpIdx ? 'selected' : '' ?>>
          <?= esc((string) ($company->cp_name ?? '')) ?>
        </option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="flex items-center gap-2">
      <button type="submit" class="bg-btn-search text-white px-4 py-1.5 rounded-sm text-sm shadow hover:opacity-90 transition">조회</button>
      <a href="<?= base_url('bag/order/lot-seed') ?>" class="text-sm text-gray-500 hover:text-gray-700">초기화</a>
    </div>
  </form>
</section>

<section class="border border-gray-300 rounded-lg overflow-hidden mt-2 bg-white">
  <div class="border-b border-gray-300 bg-gray-50 px-2 py-1 text-sm font-bold text-gray-700">발주목록</div>
  <div class="overflow-auto">
  <table class="w-full data-table text-sm">
    <thead>
      <tr>
        <th class="w-20 text-center">작업</th>
        <th class="w-24 text-center">발주일</th>
        <th class="w-28 text-center">LOT-No</th>
        <th class="text-left">제작업체</th>
        <th class="w-24 text-right">품목수</th>
        <th class="w-24 text-right">박스합계</th>
        <th class="w-28 text-right">낱장합계</th>
        <th class="w-20 text-center">상태</th>
      </tr>
    </thead>
    <tbody>
      <?php if ($orders !== []): ?>
      <?php foreach ($orders as $order): ?>
      <?php
        $boIdx = (int) ($order->bo_idx ?? 0);
        $sum = $itemSummary[$boIdx] ?? ['line_count' => 0, 'qty_box' => 0, 'qty_sheet' => 0];
        $companyName = (string) ($companyMap[(int) ($order->bo_company_idx ?? 0)] ?? '-');
        $status = (string) ($order->bo_status ?? 'normal');
      ?>
      <tr>
        <td class="text-center">
          <form method="post" action="<?= base_url('bag/order/lot-seed/generate') ?>" class="inline">
            <?= csrf_field() ?>
            <input type="hidden" name="bo_idx" value="<?= $boIdx ?>" />
            <button type="submit" class="text-blue-600 hover:underline text-xs">seed 생성</button>
          </form>
        </td>
        <td class="text-center"><?= esc((string) ($order->bo_order_date ?? '')) ?></td>
        <td class="text-center font-mono"><?= esc((string) ($order->bo_lot_no ?? '')) ?></td>
        <td class="pl-2"><?= esc($companyName) ?></td>
        <td class="text-right pr-2"><?= number_format((int) ($sum['line_count'] ?? 0)) ?></td>
        <td class="text-right pr-2"><?= number_format((int) ($sum['qty_box'] ?? 0)) ?></td>
        <td class="text-right pr-2"><?= number_format((int) ($sum['qty_sheet'] ?? 0)) ?></td>
        <td class="text-center">
          <?php if ($status === 'cancelled'): ?>
          <span class="text-orange-600">취소</span>
          <?php elseif ($status === 'deleted'): ?>
          <span class="text-red-600">삭제</span>
          <?php else: ?>
          정상
          <?php endif; ?>
        </td>
      </tr>
      <?php endforeach; ?>
      <?php else: ?>
      <tr>
        <td colspan="8" class="text-center text-gray-400 py-4">조회된 발주가 없습니다.</td>
      </tr>
      <?php endif; ?>
    </tbody>
  </table>
  </div>
</section>

<?php if (isset($pager)): ?>
<div class="mt-2 mb-2 no-print"><?= $pager->links() ?></div>
<?php endif; ?>
