<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\BagIssueModel;
use App\Models\BagInventoryModel;
use App\Models\CodeKindModel;
use App\Models\CodeDetailModel;

class BagIssue extends BaseController
{
    private BagIssueModel $issueModel;

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

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

        $builder = $this->issueModel->where('bi2_lg_idx', $lgIdx);
        $startDate = $this->request->getGet('start_date');
        $endDate   = $this->request->getGet('end_date');
        if ($startDate) $builder->where('bi2_issue_date >=', $startDate);
        if ($endDate)   $builder->where('bi2_issue_date <=', $endDate);

        $list = $builder->orderBy('bi2_issue_date', 'DESC')->orderBy('bi2_idx', 'DESC')->findAll();

        return view('admin/layout', [
            'title'   => '무료용 불출 관리',
            'content' => view('admin/bag_issue/index', compact('list', 'startDate', 'endDate')),
        ]);
    }

    public function create()
    {
        helper('admin');
        $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/bag_issue/create', compact('bagCodes')),
        ]);
    }

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

        $rules = [
            'bi2_year'       => 'required|is_natural_no_zero',
            'bi2_quarter'    => 'required|in_list[1,2,3,4]',
            'bi2_issue_type' => 'required|max_length[20]',
            'bi2_issue_date' => 'required|valid_date[Y-m-d]',
            'bi2_dest_name'  => 'required|max_length[100]',
            'bi2_bag_code'   => 'required|max_length[50]',
            'bi2_qty'        => 'required|is_natural_no_zero',
        ];
        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $bagCode = $this->request->getPost('bi2_bag_code');
        $qty     = (int) $this->request->getPost('bi2_qty');

        $kindO = model(CodeKindModel::class)->where('ck_code', 'O')->first();
        $detail = $kindO ? model(CodeDetailModel::class)->where('cd_ck_idx', $kindO->ck_idx)->where('cd_code', $bagCode)->first() : null;
        $bagName = $detail ? $detail->cd_name : '';

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

        $this->issueModel->insert([
            'bi2_lg_idx'     => $lgIdx,
            'bi2_year'       => (int) $this->request->getPost('bi2_year'),
            'bi2_quarter'    => (int) $this->request->getPost('bi2_quarter'),
            'bi2_issue_type' => $this->request->getPost('bi2_issue_type'),
            'bi2_issue_date' => $this->request->getPost('bi2_issue_date'),
            'bi2_dest_type'  => $this->request->getPost('bi2_dest_type') ?? '',
            'bi2_dest_name'  => $this->request->getPost('bi2_dest_name'),
            'bi2_bag_code'   => $bagCode,
            'bi2_bag_name'   => $bagName,
            'bi2_qty'        => $qty,
            'bi2_status'     => 'normal',
            'bi2_regdate'    => date('Y-m-d H:i:s'),
        ]);

        // 재고 감산
        model(BagInventoryModel::class)->adjustQty($lgIdx, $bagCode, $bagName, -$qty);

        $db->transComplete();

        return redirect()->to(site_url('admin/bag-issues'))->with('success', '불출 처리되었습니다.');
    }

    public function cancel(int $id)
    {
        helper('admin');
        $item = $this->issueModel->find($id);
        if (!$item || (int) $item->bi2_lg_idx !== admin_effective_lg_idx()) {
            return redirect()->to(site_url('admin/bag-issues'))->with('error', '불출 내역을 찾을 수 없습니다.');
        }

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

        $this->issueModel->update($id, ['bi2_status' => 'cancelled']);
        // 재고 복원
        model(BagInventoryModel::class)->adjustQty((int) $item->bi2_lg_idx, $item->bi2_bag_code, $item->bi2_bag_name, (int) $item->bi2_qty);

        $db->transComplete();

        return redirect()->to(site_url('admin/bag-issues'))->with('success', '불출이 취소되었습니다.');
    }
}
