<?php

declare(strict_types=1);

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\CodeKindModel;
use App\Models\CodeDetailModel;
use App\Models\LocalGovernmentModel;
use CodeIgniter\HTTP\RedirectResponse;
use Config\Roles;

class CodeDetail extends BaseController
{
    private CodeKindModel $kindModel;
    private CodeDetailModel $detailModel;

    public function __construct()
    {
        $this->kindModel   = model(CodeKindModel::class);
        $this->detailModel = model(CodeDetailModel::class);
    }

    private function redirectIfCannotManageCodeMaster(): ?RedirectResponse
    {
        if (! Roles::canManageCodeMaster((int) session()->get('mb_level'))) {
            return redirect()->to(site_url('bag/code-kinds'))->with('error', '코드 관리 권한이 없습니다.');
        }

        return null;
    }

    /** @deprecated 사이트 URL 유지용 — 세부 목록은 /bag/code-details/{ck_idx} */
    public function index(int $ckIdx): RedirectResponse
    {
        return redirect()->to(site_url('bag/code-details/' . $ckIdx));
    }

    public function create(int $ckIdx)
    {
        if ($r = $this->redirectIfCannotManageCodeMaster()) {
            return $r;
        }

        $kind = $this->kindModel->find($ckIdx);
        if ($kind === null) {
            return redirect()->to(site_url('bag/code-kinds'))->with('error', '코드 종류를 찾을 수 없습니다.');
        }

        $level            = (int) session()->get('mb_level');
        $canPlatformScope = Roles::isSuperAdminEquivalent($level);
        $govs             = $canPlatformScope
            ? model(LocalGovernmentModel::class)->where('lg_state', 1)->orderBy('lg_name', 'ASC')->findAll()
            : [];

        helper('admin');

        return $this->renderWorkPage('세부코드 등록 — ' . $kind->ck_name, 'admin/code_detail/create', [
            'kind'             => $kind,
            'canPlatformScope' => $canPlatformScope,
            'localGovernments' => $govs,
            'effectiveLgIdx'   => admin_effective_lg_idx(),
        ]);
    }

    public function store()
    {
        if ($r = $this->redirectIfCannotManageCodeMaster()) {
            return $r;
        }

        $rules = [
            'cd_ck_idx' => 'required|is_natural_no_zero',
            'cd_code'   => 'required|max_length[50]',
            'cd_name'   => 'required|max_length[100]',
            'cd_sort'   => 'permit_empty|is_natural',
        ];

        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $ckIdx = (int) $this->request->getPost('cd_ck_idx');
        $kind  = $this->kindModel->find($ckIdx);
        if ($kind === null) {
            return redirect()->to(site_url('bag/code-kinds'))->with('error', '코드 종류를 찾을 수 없습니다.');
        }

        helper('admin');
        $level = (int) session()->get('mb_level');

        if (Roles::isSuperAdminEquivalent($level)) {
            $scope = $this->request->getPost('cd_scope') === 'local' ? 'local' : 'platform';
            if ($scope === 'platform') {
                $cdSource = 'platform';
                $cdLgIdx  = 0;
            } else {
                $cdLgIdx = (int) $this->request->getPost('cd_lg_idx');
                if ($cdLgIdx < 1) {
                    return redirect()->back()->withInput()->with('error', '지자체 전용인 경우 소속 지자체를 선택해 주세요.');
                }
                $gov = model(LocalGovernmentModel::class)->find($cdLgIdx);
                if ($gov === null) {
                    return redirect()->back()->withInput()->with('error', '유효하지 않은 지자체입니다.');
                }
                $cdSource = 'local';
            }
        } else {
            $lg = admin_effective_lg_idx();
            if ($lg === null || (int) $lg < 1) {
                return redirect()->to(site_url('bag/code-kinds'))->with('error', '지자체를 선택한 뒤 등록해 주세요.');
            }
            $cdSource = 'local';
            $cdLgIdx  = (int) $lg;
        }

        $cdCode = (string) $this->request->getPost('cd_code');
        $dup    = $this->detailModel->where('cd_ck_idx', $ckIdx)->where('cd_code', $cdCode)->where('cd_lg_idx', $cdLgIdx)->first();
        if ($dup !== null) {
            return redirect()->back()->withInput()->with('error', '같은 종류·코드값·소속 범위에 이미 등록된 행이 있습니다.');
        }

        $this->detailModel->insert([
            'cd_ck_idx'  => $ckIdx,
            'cd_source'  => $cdSource,
            'cd_lg_idx'  => $cdLgIdx,
            'cd_code'    => $cdCode,
            'cd_name'    => $this->request->getPost('cd_name'),
            'cd_sort'    => (int) ($this->request->getPost('cd_sort') ?: 0),
            'cd_state'   => 1,
            'cd_regdate' => date('Y-m-d H:i:s'),
        ]);

        return redirect()->to(site_url('bag/code-details/' . $ckIdx))->with('success', '세부코드가 등록되었습니다.');
    }

    public function edit(int $id)
    {
        if ($r = $this->redirectIfCannotManageCodeMaster()) {
            return $r;
        }

        $item = $this->detailModel->find($id);
        if ($item === null) {
            return redirect()->to(site_url('bag/code-kinds'))->with('error', '세부코드를 찾을 수 없습니다.');
        }

        helper('admin');
        if (! Roles::canEditCodeDetailRow((int) session()->get('mb_level'), $item, admin_effective_lg_idx())) {
            return redirect()->to(site_url('bag/code-details/' . $item->cd_ck_idx))->with('error', '이 세부코드를 수정할 권한이 없습니다.');
        }

        $kind = $this->kindModel->find($item->cd_ck_idx);

        return $this->renderWorkPage('세부코드 수정 — ' . ($kind->ck_name ?? ''), 'admin/code_detail/edit', [
            'item' => $item,
            'kind' => $kind,
        ]);
    }

    public function update(int $id)
    {
        if ($r = $this->redirectIfCannotManageCodeMaster()) {
            return $r;
        }

        $item = $this->detailModel->find($id);
        if ($item === null) {
            return redirect()->to(site_url('bag/code-kinds'))->with('error', '세부코드를 찾을 수 없습니다.');
        }

        helper('admin');
        if (! Roles::canEditCodeDetailRow((int) session()->get('mb_level'), $item, admin_effective_lg_idx())) {
            return redirect()->to(site_url('bag/code-details/' . $item->cd_ck_idx))->with('error', '이 세부코드를 수정할 권한이 없습니다.');
        }

        $rules = [
            'cd_name'  => 'required|max_length[100]',
            'cd_sort'  => 'permit_empty|is_natural',
            'cd_state' => 'required|in_list[0,1]',
        ];

        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $this->detailModel->update($id, [
            'cd_name'  => $this->request->getPost('cd_name'),
            'cd_sort'  => (int) ($this->request->getPost('cd_sort') ?: 0),
            'cd_state' => (int) $this->request->getPost('cd_state'),
        ]);

        return redirect()->to(site_url('bag/code-details/' . $item->cd_ck_idx))->with('success', '세부코드가 수정되었습니다.');
    }

    public function delete(int $id)
    {
        if ($r = $this->redirectIfCannotManageCodeMaster()) {
            return $r;
        }

        $item = $this->detailModel->find($id);
        if ($item === null) {
            return redirect()->to(site_url('bag/code-kinds'))->with('error', '세부코드를 찾을 수 없습니다.');
        }

        helper('admin');
        if (! Roles::canEditCodeDetailRow((int) session()->get('mb_level'), $item, admin_effective_lg_idx())) {
            return redirect()->to(site_url('bag/code-details/' . $item->cd_ck_idx))->with('error', '이 세부코드를 삭제할 권한이 없습니다.');
        }

        $ckIdx = $item->cd_ck_idx;
        $this->detailModel->delete($id);

        return redirect()->to(site_url('bag/code-details/' . $ckIdx))->with('success', '세부코드가 삭제되었습니다.');
    }
}
