<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\ShopOrderModel;
use App\Models\ShopOrderItemModel;
use App\Models\DesignatedShopModel;
use App\Models\BagPriceModel;
use App\Models\PackagingUnitModel;
use App\Models\CodeKindModel;
use App\Models\CodeDetailModel;

class ShopOrder extends BaseController
{
    private ShopOrderModel $orderModel;
    private ShopOrderItemModel $itemModel;

    public function __construct()
    {
        $this->orderModel = model(ShopOrderModel::class);
        $this->itemModel  = model(ShopOrderItemModel::class);
    }

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

        $builder = $this->orderModel->where('so_lg_idx', $lgIdx);
        $startDate = $this->request->getGet('start_date');
        $endDate   = $this->request->getGet('end_date');
        if ($startDate) $builder->where('so_delivery_date >=', $startDate);
        if ($endDate)   $builder->where('so_delivery_date <=', $endDate);

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

        return view('admin/layout', [
            'title'   => '주문 접수 관리',
            'content' => view('admin/shop_order/index', compact('list', 'startDate', 'endDate')),
        ]);
    }

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

        $shops = model(DesignatedShopModel::class)->where('ds_lg_idx', $lgIdx)->where('ds_state', 1)->findAll();
        $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/shop_order/create', compact('shops', 'bagCodes')),
        ]);
    }

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

        $rules = [
            'so_ds_idx'       => 'required|is_natural_no_zero',
            'so_delivery_date'=> 'required|valid_date[Y-m-d]',
            'so_payment_type' => 'required|in_list[이체,가상계좌]',
        ];
        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

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

        $dsIdx = (int) $this->request->getPost('so_ds_idx');
        $shop = model(DesignatedShopModel::class)->find($dsIdx);

        $this->orderModel->insert([
            'so_lg_idx'       => $lgIdx,
            'so_ds_idx'       => $dsIdx,
            'so_ds_name'      => $shop ? $shop->ds_name : '',
            'so_order_date'   => date('Y-m-d'),
            'so_delivery_date'=> $this->request->getPost('so_delivery_date'),
            'so_payment_type' => $this->request->getPost('so_payment_type'),
            'so_status'       => 'normal',
            'so_orderer_idx'  => session()->get('mb_idx'),
            'so_regdate'      => date('Y-m-d H:i:s'),
        ]);
        $soIdx = (int) $this->orderModel->getInsertID();

        $bagCodes = $this->request->getPost('item_bag_code') ?? [];
        $qtys     = $this->request->getPost('item_qty') ?? [];
        $totalQty = 0; $totalAmt = 0;

        foreach ($bagCodes as $i => $code) {
            if (empty($code) || empty($qtys[$i])) continue;
            $qty = (int) $qtys[$i];

            $price = model(BagPriceModel::class)->where('bp_lg_idx', $lgIdx)->where('bp_bag_code', $code)->where('bp_state', 1)->first();
            $unitPrice = $price ? (float) $price->bp_consumer : 0;
            $amount = $unitPrice * $qty;

            $unit = model(PackagingUnitModel::class)->where('pu_lg_idx', $lgIdx)->where('pu_bag_code', $code)->where('pu_state', 1)->first();
            $boxCount = 0; $packCount = 0; $sheetCount = $qty;
            if ($unit && (int) $unit->pu_total_per_box > 0) {
                $boxCount = intdiv($qty, (int) $unit->pu_total_per_box);
                $remainder = $qty % (int) $unit->pu_total_per_box;
                if ((int) $unit->pu_pack_per_sheet > 0) {
                    $packCount = intdiv($remainder, (int) $unit->pu_pack_per_sheet);
                    $sheetCount = $remainder % (int) $unit->pu_pack_per_sheet;
                }
            }

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

            $this->itemModel->insert([
                'soi_so_idx'     => $soIdx,
                'soi_bag_code'   => $code,
                'soi_bag_name'   => $detail ? $detail->cd_name : '',
                'soi_unit_price' => $unitPrice,
                'soi_qty'        => $qty,
                'soi_amount'     => $amount,
                'soi_box_count'  => $boxCount,
                'soi_pack_count' => $packCount,
                'soi_sheet_count'=> $sheetCount,
            ]);

            $totalQty += $qty;
            $totalAmt += $amount;
        }

        $this->orderModel->update($soIdx, ['so_total_qty' => $totalQty, 'so_total_amount' => $totalAmt]);
        $db->transComplete();

        return redirect()->to(site_url('admin/shop-orders'))->with('success', '주문이 접수되었습니다.');
    }

    public function cancel(int $id)
    {
        helper('admin');
        $order = $this->orderModel->find($id);
        if (!$order || (int) $order->so_lg_idx !== admin_effective_lg_idx()) {
            return redirect()->to(site_url('admin/shop-orders'))->with('error', '주문을 찾을 수 없습니다.');
        }

        $this->orderModel->update($id, ['so_status' => 'cancelled']);
        return redirect()->to(site_url('admin/shop-orders'))->with('success', '주문이 취소되었습니다.');
    }
}
