<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Models\BagInventoryModel;
use App\Models\BagIssueModel;
use App\Models\BagOrderModel;
use App\Models\BagOrderItemModel;
use App\Models\BagPriceModel;
use App\Models\BagReceivingModel;
use App\Models\BagSaleModel;
use App\Models\CodeKindModel;
use App\Models\CodeDetailModel;
use App\Models\CompanyModel;
use App\Models\PackagingUnitModel;
use App\Models\SalesAgencyModel;
use App\Models\ShopOrderModel;

class Bag extends BaseController
{
    /**
     * 로그인 사용자의 지자체 PK 반환 (미로그인/미지정 시 null)
     */
    private function lgIdx(): ?int
    {
        helper('admin');
        return admin_effective_lg_idx();
    }

    private function render(string $title, string $viewFile, array $data = []): string
    {
        return view('bag/layout/main', [
            'title'   => $title,
            'content' => view($viewFile, $data),
        ]);
    }

    // ──────────────────────────────────────────────
    // 기본정보관리
    // ──────────────────────────────────────────────
    public function basicInfo(): string
    {
        $lgIdx = $this->lgIdx();
        $data = [];

        if ($lgIdx) {
            $data['codeKinds']     = model(CodeKindModel::class)->orderBy('ck_code', 'ASC')->findAll();
            $data['bagPrices']     = model(BagPriceModel::class)->where('bp_lg_idx', $lgIdx)->orderBy('bp_bag_code', 'ASC')->findAll();
            $data['packagingUnits'] = model(PackagingUnitModel::class)->where('pu_lg_idx', $lgIdx)->orderBy('pu_bag_code', 'ASC')->findAll();
        }

        return $this->render('기본정보관리', 'bag/basic_info', $data);
    }

    // ──────────────────────────────────────────────
    // 발주 입고 관리
    // ──────────────────────────────────────────────
    public function purchaseInbound(): string
    {
        $lgIdx = $this->lgIdx();
        $data = ['orders' => [], 'receivings' => [], 'startDate' => null, 'endDate' => null];

        if ($lgIdx) {
            $startDate = $this->request->getGet('start_date');
            $endDate   = $this->request->getGet('end_date');
            $data['startDate'] = $startDate;
            $data['endDate']   = $endDate;

            // 발주 목록
            $orderBuilder = model(BagOrderModel::class)->where('bo_lg_idx', $lgIdx);
            if ($startDate) $orderBuilder->where('bo_order_date >=', $startDate);
            if ($endDate)   $orderBuilder->where('bo_order_date <=', $endDate);
            $data['orders'] = $orderBuilder->orderBy('bo_order_date', 'DESC')->findAll();

            // 발주별 품목 합계
            $itemSummary = [];
            foreach ($data['orders'] as $order) {
                $items = model(BagOrderItemModel::class)->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)];
            }
            $data['itemSummary'] = $itemSummary;

            // 입고 목록
            $recvBuilder = model(BagReceivingModel::class)->where('br_lg_idx', $lgIdx);
            if ($startDate) $recvBuilder->where('br_receive_date >=', $startDate);
            if ($endDate)   $recvBuilder->where('br_receive_date <=', $endDate);
            $data['receivings'] = $recvBuilder->orderBy('br_receive_date', 'DESC')->findAll();
        }

        return $this->render('발주 입고 관리', 'bag/purchase_inbound', $data);
    }

    // ──────────────────────────────────────────────
    // 불출 관리
    // ──────────────────────────────────────────────
    public function issue(): string
    {
        $lgIdx = $this->lgIdx();
        $data = ['list' => [], 'startDate' => null, 'endDate' => null];

        if ($lgIdx) {
            $startDate = $this->request->getGet('start_date');
            $endDate   = $this->request->getGet('end_date');
            $data['startDate'] = $startDate;
            $data['endDate']   = $endDate;

            $builder = model(BagIssueModel::class)->where('bi2_lg_idx', $lgIdx);
            if ($startDate) $builder->where('bi2_issue_date >=', $startDate);
            if ($endDate)   $builder->where('bi2_issue_date <=', $endDate);
            $data['list'] = $builder->orderBy('bi2_issue_date', 'DESC')->findAll();
        }

        return $this->render('불출 관리', 'bag/issue', $data);
    }

    // ──────────────────────────────────────────────
    // 재고 관리
    // ──────────────────────────────────────────────
    public function inventory(): string
    {
        $lgIdx = $this->lgIdx();
        $data = ['list' => []];

        if ($lgIdx) {
            $data['list'] = model(BagInventoryModel::class)->where('bi_lg_idx', $lgIdx)->orderBy('bi_bag_code', 'ASC')->findAll();
        }

        return $this->render('재고 관리', 'bag/inventory', $data);
    }

    // ──────────────────────────────────────────────
    // 판매 관리
    // ──────────────────────────────────────────────
    public function sales(): string
    {
        $lgIdx = $this->lgIdx();
        $data = ['salesList' => [], 'orderList' => [], 'startDate' => null, 'endDate' => null];

        if ($lgIdx) {
            $startDate = $this->request->getGet('start_date');
            $endDate   = $this->request->getGet('end_date');
            $data['startDate'] = $startDate;
            $data['endDate']   = $endDate;

            // 판매/반품
            $saleBuilder = model(BagSaleModel::class)->where('bs_lg_idx', $lgIdx);
            if ($startDate) $saleBuilder->where('bs_sale_date >=', $startDate);
            if ($endDate)   $saleBuilder->where('bs_sale_date <=', $endDate);
            $data['salesList'] = $saleBuilder->orderBy('bs_sale_date', 'DESC')->findAll();

            // 주문 접수
            $orderBuilder = model(ShopOrderModel::class)->where('so_lg_idx', $lgIdx);
            if ($startDate) $orderBuilder->where('so_delivery_date >=', $startDate);
            if ($endDate)   $orderBuilder->where('so_delivery_date <=', $endDate);
            $data['orderList'] = $orderBuilder->orderBy('so_idx', 'DESC')->findAll();
        }

        return $this->render('판매 관리', 'bag/sales', $data);
    }

    // ──────────────────────────────────────────────
    // 판매 현황
    // ──────────────────────────────────────────────
    public function salesStats(): string
    {
        $lgIdx = $this->lgIdx();
        $data = ['result' => [], 'startDate' => null, 'endDate' => null];

        if ($lgIdx) {
            $startDate = $this->request->getGet('start_date');
            $endDate   = $this->request->getGet('end_date');
            $data['startDate'] = $startDate;
            $data['endDate']   = $endDate;

            $builder = model(BagSaleModel::class)->where('bs_lg_idx', $lgIdx)->where('bs_type', 'sale');
            if ($startDate) $builder->where('bs_sale_date >=', $startDate);
            if ($endDate)   $builder->where('bs_sale_date <=', $endDate);
            $data['result'] = $builder->orderBy('bs_sale_date', 'DESC')->findAll();
        }

        return $this->render('판매 현황', 'bag/sales_stats', $data);
    }

    // ──────────────────────────────────────────────
    // 봉투 수불 관리
    // ──────────────────────────────────────────────
    public function flow(): string
    {
        $lgIdx = $this->lgIdx();
        $data = ['receiving' => [], 'sales' => [], 'issues' => [], 'inventory' => [], 'startDate' => null, 'endDate' => null];

        if ($lgIdx) {
            $startDate = $this->request->getGet('start_date');
            $endDate   = $this->request->getGet('end_date');
            $data['startDate'] = $startDate;
            $data['endDate']   = $endDate;

            $data['inventory'] = model(BagInventoryModel::class)->where('bi_lg_idx', $lgIdx)->findAll();

            $recvBuilder = model(BagReceivingModel::class)->where('br_lg_idx', $lgIdx);
            if ($startDate) $recvBuilder->where('br_receive_date >=', $startDate);
            if ($endDate)   $recvBuilder->where('br_receive_date <=', $endDate);
            $data['receiving'] = $recvBuilder->findAll();

            $saleBuilder = model(BagSaleModel::class)->where('bs_lg_idx', $lgIdx);
            if ($startDate) $saleBuilder->where('bs_sale_date >=', $startDate);
            if ($endDate)   $saleBuilder->where('bs_sale_date <=', $endDate);
            $data['sales'] = $saleBuilder->findAll();

            $issueBuilder = model(BagIssueModel::class)->where('bi2_lg_idx', $lgIdx);
            if ($startDate) $issueBuilder->where('bi2_issue_date >=', $startDate);
            if ($endDate)   $issueBuilder->where('bi2_issue_date <=', $endDate);
            $data['issues'] = $issueBuilder->findAll();
        }

        return $this->render('봉투 수불 관리', 'bag/flow', $data);
    }

    // ──────────────────────────────────────────────
    // 통계 분석 관리
    // ──────────────────────────────────────────────
    public function analytics(): string
    {
        return $this->render('통계 분석 관리', 'bag/analytics', []);
    }

    // ──────────────────────────────────────────────
    // 창 (프로그램 창 관리 - 추후)
    // ──────────────────────────────────────────────
    public function window(): string
    {
        return $this->render('창', 'bag/window', []);
    }

    // ──────────────────────────────────────────────
    // 도움말
    // ──────────────────────────────────────────────
    public function help(): string
    {
        return $this->render('도움말', 'bag/help', []);
    }
}
