<?php

declare(strict_types=1);

namespace App\Libraries;

use App\Models\CodeDetailModel;
use App\Models\CodeKindModel;
use Config\Roles;

/**
 * 공공 포털형 기본 코드관리 UI 시안 전용 데이터 (/bag/code-kinds 와 별도 URL, 동일 집계)
 */
class GovPortalCodeKindsPage
{
    /**
     * @return array<string, mixed>
     */
    public function buildPageData(?int $lgIdx, int $level, ?int $adminLgIdx, int $selectedCkIdx, array $filters): array
    {
        $kindModel   = model(CodeKindModel::class);
        $detailModel = model(CodeDetailModel::class);
        $kinds       = [];
        $countMap    = [];
        $selectedKind = null;
        $detailList   = [];
        $rowCanEdit   = [];

        $qCode  = trim((string) ($filters['q_code'] ?? ''));
        $qName  = trim((string) ($filters['q_name'] ?? ''));
        $qState = (string) ($filters['q_state'] ?? '');

        try {
            $builder = $kindModel->orderBy('ck_code', 'ASC');
            if ($qCode !== '') {
                $builder->like('ck_code', $qCode);
            }
            if ($qName !== '') {
                $builder->like('ck_name', $qName);
            }
            if ($qState === '1' || $qState === '0') {
                $builder->where('ck_state', (int) $qState);
            }
            $kinds = $builder->findAll();
            foreach ($kinds as $row) {
                $countMap[$row->ck_idx] = (int) $detailModel->where('cd_ck_idx', $row->ck_idx)
                    ->filterByTenantScope($lgIdx)
                    ->countAllResults();
            }
        } catch (\Throwable $e) {
            log_message('error', '[GovPortalCodeKinds] {type} {message}', [
                'type'    => $e::class,
                'message' => $e->getMessage(),
            ]);
        }

        $canManageKinds   = Roles::canManageCodeKindMaster($level);
        $canManageDetails = Roles::canManageCodeMaster($level);

        if ($kinds !== []) {
            foreach ($kinds as $row) {
                if ((int) $row->ck_idx === $selectedCkIdx) {
                    $selectedKind = $row;
                    break;
                }
            }
            if ($selectedKind === null) {
                $selectedKind = $kinds[0];
            }
        }

        if ($selectedKind !== null) {
            $detailList = $detailModel->where('cd_ck_idx', (int) $selectedKind->ck_idx)
                ->filterByTenantScope($lgIdx)
                ->orderBy('cd_sort', 'ASC')
                ->orderBy('cd_code', 'ASC')
                ->orderBy('cd_idx', 'ASC')
                ->findAll();

            foreach ($detailList as $row) {
                $rowCanEdit[$row->cd_idx] = Roles::canEditCodeDetailRow($level, $row, $adminLgIdx);
            }
        }

        return [
            'codeKinds'        => $kinds,
            'countMap'         => $countMap,
            'canManageKinds'   => $canManageKinds,
            'canManageDetails' => $canManageDetails,
            'selectedKind'     => $selectedKind,
            'detailList'       => $detailList,
            'rowCanEdit'       => $rowCanEdit,
            'totalCount'       => count($kinds),
            'filters'          => [
                'q_code'  => $qCode,
                'q_name'  => $qName,
                'q_state' => $qState,
            ],
        ];
    }
}
