<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\BagReceivingModel;
use App\Models\BagOrderModel;
use App\Models\BagOrderItemModel;
use App\Models\BagInventoryModel;
use App\Models\CompanyModel;

class BagReceiving extends BaseController
{
    private BagReceivingModel $recvModel;

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

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

        $builder = $this->recvModel->where('br_lg_idx', $lgIdx);
        $startDate = $this->request->getGet('start_date');
        $endDate   = $this->request->getGet('end_date');
        if ($startDate) {
            $builder->where('br_receive_date >=', $startDate);
        }
        if ($endDate) {
            $builder->where('br_receive_date <=', $endDate);
        }

        $list  = $builder->orderBy('br_receive_date', 'DESC')->orderBy('br_idx', 'DESC')->paginate(20);
        $pager = $this->recvModel->pager;

        return $this->renderWorkPage('입고 현황', 'admin/bag_receiving/index', compact('list', 'startDate', 'endDate', 'pager'));
    }

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

        $orders = model(BagOrderModel::class)->where('bo_lg_idx', $lgIdx)->whereLatestHead($lgIdx)->where('bo_status', 'normal')->orderBy('bo_order_date', 'DESC')->findAll();

        return $this->renderWorkPage('입고 처리', 'admin/bag_receiving/create', compact('orders'));
    }

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

        $rules = [
            'br_bo_idx'       => 'required|is_natural_no_zero',
            'br_bag_code'     => 'required|max_length[50]',
            'br_qty_box'      => 'required|is_natural_no_zero',
            'br_receive_date' => 'required|valid_date[Y-m-d]',
        ];
        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $boIdx   = (int) $this->request->getPost('br_bo_idx');
        $bagCode = $this->request->getPost('br_bag_code');
        $qtyBox  = (int) $this->request->getPost('br_qty_box');

        $unit = model(\App\Models\PackagingUnitModel::class)->where('pu_lg_idx', $lgIdx)->where('pu_bag_code', $bagCode)->where('pu_state', 1)->first();
        $totalPerBox = $unit ? (int) $unit->pu_total_per_box : 1;
        $qtySheet    = $qtyBox * $totalPerBox;

        $kindO  = model(\App\Models\CodeKindModel::class)->where('ck_code', 'O')->first();
        $detail = $kindO ? model(\App\Models\CodeDetailModel::class)->findResolvedByKindAndCode((int) $kindO->ck_idx, (string) $bagCode, $lgIdx) : null;
        $bagName = $detail ? $detail->cd_name : '';

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

        $this->recvModel->insert([
            'br_bo_idx'       => $boIdx,
            'br_lg_idx'       => $lgIdx,
            'br_bag_code'     => $bagCode,
            'br_bag_name'     => $bagName,
            'br_qty_box'      => $qtyBox,
            'br_qty_sheet'    => $qtySheet,
            'br_receive_date' => $this->request->getPost('br_receive_date'),
            'br_receiver_idx' => session()->get('mb_idx'),
            'br_sender_name'  => $this->request->getPost('br_sender_name') ?? '',
            'br_type'         => $this->request->getPost('br_type') ?? 'batch',
            'br_regdate'      => date('Y-m-d H:i:s'),
        ]);

        model(BagInventoryModel::class)->adjustQty($lgIdx, $bagCode, $bagName, $qtySheet);

        $db->transComplete();

        return redirect()->to(mgmt_url('bag-receivings'))->with('success', '입고 처리되었습니다. (' . $bagName . ' ' . $qtyBox . '박스)');
    }
}
