<?php

declare(strict_types=1);

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\SalesAgencyModel;

class SalesAgency extends BaseController
{
    private const SCHEMA_ERROR = '판매 대행소 테이블에 sa_kind·sa_code 컬럼이 없습니다. DB에 writable/database/sales_agency_migrate_to_kind_code_name.sql(또는 신규용 sales_agency_tables.sql)을 적용한 뒤 다시 시도해 주세요.';

    private SalesAgencyModel $model;

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

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

        $saKind = trim((string) ($this->request->getGet('sa_kind') ?? ''));
        $saCode = trim((string) ($this->request->getGet('sa_code') ?? ''));
        $saName = trim((string) ($this->request->getGet('sa_name') ?? ''));
        $saIdx  = trim((string) ($this->request->getGet('sa_idx') ?? ''));

        $builder = $this->model->where('sa_lg_idx', $lgIdx);
        if ($saKind !== '') {
            $builder->like('sa_kind', $saKind);
        }
        if ($saCode !== '') {
            $builder->like('sa_code', $saCode);
        }
        if ($saName !== '') {
            $builder->like('sa_name', $saName);
        }
        if ($saIdx !== '' && ctype_digit($saIdx)) {
            $builder->where('sa_idx', (int) $saIdx);
        }

        // 방금 등록한 대행소가 맨 위에 보이도록 최신 등록순(번호 내림차순)으로 정렬
        $list  = $builder->orderBy('sa_idx', 'DESC')->paginate(20);
        $pager = $this->model->pager;

        $queryForPager = [
            'sa_kind' => $saKind,
            'sa_code' => $saCode,
            'sa_name' => $saName,
            'sa_idx'  => $saIdx,
        ];
        $queryForPager = array_filter($queryForPager, static fn ($v) => $v !== null && $v !== '');
        apply_pager_path($pager, mgmt_path('sales-agencies'), $queryForPager);

        return $this->renderWorkPage('판매 대행소 관리', 'admin/sales_agency/index', [
            'list'    => $list,
            'pager'   => $pager,
            'sa_kind' => $saKind,
            'sa_code' => $saCode,
            'sa_name' => $saName,
            'sa_idx'  => $saIdx,
        ]);
    }

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

        return $this->renderWorkPage('판매 대행소 등록', 'admin/sales_agency/create');
    }

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

        if (! $this->model->hasKindCodeColumns()) {
            return redirect()->back()->withInput()->with('error', self::SCHEMA_ERROR);
        }

        $rules = [
            'sa_kind' => 'required|max_length[50]',
            'sa_code' => 'required|max_length[50]',
            'sa_name' => 'required|max_length[100]',
        ];
        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $code = trim((string) $this->request->getPost('sa_code'));
        if ($this->model->where('sa_lg_idx', $lgIdx)->where('sa_code', $code)->first() !== null) {
            return redirect()->back()->withInput()->with('error', '동일 지자체에 같은 대행소 코드가 이미 있습니다.');
        }

        $this->model->insert([
            'sa_lg_idx'  => $lgIdx,
            'sa_kind'    => trim((string) $this->request->getPost('sa_kind')),
            'sa_code'    => $code,
            'sa_name'    => trim((string) $this->request->getPost('sa_name')),
            'sa_regdate' => date('Y-m-d H:i:s'),
        ]);

        return redirect()->to(mgmt_url('sales-agencies'))->with('success', '판매 대행소가 등록되었습니다.');
    }

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

        return $this->renderWorkPage('판매 대행소 수정', 'admin/sales_agency/edit', ['item' => $item]);
    }

    public function update(int $id)
    {
        helper('admin');
        $lgIdx = admin_effective_lg_idx();
        $item  = $this->model->find($id);
        if (! $item || ! $lgIdx || (int) $item->sa_lg_idx !== $lgIdx) {
            return redirect()->to(mgmt_url('sales-agencies'))->with('error', '대행소를 찾을 수 없습니다.');
        }

        if (! $this->model->hasKindCodeColumns()) {
            return redirect()->back()->withInput()->with('error', self::SCHEMA_ERROR);
        }

        $rules = [
            'sa_kind' => 'required|max_length[50]',
            'sa_code' => 'required|max_length[50]',
            'sa_name' => 'required|max_length[100]',
        ];
        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $code = trim((string) $this->request->getPost('sa_code'));
        $dup  = $this->model->where('sa_lg_idx', $lgIdx)->where('sa_code', $code)->where('sa_idx !=', $id)->first();
        if ($dup !== null) {
            return redirect()->back()->withInput()->with('error', '동일 지자체에 같은 대행소 코드가 이미 있습니다.');
        }

        $this->model->update($id, [
            'sa_kind' => trim((string) $this->request->getPost('sa_kind')),
            'sa_code' => $code,
            'sa_name' => trim((string) $this->request->getPost('sa_name')),
        ]);

        return redirect()->to(mgmt_url('sales-agencies'))->with('success', '판매 대행소가 수정되었습니다.');
    }

    public function delete(int $id)
    {
        helper('admin');
        $lgIdx = admin_effective_lg_idx();
        $item  = $this->model->find($id);
        if (! $item || ! $lgIdx || (int) $item->sa_lg_idx !== $lgIdx) {
            return redirect()->to(mgmt_url('sales-agencies'))->with('error', '대행소를 찾을 수 없습니다.');
        }

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

        return redirect()->to(mgmt_url('sales-agencies'))->with('success', '삭제되었습니다.');
    }
}
