<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\FreeRecipientModel;
use App\Models\CodeKindModel;
use App\Models\CodeDetailModel;

class FreeRecipient extends BaseController
{
    private FreeRecipientModel $model;

    public function __construct()
    {
        $this->model = model(FreeRecipientModel::class);
    }

    /**
     * 무료용 대상 구분(스크린샷 기준): 사람뿐 아니라 동사무소 자체도 등록 가능.
     *
     * @return array<string,string>
     */
    private function recipientTypeOptions(): array
    {
        return [
            'office' => '읍.면.동 사무소',
            'target' => '무료 대상자',
        ];
    }

    private function getCodeOptions(string $ckCode): array
    {
        helper('admin');
        $lgIdx = admin_effective_lg_idx();
        $kind  = model(CodeKindModel::class)->where('ck_code', $ckCode)->first();

        return $kind ? model(CodeDetailModel::class)->getByKind((int) $kind->ck_idx, true, $lgIdx) : [];
    }

    public function index()
    {
        helper('admin');
        $lgIdx = admin_effective_lg_idx();
        if (! $lgIdx) {
            return redirect()->to(work_area_home_url())->with('error', '지자체를 선택해 주세요.');
        }

        $list  = $this->model
            ->where('fr_lg_idx', $lgIdx)
            ->orderBy('fr_type_code', 'ASC')
            ->orderBy('fr_name', 'ASC')
            ->orderBy('fr_idx', 'DESC')
            ->paginate(20);
        $pager = $this->model->pager;
        $perPage = 20;
        $currentPage = (int) ($pager->getCurrentPage() ?: 1);
        $totalCount = (int) $this->model
            ->where('fr_lg_idx', $lgIdx)
            ->countAllResults();
        $dongNameMap = [];
        foreach ($this->getCodeOptions('D') as $dong) {
            $code = (string) ($dong->cd_code ?? '');
            if ($code === '') {
                continue;
            }
            $dongNameMap[$code] = (string) ($dong->cd_name ?? $code);
        }

        return $this->renderWorkPage('무료용 대상자 관리', 'admin/free_recipient/index', [
            'list' => $list,
            'pager' => $pager,
            'recipientTypeOptions' => $this->recipientTypeOptions(),
            'dongNameMap' => $dongNameMap,
            'totalCount' => $totalCount,
            'currentPage' => $currentPage,
            'perPage' => $perPage,
        ]);
    }

    public function create()
    {
        return $this->renderWorkPage('무료용 대상자 등록', 'admin/free_recipient/create', [
            'recipientTypeOptions' => $this->recipientTypeOptions(),
            'dongCodes' => $this->getCodeOptions('D'),
        ]);
    }

    public function store()
    {
        helper('admin');
        $rules = [
            'fr_type_code' => 'required|max_length[20]',
            'fr_name'      => 'required|max_length[100]',
            'fr_end_date'  => 'permit_empty|valid_date[Y-m-d]',
        ];
        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $this->model->insert([
            'fr_lg_idx'    => admin_effective_lg_idx(),
            'fr_type_code' => $this->request->getPost('fr_type_code'),
            'fr_name'      => $this->request->getPost('fr_name'),
            'fr_phone'     => $this->request->getPost('fr_phone') ?? '',
            'fr_addr'      => $this->request->getPost('fr_addr') ?? '',
            'fr_dong_code' => $this->request->getPost('fr_dong_code') ?? '',
            'fr_note'      => $this->request->getPost('fr_note') ?? '',
            'fr_end_date'  => $this->request->getPost('fr_end_date') ?: null,
            'fr_state'     => 1,
            'fr_regdate'   => date('Y-m-d H:i:s'),
        ]);

        return redirect()->to(mgmt_url('free-recipients'))->with('success', '무료용 대상자가 등록되었습니다.');
    }

    public function edit(int $id)
    {
        helper('admin');
        $item = $this->model->find($id);
        if (! $item || (int) $item->fr_lg_idx !== admin_effective_lg_idx()) {
            return redirect()->to(mgmt_url('free-recipients'))->with('error', '대상자를 찾을 수 없습니다.');
        }

        return $this->renderWorkPage('무료용 대상자 수정', 'admin/free_recipient/edit', [
            'item'      => $item,
            'recipientTypeOptions' => $this->recipientTypeOptions(),
            'dongCodes' => $this->getCodeOptions('D'),
        ]);
    }

    public function update(int $id)
    {
        helper('admin');
        $item = $this->model->find($id);
        if (! $item || (int) $item->fr_lg_idx !== admin_effective_lg_idx()) {
            return redirect()->to(mgmt_url('free-recipients'))->with('error', '대상자를 찾을 수 없습니다.');
        }

        $rules = [
            'fr_name'  => 'required|max_length[100]',
            'fr_state' => 'required|in_list[0,1]',
        ];
        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $this->model->update($id, [
            'fr_type_code' => $this->request->getPost('fr_type_code') ?? $item->fr_type_code,
            'fr_name'      => $this->request->getPost('fr_name'),
            'fr_phone'     => $this->request->getPost('fr_phone') ?? '',
            'fr_addr'      => $this->request->getPost('fr_addr') ?? '',
            'fr_dong_code' => $this->request->getPost('fr_dong_code') ?? '',
            'fr_note'      => $this->request->getPost('fr_note') ?? '',
            'fr_end_date'  => $this->request->getPost('fr_end_date') ?: null,
            'fr_state'     => (int) $this->request->getPost('fr_state'),
        ]);

        return redirect()->to(mgmt_url('free-recipients'))->with('success', '무료용 대상자가 수정되었습니다.');
    }

    public function delete(int $id)
    {
        helper('admin');
        $item = $this->model->find($id);
        if (! $item || (int) $item->fr_lg_idx !== admin_effective_lg_idx()) {
            return redirect()->to(mgmt_url('free-recipients'))->with('error', '대상자를 찾을 수 없습니다.');
        }

        $this->model->delete($id);

        return redirect()->to(mgmt_url('free-recipients'))->with('success', '무료용 대상자가 삭제되었습니다.');
    }
}
