<?php
  $month = $month ?? date('Y-m');
  $hubMode = in_array(($hubMode ?? 'meta'), ['price', 'meta', 'delete'], true) ? (string) ($hubMode ?? 'meta') : 'meta';
  $monthOptionValues = [];
  $y = (int) substr($month, 0, 4);
  for ($year = $y - 2; $year <= $y + 2; $year++) {
      for ($m = 1; $m <= 12; $m++) {
          $monthValue = sprintf('%04d-%02d', $year, $m);
          $monthOptionValues[] = ['value' => $monthValue, 'label' => $year . '년 ' . $m . '월'];
      }
  }
  $statusMap = ['normal' => '정상', 'cancelled' => '취소', 'deleted' => '삭제'];
?>

<section class="border-b border-gray-300 p-2 shrink-0 bg-control-panel flex flex-wrap items-center justify-between gap-2">
  <span class="text-sm font-bold text-gray-700">발주 변경</span>
  <a href="<?= base_url('bag/purchase-inbound') ?>" class="text-sm text-gray-600 hover:underline">발주 입고 관리로</a>
</section>

<div class="mt-2 space-y-3">
  <?php /* 플래시 메시지는 레이아웃(embed/portal)에서 한 번만 표시 — 중복 출력 방지 */ ?>

  <form method="get" action="<?= base_url('bag/order/change') ?>" class="border border-gray-300 rounded-lg bg-white p-3 flex flex-wrap items-end gap-4">
    <div class="flex items-center gap-2">
      <label for="hub_month" class="text-sm font-bold text-gray-700">발주월</label>
      <select id="hub_month" name="month" class="border border-gray-300 rounded px-2 py-1 w-44 text-sm">
        <?php foreach ($monthOptionValues as $opt): ?>
        <option value="<?= esc($opt['value']) ?>" <?= $opt['value'] === $month ? 'selected' : '' ?>><?= esc($opt['label']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <fieldset class="border border-gray-200 rounded px-3 py-2">
      <legend class="text-xs font-bold text-gray-600 px-1">변경 구분</legend>
      <div class="flex flex-wrap gap-x-4 gap-y-1 text-sm">
        <label class="inline-flex items-center gap-1 cursor-pointer">
          <input type="radio" name="hub_mode" value="price" <?= $hubMode === 'price' ? 'checked' : '' ?> />
          <span>발주·도매·판매 단가</span>
        </label>
        <label class="inline-flex items-center gap-1 cursor-pointer">
          <input type="radio" name="hub_mode" value="meta" <?= $hubMode === 'meta' ? 'checked' : '' ?> />
          <span>업체·수수료·협회·발주</span>
        </label>
        <label class="inline-flex items-center gap-1 cursor-pointer">
          <input type="radio" name="hub_mode" value="delete" <?= $hubMode === 'delete' ? 'checked' : '' ?> />
          <span>발주 삭제</span>
        </label>
      </div>
    </fieldset>
    <button type="submit" class="bg-btn-search text-white px-4 py-1.5 rounded-sm text-sm shadow hover:opacity-90">조회</button>
  </form>

  <div class="grid grid-cols-1 lg:grid-cols-12 gap-2">
    <section class="lg:col-span-5 border border-gray-300 rounded-lg overflow-hidden 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 max-h-[min(420px,60vh)]">
        <table class="w-full data-table text-sm">
          <thead>
            <tr>
              <th class="w-28 text-center">발주일</th>
              <th class="text-left">제작업체</th>
              <th class="w-20 text-center">상태</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach (($monthOrders ?? []) as $row): ?>
            <?php
              $canEdit = ((string) ($row->bo_status ?? '')) === 'normal';
              $href = base_url('bag/order/revise/' . (int) $row->bo_idx . '?change_mode=' . rawurlencode($hubMode));
            ?>
            <tr class="<?= $canEdit ? '' : 'opacity-70' ?>">
              <td class="text-center">
                <?php if ($canEdit): ?>
                <a href="<?= esc($href) ?>" class="text-blue-600 hover:underline font-medium"><?= esc((string) ($row->bo_order_date ?? '')) ?></a>
                <?php else: ?>
                <span><?= esc((string) ($row->bo_order_date ?? '')) ?></span>
                <?php endif; ?>
              </td>
              <td class="text-left pl-2"><?= esc((string) ($companyMap[(int) ($row->bo_company_idx ?? 0)] ?? '-')) ?></td>
              <td class="text-center text-xs"><?= esc((string) ($statusMap[(string) ($row->bo_status ?? '')] ?? $row->bo_status)) ?></td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($monthOrders)): ?>
            <tr><td colspan="3" class="text-center text-gray-400 py-6">해당 월 발주가 없습니다.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </section>

    <section class="lg:col-span-7 border border-dashed border-gray-300 bg-gray-50 p-4 text-sm text-gray-600">
      <p class="font-bold text-gray-800 mb-2">안내</p>
      <ul class="list-disc pl-5 space-y-1">
        <li><strong class="text-gray-900">발주 삭제</strong>를 선택하고 <strong class="text-gray-900">조회</strong>하면 발주 삭제 화면으로 이동합니다 (해당 월에 정상 발주가 있을 때).</li>
        <li>그 외 변경 구분에서는 왼쪽 목록에서 <strong class="text-gray-900">발주일</strong>을 클릭하면 선택한 <strong class="text-gray-900">변경 구분</strong>으로 발주 변경 화면이 열립니다.</li>
        <li><strong class="text-gray-900">발주·도매·판매 단가</strong>: 품목별 단가를 수정해 저장합니다 (발주 변경 시에만).</li>
        <li><strong class="text-gray-900">업체·수수료·협회·발주</strong>: 발주일·입고처·수량 등을 수정해 저장합니다.</li>
        <li><strong class="text-gray-900">발주 삭제</strong> 화면에서 목록을 선택해 삭제 처리합니다 (복구 불가에 가깝게 동작하므로 확인 후 진행하세요).</li>
      </ul>
    </section>
  </div>
</div>
