<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\BagPriceHistoryModel;
use App\Models\BagPriceModel;
use App\Models\CodeDetailModel;
use App\Models\CodeKindModel;

class BagPrice extends BaseController
{
    private BagPriceModel $priceModel;
    private BagPriceHistoryModel $historyModel;

    public function __construct()
    {
        $this->priceModel   = model(BagPriceModel::class);
        $this->historyModel = model(BagPriceHistoryModel::class);
    }

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

        $get = $this->request->getGet();
        $readSrc = static function (array $src, string $key): ?string {
            if (! array_key_exists($key, $src)) {
                return null;
            }
            $v = $src[$key];
            if ($v === null || is_array($v)) {
                return null;
            }
            $s = trim((string) $v);

            return $s === '' ? null : $s;
        };

        $sy = $readSrc($get, 'start_y');
        $sm = $readSrc($get, 'start_m');
        $sd = $readSrc($get, 'start_d');
        $ey = $readSrc($get, 'end_y');
        $em = $readSrc($get, 'end_m');
        $ed = $readSrc($get, 'end_d');

        $startDate = null;
        if ($sy !== null && $sy !== '' && $sm !== null && $sm !== '' && $sd !== null && $sd !== '') {
            $startDate = parse_ymd_from_triple($sy, $sm, $sd);
        }
        if ($startDate === null) {
            $legacyStart = $readSrc($get, 'start_date');
            $startDate = ($legacyStart !== null && $legacyStart !== '') ? $legacyStart : null;
        }

        $endDate = null;
        if ($ey !== null && $ey !== '' && $em !== null && $em !== '' && $ed !== null && $ed !== '') {
            $endDate = parse_ymd_from_triple($ey, $em, $ed);
        }
        if ($endDate === null) {
            $legacyEnd = $readSrc($get, 'end_date');
            $endDate = ($legacyEnd !== null && $legacyEnd !== '') ? $legacyEnd : null;
        }

        $startParts = ['y' => '', 'm' => '', 'd' => ''];
        $endParts   = ['y' => '', 'm' => '', 'd' => ''];
        if ($startDate !== null && preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $startDate, $m)) {
            $startParts = ['y' => $m[1], 'm' => (int) $m[2], 'd' => (int) $m[3]];
        }
        if ($endDate !== null && preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $endDate, $m)) {
            $endParts = ['y' => $m[1], 'm' => (int) $m[2], 'd' => (int) $m[3]];
        }

        $bagKindE = $readSrc($get, 'bag_kind_e');
        $bagCode  = $readSrc($get, 'bag_code');

        $builder = $this->priceModel->where('bp_lg_idx', $lgIdx);
        if (($startDate !== null && $startDate !== '') || ($endDate !== null && $endDate !== '')) {
            $qStart = ($startDate !== null && $startDate !== '') ? $startDate : $endDate;
            $qEnd   = ($endDate !== null && $endDate !== '') ? $endDate : $startDate;
            if (strcmp((string) $qStart, (string) $qEnd) > 0) {
                [$qStart, $qEnd] = [$qEnd, $qStart];
            }
            $builder->where('bp_start_date <=', $qEnd);
            $builder->groupStart()
                ->where('bp_end_date IS NULL')
                ->orWhere('bp_end_date >=', $qStart)
            ->groupEnd();
        }

        if ($bagKindE !== null && $bagKindE !== '') {
            $kindE = model(CodeKindModel::class)->where('ck_code', 'E')->first();
            if ($kindE) {
                $detailE = model(CodeDetailModel::class)
                    ->where('cd_ck_idx', (int) $kindE->ck_idx)
                    ->where('cd_code', $bagKindE)
                    ->where('cd_state', 1)
                    ->first();
                if ($detailE !== null) {
                    $builder->like('bp_bag_code', $bagKindE, 'after');
                }
            }
        }

        if ($bagCode !== null && $bagCode !== '') {
            $kindO = model(CodeKindModel::class)->where('ck_code', 'O')->first();
            if ($kindO) {
                $detailO = model(CodeDetailModel::class)->findResolvedByKindAndCode((int) $kindO->ck_idx, $bagCode, $lgIdx);
                if ($detailO !== null) {
                    $builder->where('bp_bag_code', $bagCode);
                }
            }
        }

        $list = $builder
            ->orderBy('bp_bag_code', 'ASC')
            ->orderBy('bp_start_date', 'DESC')
            ->paginate(20);

        $queryForPager = [];
        if ($sy !== null && $sm !== null && $sd !== null && $sy !== '' && $sm !== '' && $sd !== '') {
            $queryForPager['start_y'] = $sy;
            $queryForPager['start_m'] = $sm;
            $queryForPager['start_d'] = $sd;
        }
        if ($ey !== null && $em !== null && $ed !== null && $ey !== '' && $em !== '' && $ed !== '') {
            $queryForPager['end_y'] = $ey;
            $queryForPager['end_m'] = $em;
            $queryForPager['end_d'] = $ed;
        }
        if ($bagKindE !== null && $bagKindE !== '') {
            $queryForPager['bag_kind_e'] = $bagKindE;
        }
        if ($bagCode !== null && $bagCode !== '') {
            $queryForPager['bag_code'] = $bagCode;
        }
        apply_pager_path($this->priceModel->pager, mgmt_path('bag-prices'), $queryForPager);

        $kindO = model(CodeKindModel::class)->where('ck_code', 'O')->first();
        $bagCodes = $kindO
            ? model(CodeDetailModel::class)->getByKind((int) $kindO->ck_idx, true, $lgIdx)
            : [];
        $kindE = model(CodeKindModel::class)->where('ck_code', 'E')->first();
        $bagKindOptions = $kindE
            ? model(CodeDetailModel::class)->getByKind((int) $kindE->ck_idx, true, null)
            : [];

        return $this->renderWorkPage('봉투 단가 관리', 'admin/bag_price/index', [
            'list' => $list,
            'pager' => $this->priceModel->pager,
            'startParts' => $startParts,
            'endParts' => $endParts,
            'dateYearMin' => (int) date('Y') - 12,
            'dateYearMax' => (int) date('Y') + 2,
            'bag_kind_e' => $bagKindE,
            'bag_code' => $bagCode,
            'bag_codes' => $bagCodes,
            'bag_kind_options' => $bagKindOptions,
        ]);
    }

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

        $kindModel = model(CodeKindModel::class);
        $kind      = $kindModel->where('ck_code', 'O')->first();
        $bagCodes  = [];
        if ($kind) {
            $bagCodes = model(CodeDetailModel::class)->getByKind((int) $kind->ck_idx, true, $lgIdx);
        }

        return $this->renderWorkPage('봉투 단가 등록', 'admin/bag_price/create', ['bagCodes' => $bagCodes]);
    }

    public function store()
    {
        helper('admin');
        $lgIdx = admin_effective_lg_idx();

        $rules = [
            'bp_bag_code'    => 'required|max_length[50]',
            'bp_order_price' => 'required|decimal',
            'bp_wholesale'   => 'required|decimal',
            'bp_consumer'    => 'required|decimal',
            'bp_start_date'  => 'required|valid_date[Y-m-d]',
            'bp_end_date'    => 'permit_empty|valid_date[Y-m-d]',
        ];

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

        $bagCode   = $this->request->getPost('bp_bag_code');
        $kindModel = model(CodeKindModel::class);
        $kind      = $kindModel->where('ck_code', 'O')->first();
        $bagName   = '';
        if ($kind) {
            $detail = model(CodeDetailModel::class)->findResolvedByKindAndCode((int) $kind->ck_idx, (string) $bagCode, $lgIdx);
            $bagName = $detail ? $detail->cd_name : '';
        }

        $this->priceModel->insert([
            'bp_lg_idx'      => $lgIdx,
            'bp_bag_code'    => $bagCode,
            'bp_bag_name'    => $bagName,
            'bp_order_price' => $this->request->getPost('bp_order_price'),
            'bp_wholesale'   => $this->request->getPost('bp_wholesale'),
            'bp_consumer'    => $this->request->getPost('bp_consumer'),
            'bp_start_date'  => $this->request->getPost('bp_start_date'),
            'bp_end_date'    => $this->request->getPost('bp_end_date') ?: null,
            'bp_state'       => 1,
            'bp_regdate'     => date('Y-m-d H:i:s'),
            'bp_reg_mb_idx'  => session()->get('mb_idx'),
        ]);

        return redirect()->to(mgmt_url('bag-prices'))->with('success', '봉투 단가가 등록되었습니다.');
    }

    public function edit(int $id)
    {
        helper('admin');
        $lgIdx = admin_effective_lg_idx();
        $item  = $this->priceModel->find($id);
        if (! $item || (int) $item->bp_lg_idx !== $lgIdx) {
            return redirect()->to(mgmt_url('bag-prices'))->with('error', '단가 정보를 찾을 수 없습니다.');
        }

        $kindModel = model(CodeKindModel::class);
        $kind      = $kindModel->where('ck_code', 'O')->first();
        $bagCodes  = [];
        if ($kind) {
            $bagCodes = model(CodeDetailModel::class)->getByKind((int) $kind->ck_idx, true, $lgIdx);
        }

        return $this->renderWorkPage('봉투 단가 수정', 'admin/bag_price/edit', ['item' => $item, 'bagCodes' => $bagCodes]);
    }

    public function update(int $id)
    {
        helper('admin');
        $item = $this->priceModel->find($id);
        if (! $item || (int) $item->bp_lg_idx !== admin_effective_lg_idx()) {
            return redirect()->to(mgmt_url('bag-prices'))->with('error', '단가 정보를 찾을 수 없습니다.');
        }

        $rules = [
            'bp_order_price' => 'required|decimal',
            'bp_wholesale'   => 'required|decimal',
            'bp_consumer'    => 'required|decimal',
            'bp_start_date'  => 'required|valid_date[Y-m-d]',
            'bp_end_date'    => 'permit_empty|valid_date[Y-m-d]',
            'bp_state'       => 'required|in_list[0,1]',
        ];

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

        $db = \Config\Database::connect();
        $db->transStart();

        $priceFields = ['bp_order_price', 'bp_wholesale', 'bp_consumer'];
        foreach ($priceFields as $field) {
            $oldVal = (string) $item->$field;
            $newVal = (string) $this->request->getPost($field);
            if ($oldVal !== $newVal) {
                $this->historyModel->insert([
                    'bph_bp_idx'     => $id,
                    'bph_field'      => $field,
                    'bph_old_value'  => $oldVal,
                    'bph_new_value'  => $newVal,
                    'bph_changed_at' => date('Y-m-d H:i:s'),
                    'bph_changed_by' => session()->get('mb_idx'),
                ]);
            }
        }

        $this->priceModel->update($id, [
            'bp_order_price' => $this->request->getPost('bp_order_price'),
            'bp_wholesale'   => $this->request->getPost('bp_wholesale'),
            'bp_consumer'    => $this->request->getPost('bp_consumer'),
            'bp_start_date'  => $this->request->getPost('bp_start_date'),
            'bp_end_date'    => $this->request->getPost('bp_end_date') ?: null,
            'bp_state'       => (int) $this->request->getPost('bp_state'),
            'bp_moddate'     => date('Y-m-d H:i:s'),
        ]);

        $db->transComplete();

        return redirect()->to(mgmt_url('bag-prices'))->with('success', '봉투 단가가 수정되었습니다.');
    }

    public function delete(int $id)
    {
        helper('admin');
        $item = $this->priceModel->find($id);
        if (! $item || (int) $item->bp_lg_idx !== admin_effective_lg_idx()) {
            return redirect()->to(mgmt_url('bag-prices'))->with('error', '단가 정보를 찾을 수 없습니다.');
        }

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

        return redirect()->to(mgmt_url('bag-prices'))->with('success', '봉투 단가가 삭제되었습니다.');
    }

    public function history(int $bpIdx)
    {
        helper('admin');
        $item = $this->priceModel->find($bpIdx);
        if (! $item || (int) $item->bp_lg_idx !== admin_effective_lg_idx()) {
            return redirect()->to(mgmt_url('bag-prices'))->with('error', '단가 정보를 찾을 수 없습니다.');
        }

        $list = $this->historyModel->where('bph_bp_idx', $bpIdx)->orderBy('bph_changed_at', 'DESC')->findAll();

        return $this->renderWorkPage('단가 변경 이력 — ' . $item->bp_bag_name, 'admin/bag_price/history', ['item' => $item, 'list' => $list]);
    }
}
