{include file="app/manage/view/index/emlog_nav"}

<input type="hidden" id="csrfToken" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">

<h1 class="page-title">
    <i class="fas fa-edit"></i>
    自营商城 · 商品<?php echo empty($goods) ? '发布' : '编辑'; ?>
</h1>

<div class="card">
    <div class="card-body">
        <input type="hidden" id="goodsId" value="<?php echo isset($goods['id']) ? $goods['id'] : 0; ?>">
        <div class="row">
            <div class="col-md-8">
                <div class="form-group">
                    <label>商品标题 <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="title" value="<?php echo isset($goods['title']) ? htmlspecialchars($goods['title']) : ''; ?>" placeholder="商品标题">
                </div>
                <div class="form-group">
                    <label>副标题</label>
                    <input type="text" class="form-control" id="subtitle" value="<?php echo isset($goods['subtitle']) ? htmlspecialchars($goods['subtitle']) : ''; ?>" placeholder="副标题/卖点">
                </div>
                <div class="form-group">
                    <label>商品详情</label>
                    <textarea class="form-control" id="content" rows="6" placeholder="商品详情HTML"><?php echo isset($goods['content']) ? htmlspecialchars($goods['content']) : ''; ?></textarea>
                </div>
                <div class="form-group">
                    <label>详情图（多个用逗号分隔 URL）</label>
                    <input type="text" class="form-control" id="images" value="<?php echo isset($goods['images']) ? htmlspecialchars($goods['images']) : ''; ?>" placeholder="https://...jpg,https://...jpg">
                </div>
            </div>
            <div class="col-md-4">
                <div class="form-group">
                    <label>商品分类</label>
                    <select class="form-control" id="cat_id">
                        <option value="0">未分类</option>
                        <?php foreach (($categories ?: array()) as $c): ?>
                        <option value="<?php echo $c['id']; ?>" <?php echo (isset($goods['cat_id']) && $goods['cat_id']==$c['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($c['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>售价(元) <span class="text-danger">*</span></label>
                    <input type="number" step="0.01" class="form-control" id="price" value="<?php echo isset($goods['price']) ? $goods['price'] : ''; ?>">
                </div>
                <div class="form-group">
                    <label>原价(元)</label>
                    <input type="number" step="0.01" class="form-control" id="original_price" value="<?php echo isset($goods['original_price']) ? $goods['original_price'] : ''; ?>">
                </div>
                <div class="form-group">
                    <label>库存</label>
                    <input type="number" class="form-control" id="stock" value="<?php echo isset($goods['stock']) ? $goods['stock'] : 0; ?>">
                </div>
                <div class="form-group">
                    <label>排序</label>
                    <input type="number" class="form-control" id="sort" value="<?php echo isset($goods['sort']) ? $goods['sort'] : 0; ?>">
                </div>
                <div class="form-group">
                    <label>状态</label>
                    <select class="form-control" id="status">
                        <option value="1" <?php echo (!isset($goods['status']) || $goods['status']==1) ? 'selected' : ''; ?>>上架</option>
                        <option value="0" <?php echo (isset($goods['status']) && $goods['status']==0) ? 'selected' : ''; ?>>下架</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>封面图</label>
                    <div class="d-flex align-items-center">
                        <input type="text" class="form-control" id="cover" value="<?php echo isset($goods['cover']) ? htmlspecialchars($goods['cover']) : ''; ?>" placeholder="封面图URL" readonly style="background:#f8fafc;">
                        <button type="button" class="btn btn-outline-secondary ml-2" onclick="pickImage()" style="white-space:nowrap;">选择图片</button>
                    </div>
                    <?php if (!empty($goods['cover'])): ?><img src="<?php echo htmlspecialchars($goods['cover']); ?>" id="coverPrev" style="width:80px;height:80px;object-fit:cover;margin-top:8px;border-radius:6px;"><?php endif; ?>
                </div>
                <input type="file" id="coverFile" accept="image/*" style="display:none;" onchange="uploadImage()">
            </div>
        </div>

        <div class="border-top pt-3 mt-3">
            <button class="btn btn-primary px-5" id="saveBtn" onclick="saveGoods()"><i class="fas fa-save"></i> 保存</button>
            <a href="index.php?r=manage/shop/goods" class="btn btn-outline-secondary ml-2">返回</a>
        </div>
    </div>
</div>

{include file="app/manage/view/index/emlog_footer"}

<script>
function pickImage() { document.getElementById('coverFile').click(); }
function uploadImage() {
    var f = document.getElementById('coverFile').files[0];
    if (!f) return;
    var token = document.getElementById('csrfToken').value;
    var fd = new FormData();
    fd.append('file', f);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'index.php?r=manage/File/upload&type=shop&field=file&_token=' + token, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            try {
                var r = JSON.parse(xhr.responseText);
                if (r.status === 'y' && r.url) {
                    document.getElementById('cover').value = r.url;
                    var prev = document.getElementById('coverPrev');
                    if (prev) { prev.src = r.url; } else {
                        var img = document.createElement('img');
                        img.id = 'coverPrev'; img.src = r.url;
                        img.style.cssText = 'width:80px;height:80px;object-fit:cover;margin-top:8px;border-radius:6px;';
                        document.getElementById('cover').parentNode.appendChild(img);
                    }
                    showToast('封面上传成功', 'success');
                } else { showToast(r.info || '上传失败', 'danger'); }
            } catch(e) { showToast('上传响应异常', 'danger'); }
        }
    };
    xhr.send(fd);
}
function saveGoods() {
    var id = document.getElementById('goodsId').value;
    var title = document.getElementById('title').value.trim();
    var price = document.getElementById('price').value;
    if (!title) { showToast('请填写商品标题', 'danger'); return; }
    if (!price || parseFloat(price) <= 0) { showToast('售价必须大于0', 'danger'); return; }
    var token = document.getElementById('csrfToken').value;
    var btn = document.getElementById('saveBtn');
    btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
    var data = 'id=' + id
        + '&cat_id=' + document.getElementById('cat_id').value
        + '&title=' + encodeURIComponent(title)
        + '&subtitle=' + encodeURIComponent(document.getElementById('subtitle').value)
        + '&cover=' + encodeURIComponent(document.getElementById('cover').value)
        + '&images=' + encodeURIComponent(document.getElementById('images').value)
        + '&price=' + price
        + '&original_price=' + document.getElementById('original_price').value
        + '&stock=' + document.getElementById('stock').value
        + '&sort=' + document.getElementById('sort').value
        + '&status=' + document.getElementById('status').value
        + '&content=' + encodeURIComponent(document.getElementById('content').value);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'index.php?r=manage/shop/goodsSave&_token=' + token, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            btn.disabled = false; btn.innerHTML = '<i class="fas fa-save"></i> 保存';
            try {
                var r = JSON.parse(xhr.responseText);
                if (r.status === 'y') { showToast(r.info, 'success'); setTimeout(function(){ location.href='index.php?r=manage/shop/goods'; }, 800); }
                else showToast(r.info || '保存失败', 'danger');
            } catch(e) { showToast('响应异常', 'danger'); }
        }
    };
    xhr.send(data);
}
function showToast(message, type) {
    type = type || 'success';
    var toast = document.createElement('div');
    toast.className = 'toast align-items-center text-white bg-' + type + ' border-0 position-fixed show';
    toast.setAttribute('role', 'alert');
    toast.style.cssText = 'top:20px;right:20px;z-index:9999;min-width:280px;opacity:1;transition:opacity .3s ease;';
    toast.innerHTML = '<div class="d-flex"><div class="toast-body"><i class="fas fa-' + (type==='success'?'check-circle':'exclamation-circle') + ' mr-2"></i>' + message + '</div><button type="button" class="btn-close btn-close-white me-2 m-auto" onclick="this.parentElement.parentElement.remove()"></button></div>';
    document.body.appendChild(toast);
    setTimeout(function(){ toast.style.opacity='0'; setTimeout(function(){ if(toast.parentNode) toast.parentNode.removeChild(toast); }, 350); }, 3000);
}
</script>
