<?php
namespace App\Controllers\PSI;

use App\Controllers\Controller;
use App\Models\PSI\Purchase;
use App\Models\PSI\Supplier;

/** 采购入库：写入采购单并自动增加物料/成品库存 + 流水 */
class PurchasesController extends Controller
{
    use StockHelper;



    public function index()
    {
        $purchases = (new Purchase())->all();
        $suppliers = (new Supplier())->all();
        $smap = [];
        foreach ($suppliers as $s) { $smap[$s['id']] = $s['name']; }
        return $this->renderSubsys('psi', 'psi/purchases', ['purchases' => $purchases, 'smap' => $smap], \psi_nav(), 'purchases');
    }

    public function create()
    {
        subsys_admin('psi') or \Core\App::forbidden('需要 PSI 管理员权限');
        $suppliers = (new Supplier())->all();
        $materials = (new \App\Models\PSI\Material())->all();
        $products  = (new \App\Models\PSI\Product())->all();
        return $this->renderSubsys('psi', 'psi/purchase_form', [
            'purchase'  => null, 'suppliers' => $suppliers,
            'materials' => $materials, 'products' => $products,
        ], \psi_nav(), 'purchases');
    }

    public function store()
    {
        subsys_admin('psi') or \Core\App::forbidden('需要 PSI 管理员权限');
        if (!csrf_check()) return $this->redirect('PSI/purchases');
        $itemType = $this->post('item_type') === 'product' ? 'product' : 'material';
        $itemId = (int)$this->post('item_id');
        $qty = (float)$this->post('qty');
        $price = (float)$this->post('price');
        if ($itemId <= 0 || $qty <= 0) { $this->flash('请选择有效的物料/成品并填写数量'); return $this->redirect('PSI/purchases'); }
        $no = 'PI' . date('Ymd') . '-' . substr(uniqid(), -4);
        (new Purchase())->insert([
            'order_no'    => $no,
            'supplier_id' => (int)$this->post('supplier_id'),
            'item_type'   => $itemType,
            'item_id'     => $itemId,
            'qty'         => $qty,
            'price'       => $price,
            'amount'      => $qty * $price,
            'status'      => 'stocked',
            'batch_no'    => trim($this->post('batch_no')),
            'expected_at' => trim($this->post('expected_at')),
            'remark'      => trim($this->post('remark')),
            'created_at'  => date('Y-m-d'),
        ]);
        $this->adjustStock($itemType, $itemId, $qty, 'in', $no, trim($this->post('batch_no')));
        $this->flash('采购入库成功，库存已更新', 'ok');
        return $this->redirect('PSI/purchases');
    }

    public function destroy($id)
    {
        subsys_admin('psi') or \Core\App::forbidden('需要 PSI 管理员权限');
        (new Purchase())->delete($id);
        return $this->redirect('PSI/purchases');
    }
}
