<?php
/** PSI 采购订单录入/编辑 */
/** @var array|null $o @var array $items @var array $materials @var array $products */
$isEdit = !empty($o);
$cat = ['material' => [], 'product' => []];
foreach ($materials as $m) { $cat['material'][(int)$m['id']] = ['name' => $m['name'], 'spec' => $m['spec'] ?? '', 'unit' => $m['unit'] ?? '', 'price' => (float)($m['price'] ?? 0)]; }
foreach ($products as $p) { $cat['product'][(int)$p['id']] = ['name' => $p['name'], 'spec' => $p['spec'] ?? '', 'unit' => $p['unit'] ?? '', 'price' => (float)($p['price'] ?? 0)]; }
?>
<div class="page-head">
    <div><h1><?php echo $isEdit ? '编辑采购订单' : '新建采购订单'; ?></h1><div class="desc">选择供应商与采购明细（物料 / 成品），收货后自动入库</div></div>
    <a class="btn-ghost" href="<?php echo site_url('PSI/purchase_orders'); ?>">← 返回</a>
</div>

<div class="panel form-card">
    <form method="post" action="<?php echo site_url($isEdit ? ('PSI/purchase_orders/update/' . $o['id']) : 'PSI/purchase_orders/store'); ?>">
        <?php echo csrf_field(); ?>
        <div class="form-row">
            <label>供应商 <span class="req">*</span></label>
            <input type="text" name="supplier_name" value="<?php echo e($o['supplier_name'] ?? ''); ?>" required placeholder="供应商名称">
        </div>
        <div class="form-row">
            <label>采购员</label>
            <input type="text" name="salesman" value="<?php echo e($o['salesman'] ?? ($_SESSION['admin_name'] ?? '')); ?>" placeholder="默认当前登录人">
        </div>
        <div class="form-row">
            <label>期望到货</label>
            <input type="date" name="expected_at" value="<?php echo e($o['expected_at'] ?? ''); ?>">
        </div>
        <div class="form-row">
            <label>备注</label>
            <textarea name="remark" rows="2" placeholder="选填"><?php echo e($o['remark'] ?? ''); ?></textarea>
        </div>

        <div class="form-row">
            <label>采购明细 <span class="req">*</span></label>
            <div class="table-wrap">
                <table class="tbl" id="itemTbl">
                    <thead><tr>
                        <th style="width:90px">类型</th><th style="width:160px">选择</th><th>名称</th><th>规格</th><th>单位</th>
                        <th>数量</th><th>单价</th><th>金额</th><th></th>
                    </tr></thead>
                    <tbody id="itemBody"></tbody>
                </table>
            </div>
            <button type="button" class="btn" id="addRow" style="margin-top:10px"><?php echo admin_icon('plus', 16); ?> 添加明细</button>
        </div>

        <div class="form-row" style="margin-bottom:14px">
            <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-weight:normal">
                <input type="checkbox" name="auto_print" value="1" checked style="width:auto;margin:0"> 保存后打印预览
            </label>
        </div>
        <div class="form-actions">
            <button type="submit" class="btn-primary">保存</button>
            <a class="btn-ghost" href="<?php echo site_url('PSI/purchase_orders'); ?>">取消</a>
        </div>
    </form>
</div>

<script>
const CAT = <?php echo json_encode($cat, JSON_UNESCAPED_UNICODE); ?>;
let ROW = 0;
function opts(type){
    let h = '<option value="0">手动输入</option>';
    for (const id in CAT[type]) h += `<option value="${id}">${CAT[type][id].name}</option>`;
    return h;
}
function newRow(p){
    p = p || {};
    const type = p.item_type || 'material';
    const tr = document.createElement('tr');
    tr.className = 'item-row';
    tr.innerHTML = `
        <td><select class="itype">
                <option value="material" ${type==='material'?'selected':''}>物料</option>
                <option value="product" ${type==='product'?'selected':''}>成品</option>
            </select>
            <input type="hidden" name="items[${ROW}][item_type]" class="itype-h" value="${type}"></td>
        <td><select class="isel" style="width:100%">${opts(type)}</select>
            <input type="hidden" name="items[${ROW}][item_id]" class="iid" value="${p.item_id||0}"></td>
        <td><input type="text" name="items[${ROW}][name]" value="${p.name||''}" required style="width:100%"></td>
        <td><input type="text" name="items[${ROW}][spec]" value="${p.spec||''}" style="width:90px"></td>
        <td><input type="text" name="items[${ROW}][unit]" value="${p.unit||''}" style="width:50px"></td>
        <td><input type="number" min="1" name="items[${ROW}][qty]" value="${p.qty||1}" class="qty" style="width:64px"></td>
        <td><input type="number" step="0.01" min="0" name="items[${ROW}][price]" value="${p.price||0}" class="price" style="width:84px"></td>
        <td class="amt" style="white-space:nowrap">¥0.00</td>
        <td><button type="button" class="row-del" title="删除">×</button></td>`;
    ROW++;
    const sel = tr.querySelector('.isel');
    const typeSel = tr.querySelector('.itype');
    sel.value = p.item_id || '0';
    typeSel.addEventListener('change', e=>{
        const t = e.target.value;
        tr.querySelector('.itype-h').value = t;
        sel.innerHTML = opts(t); sel.value = '0';
    });
    sel.addEventListener('change', e=>{
        const id = e.target.value;
        tr.querySelector('.iid').value = id;
        if (CAT[type][id]) { const d=CAT[type][id];
            tr.querySelector('input[name$="[name]"]').value=d.name;
            tr.querySelector('input[name$="[spec]"]').value=d.spec;
            tr.querySelector('input[name$="[unit]"]').value=d.unit;
            tr.querySelector('input[name$="[price]"]').value=d.price; calc(tr);
        }
    });
    tr.querySelector('.qty').addEventListener('input', ()=>calc(tr));
    tr.querySelector('.price').addEventListener('input', ()=>calc(tr));
    tr.querySelector('.row-del').addEventListener('click', ()=>tr.remove());
    return tr;
}
function calc(tr){
    const q=parseFloat(tr.querySelector('.qty').value)||0, p=parseFloat(tr.querySelector('.price').value)||0;
    tr.querySelector('.amt').textContent='¥'+(q*p).toFixed(2);
}
document.getElementById('addRow').addEventListener('click', ()=>document.getElementById('itemBody').appendChild(newRow()));
<?php if (!empty($items)): ?>
<?php foreach ($items as $it): ?>
document.getElementById('itemBody').appendChild(newRow({
    item_type:'<?php echo $it['item_type']==='product'?'product':'material'; ?>',
    item_id:<?php echo (int)($it['item_id'] ?? 0); ?>,
    name:<?php echo json_encode($it['name'] ?? '', JSON_UNESCAPED_UNICODE); ?>,
    spec:<?php echo json_encode($it['spec'] ?? '', JSON_UNESCAPED_UNICODE); ?>,
    unit:<?php echo json_encode($it['unit'] ?? '', JSON_UNESCAPED_UNICODE); ?>,
    qty:<?php echo (int)($it['qty'] ?? 1); ?>,
    price:<?php echo (float)($it['price'] ?? 0); ?>
}));
<?php endforeach; ?>
<?php else: ?>
document.getElementById('itemBody').appendChild(newRow());
<?php endif; ?>
</script>
