<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action'])) {
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        $ajaxAct = $_POST['ajax_action'];

        if ($ajaxAct === 'delete') {
            $idsRaw = isset($_POST['ids']) ? $_POST['ids'] : '[]';
            $ids = json_decode($idsRaw, true);
            if (!is_array($ids)) { $ids = []; }
            $ids = array_map('intval', $ids);
            if (empty($ids)) { echo json_encode(['code'=>400,'msg'=>'请选择要删除的项']); exit; }
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $db->query("DELETE FROM {$db->table('product')} WHERE id IN ($placeholders)", $ids);
            echo json_encode(['code'=>200,'msg'=>'已删除 '.count($ids).' 项']); exit;
        }

        if ($ajaxAct === 'show') {
            $idsRaw = isset($_POST['ids']) ? $_POST['ids'] : '[]';
            $ids = json_decode($idsRaw, true);
            if (!is_array($ids)) { $ids = []; }
            $ids = array_map('intval', $ids);
            if (empty($ids)) { echo json_encode(['code'=>400,'msg'=>'请选择']); exit; }
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $db->query("UPDATE {$db->table('product')} SET status=1, update_time=? WHERE id IN ($placeholders)", array_merge([time()], $ids));
            echo json_encode(['code'=>200,'msg'=>'已显示']); exit;
        }

        if ($ajaxAct === 'hide') {
            $idsRaw = isset($_POST['ids']) ? $_POST['ids'] : '[]';
            $ids = json_decode($idsRaw, true);
            if (!is_array($ids)) { $ids = []; }
            $ids = array_map('intval', $ids);
            if (empty($ids)) { echo json_encode(['code'=>400,'msg'=>'请选择']); exit; }
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $db->query("UPDATE {$db->table('product')} SET status=0, update_time=? WHERE id IN ($placeholders)", array_merge([time()], $ids));
            echo json_encode(['code'=>200,'msg'=>'已隐藏']); exit;
        }
    }


$action = isset($_GET['action']) ? $_GET['action'] : 'list';
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$pageSize = 15;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $license = new \Core\Lib\License();
    if (!$license->canAddProduct()) {
        echo '<script>alert("免费版产品数量已上限（5个），请升级到基础版或专业版");history.back();</script>';
        exit;
    }
    if ($action === 'save') {
        $specs = isset($_POST['specs']) ? json_encode($_POST['specs'], JSON_UNESCAPED_UNICODE) : '';
        $attrs = isset($_POST['attrs']) ? json_encode($_POST['attrs'], JSON_UNESCAPED_UNICODE) : '';
        $data = [
            'channel_id' => intval((isset($_POST['channel_id']) ? $_POST['channel_id'] : 0)),
            'title' => trim((isset($_POST['title']) ? $_POST['title'] : '')),
            'product_code' => trim((isset($_POST['product_code']) ? $_POST['product_code'] : '')),
            'litpic' => trim((isset($_POST['litpic']) ? $_POST['litpic'] : '')),
            'pictures' => isset($_POST['pictures']) ? trim($_POST['pictures']) : '',
            'flag' => isset($_POST['flag']) ? implode(',', $_POST['flag']) : '',
            'tags' => trim((isset($_POST['tags']) ? $_POST['tags'] : '')),
            'summary' => trim((isset($_POST['summary']) ? $_POST['summary'] : '')),
            'content' => isset($_POST['content']) ? $_POST['content'] : '',
            'seo_title' => trim((isset($_POST['seo_title']) ? $_POST['seo_title'] : '')),
            'seo_keywords' => trim((isset($_POST['seo_keywords']) ? $_POST['seo_keywords'] : '')),
            'seo_description' => trim((isset($_POST['seo_description']) ? $_POST['seo_description'] : '')),
            'price' => floatval((isset($_POST['price']) ? $_POST['price'] : 0)),
            'market_price' => floatval((isset($_POST['market_price']) ? $_POST['market_price'] : 0)),
            'cost_price' => floatval((isset($_POST['cost_price']) ? $_POST['cost_price'] : 0)),
            'unit' => trim((isset($_POST['unit']) ? $_POST['unit'] : '')),
            'stock' => intval((isset($_POST['stock']) ? $_POST['stock'] : 999)),
            'specs' => $specs,
            'attrs' => $attrs,
            'sort_order' => intval((isset($_POST['sort_order']) ? $_POST['sort_order'] : 100)),
            'status' => isset($_POST['status']) ? 1 : 0,
            'update_time' => time()
        ];
        $postId = isset($_POST['id']) ? intval($_POST['id']) : 0;
        if ($postId > 0) {
            $db->update('product', $data, 'id = ?', [$postId]);
            addLog('修改', '产品管理', '修改产品 ' . $data['title']);
        } else {
            $data['create_time'] = time();
            $db->insert('product', $data);
            addLog('添加', '产品管理', '添加产品 ' . $data['title']);
        }
        echo '<script>alert("保存成功");location.href="?act=product"</script>';
        exit;
    }
    if ($action === 'delete') {
        $id = intval($_POST['id']);
        $product = $db->fetch("SELECT title FROM {$db->table('product')} WHERE id = ?", [$id]);
        $db->delete('product', 'id = ?', [$id]);
        addLog('删除', '产品管理', '删除产品 ' . ((isset($product['title']) ? $product['title'] : $id)));
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }
}

if ($action === 'export') {
    $keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';
    $channelId = isset($_GET['channel_id']) ? intval($_GET['channel_id']) : 0;
    $where = '1=1';
    $params = [];
    if ($channelId > 0) { $where .= ' AND p.channel_id = ?'; $params[] = $channelId; }
    if (!empty($keyword)) { $where .= ' AND (p.title LIKE ? OR p.product_code LIKE ?)'; $params[] = '%'.$keyword.'%'; $params[] = '%'.$keyword.'%'; }
    $products = $db->fetchAll("SELECT p.*, c.channel_name FROM {$db->table('product')} p LEFT JOIN {$db->table('channel')} c ON p.channel_id = c.id WHERE {$where} ORDER BY p.id DESC", $params);
    header('Content-Type: application/vnd.ms-excel;charset=utf-8');
    header('Content-Disposition: attachment;filename=products_'.date('YmdHis').'.xls');
    echo '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><style>td,th{border:1px solid #ccc;padding:6px 10px;white-space:nowrap;}th{background:#2563eb;color:#fff;font-weight:600;}</style></head><body><table>';
    echo '<tr><th>ID</th><th>产品名称</th><th>货号</th><th>分类</th><th>售价</th><th>市场价</th><th>成本价</th><th>单位</th><th>库存</th><th>标签</th><th style="width:100px;">状态</th><th>添加时间</th></tr>';
    foreach ($products as $p) {
        echo '<tr>';
        echo '<td>'.$p['id'].'</td>';
        echo '<td>'.htmlspecialchars($p['title']).'</td>';
        echo '<td>'.htmlspecialchars($p['product_code'] ?: '-').'</td>';
        echo '<td>'.htmlspecialchars((isset($p['channel_name']) ? $p['channel_name'] : '-')).'</td>';
        echo '<td>'.$p['price'].'</td>';
        echo '<td>'.$p['market_price'].'</td>';
        echo '<td>'.$p['cost_price'].'</td>';
        echo '<td>'.htmlspecialchars($p['unit']).'</td>';
        echo '<td>'.$p['stock'].'</td>';
        echo '<td>'.htmlspecialchars($p['tags'] ?: '-').'</td>';
        echo '<td>'.($p['status'] ? '上架' : '下架').'</td>';
        echo '<td>'.($p['create_time'] ? date('Y-m-d H:i', $p['create_time']) : '-').'</td>';
        echo '</tr>';
    }
    echo '</table></body></html>';
    exit;
}

if ($action === 'list') {
    $where = '1=1';
    $params = [];
    $channelId = isset($_GET['channel_id']) ? intval($_GET['channel_id']) : 0;
    if ($channelId > 0) { $where .= ' AND channel_id = ?'; $params[] = $channelId; }
    $keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';
    if (!empty($keyword)) {
        $where .= ' AND (title LIKE ? OR product_code LIKE ?)';
        $params[] = '%' . $keyword . '%';
        $params[] = '%' . $keyword . '%';
    }
    $offset = ($page - 1) * $pageSize;
    $products = $db->fetchAll("SELECT * FROM {$db->table('product')} WHERE {$where} ORDER BY id DESC LIMIT {$offset}, {$pageSize}", $params);
    $total = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('product')} WHERE {$where}", $params)['cnt'];
    $totalPages = ceil($total / $pageSize);
    $channels = $db->fetchAll("SELECT id, channel_name FROM {$db->table('channel')} WHERE channel_type = 2 ORDER BY list_order ASC");
    $totalProducts = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('product')}")['cnt'];
    $onlineCount = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('product')} WHERE status = 1")['cnt'];
    $offlineCount = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('product')} WHERE status = 0")['cnt'];
    $lowStock = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('product')} WHERE stock < 10 AND status = 1")['cnt'];
    ?>
    <div class="page-container fade-in">
        <div class="page-header">
            <div class="page-title">
                <div class="page-icon"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 0 1-8 0"/></svg></div>
                <div>
                    <h1>产品管理</h1>
                    <p style="font-size:12px;color:#64748b;margin:0;">管理系统产品</p>
                </div>
            </div>
            <div class="page-actions">
                <a href="?act=product&action=export" class="btn btn-secondary"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg></i> 导出</a>
                <a href="?act=product&action=add" class="btn btn-primary"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg></i> 添加产品</a>
            </div>
        </div>
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon" style="background:#eff6ff;color:#2563eb;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M16.5 9.4l-9-5.19"/><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg></div>
                <div class="stat-info"><div class="stat-value"><?php echo $totalProducts; ?></div><div class="stat-label">产品总数</div></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background:#ecfdf5;color:#10b981;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg></div>
                <div class="stat-info"><div class="stat-value"><?php echo $onlineCount; ?></div><div class="stat-label">上架中</div></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background:#fffbeb;color:#f59e0b;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M16.5 9.4l-9-5.19"/><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></div>
                <div class="stat-info"><div class="stat-value"><?php echo $offlineCount; ?></div><div class="stat-label">已下架</div></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background:#fef2f2;color:#ef4444;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg></div>
                <div class="stat-info"><div class="stat-value"><?php echo $lowStock; ?></div><div class="stat-label">库存不足</div></div>
            </div>
        </div>
        <div class="filter-bar">
            <form method="get" style="display:flex;gap:12px;flex-wrap:wrap;align-items:center;width:100%;">
                <input type="hidden" name="act" value="product">
                <select name="channel_id" class="form-control" style="width:160px;">
                    <option value="">全部分类</option>
                    <?php foreach ($channels as $ch): ?>
                    <option value="<?php echo $ch['id']; ?>" <?php echo $channelId == $ch['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($ch['channel_name']); ?></option>
                    <?php endforeach; ?>
                </select>
                <input type="text" name="keyword" class="form-control" value="<?php echo htmlspecialchars($keyword); ?>" placeholder="搜索产品名称/货号..." style="width:200px;">
                <button type="submit" class="btn btn-primary">筛选</button>
                <?php if ($channelId > 0 || !empty($keyword)): ?>
                <a href="?act=product" class="btn btn-secondary">重置</a>
                <?php endif; ?>
            </form>
        </div>
        <div class="content-card">
            <?php if (empty($products)): ?>
            <div class="empty-state">
                <div class="empty-icon"><svg style="width:40px;height:40px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M16.5 9.4l-9-5.19"/><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></div>
                <h3>暂无产品</h3>
                <p>添加第一个产品吧</p>
                <a href="?act=product&action=add" class="btn btn-primary">添加产品</a>
            </div>
            <?php else: ?>
            <table class="data-table">
                <thead><tr><th style="width:50px;">ID</th><th style="width:60px;">缩略图</th><th style="width:300px;">产品名称</th><th style="width:100px;">分类</th><th style="width:100px;">库存</th><th style="width:120px;">价格</th><th style="width:80px;">状态</th><th style="width:120px;">操作</th></tr></thead>
                <tbody>
                    <?php foreach ($products as $item): ?>
                    <?php $channel = $db->fetch("SELECT channel_name FROM {$db->table('channel')} WHERE id = ?", [$item['channel_id']]); ?>
                    <tr>
                        <td class="id-cell"><?php echo $item['id']; ?></td>
                        <td>
                            <?php
                            $thumbUrl = '';
                            $db_pics_raw = isset($item['pictures']) ? $item['pictures'] : '';
                            if (!empty($item['litpic']) && strpos($item['litpic'], '/') !== false) {
                                $thumbUrl = $item['litpic'];
                            } elseif (!empty($db_pics_raw)) {
                                $pics = json_decode($db_pics_raw, true);
                                if (is_array($pics) && !empty($pics[0])) {
                                    $thumbUrl = $pics[0];
                                }
                            }
                            if (!empty($thumbUrl) && ($thumbUrl === 'undefined' || stripos($thumbUrl, 'undefined') === 0)) {
                                $thumbUrl = '';
                            }
                            if (!empty($thumbUrl)): ?>
                            <img src="<?php echo htmlspecialchars($thumbUrl); ?>" style="width:48px;height:36px;object-fit:cover;border-radius:4px;border:1px solid #e2e8f0;">
                            <?php else: ?>
                            <div style="width:48px;height:36px;background:#f1f5f9;border-radius:4px;display:flex;align-items:center;justify-content:center;"><svg style="width:20px;height:20px;color:#94a3b8;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg></div>
                            <?php endif; ?>
                        </td>
                        <td><a href="?act=product&action=edit&id=<?php echo $item['id']; ?>" style="color:#334155;text-decoration:none;"><?php echo htmlspecialchars($item['title']); ?></a></td>
                        <td style="font-size:12px;color:#64748b;"><?php echo htmlspecialchars(isset($channel['channel_name']) ? $channel['channel_name'] : '-'); ?></td>
                        <td style="font-family:monospace;"><?php echo $item['stock']; ?></td>
                        <td style="font-size:12px;color:#ef4444;font-weight:600;font-family:monospace;">¥<?php echo number_format($item['price'], 2); ?></td>
                        <td>
                            <?php if ($item['status'] == 1): ?>
                            <span class="badge badge-success">上架</span>
                            <?php else: ?>
                            <span class="badge badge-secondary">下架</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="btn-group">
                                <a href="?act=product&action=edit&id=<?php echo $item['id']; ?>" class="btn btn-sm btn-primary"><svg style="width:12px;height:12px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg> 编辑</a>
                                <a href="javascript:delProduct(<?php echo $item['id']; ?>);" class="btn btn-sm btn-danger"><svg style="width:12px;height:12px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg> 删除</a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
        <?php if ($totalPages > 1): ?>
        <div class="pagination">
            <?php if ($page > 1): ?><a href="?act=product&page=<?php echo $page - 1; ?>&channel_id=<?php echo $channelId; ?>&keyword=<?php echo urlencode($keyword); ?>">&laquo; 上一页</a><?php endif; ?>
            <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
            <a href="?act=product&page=<?php echo $i; ?>&channel_id=<?php echo $channelId; ?>&keyword=<?php echo urlencode($keyword); ?>" <?php echo $i == $page ? 'class="active"' : ''; ?>><?php echo $i; ?></a>
            <?php endfor; ?>
            <?php if ($page < $totalPages): ?><a href="?act=product&page=<?php echo $page + 1; ?>&channel_id=<?php echo $channelId; ?>&keyword=<?php echo urlencode($keyword); ?>">下一页 &raquo;</a><?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
    <script>
    function delProduct(id) { if (confirm('确定删除这个产品?')) { fetch('?act=product&action=delete', {method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id='+id}).then(r=>r.json()).then(d=>{alert(d.msg);if(d.code==200)location.reload();}); } }
    function toggleCheckAll(cb) { document.querySelectorAll('.row-check').forEach(function(c){c.checked=cb.checked;}); }
    function getSelectedIds() { var ids=[]; document.querySelectorAll('.row-check:checked').forEach(function(c){ids.push(c.value);}); return ids; }
    function batchAction(action) {
        var ids = getSelectedIds();
        if (ids.length === 0) { alert('请先勾选要操作的项'); return; }
        if (action === 'delete') {
            if (!confirm('确定删除选中的 ' + ids.length + ' 项？')) return;
        }
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=product&action=batch', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                try { var d = JSON.parse(xhr.responseText); alert(d.msg||'操作完成'); if(d.code==200) location.reload(); }
                catch(e) { alert('JSON解析失败'); }
            }
        };
        xhr.send('ajax_action=' + action + '&ids=' + encodeURIComponent(JSON.stringify(ids)));
    }

</script>
    <?php
}

if ($action === 'add' || $action === 'edit') {
    $defaults = ['id'=>'','channel_id'=>0,'title'=>'','product_code'=>'','litpic'=>'','pictures'=>'','flag'=>'','tags'=>'','summary'=>'','content'=>'','seo_title'=>'','seo_keywords'=>'','seo_description'=>'','price'=>0,'market_price'=>0,'cost_price'=>0,'unit'=>'','stock'=>999,'specs'=>'','attrs'=>'','sort_order'=>100,'status'=>1];
    if ($action === 'add' && isset($_GET['channel_id'])) {
        $defaults['channel_id'] = intval($_GET['channel_id']);
    }
    $editData = $defaults;
    if ($action === 'edit' && isset($_GET['id'])) {
        $editData = $db->fetch("SELECT * FROM {$db->table('product')} WHERE id = ?", [intval($_GET['id'])]);
    }
    $channels = $db->fetchAll("SELECT id, parent_id, channel_name FROM {$db->table('channel')} WHERE channel_type = 2 ORDER BY list_order ASC");

    function renderProductChannelSelect($channels, $parentId = 0, $selected = 0, $depth = 0) {
        foreach ($channels as $ch) {
            if ($ch['parent_id'] == $parentId) {
                echo '<option value="' . $ch['id'] . '"' . ($selected == $ch['id'] ? ' selected' : '') . '>' . str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $depth) . $ch['channel_name'] . '</option>';
                renderProductChannelSelect($channels, $ch['id'], $selected, $depth + 1);
            }
        }
    }

    $isEdit = $action === 'edit';
    ?>
    <div class="page-container fade-in">
        <div class="page-header">
            <div class="page-title">
                <div class="page-icon"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg></div>
                <div>
                    <h1><?php echo $isEdit ? '编辑产品' : '添加产品'; ?></h1>
                    <p style="font-size:12px;color:#64748b;margin:0;">填写产品信息</p>
                </div>
            </div>
            <div class="page-actions"><a href="?act=product" class="btn btn-secondary">&larr; 返回</a></div>
        </div>
        <form method="post" id="productForm" action="?act=product&action=save" onsubmit="UE.ensureSync();">
            <input type="hidden" name="id" value="<?php echo $editData['id']; ?>">
            <div style="display:grid;grid-template-columns:820px 360px;gap:20px;align-items:start;">
                <div>
                    <div class="form-section">
                        <div class="form-section-header"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg> 基本信息</div>
                        <div class="form-section-body">
                            <div class="form-row">
                                <div class="form-group">
                                    <label>产品分类 <span class="required">*</span></label>
                                    <select name="channel_id" class="form-control" required>
                                        <option value="">请选择分类</option>
                                        <?php renderProductChannelSelect($channels, 0, $editData['channel_id']); ?>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label>产品货号</label>
                                    <input type="text" name="product_code" class="form-control" value="<?php echo htmlspecialchars($editData['product_code']); ?>" placeholder="产品唯一编号">
                                </div>
                            </div>
                            <div class="form-group">
                                <label>产品名称 <span class="required">*</span></label>
                                <input type="text" name="title" class="form-control" value="<?php echo htmlspecialchars($editData['title']); ?>" placeholder="请输入产品名称" required>
                            </div>
                            <div class="form-group">
                                <label>产品标签</label>
                                <input type="text" name="tags" class="form-control" value="<?php echo htmlspecialchars($editData['tags']); ?>" placeholder="多个标签用逗号分隔">
                            </div>
                        </div>
                    </div>
                    <div class="form-section">
                        <div class="form-section-header"><svg style="width:18px;height:18px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="1" y="4" width="22" height="16" rx="2" ry="2"/><line x1="1" y1="10" x2="23" y2="10"/></svg> 价格与库存</div>
                        <div class="form-section-body">
                            <div class="form-row" style="grid-template-columns:1fr 1fr 1fr;">
                                <div class="form-group"><label>售价</label><input type="number" name="price" class="form-control" value="<?php echo $editData['price']; ?>" step="0.01" min="0"></div>
                                <div class="form-group"><label>市场价</label><input type="number" name="market_price" class="form-control" value="<?php echo $editData['market_price']; ?>" step="0.01" min="0"></div>
                                <div class="form-group"><label>成本价</label><input type="number" name="cost_price" class="form-control" value="<?php echo $editData['cost_price']; ?>" step="0.01" min="0"></div>
                            </div>
                            <div class="form-row">
                                <div class="form-group"><label>单位</label><input type="text" name="unit" class="form-control" value="<?php echo htmlspecialchars($editData['unit']); ?>" placeholder="如：个、台、件"></div>
                                <div class="form-group"><label>库存</label><input type="number" name="stock" class="form-control" value="<?php echo $editData['stock']; ?>" min="0"></div>
                            </div>
                        </div>
                    </div>
                    <div class="form-section">
                        <div class="form-section-header"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg> 产品详情</div>
                        <div class="form-section-body product-ueditor-wrap">
                            <script src="/public/ueditor/ueditor.config.js"></script>
                            <script src="/public/ueditor/ueditor.all.min.js"></script>
                            <script type="text/plain" id="product_content_editor" name="content" style="width:780px;height:420px;"><?php echo str_replace('</script>', '<\/script>', isset($editData['content']) ? $editData['content'] : ''); ?></script>
                            <script>
                            (function(){
                                var editorId = 'product_content_editor';
                                var editorContent = <?php echo json_encode(isset($editData['content']) ? $editData['content'] : '', JSON_UNESCAPED_UNICODE); ?>;
                                function initProductUeditor(){
                                    if (!window.UE) {
                                        alert('UEditor资源加载失败，请检查 /public/ueditor/ 目录');
                                        return;
                                    }
                                    try {
                                        if (UE.instants && UE.instants[editorId]) {
                                            UE.instants[editorId].destroy();
                                        }
                                    } catch(e) {}
                                    window.productContentEditor = UE.getEditor(editorId, {
                                        initialFrameWidth: 780,
                                        initialFrameHeight: 360,
                                        autoHeightEnabled: false,
                                        autoFloatEnabled: false,
                                        scaleEnabled: false,
                                        zIndex: 900,
                                        serverUrl: '/public/ueditor/php/controller.php',
                                        toolbars: [[
                                            'source', '|', 'undo', 'redo', '|',
                                            'bold', 'italic', 'underline', 'strikethrough', 'removeformat', '|',
                                            'forecolor', 'backcolor', '|',
                                            'insertorderedlist', 'insertunorderedlist', '|',
                                            'paragraph', 'fontfamily', 'fontsize', '|',
                                            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
                                            'link', 'unlink', '|',
                                            'simpleupload', 'insertimage', 'insertvideo', 'attachment', '|',
                                            'inserttable', 'horizontal', 'spechars', '|',
                                            'preview', 'fullscreen'
                                        ]]
                                    });
                                    productContentEditor.ready(function(){
                                        productContentEditor.setContent(editorContent || '');
                                    });
                                }
                                if (document.readyState === 'complete' || document.readyState === 'interactive') {
                                    setTimeout(initProductUeditor, 0);
                                } else {
                                    document.addEventListener('DOMContentLoaded', initProductUeditor);
                                }
                            })();
                            </script>
                            <style>
                            .product-ueditor-wrap{overflow:hidden !important;padding:20px !important;box-sizing:border-box;height:500px !important;}
                            #product_content_editor{width:780px !important;height:360px;}
                            #edui1,.edui-editor{width:780px !important;max-width:780px !important;box-sizing:border-box;}
                            .edui-editor-toolbarbox,.edui-editor-iframeholder{width:780px !important;max-width:780px !important;box-sizing:border-box;}
                            </style>
                        </div>
                    </div>
                </div>
                <div>
                    <div class="form-section">
                        <div class="form-section-header"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg> 产品图片</div>
                        <div class="form-section-body">
                            <div class="form-group">
                                <label style="font-size:12px;color:#64748b;margin-bottom:6px;">产品图片（用于列表及前台展示）</label>
                                <input type="hidden" name="litpic" id="litpicInput" value="<?php echo htmlspecialchars((isset($editData['litpic']) ? $editData['litpic'] : '')); ?>">
                                <div id="litpicPreview" onclick="document.getElementById('litpicFile').click()" style="width:100%;height:200px;border:2px dashed #e2e8f0;border-radius:6px;cursor:pointer;display:flex;align-items:center;justify-content:center;overflow:hidden;background:#fafafa;">
                                    <?php if (!empty($editData['litpic'])): ?>
                                    <img src="<?php echo htmlspecialchars($editData['litpic']); ?>" style="width:100%;height:100%;object-fit:cover;">
                                    <?php else: ?>
                                    <div style="text-align:center;"><svg style="width:32px;height:32px;color:#cbd5e1;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg><p style="font-size:12px;color:#94a3b8;margin:8px 0 0 0;">点击上传产品图片</p></div>
                                    <?php endif; ?>
                                </div>
                                <input type="file" id="litpicFile" accept="image/*" style="display:none;" onchange="handleLitpicUpload(this)">
                                <p style="font-size:11px;color:#94a3b8;margin-top:4px;">支持 JPG/PNG/GIF，不超过 5MB</p>
                            </div>
                        </div>
                    </div>
                    <div class="form-section">
                        <div class="form-section-header"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg> 发布设置</div>
                        <div class="form-section-body">
                            <div class="form-group"><label>排序</label><input type="number" name="sort_order" class="form-control" value="<?php echo $editData['sort_order']; ?>" min="0"></div>
                            <div class="form-group">
                                <label style="display:flex;align-items:center;gap:12px;cursor:pointer;padding-top:8px;">
                                    <input type="checkbox" name="status" value="1" <?php echo $editData['status'] ? 'checked' : ''; ?> id="statusToggle" style="display:none;">
                                    <div id="statusSwitch" style="width:44px;height:24px;background:<?php echo $editData['status'] ? '#10b981' : '#cbd5e1'; ?>;border-radius:12px;position:relative;transition:all 0.2s;"><div style="width:18px;height:18px;background:#fff;border-radius:50%;position:absolute;top:3px;left:<?php echo $editData['status'] ? '23px' : '3px'; ?>;transition:all 0.2s;"></div></div>
                                    <span id="statusLabel" style="font-weight:500;color:<?php echo $editData['status'] ? '#10b981' : '#64748b'; ?>;"><?php echo $editData['status'] ? '上架' : '下架'; ?></span>
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="form-section">
                        <div class="form-section-header"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg> SEO优化</div>
                        <div class="form-section-body">
                            <div class="form-group"><label>SEO标题</label><input type="text" name="seo_title" class="form-control" value="<?php echo htmlspecialchars($editData['seo_title']); ?>" placeholder="留空使用产品名称"></div>
                            <div class="form-group"><label>SEO关键字</label><input type="text" name="seo_keywords" class="form-control" value="<?php echo htmlspecialchars($editData['seo_keywords']); ?>" placeholder="关键字1,关键字2"></div>
                            <div class="form-group"><label>SEO描述</label><textarea name="seo_description" class="form-control" rows="3" placeholder="产品描述"><?php echo htmlspecialchars($editData['seo_description']); ?></textarea></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="form-actions" style="background:#fff;padding:20px;border-radius:8px;margin-top:20px;">
                <button type="submit" class="btn btn-success btn-lg"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg> <?php echo $isEdit ? '保存修改' : '添加产品'; ?></button>
                <a href="?act=product" class="btn btn-secondary btn-lg">取消</a>
            </div>
        </form>
    </div>
    <script>
    document.getElementById('statusToggle').addEventListener('change', function() {
        var sw = document.getElementById('statusSwitch');
        var lb = document.getElementById('statusLabel');
        if (this.checked) { sw.style.background = '#10b981'; sw.querySelector('div').style.left = '23px'; lb.textContent = '上架'; lb.style.color = '#10b981'; }
        else { sw.style.background = '#cbd5e1'; sw.querySelector('div').style.left = '3px'; lb.textContent = '下架'; lb.style.color = '#64748b'; }
    });
    function uploadFile(file, targetId, previewId) {
        var formData = new FormData();
        formData.append('file', file);
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=upload', true);
        xhr.onload = function() {
            if (xhr.status === 200) {
                var d = JSON.parse(xhr.responseText);
                if (d.code === 200) {
                    document.getElementById(targetId).value = d.data.url;
                    var preview = document.getElementById(previewId);
                    preview.innerHTML = '<img src="' + d.data.url + '" style="width:100%;height:100%;object-fit:cover;">';
                } else { alert(d.msg); }
            }
        };
        xhr.send(formData);
    }
    function handleLitpicUpload(input) {
        var file = input.files[0];
        if (!file) return;
        if (file.size > 5 * 1024 * 1024) { alert('图片大小不能超过5MB'); return; }
        var formData = new FormData();
        formData.append('file', file);
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=upload', true);
        xhr.onload = function() {
            if (xhr.status === 200) {
                var d = JSON.parse(xhr.responseText);
                if (d.code === 200) {
                    document.getElementById('litpicInput').value = d.data.url;
                    document.getElementById('litpicPreview').innerHTML = '<img src="' + d.data.url + '" style="width:100%;height:100%;object-fit:cover;">';
                } else { alert(d.msg); }
            }
        };
        xhr.send(formData);
    }
    function handleMultiImageUpload(input) {
        var files = input.files;
        if (!files.length) return;
        var formData = new FormData();
        for (var i = 0; i < files.length; i++) {
            if (files[i].size > 5 * 1024 * 1024) { alert('图片大小不能超过5MB'); return; }
        }
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=upload', true);
        xhr.onload = function() {
            if (xhr.status === 200) {
                var d = JSON.parse(xhr.responseText);
                if (d.code === 200) {
                    var current = document.getElementById('picturesInput').value;
                    var pics = current ? JSON.parse(current) : [];
                    pics.push(d.data.url);
                    document.getElementById('picturesInput').value = JSON.stringify(pics);
                    renderPictures(pics);
                } else { alert(d.msg); }
            }
        };
        // 上传所有文件
        var uploaded = 0, urls = [];
        function uploadNext(idx) {
            if (idx >= files.length) {
                var allUrls = urls.concat(JSON.parse(document.getElementById('picturesInput').value || '[]'));
                document.getElementById('picturesInput').value = JSON.stringify(allUrls);
                renderPictures(allUrls);
                return;
            }
            var fd = new FormData();
            fd.append('file', files[idx]);
            var x = new XMLHttpRequest();
            x.open('POST', '?act=upload', true);
            x.onload = function() {
                if (x.status === 200) {
                    var r = JSON.parse(x.responseText);
                    if (r.code === 200) urls.push(r.data.url);
                }
                uploadNext(idx + 1);
            };
            x.send(fd);
        }
        uploadNext(0);
    }
    function renderPictures(pics) {
        var grid = document.getElementById('picturesGrid');
        grid.innerHTML = '';
        pics.forEach(function(url, idx) {
            var div = document.createElement('div');
            div.className = 'pic-item';
            div.dataset.url = url;
            div.style.cssText = 'position:relative;border-radius:6px;overflow:hidden;border:1px solid #e2e8f0;';
            var img = document.createElement('img');
            img.src = url;
            img.style.cssText = 'width:100%;height:80px;object-fit:cover;display:block;';
            var remove = document.createElement('span');
            remove.style.cssText = 'position:absolute;top:2px;right:2px;width:20px;height:20px;background:rgba(239,68,68,0.9);color:#fff;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:14px;cursor:pointer;line-height:1;';
            remove.innerHTML = '×';
            remove.onclick = function() { removePic(remove); };
            var label = document.createElement('span');
            label.style.cssText = 'position:absolute;bottom:0;left:0;right:0;background:rgba(37,99,235,0.85);color:#fff;font-size:10px;text-align:center;padding:2px;';
            label.innerHTML = '封面';
            div.appendChild(img);
            div.appendChild(remove);
            if (idx === 0) div.appendChild(label);
            grid.appendChild(div);
        });
    }
    function toggleCheckAll(cb) { document.querySelectorAll('.row-check').forEach(function(c){c.checked=cb.checked;}); }
    function getSelectedIds() { var ids=[]; document.querySelectorAll('.row-check:checked').forEach(function(c){ids.push(c.value);}); return ids; }
    function batchAction(action) {
        var ids = getSelectedIds();
        if (ids.length === 0) { alert('请先勾选要操作的项'); return; }
        if (action === 'delete') {
            if (!confirm('确定删除选中的 ' + ids.length + ' 项？')) return;
        }
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=product&action=batch', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                try { var d = JSON.parse(xhr.responseText); alert(d.msg||'操作完成'); if(d.code==200) location.reload(); }
                catch(e) { alert('JSON解析失败'); }
            }
        };
        xhr.send('ajax_action=' + action + '&ids=' + encodeURIComponent(JSON.stringify(ids)));
    }
</script>
    <?php
}
?>
