<?php

namespace App\Controllers\Admin;

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

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) {
            return redirect()->to(site_url('admin'))->with('error', '지자체를 선택해 주세요.');
        }

        $builder = $this->priceModel->where('bp_lg_idx', $lgIdx);

        // 기간 필터 (P2-04)
        $startDate = $this->request->getGet('start_date');
        $endDate   = $this->request->getGet('end_date');
        if ($startDate) {
            $builder->where('bp_start_date >=', $startDate);
        }
        if ($endDate) {
            $builder->groupStart()
                ->where('bp_end_date IS NULL')
                ->orWhere('bp_end_date <=', $endDate)
            ->groupEnd();
        }

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

        return view('admin/layout', [
            'title'   => '봉투 단가 관리',
            'content' => view('admin/bag_price/index', [
                'list'      => $list,
                'startDate' => $startDate,
                'endDate'   => $endDate,
            ]),
        ]);
    }

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

        // 봉투명 코드(O) 목록
        $kindModel = model(CodeKindModel::class);
        $kind = $kindModel->where('ck_code', 'O')->first();
        $bagCodes = [];
        if ($kind) {
            $bagCodes = model(CodeDetailModel::class)->getByKind((int) $kind->ck_idx, true);
        }

        return view('admin/layout', [
            'title'   => '봉투 단가 등록',
            'content' => view('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)->where('cd_ck_idx', $kind->ck_idx)->where('cd_code', $bagCode)->first();
            $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(site_url('admin/bag-prices'))->with('success', '봉투 단가가 등록되었습니다.');
    }

    public function edit(int $id)
    {
        helper('admin');
        $item = $this->priceModel->find($id);
        if (!$item || (int) $item->bp_lg_idx !== admin_effective_lg_idx()) {
            return redirect()->to(site_url('admin/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);
        }

        return view('admin/layout', [
            'title'   => '봉투 단가 수정',
            'content' => view('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(site_url('admin/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(site_url('admin/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(site_url('admin/bag-prices'))->with('error', '단가 정보를 찾을 수 없습니다.');
        }

        $this->priceModel->delete($id);
        return redirect()->to(site_url('admin/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(site_url('admin/bag-prices'))->with('error', '단가 정보를 찾을 수 없습니다.');
        }

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

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