<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\PackagingUnitModel;
use App\Models\PackagingUnitHistoryModel;
use App\Models\CodeKindModel;
use App\Models\CodeDetailModel;

class PackagingUnit extends BaseController
{
    private PackagingUnitModel $unitModel;
    private PackagingUnitHistoryModel $historyModel;

    public function __construct()
    {
        $this->unitModel    = model(PackagingUnitModel::class);
        $this->historyModel = model(PackagingUnitHistoryModel::class);
    }

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

        $builder = $this->unitModel->where('pu_lg_idx', $lgIdx);

        $startDate = $this->request->getGet('start_date');
        $endDate   = $this->request->getGet('end_date');
        if ($startDate) {
            $builder->where('pu_start_date >=', $startDate);
        }
        if ($endDate) {
            $builder->groupStart()->where('pu_end_date IS NULL')->orWhere('pu_end_date <=', $endDate)->groupEnd();
        }

        $list = $builder->orderBy('pu_bag_code', 'ASC')->orderBy('pu_start_date', 'DESC')->findAll();

        return view('admin/layout', [
            'title'   => '포장 단위 관리',
            'content' => view('admin/packaging_unit/index', [
                'list' => $list, 'startDate' => $startDate, 'endDate' => $endDate,
            ]),
        ]);
    }

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

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

        return view('admin/layout', [
            'title'   => '포장 단위 등록',
            'content' => view('admin/packaging_unit/create', ['bagCodes' => $bagCodes]),
        ]);
    }

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

        $rules = [
            'pu_bag_code'       => 'required|max_length[50]',
            'pu_box_per_pack'   => 'required|is_natural_no_zero',
            'pu_pack_per_sheet' => 'required|is_natural_no_zero',
            'pu_start_date'     => 'required|valid_date[Y-m-d]',
            'pu_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('pu_bag_code');
        $kind = model(CodeKindModel::class)->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 : '';
        }

        $boxPerPack   = (int) $this->request->getPost('pu_box_per_pack');
        $packPerSheet = (int) $this->request->getPost('pu_pack_per_sheet');

        $this->unitModel->insert([
            'pu_lg_idx'         => $lgIdx,
            'pu_bag_code'       => $bagCode,
            'pu_bag_name'       => $bagName,
            'pu_box_per_pack'   => $boxPerPack,
            'pu_pack_per_sheet' => $packPerSheet,
            'pu_total_per_box'  => $boxPerPack * $packPerSheet,
            'pu_start_date'     => $this->request->getPost('pu_start_date'),
            'pu_end_date'       => $this->request->getPost('pu_end_date') ?: null,
            'pu_state'          => 1,
            'pu_regdate'        => date('Y-m-d H:i:s'),
            'pu_reg_mb_idx'     => session()->get('mb_idx'),
        ]);

        return redirect()->to(site_url('admin/packaging-units'))->with('success', '포장 단위가 등록되었습니다.');
    }

    public function edit(int $id)
    {
        helper('admin');
        $item = $this->unitModel->find($id);
        if (!$item || (int) $item->pu_lg_idx !== admin_effective_lg_idx()) {
            return redirect()->to(site_url('admin/packaging-units'))->with('error', '포장 단위를 찾을 수 없습니다.');
        }

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

        return view('admin/layout', [
            'title'   => '포장 단위 수정',
            'content' => view('admin/packaging_unit/edit', ['item' => $item, 'bagCodes' => $bagCodes]),
        ]);
    }

    public function update(int $id)
    {
        helper('admin');
        $item = $this->unitModel->find($id);
        if (!$item || (int) $item->pu_lg_idx !== admin_effective_lg_idx()) {
            return redirect()->to(site_url('admin/packaging-units'))->with('error', '포장 단위를 찾을 수 없습니다.');
        }

        $rules = [
            'pu_box_per_pack'   => 'required|is_natural_no_zero',
            'pu_pack_per_sheet' => 'required|is_natural_no_zero',
            'pu_start_date'     => 'required|valid_date[Y-m-d]',
            'pu_end_date'       => 'permit_empty|valid_date[Y-m-d]',
            'pu_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();

        $trackFields = ['pu_box_per_pack', 'pu_pack_per_sheet'];
        foreach ($trackFields as $field) {
            $oldVal = (string) $item->$field;
            $newVal = (string) $this->request->getPost($field);
            if ($oldVal !== $newVal) {
                $this->historyModel->insert([
                    'puh_pu_idx'    => $id,
                    'puh_field'     => $field,
                    'puh_old_value' => $oldVal,
                    'puh_new_value' => $newVal,
                    'puh_changed_at'=> date('Y-m-d H:i:s'),
                    'puh_changed_by'=> session()->get('mb_idx'),
                ]);
            }
        }

        $boxPerPack   = (int) $this->request->getPost('pu_box_per_pack');
        $packPerSheet = (int) $this->request->getPost('pu_pack_per_sheet');

        $this->unitModel->update($id, [
            'pu_box_per_pack'   => $boxPerPack,
            'pu_pack_per_sheet' => $packPerSheet,
            'pu_total_per_box'  => $boxPerPack * $packPerSheet,
            'pu_start_date'     => $this->request->getPost('pu_start_date'),
            'pu_end_date'       => $this->request->getPost('pu_end_date') ?: null,
            'pu_state'          => (int) $this->request->getPost('pu_state'),
            'pu_moddate'        => date('Y-m-d H:i:s'),
        ]);

        $db->transComplete();
        return redirect()->to(site_url('admin/packaging-units'))->with('success', '포장 단위가 수정되었습니다.');
    }

    public function delete(int $id)
    {
        helper('admin');
        $item = $this->unitModel->find($id);
        if (!$item || (int) $item->pu_lg_idx !== admin_effective_lg_idx()) {
            return redirect()->to(site_url('admin/packaging-units'))->with('error', '포장 단위를 찾을 수 없습니다.');
        }

        $this->unitModel->delete($id);
        return redirect()->to(site_url('admin/packaging-units'))->with('success', '포장 단위가 삭제되었습니다.');
    }

    public function history(int $puIdx)
    {
        helper('admin');
        $item = $this->unitModel->find($puIdx);
        if (!$item || (int) $item->pu_lg_idx !== admin_effective_lg_idx()) {
            return redirect()->to(site_url('admin/packaging-units'))->with('error', '포장 단위를 찾을 수 없습니다.');
        }

        $list = $this->historyModel->where('puh_pu_idx', $puIdx)->orderBy('puh_changed_at', 'DESC')->findAll();

        return view('admin/layout', [
            'title'   => '포장 단위 변경 이력 — ' . $item->pu_bag_name,
            'content' => view('admin/packaging_unit/history', ['item' => $item, 'list' => $list]),
        ]);
    }
}
