<?php
declare(strict_types=1);
/** @var list<object> $codeKinds */
/** @var array<int,int> $countMap */
/** @var bool $canManageKinds */
/** @var bool $canManageDetails */
/** @var object|null $selectedKind */
/** @var list<object> $detailList */
/** @var array<int,bool> $rowCanEdit */
/** @var int $totalCount */
/** @var array<string,string> $filters */
/** @var string $pageBaseUrl */

$canManageKinds   = ! empty($canManageKinds);
$canManageDetails = ! empty($canManageDetails);
$selectedKindId   = (int) ($selectedKind->ck_idx ?? 0);
$filters          = is_array($filters ?? null) ? $filters : [];
$activeVariant    = (string) ($activeVariant ?? 'base');
$pageBaseUrl      = (string) ($pageBaseUrl ?? site_url(gov_portal_code_kinds_portal_path($activeVariant)));

$buildUrl = static function (array $extra = []) use ($filters, $selectedKindId, $pageBaseUrl): string {
    $q = array_merge([
        'search' => '1',
        'q_code' => $filters['q_code'] ?? '',
        'q_name' => $filters['q_name'] ?? '',
        'q_state' => $filters['q_state'] ?? '',
        'ck_idx' => $selectedKindId > 0 ? (string) $selectedKindId : '',
    ], $extra);
    foreach ($q as $k => $v) {
        if ($v === '' || $v === null) {
            unset($q[$k]);
        }
    }

    return $pageBaseUrl . '?' . http_build_query($q);
};
?>
<nav class="work-breadcrumb" aria-label="breadcrumb">
  <a href="<?= base_url($activeVariant === 'strip' ? 'dashboard/gov-portal-strip' : 'dashboard/gov-portal') ?>">Home</a>
  <span class="sep">&gt;</span>
  <span>시스템관리</span>
  <span class="sep">&gt;</span>
  <span>기본 코드관리(포털 UI 시안)</span>
</nav>

<div class="work-page-hd">
  <h1 class="work-page-title">
    <span>기본 코드관리</span>
    <span style="font-size:0.75rem;font-weight:600;color:#666;">포털 UI 시안</span>
    <i class="fa-regular fa-star fav" title="즐겨찾기(목업)" aria-hidden="true"></i>
  </h1>
  <div class="work-actions">
    <?php if ($canManageKinds): ?>
    <a href="<?= base_url('admin/code-kinds/create') ?>" class="btn-portal btn-portal-primary">
      <i class="fa-solid fa-plus"></i> 등록
    </a>
    <?php endif; ?>
    <a href="<?= base_url('bag/code-kinds') ?>" class="btn-portal btn-portal-secondary" title="운영 중인 기본 코드관리 화면">
      <i class="fa-solid fa-table-columns"></i> 운영 화면 (/bag/code-kinds)
    </a>
  </div>
</div>

<?php if (session()->getFlashdata('success')): ?>
<div class="flash-banner ok"><?= esc(session()->getFlashdata('success')) ?></div>
<?php endif; ?>
<?php if (session()->getFlashdata('error')): ?>
<div class="flash-banner err"><?= esc(session()->getFlashdata('error')) ?></div>
<?php endif; ?>

<form method="get" action="<?= esc($pageBaseUrl, 'attr') ?>" class="search-panel">
  <input type="hidden" name="search" value="1"/>
  <?php if ($selectedKindId > 0): ?>
  <input type="hidden" name="ck_idx" value="<?= $selectedKindId ?>"/>
  <?php endif; ?>
  <table>
    <tbody>
      <tr>
        <th>코드</th>
        <td><input type="text" name="q_code" value="<?= esc($filters['q_code'] ?? '') ?>" placeholder="종류 코드"/></td>
        <th>코드명</th>
        <td><input type="text" name="q_name" value="<?= esc($filters['q_name'] ?? '') ?>" placeholder="종류명"/></td>
        <th>사용여부</th>
        <td>
          <select name="q_state">
            <option value="">전체</option>
            <option value="1" <?= ($filters['q_state'] ?? '') === '1' ? 'selected' : '' ?>>사용</option>
            <option value="0" <?= ($filters['q_state'] ?? '') === '0' ? 'selected' : '' ?>>미사용</option>
          </select>
        </td>
      </tr>
    </tbody>
  </table>
  <div class="search-panel-foot">
    <a href="<?= esc($pageBaseUrl, 'attr') ?>" class="btn-portal btn-portal-reset">
      <i class="fa-solid fa-rotate-left"></i> 초기화
    </a>
    <button type="submit" class="btn-portal btn-portal-search">
      <i class="fa-solid fa-magnifying-glass"></i> 검색
    </button>
  </div>
</form>

<section aria-labelledby="codeKindTableLabel">
  <div class="table-toolbar">
    <div class="total">전체 <strong><?= number_format($totalCount) ?></strong> 건</div>
    <div class="tools">
      <span class="text-gray-500">코드 종류</span>
    </div>
  </div>
  <div class="portal-data-table-wrap">
    <table class="portal-data-table" id="codeKindTableLabel">
      <thead>
        <tr>
          <th class="w-12">번호</th>
          <th class="w-20">코드</th>
          <th>코드명</th>
          <th class="w-20">세부코드</th>
          <th class="w-16">사용여부</th>
          <th class="w-28">등록일</th>
          <?php if ($canManageKinds): ?>
          <th class="w-24">작업</th>
          <?php endif; ?>
        </tr>
      </thead>
      <tbody>
      <?php if ($codeKinds !== []): ?>
        <?php $i = 0; foreach ($codeKinds as $row): $i++; ?>
        <?php $isSelected = (int) $row->ck_idx === $selectedKindId; ?>
        <tr class="<?= $isSelected ? 'is-selected' : '' ?>"
            onclick="window.location.href='<?= esc($buildUrl(['ck_idx' => (string) $row->ck_idx]), 'attr') ?>'"
            style="cursor:pointer">
          <td><?= (string) $i ?></td>
          <td class="font-mono"><?= esc($row->ck_code) ?></td>
          <td class="text-left"><?= esc($row->ck_name) ?></td>
          <td><?= (int) ($countMap[$row->ck_idx] ?? 0) ?>개</td>
          <td><?= (int) ($row->ck_state ?? 0) === 1 ? '사용' : '미사용' ?></td>
          <td><?= esc($row->ck_regdate ?? '') ?></td>
          <?php if ($canManageKinds): ?>
          <td onclick="event.stopPropagation()">
            <a href="<?= base_url('admin/code-kinds/edit/' . (int) $row->ck_idx) ?>">수정</a>
          </td>
          <?php endif; ?>
        </tr>
        <?php endforeach; ?>
      <?php else: ?>
        <tr class="empty-row">
          <td colspan="<?= $canManageKinds ? '7' : '6' ?>">등록된 코드 종류가 없습니다.</td>
        </tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</section>

<?php if ($selectedKind !== null): ?>
<section class="detail-section" aria-labelledby="codeDetailTableLabel">
  <h2 class="detail-section-hd" id="codeDetailTableLabel">
    세부코드 — <?= esc($selectedKind->ck_name) ?> (<?= esc($selectedKind->ck_code) ?>)
  </h2>
  <div class="table-toolbar">
    <div class="total">세부 <strong><?= number_format(count($detailList)) ?></strong> 건</div>
    <div class="tools">
      <?php if ($canManageDetails): ?>
      <a href="<?= base_url('admin/code-details/' . (int) $selectedKind->ck_idx . '/create') ?>" class="btn-portal btn-portal-primary">
        <i class="fa-solid fa-plus"></i> 세부코드 등록
      </a>
      <?php endif; ?>
    </div>
  </div>
  <div class="portal-data-table-wrap">
    <table class="portal-data-table">
      <thead>
        <tr>
          <th>번호</th>
          <th>코드</th>
          <th>코드명</th>
          <th>범위</th>
          <th>정렬</th>
          <th>사용여부</th>
          <th>등록일</th>
          <?php if ($canManageDetails): ?>
          <th>작업</th>
          <?php endif; ?>
        </tr>
      </thead>
      <tbody>
      <?php if ($detailList !== []): ?>
        <?php $dNo = 0; foreach ($detailList as $row): $dNo++; ?>
        <?php
          $isPlatform = (($row->cd_source ?? 'platform') === 'platform' && (int) ($row->cd_lg_idx ?? 0) === 0);
          $scopeLabel = $isPlatform ? '공통' : '지자체';
        ?>
        <tr>
          <td><?= (string) $dNo ?></td>
          <td class="font-mono"><?= esc($row->cd_code) ?></td>
          <td class="text-left"><?= esc($row->cd_name) ?></td>
          <td><?= esc($scopeLabel) ?></td>
          <td><?= (int) ($row->cd_sort ?? 0) ?></td>
          <td><?= (int) ($row->cd_state ?? 0) === 1 ? '사용' : '미사용' ?></td>
          <td><?= esc($row->cd_regdate ?? '') ?></td>
          <?php if ($canManageDetails): ?>
          <td>
            <?php if (! empty($rowCanEdit[$row->cd_idx])): ?>
            <a href="<?= base_url('admin/code-details/edit/' . (int) $row->cd_idx) ?>">수정</a>
            <?php else: ?>
            <span style="color:#aaa">—</span>
            <?php endif; ?>
          </td>
          <?php endif; ?>
        </tr>
        <?php endforeach; ?>
      <?php else: ?>
        <tr class="empty-row">
          <td colspan="<?= $canManageDetails ? '8' : '7' ?>">등록된 세부코드가 없습니다.</td>
        </tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</section>
<?php elseif ($codeKinds !== []): ?>
<p style="font-size:0.75rem;color:#888;margin-top:0.75rem;">위 표에서 코드 종류를 선택하면 세부코드가 표시됩니다.</p>
<?php endif; ?>
