<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\BagOrderModel;
use App\Models\BagOrderItemModel;
use App\Models\BagPriceModel;
use App\Models\PackagingUnitModel;
use App\Models\CompanyModel;
use App\Models\SalesAgencyModel;
use App\Models\CodeKindModel;
use App\Models\CodeDetailModel;
use Ramsey\Uuid\Uuid;

class BagOrder extends BaseController
{
    private BagOrderModel $orderModel;
    private BagOrderItemModel $itemModel;

    public function __construct()
    {
        $this->orderModel = model(BagOrderModel::class);
        $this->itemModel  = model(BagOrderItemModel::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('bo_lg_idx', $lgIdx);

        // 기간 필터
        $startDate = $this->request->getGet('start_date');
        $endDate   = $this->request->getGet('end_date');
        $status    = $this->request->getGet('status');
        if ($startDate) $builder->where('bo_order_date >=', $startDate);
        if ($endDate)   $builder->where('bo_order_date <=', $endDate);
        if ($status)    $builder->where('bo_status', $status);

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

        // 발주별 품목 합계
        $itemSummary = [];
        foreach ($list as $order) {
            $items = $this->itemModel->where('boi_bo_idx', $order->bo_idx)->findAll();
            $totalQty = 0; $totalAmt = 0;
            foreach ($items as $it) { $totalQty += (int) $it->boi_qty_sheet; $totalAmt += (float) $it->boi_amount; }
            $itemSummary[$order->bo_idx] = ['qty' => $totalQty, 'amount' => $totalAmt, 'count' => count($items)];
        }

        // 제작업체/대행소 이름 매핑
        $companyMap = []; $agencyMap = [];
        foreach (model(CompanyModel::class)->where('cp_lg_idx', $lgIdx)->findAll() as $c) $companyMap[$c->cp_idx] = $c->cp_name;
        foreach (model(SalesAgencyModel::class)->where('sa_lg_idx', $lgIdx)->findAll() as $a) $agencyMap[$a->sa_idx] = $a->sa_name;

        return view('admin/layout', [
            'title'   => '발주 현황',
            'content' => view('admin/bag_order/index', compact('list', 'itemSummary', 'companyMap', 'agencyMap', 'startDate', 'endDate', 'status')),
        ]);
    }

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

        // 봉투 종류 + 단가 + 포장단위
        $kind = model(CodeKindModel::class)->where('ck_code', 'O')->first();
        $bagCodes = $kind ? model(CodeDetailModel::class)->getByKind((int) $kind->ck_idx, true) : [];
        $prices = model(BagPriceModel::class)->where('bp_lg_idx', $lgIdx)->where('bp_state', 1)->findAll();
        $units = model(PackagingUnitModel::class)->where('pu_lg_idx', $lgIdx)->where('pu_state', 1)->findAll();
        $companies = model(CompanyModel::class)->where('cp_lg_idx', $lgIdx)->where('cp_type', '제작업체')->where('cp_state', 1)->findAll();
        $agencies = model(SalesAgencyModel::class)->where('sa_lg_idx', $lgIdx)->where('sa_state', 1)->findAll();

        return view('admin/layout', [
            'title'   => '발주 등록',
            'content' => view('admin/bag_order/create', compact('bagCodes', 'prices', 'units', 'companies', 'agencies')),
        ]);
    }

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

        $rules = [
            'bo_order_date'  => 'required|valid_date[Y-m-d]',
            'bo_company_idx' => 'permit_empty|is_natural_no_zero',
            'bo_agency_idx'  => 'permit_empty|is_natural_no_zero',
        ];
        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

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

        // UUID 생성
        $uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));

        // LOT 번호 생성
        $lotNo = 'LOT-' . date('Ymd') . '-' . strtoupper(substr(md5($uuid), 0, 6));

        $orderData = [
            'bo_uuid'        => $uuid,
            'bo_version'     => 1,
            'bo_lg_idx'      => $lgIdx,
            'bo_gugun_code'  => $this->request->getPost('bo_gugun_code') ?? '',
            'bo_dong_code'   => $this->request->getPost('bo_dong_code') ?? '',
            'bo_company_idx' => $this->request->getPost('bo_company_idx') ?: null,
            'bo_agency_idx'  => $this->request->getPost('bo_agency_idx') ?: null,
            'bo_fee_rate'    => (float) ($this->request->getPost('bo_fee_rate') ?: 0),
            'bo_order_date'  => $this->request->getPost('bo_order_date'),
            'bo_lot_no'      => $lotNo,
            'bo_status'      => 'normal',
            'bo_orderer_idx' => session()->get('mb_idx'),
            'bo_regdate'     => date('Y-m-d H:i:s'),
        ];

        // SHA-256 해시
        $orderData['bo_hash'] = hash('sha256', json_encode($orderData));

        $this->orderModel->insert($orderData);
        $boIdx = (int) $this->orderModel->getInsertID();

        // 품목 저장
        $bagCodes = $this->request->getPost('item_bag_code') ?? [];
        $qtyBoxes = $this->request->getPost('item_qty_box') ?? [];
        foreach ($bagCodes as $i => $code) {
            if (empty($code) || empty($qtyBoxes[$i])) continue;
            $qtyBox = (int) $qtyBoxes[$i];

            // 포장단위에서 낱장 환산
            $unit = model(PackagingUnitModel::class)->where('pu_lg_idx', $lgIdx)->where('pu_bag_code', $code)->where('pu_state', 1)->first();
            $totalPerBox = $unit ? (int) $unit->pu_total_per_box : 1;
            $qtySheet = $qtyBox * $totalPerBox;

            // 단가
            $price = model(BagPriceModel::class)->where('bp_lg_idx', $lgIdx)->where('bp_bag_code', $code)->where('bp_state', 1)->first();
            $unitPrice = $price ? (float) $price->bp_order_price : 0;

            // 봉투명
            $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([
                'boi_bo_idx'     => $boIdx,
                'boi_bag_code'   => $code,
                'boi_bag_name'   => $detail ? $detail->cd_name : '',
                'boi_unit_price' => $unitPrice,
                'boi_qty_box'    => $qtyBox,
                'boi_qty_sheet'  => $qtySheet,
                'boi_amount'     => $unitPrice * $qtySheet,
            ]);
        }

        $db->transComplete();

        return redirect()->to(site_url('admin/bag-orders'))->with('success', '발주가 등록되었습니다. LOT: ' . $lotNo);
    }

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

        $items = $this->itemModel->where('boi_bo_idx', $id)->findAll();

        $companyName = '';
        if ($order->bo_company_idx) {
            $c = model(CompanyModel::class)->find($order->bo_company_idx);
            $companyName = $c ? $c->cp_name : '';
        }
        $agencyName = '';
        if ($order->bo_agency_idx) {
            $a = model(SalesAgencyModel::class)->find($order->bo_agency_idx);
            $agencyName = $a ? $a->sa_name : '';
        }

        return view('admin/layout', [
            'title'   => '발주 상세 — ' . $order->bo_lot_no,
            'content' => view('admin/bag_order/detail', compact('order', 'items', 'companyName', 'agencyName')),
        ]);
    }

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

        $this->orderModel->update($id, ['bo_status' => 'cancelled', 'bo_moddate' => date('Y-m-d H:i:s')]);
        return redirect()->to(site_url('admin/bag-orders'))->with('success', '발주가 취소되었습니다.');
    }

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

        $this->orderModel->update($id, ['bo_status' => 'deleted', 'bo_moddate' => date('Y-m-d H:i:s')]);
        return redirect()->to(site_url('admin/bag-orders'))->with('success', '발주가 삭제 처리되었습니다.');
    }
}
