<?php
/** PSI 销售订单录入/编辑 */
/** @var array|null $o @var array $items @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)]; }
?>
<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/sales_orders'); ?>">← 返回</a>
</div>

<div class="panel form-card">
    <form method="post" action="<?php echo site_url($isEdit ? ('PSI/sales_orders/update/' . $o['id']) : 'PSI/sales_orders/store'); ?>">
        <?php echo csrf_field(); ?>
        <div class="form-row">
            <label>客户 <span class="req">*</span></label>
            <input type="text" name="customer" value="<?php echo e($o['customer'] ?? ''); ?>" 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="radio-row" style="margin-bottom:16px">
            <label class="radio"><input type="radio" name="channel" value="domestic" <?php echo (!empty($o) && $o['channel']==='export')?'':'checked'; ?>> 内贸</label>
            <label class="radio"><input type="radio" name="channel" value="export" <?php echo (!empty($o) && $o['channel']==='export')?'checked':''; ?>> 外贸</label>
        </div>
        <div class="form-row">
            <label>地区</label>
            <input type="text" name="region" value="<?php echo e($o['region'] ?? ''); ?>" placeholder="如：华东 / 北美">
        </div>
        <div class="form-row">
            <label>交货日期</label>
            <input type="date" name="delivery_date" value="<?php echo e($o['delivery_date'] ?? ''); ?>">
        </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: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/sales_orders'); ?>">取消</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}][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;
            tr.querySelector('.pid').value = id;
            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;
    const 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({
    product_id: <?php echo (int)($it['product_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>
