<?php
/** PSI 采购表单（物料/成品统一） */
$mats = isset($GLOBALS['_psi_materials']) ? $GLOBALS['_psi_materials'] : [];
$prods = isset($GLOBALS['_psi_products']) ? $GLOBALS['_psi_products'] : [];
// 通过控制器注入时取不到，这里改为从全局读取；若为空则由控制器提供
?>
<div class="page-head"><h1>新增采购入库</h1></div>
<div class="panel">
    <form method="post" action="<?php echo site_url('PSI/purchases/store'); ?>">
        <?php echo csrf_field(); ?>
        <div class="form-grid">
            <div class="field"><label>供应商</label>
                <select name="supplier_id">
                    <option value="0">未选择</option>
                    <?php foreach ($suppliers as $s): ?>
                        <option value="<?php echo e($s['id']); ?>"><?php echo e($s['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="field"><label>入库类型</label>
                <select name="item_type" id="item_type">
                    <option value="material">物料</option>
                    <option value="product">成品</option>
                </select>
            </div>
            <div class="field"><label>物料/成品</label>
                <select name="item_id" id="item_id">
                    <optgroup label="物料">
                        <?php foreach ($materials as $m): ?><option value="<?php echo e($m['id']); ?>"><?php echo e($m['name']); ?></option><?php endforeach; ?>
                    </optgroup>
                    <optgroup label="成品">
                        <?php foreach ($products as $p): ?><option value="<?php echo e($p['id']); ?>"><?php echo e($p['name']); ?></option><?php endforeach; ?>
                    </optgroup>
                </select>
            </div>
            <div class="field"><label>数量 *</label><input name="qty" type="number" step="0.01" required></div>
            <div class="field"><label>单价</label><input name="price" type="number" step="0.01" value="0"></div>
            <div class="field"><label>批次/缸号</label><input name="batch_no" placeholder="面辅料缸号/批次"></div>
            <div class="field"><label>预计到货</label><input name="expected_at" type="date"></div>
        </div>
        <div class="field"><label>备注</label><textarea name="remark" rows="2"></textarea></div>
        <button class="btn-primary" type="submit">入库并提交</button>
        <a class="btn-soft" href="<?php echo site_url('PSI/purchases'); ?>">取消</a>
    </form>
</div>
<script>
// 切换类型时仅保留对应分组的选项
document.getElementById('item_type').addEventListener('change', function(){
    var type = this.value; // material|product
    var sel = document.getElementById('item_id');
    Array.prototype.forEach.call(sel.querySelectorAll('optgroup'), function(og){
        og.style.display = (og.label === (type==='product'?'成品':'物料')) ? '' : 'none';
    });
    sel.selectedIndex = 0;
});
</script>
