<?php
namespace App\Controllers\PSI;

use App\Controllers\Controller;
use App\Models\PSI\PurchaseOrder;
use App\Models\PSI\PurchaseOrderItem;
use App\Models\PSI\SalesOrder;
use App\Models\PSI\SalesOrderItem;
use App\Models\PSI\Outbound;
use App\Models\PSI\OutboundItem;

/**
 * 报表中心：采购订单明细 / 销售·采购订单明细 / 交付明细。
 * 集中展示单据之间的关联性（采购→入库、销售订单→出库交付）。
 */
class ReportsController extends Controller
{
    public function index()
    {
        return $this->renderSubsys('psi', 'psi/reports', [
            'poCount'  => count((new PurchaseOrder())->all()),
            'soCount'  => count((new SalesOrder())->all()),
            'obCount'  => count((new Outbound())->all()),
        ], \psi_nav(), 'reports');
    }

    /** 采购订单明细 */
    public function poDetail()
    {
        $orders = array_reverse((new PurchaseOrder())->all());
        $itemM = new PurchaseOrderItem();
        foreach ($orders as &$o) { $o['_items'] = $itemM->whereAll('po_id', $o['id']); }
        return $this->renderSubsys('psi', 'psi/report_po_detail', ['orders' => $orders], \psi_nav(), 'reports');
    }

    /** 销售 / 采购订单明细（合并筛选） */
    public function soPo()
    {
        $type = $this->get('type', 'all');
        $so = $po = [];
        if ($type !== 'purchase') {
            $so = array_reverse((new SalesOrder())->all());
            $soItemM = new SalesOrderItem();
            foreach ($so as &$o) {
                $o['_items'] = $soItemM->whereAll('so_id', $o['id']);
                $o['_amt'] = array_sum(array_map(fn($i) => (float)($i['amount'] ?? 0), $o['_items']));
            }
        }
        if ($type !== 'sales') {
            $po = array_reverse((new PurchaseOrder())->all());
            $poItemM = new PurchaseOrderItem();
            foreach ($po as &$o) {
                $o['_items'] = $poItemM->whereAll('po_id', $o['id']);
                $o['_amt'] = array_sum(array_map(fn($i) => (float)($i['amount'] ?? 0), $o['_items']));
            }
        }
        return $this->renderSubsys('psi', 'psi/report_so_po', [
            'type' => $type, 'so' => $so, 'po' => $po,
        ], \psi_nav(), 'reports');
    }

    /** 交付明细：出库单 + 销售订单交付进度（应发/已发/未发） */
    public function delivery()
    {
        $list = array_reverse((new Outbound())->all());
        $obItemM = new OutboundItem();
        foreach ($list as &$o) { $o['_items'] = $obItemM->whereAll('ob_id', $o['id']); }

        $soList = (new SalesOrder())->all();
        $soItemM = new SalesOrderItem();
        $progress = [];
        foreach ($soList as $so) {
            $items = $soItemM->whereAll('so_id', $so['id']);
            $ordered = array_sum(array_map(fn($i) => (int)($i['qty'] ?? 0), $items));
            $delivered = array_sum(array_map(fn($i) => (int)($i['delivered_qty'] ?? 0), $items));
            $amt = array_sum(array_map(fn($i) => (float)($i['amount'] ?? 0), $items));
            if ($ordered <= 0) continue;
            $progress[] = [
                'order_no'  => $so['order_no'],
                'customer'  => $so['customer'],
                'salesman'  => $so['salesman'],
                'status'    => $so['status'],
                'ordered'   => $ordered,
                'delivered' => $delivered,
                'remain'    => max(0, $ordered - $delivered),
                'amount'    => $amt,
            ];
        }
        return $this->renderSubsys('psi', 'psi/report_delivery', [
            'list' => $list, 'progress' => $progress,
        ], \psi_nav(), 'reports');
    }
}
