<?php
/** PSI 出库单录入/编辑 */
/** @var array|null $o @var array $items @var array|null $so @var array $soItems @var array $products */
$isEdit = !empty($o);
$prodMap = [];
foreach ($products as $p) { $prodMap[(int)$p['id']] = ['name' => $p['name'], 'spec' => $p['spec'] ?? '', 'unit' => $p['unit'] ?? '', 'price' => (float)($p['price'] ?? 0)]; }

// 行数据来源：编辑=出库明细；新建且带销售订单=销售订单未交明细；否则空行
$rows = [];
if ($isEdit) {
    foreach ($items as $it) $rows[] = ['so_item_id' => $it['so_item_id'], 'product_id' => $it['product_id'], 'name' => $it['name'], 'spec' => $it['spec'], 'unit' => $it['unit'], 'qty' => $it['qty'], 'price' => $it['price']];
} elseif ($so) {
    foreach ($soItems as $si) { $remain = max(0, (int)($si['qty'] ?? 0) - (int)($si['delivered_qty'] ?? 0)); if ($remain <= 0) continue;
        $rows[] = ['so_item_id' => $si['id'], 'product_id' => $si['product_id'], 'name' => $si['name'], 'spec' => $si['spec'], 'unit' => $si['unit'], 'qty' => $remain, 'price' => $si['price']];
    }
}
?>
<div class="page-head">
    <div><h1><?php echo $isEdit ? '编辑出库单' : '新建出库单'; ?></h1>
        <div class="desc"><?php echo $so ? ('关联销售订单：<b>' . e($so['order_no']) . '</b> · 已预填未交明细') : '填写出库明细，保存后自动扣减库存'; ?></div></div>
    <a class="btn-ghost" href="<?php echo site_url('PSI/outbounds'); ?>">← 返回</a>
</div>

<div class="panel form-card">
    <form method="post" action="<?php echo site_url($isEdit ? ('PSI/outbounds/update/' . $o['id']) : 'PSI/outbounds/store'); ?>">
        <?php echo csrf_field(); ?>
        <input type="hidden" name="so_no" value="<?php echo e($o['so_no'] ?? ($so['order_no'] ?? '')); ?>">
        <div class="form-row">
            <label>关联销售订单</label>
            <input type="text" value="<?php echo e($o['so_no'] ?? ($so['order_no'] ?? '')); ?>" readonly placeholder="可选，留空为独立出库">
        </div>
        <div class="form-row">
            <label>客户 <span class="req">*</span></label>
            <input type="text" name="customer" value="<?php echo e($o['customer'] ?? ($so['customer'] ?? '')); ?>" required>
        </div>
        <div class="form-row">
            <label>业务员</label>
            <input type="text" name="salesman" value="<?php echo e($o['salesman'] ?? ($so['salesman'] ?? ($_SESSION['admin_name'] ?? ''))); ?>">
        </div>
        <div class="form-row">
            <label>仓库</label>
            <input type="text" name="warehouse" value="<?php echo e($o['warehouse'] ?? ''); ?>" placeholder="如：主仓">
        </div>
        <div class="form-row">
            <label>出库日期</label>
            <input type="date" name="delivery_date" value="<?php echo e($o['delivery_date'] ?? date('Y-m-d')); ?>">
        </div>
        <div class="form-row">
            <label>备注</label>
            <textarea name="remark" rows="2"><?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:150px">关联成品</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/outbounds'); ?>">取消</a>
        </div>
    </form>
</div>

<script>
const PROD = <?php echo json_encode($prodMap, JSON_UNESCAPED_UNICODE); ?>;
let ROW = 0;
function newRow(p){
    p = p || {};
    const tr = document.createElement('tr');
    tr.className='item-row';
    tr.innerHTML = `
        <td><select class="prod-sel" style="width:100%">
                <option value="0">手动输入</option>
                ${Object.keys(PROD).map(id=>`<option value="${id}">${PROD[id].name}</option>`).join('')}
            </select>
            <input type="hidden" name="items[${ROW}][so_item_id]" value="${p.so_item_id||0}">
            <input type="hidden" name="items[${ROW}][product_id]" class="pid" value="${p.product_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++;
    tr.querySelector('.prod-sel').addEventListener('change', e=>{ const id=e.target.value;
        if(PROD[id]){ const d=PROD[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('.pid').value=id;
        }});
    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($rows)): ?>
<?php foreach ($rows as $r): ?>
document.getElementById('itemBody').appendChild(newRow({
    so_item_id:<?php echo (int)($r['so_item_id'] ?? 0); ?>,
    product_id:<?php echo (int)($r['product_id'] ?? 0); ?>,
    name:<?php echo json_encode($r['name'] ?? '', JSON_UNESCAPED_UNICODE); ?>,
    spec:<?php echo json_encode($r['spec'] ?? '', JSON_UNESCAPED_UNICODE); ?>,
    unit:<?php echo json_encode($r['unit'] ?? '', JSON_UNESCAPED_UNICODE); ?>,
    qty:<?php echo (int)($r['qty'] ?? 1); ?>,
    price:<?php echo (float)($r['price'] ?? 0); ?>
}));
<?php endforeach; ?>
<?php else: ?>
document.getElementById('itemBody').appendChild(newRow());
<?php endif; ?>
</script>
