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

require_once ROOT_PATH . 'core/lib/product_spec.php';
require_once ROOT_PATH . 'core/lib/content_workflow.php';

$productTable = $db->table('product');

if (!function_exists('normalizeProductPicturesForStorage')) {
    function normalizeProductPicturesForStorage($rawPictures, $litpic = '')
    {
        $items = [];
        if (is_array($rawPictures)) {
            $items = $rawPictures;
        } else {
            $rawPictures = trim((string) $rawPictures);
            $decoded = json_decode($rawPictures, true);
            if (is_array($decoded)) {
                $items = $decoded;
            } elseif ($rawPictures !== '') {
                $items = preg_split('/[,\r\n]+/', $rawPictures);
            }
        }

        array_unshift($items, $litpic);
        $pictures = [];
        foreach ($items as $item) {
            $url = is_array($item) ? trim((string) ($item['url'] ?? '')) : trim((string) $item);
            if ($url === '' || preg_match('/^(?:javascript|data):/i', $url) || in_array($url, $pictures, true)) {
                continue;
            }
            $pictures[] = $url;
            if (count($pictures) === 5) {
                break;
            }
        }
        return $pictures;
    }
}

if (!function_exists('upsertProductConfig')) {
    function upsertProductConfig($db, $key, $value, $type = 'text')
    {
        $exists = $db->fetch("SELECT id FROM {$db->table('config')} WHERE config_key = ?", [$key]);
        if ($exists) {
            $db->update('config', ['config_value' => $value, 'update_time' => time()], 'config_key = ?', [$key]);
        } else {
            $db->insert('config', [
                'config_key' => $key,
                'config_value' => $value,
                'config_type' => $type,
                'config_group' => 'product',
                'update_time' => time()
            ]);
        }
    }
}

if (!function_exists('productFeatureDisabledAttr')) {
    function productFeatureDisabledAttr($enabled)
    {
        return $enabled ? '' : 'disabled';
    }
}

if (!function_exists('productFeatureFieldStyle')) {
    function productFeatureFieldStyle($enabled)
    {
        return $enabled ? '' : 'opacity:0.6;';
    }
}

$productLicenseObj = new \Core\Lib\License();
$productAuthorizedFeature = $productLicenseObj->isAuthorized();
$productProFeature = $productLicenseObj->getLevel() >= \Core\Lib\License::LEVEL_PRO;

$productFeatureConfig = [
    'consult_enabled' => intval(getSiteConfig('product_consult_enabled', '1')),
    'consult_type' => trim(getSiteConfig('product_consult_type', 'phone')),
    'consult_phone' => trim(getSiteConfig('product_consult_phone', '')),
    'consult_phone_text' => trim(getSiteConfig('product_consult_phone_text', '电话咨询')),
    'consult_wechat_qr' => trim(getSiteConfig('product_consult_wechat_qr', '')),
    'consult_wechat_text' => trim(getSiteConfig('product_consult_wechat_text', '添加微信')),
    'consult_email' => trim(getSiteConfig('product_consult_email', '')),
    'consult_email_text' => trim(getSiteConfig('product_consult_email_text', '邮件咨询')),
    'consult_link' => trim(getSiteConfig('product_consult_link', '')),
    'consult_link_text' => trim(getSiteConfig('product_consult_link_text', '立即咨询')),
    'form_button_type' => trim(getSiteConfig('product_form_button_type', 'inquiry')),
    'form_button_text' => trim(getSiteConfig('product_form_button_text', '在线询价')),
    'qrcode' => intval(getSiteConfig('product_feature_qrcode', '1')),
    'external_link' => $productProFeature ? intval(getSiteConfig('product_feature_external_link', '1')) : 0,
    'view_permission' => $productProFeature ? intval(getSiteConfig('product_feature_view_permission', '1')) : 0,
];

$productPageConfig = [
    'summary' => intval(getSiteConfig('product_page_summary', '1')),
    'favorite' => $productProFeature ? intval(getSiteConfig('product_page_favorite', '1')) : 0,
    'main_video' => $productProFeature ? intval(getSiteConfig('product_page_main_video', '1')) : 0,
    'comment' => $productProFeature ? intval(getSiteConfig('product_page_comment', '1')) : 0,
];

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

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

    if (in_array($ajaxAct, ['delete', 'restore', 'purge', 'show', 'hide'], true)) {
        $ids = json_decode($_POST['ids'] ?? '[]', true);
        $ids = is_array($ids) ? array_map('intval', $ids) : [];
        if (empty($ids)) {
            echo json_encode(['code' => 400, 'msg' => '请选择要删除的项']);
            exit;
        }
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        if ($ajaxAct === 'delete') {
            $db->query("UPDATE {$db->table('product')} SET status = 0, deleted_at = ?, update_time = ? WHERE id IN ({$placeholders}) AND deleted_at = 0", array_merge([time(), time()], $ids));
            $message = '已移入回收站 ' . count($ids) . ' 项';
        } elseif ($ajaxAct === 'restore') {
            $db->query("UPDATE {$db->table('product')} SET status = 0, deleted_at = 0, update_time = ? WHERE id IN ({$placeholders}) AND deleted_at > 0", array_merge([time()], $ids));
            $message = '已恢复为下架状态 ' . count($ids) . ' 项';
        } elseif ($ajaxAct === 'purge') {
            $db->query("DELETE FROM {$db->table('product')} WHERE id IN ({$placeholders}) AND deleted_at > 0", $ids);
            $message = '已永久删除 ' . count($ids) . ' 项';
        } else {
            $status = $ajaxAct === 'show' ? 1 : 0;
            $db->query("UPDATE {$db->table('product')} SET status = ?, update_time = ? WHERE id IN ({$placeholders}) AND deleted_at = 0", array_merge([$status, time()], $ids));
            $message = $status ? '已批量上架' : '已批量下架';
        }
        addLog('批量操作', '产品管理', $message);
        echo json_encode(['code' => 200, 'msg' => $message]);
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'save') {
        requireAdminCsrfToken();
        $postId = intval($_POST['id'] ?? 0);
        if ($postId <= 0) {
            $license = new \Core\Lib\License();
            if (!$license->canAddProduct()) {
                echo '<script>alert("免费版产品数量已上限（5个），请升级到基础版或专业版");history.back();</script>';
                exit;
            }
        }
        $viewGroupIds = isset($_POST['view_group_ids']) && is_array($_POST['view_group_ids']) ? array_map('intval', $_POST['view_group_ids']) : [];
        $productPictures = normalizeProductPicturesForStorage($_POST['pictures'] ?? '', $_POST['litpic'] ?? '');
        $data = [
            'channel_id' => intval($_POST['channel_id'] ?? 0),
            'title' => trim($_POST['title'] ?? ''),
            'consult_button_mode' => trim($_POST['consult_button_mode'] ?? 'pay'),
            'consult_phone' => trim($_POST['consult_phone'] ?? ''),
            'consult_wechat_qr' => trim($_POST['consult_wechat_qr'] ?? ''),
            'consult_email' => trim($_POST['consult_email'] ?? ''),
            'litpic' => $productPictures ? $productPictures[0] : '',
            'pictures' => json_encode($productPictures, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'flag' => isset($_POST['flag']) && is_array($_POST['flag']) ? implode(',', $_POST['flag']) : '',
            'tags' => trim($_POST['tags'] ?? ''),
            'external_url' => ($productProFeature && $productFeatureConfig['external_link']) ? trim($_POST['external_url'] ?? '') : '',
            'summary' => trim($_POST['summary'] ?? ''),
            'content' => $_POST['content'] ?? '',
            'seo_title' => trim($_POST['seo_title'] ?? ''),
            'seo_keywords' => trim($_POST['seo_keywords'] ?? ''),
            'seo_description' => trim($_POST['seo_description'] ?? ''),
            'price' => floatval($_POST['price'] ?? 0),
            'market_price' => floatval($_POST['market_price'] ?? 0),
            'cost_price' => floatval($_POST['cost_price'] ?? 0),
            'stock' => intval($_POST['stock'] ?? 999),
            'specs' => \Core\Lib\ProductSpec::normalizeForStorage($_POST['specs_text'] ?? ($_POST['specs'] ?? '')),
            'attrs' => isset($_POST['attrs']) ? json_encode($_POST['attrs'], JSON_UNESCAPED_UNICODE) : '',
            'sort_order' => intval($_POST['sort_order'] ?? 100),
            'status' => cmsContentSaveStatus($_POST['save_mode'] ?? (isset($_POST['status']) ? 'publish' : 'draft')),
            'main_video_url' => ($productProFeature && $productPageConfig['main_video']) ? trim($_POST['main_video_url'] ?? '') : '',
            'is_knowledge_paid' => $productAuthorizedFeature ? (isset($_POST['is_knowledge_paid']) ? 1 : 0) : 0,
            'view_group_ids' => ($productProFeature && $productFeatureConfig['view_permission']) ? implode(',', array_filter($viewGroupIds)) : '',
            'update_time' => time()
        ];
        if ($postId > 0) {
            $db->update('product', $data, 'id = ? AND deleted_at = 0', [$postId]);
            addLog('修改', '产品管理', '修改产品 ' . $data['title']);
        } else {
            $data['create_time'] = time();
            $db->insert('product', $data);
            addLog('添加', '产品管理', '添加产品 ' . $data['title']);
        }
        echo '<script>alert(' . json_encode($data['status'] ? '产品已上架' : '产品已保存为下架', JSON_UNESCAPED_UNICODE) . ');location.href="?act=product&state=' . ($data['status'] ? 'published' : 'draft') . '";</script>';
        exit;
    }

    if ($action === 'delete') {
        requireAdminCsrfToken(true);
        while (ob_get_level() > 0) {
            ob_end_clean();
        }
        header('Content-Type: application/json; charset=utf-8');
        header('Cache-Control: no-store');
        $id = intval($_POST['id'] ?? 0);
        $product = $db->fetch("SELECT title FROM {$db->table('product')} WHERE id = ?", [$id]);
        $db->update('product', ['status' => 0, 'deleted_at' => time(), 'update_time' => time()], 'id = ? AND deleted_at = 0', [$id]);
        addLog('回收', '产品管理', '产品移入回收站 ' . ($product['title'] ?? $id));
        echo json_encode(['code' => 200, 'msg' => '已移入回收站']);
        exit;
    }
}

if ($action === 'export') {
    $keyword = trim($_GET['keyword'] ?? '');
    $channelId = intval($_GET['channel_id'] ?? 0);
    $where = cmsContentStateCondition('p', $state);
    $params = [];
    if ($channelId > 0) {
        $where .= ' AND p.channel_id = ?';
        $params[] = $channelId;
    }
    if ($keyword !== '') {
        $where .= ' AND p.title LIKE ?';
        $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></tr>';
    foreach ($products as $p) {
        echo '<tr>';
        echo '<td>' . intval($p['id']) . '</td>';
        echo '<td>' . htmlspecialchars($p['title']) . '</td>';
        echo '<td>' . htmlspecialchars($p['channel_name'] ?? '-') . '</td>';
        echo '<td>' . floatval($p['price']) . '</td>';
        echo '<td>' . intval($p['stock']) . '</td>';
        echo '<td>' . (!empty($p['is_knowledge_paid']) ? '是' : '否') . '</td>';
        echo '<td>' . (!empty($p['create_time']) ? date('Y-m-d H:i', intval($p['create_time'])) : '-') . '</td>';
        echo '</tr>';
    }
    echo '</table></body></html>';
    exit;
}

if ($action === 'list') {
    $where = cmsContentStateCondition('p', $state);
    $params = [];
    $channelId = intval($_GET['channel_id'] ?? 0);
    $keyword = trim($_GET['keyword'] ?? '');
    if ($channelId > 0) {
        $where .= ' AND p.channel_id = ?';
        $params[] = $channelId;
    }
    if ($keyword !== '') {
        $where .= ' AND (p.title LIKE ? OR p.product_code LIKE ?)';
        $params[] = '%' . $keyword . '%';
        $params[] = '%' . $keyword . '%';
    }
    $total = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('product')} p WHERE {$where}", $params)['cnt'] ?? 0);
    $totalPages = max(1, intval(ceil($total / $pageSize)));
    $page = min($page, $totalPages);
    $offset = ($page - 1) * $pageSize;
    $products = $db->fetchAll("SELECT p.*, c.channel_name FROM {$db->table('product')} p LEFT JOIN {$db->table('channel')} c ON c.id = p.channel_id WHERE {$where} ORDER BY p.id DESC LIMIT {$offset}, {$pageSize}", $params);
    $channels = $db->fetchAll("SELECT id, channel_name FROM {$db->table('channel')} WHERE channel_type = 2 ORDER BY list_order ASC");
    $onlineCount = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('product')} WHERE deleted_at = 0 AND status = 1")['cnt'] ?? 0);
    $offlineCount = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('product')} WHERE deleted_at = 0 AND status = 0")['cnt'] ?? 0);
    $trashCount = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('product')} WHERE deleted_at > 0")['cnt'] ?? 0);
    ?>
    <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 product-page-actions">
                <?php if ($state === 'trash'): ?>
                <button type="button" class="btn btn-secondary" onclick="batchAction('restore')">批量恢复</button>
                <button type="button" class="btn btn-danger" onclick="batchAction('purge')">永久删除</button>
                <?php else: ?>
                <button type="button" class="btn btn-secondary" onclick="batchAction('show')">批量上架</button>
                <button type="button" class="btn btn-secondary" onclick="batchAction('hide')">批量下架</button>
                <button type="button" class="btn btn-danger" onclick="batchAction('delete')">移入回收站</button>
                <a href="?act=product&action=export" class="btn btn-secondary">导出</a>
                <a href="?act=product&action=add" class="btn btn-primary">添加产品</a>
                <?php endif; ?>
            </div>
        </div>
        <nav class="article-subnav">
            <a class="article-subnav-link <?php echo $state === 'all' ? 'is-active' : ''; ?>" href="?act=product&state=all">全部 <?php echo $onlineCount + $offlineCount; ?></a>
            <a class="article-subnav-link <?php echo $state === 'published' ? 'is-active' : ''; ?>" href="?act=product&state=published">已上架 <?php echo $onlineCount; ?></a>
            <a class="article-subnav-link <?php echo $state === 'draft' ? 'is-active' : ''; ?>" href="?act=product&state=draft">已下架 <?php echo $offlineCount; ?></a>
            <a class="article-subnav-link <?php echo $state === 'trash' ? 'is-active' : ''; ?>" href="?act=product&state=trash">回收站 <?php echo $trashCount; ?></a>
        </nav>
        <div class="filter-bar product-filter-bar">
            <form method="get" class="product-filter-form">
                <input type="hidden" name="act" value="product">
                <input type="hidden" name="state" value="<?php echo htmlspecialchars($state); ?>">
                <select name="channel_id" class="form-control" style="width:160px;">
                    <option value="">全部分类</option>
                    <?php foreach ($channels as $ch): ?>
                    <option value="<?php echo intval($ch['id']); ?>" <?php echo $channelId === intval($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:220px;">
                <button type="submit" class="btn btn-primary">筛选</button>
                <?php if ($channelId > 0 || $keyword !== ''): ?>
                <a href="?act=product&state=<?php echo urlencode($state); ?>" class="btn btn-secondary">重置</a>
                <?php endif; ?>
            </form>
        </div>
        <div class="content-card product-list-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: ?>
            <div style="overflow-x:auto;">
                <table class="data-table product-data-table">
                    <thead>
                    <tr>
                        <th style="width:40px;"><input type="checkbox" id="checkAll" onchange="toggleCheckAll(this)" style="accent-color:#2563eb;width:16px;height:16px;cursor:pointer;"></th>
                        <th style="width:50px;">ID</th>
                        <th style="width:64px;">缩略图</th>
                        <th>产品名称</th>
                        <th style="width:120px;">分类</th>
                        <th style="width:90px;">库存</th>
                        <th style="width:120px;">价格</th>
                        <th style="width:110px;">知识付费</th>
                        <th style="width:80px;">状态</th>
                        <th style="width:140px;">操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($products as $item): ?>
                    <tr>
                        <td style="text-align:center;"><input type="checkbox" class="row-check" value="<?php echo intval($item['id']); ?>" style="accent-color:#2563eb;width:16px;height:16px;cursor:pointer;"></td>
                        <td><?php echo intval($item['id']); ?></td>
                        <td>
                            <?php if (!empty($item['litpic'])): ?>
                            <img src="<?php echo htmlspecialchars($item['litpic']); ?>" 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><?php if ($state !== 'trash'): ?><a href="?act=product&action=edit&id=<?php echo intval($item['id']); ?>" style="color:#334155;text-decoration:none;"><?php echo htmlspecialchars($item['title']); ?></a><?php else: ?><?php echo htmlspecialchars($item['title']); ?><?php endif; ?></td>
                        <td style="font-size:12px;color:#64748b;"><?php echo htmlspecialchars($item['channel_name'] ?? '-'); ?></td>
                        <td style="font-family:monospace;"><?php echo intval($item['stock']); ?></td>
                        <td style="font-size:12px;color:#ef4444;font-weight:600;font-family:monospace;">¥<?php echo number_format(floatval($item['price']), 2); ?></td>
                        <td>
                            <?php if (!empty($item['is_knowledge_paid'])): ?>
                            <span class="badge" style="background:#fff7ed;color:#d97706;">已开启</span>
                            <?php else: ?>
                            <span class="badge badge-secondary">关闭</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if (intval($item['deleted_at'] ?? 0) > 0): ?><span class="badge badge-secondary">回收站</span>
                            <?php elseif (intval($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">
                                <?php if ($state !== 'trash'): ?><a href="?act=product&action=edit&id=<?php echo intval($item['id']); ?>" class="btn btn-sm btn-primary">编辑</a><a href="javascript:delProduct(<?php echo intval($item['id']); ?>);" class="btn btn-sm btn-danger">回收</a><?php else: ?><button type="button" class="btn btn-secondary" onclick="singleWorkflow('restore',<?php echo intval($item['id']); ?>)">恢复</button><button type="button" class="btn btn-danger" onclick="singleWorkflow('purge',<?php echo intval($item['id']); ?>)">永久删除</button><?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>
        <?php cmsRenderContentWorkflowPagination('product', $state, $page, $totalPages, ['channel_id' => $channelId, 'keyword' => $keyword]); ?>
    </div>
    <style>
    .product-page-actions{display:flex;gap:10px;flex-wrap:wrap;}
    .article-subnav{display:flex;gap:12px;margin-bottom:16px;flex-wrap:wrap}.article-subnav-link{padding:10px 16px;border-radius:12px;background:#fff;border:1px solid #e2e8f0;color:#475569;font-weight:600}.article-subnav-link.is-active{background:#eff6ff;border-color:#bfdbfe;color:#2563eb}
    .product-filter-bar{border:1px solid #e2e8f0;border-radius:14px;background:#fff;padding:14px 16px;margin-bottom:16px;}
    .product-filter-form{display:flex;gap:12px;flex-wrap:wrap;align-items:center;width:100%;}
    .product-list-card{border:1px solid #e2e8f0;border-radius:16px;overflow:hidden;box-shadow:0 10px 30px rgba(15,23,42,.05);}
    .product-data-table thead th{background:#f8fafc;color:#64748b;font-size:12px;font-weight:700;}
    .product-data-table tbody tr:hover{background:#fbfdff;}
    @media (max-width: 768px){.product-filter-form{flex-direction:column;align-items:stretch;}}
    </style>
    <script>
    function delProduct(id) {
        if (!confirm('确定删除这个产品?')) return;
        fetch('?act=product&action=delete', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'},
            credentials: 'same-origin',
            body: 'id=' + encodeURIComponent(id) + '&csrf_token=<?php echo rawurlencode(getAdminCsrfToken()); ?>'
        }).then(function(r){ return r.json(); }).then(function(d){
            if (d.code === 200) {
                CMSAdminUI.flash(d.msg || '已移入回收站', 'success');
                window.location.reload();
                return;
            }
            CMSAdminUI.toast(d.msg || '回收失败', 'error');
        }).catch(function(){
            CMSAdminUI.toast('回收请求失败，请稍后重试', 'error');
        });
    }
    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) { alert('请先勾选要操作的项'); return; }
        if (action === 'delete' && !confirm('确定将选中的 ' + ids.length + ' 项移入回收站？')) return;
        if (action === 'purge' && !confirm('永久删除后无法恢复，确定继续？')) 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('操作失败');
                }
            }
        };
        xhr.send('ajax_action=' + encodeURIComponent(action) + '&ids=' + encodeURIComponent(JSON.stringify(ids)) + '&csrf_token=<?php echo rawurlencode(getAdminCsrfToken()); ?>');
    }
    function singleWorkflow(action,id){document.querySelectorAll('.row-check').forEach(function(c){c.checked=String(c.value)===String(id);});batchAction(action);}
    </script>
    <?php
}

if ($action === 'add' || $action === 'edit') {
    $defaults = [
        'id' => '',
        'channel_id' => 0,
        'title' => '',
        'consult_button_mode' => 'pay',
        'consult_phone' => '',
        'consult_wechat_qr' => '',
        'consult_email' => '',
        'litpic' => '',
        'pictures' => '',
        'flag' => '',
        'tags' => '',
        'external_url' => '',
        'summary' => '',
        'content' => '',
        'seo_title' => '',
        'seo_keywords' => '',
        'seo_description' => '',
        'price' => 0,
        'market_price' => 0,
        'cost_price' => 0,
        'stock' => 999,
        'specs' => '',
        'attrs' => '',
        'sort_order' => 100,
        'status' => 1,
        'main_video_url' => '',
        'is_knowledge_paid' => 0,
        'view_group_ids' => ''
    ];
    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 = ? AND deleted_at = 0", [intval($_GET['id'])]);
        if (!$editData) {
            echo '<script>alert("产品不存在或已在回收站");location.href="?act=product";</script>'; exit;
        }
    }
    $channels = $db->fetchAll("SELECT id, parent_id, channel_name FROM {$db->table('channel')} WHERE channel_type = 2 ORDER BY list_order ASC");
    $memberGroups = $db->fetchAll("SELECT id, group_name FROM {$db->table('member_group')} ORDER BY sort_order ASC, id ASC");
    $flagChecked = !empty($editData['flag']) ? explode(',', $editData['flag']) : [];
    $viewGroupChecked = !empty($editData['view_group_ids']) ? array_map('intval', array_filter(explode(',', $editData['view_group_ids']))) : [];
    $productPictures = normalizeProductPicturesForStorage($editData['pictures'] ?? '', $editData['litpic'] ?? '');
    $isEdit = $action === 'edit';

    if (!function_exists('renderProductChannelSelectTree')) {
        function renderProductChannelSelectTree($channels, $parentId = 0, $selected = 0, $depth = 0)
        {
            foreach ($channels as $channel) {
                if (intval($channel['parent_id']) === intval($parentId)) {
                    echo '<option value="' . intval($channel['id']) . '"' . ($selected == $channel['id'] ? ' selected' : '') . '>' . str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $depth) . htmlspecialchars($channel['channel_name']) . '</option>';
                    renderProductChannelSelectTree($channels, intval($channel['id']), $selected, $depth + 1);
                }
            }
        }
    }
    ?>
    <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">
            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
            <input type="hidden" name="id" value="<?php echo intval($editData['id']); ?>">
            <input type="hidden" name="pictures" id="picturesInput" value="<?php echo htmlspecialchars(json_encode($productPictures, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); ?>">
            <div style="display:grid;grid-template-columns:minmax(0,1fr) minmax(280px,360px);gap:20px;align-items:start;">
                <div>
                    <div class="form-section">
                        <div class="form-section-header">基本信息</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 renderProductChannelSelectTree($channels, 0, intval($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-row" style="grid-template-columns:1fr 1fr;">
                                <div class="form-group">
                                    <label>产品规格</label>
                                    <input type="text" name="param_spec" class="form-control" value="<?php echo htmlspecialchars($editData['param_spec'] ?? ''); ?>" placeholder="例如：1000x600x800mm">
                                </div>
                                <div class="form-group">
                                    <label>产品材质</label>
                                    <input type="text" name="param_material" class="form-control" value="<?php echo htmlspecialchars($editData['param_material'] ?? ''); ?>" placeholder="例如：304不锈钢">
                                </div>
                            </div>
                            <div class="form-row" style="grid-template-columns:1fr 1fr;">
                                <div class="form-group">
                                    <label>产品颜色</label>
                                    <input type="text" name="param_color" class="form-control" value="<?php echo htmlspecialchars($editData['param_color'] ?? ''); ?>" placeholder="例如：银灰色">
                                </div>
                                <div class="form-group">
                                    <label>产品品牌</label>
                                    <input type="text" name="param_brand" class="form-control" value="<?php echo htmlspecialchars($editData['param_brand'] ?? ''); ?>" placeholder="例如：XX品牌">
                                </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 class="form-group">
                                <label>产品简介</label>
                                <textarea name="summary" class="form-control" rows="4" placeholder="用于产品简介卡片"><?php echo htmlspecialchars($editData['summary']); ?></textarea>
                            </div>
                            <div class="form-group">
                                <label>属性</label>
                                <div style="display:flex;gap:16px;flex-wrap:wrap;">
                                    <label style="display:flex;align-items:center;gap:6px;cursor:pointer;"><input type="checkbox" name="flag[]" value="top" <?php echo in_array('top', $flagChecked, true) ? 'checked' : ''; ?>> 置顶</label>
                                    <label style="display:flex;align-items:center;gap:6px;cursor:pointer;"><input type="checkbox" name="flag[]" value="recommend" <?php echo in_array('recommend', $flagChecked, true) ? 'checked' : ''; ?>> 推荐</label>
                                    <label style="display:flex;align-items:center;gap:6px;cursor:pointer;"><input type="checkbox" name="flag[]" value="hot" <?php echo in_array('hot', $flagChecked, true) ? 'checked' : ''; ?>> 热销</label>
                                </div>
                            </div>
                            <div class="form-row" style="<?php echo productFeatureFieldStyle($productProFeature && $productFeatureConfig['external_link']); ?>">
                                <div class="form-group">
                                    <label>外部产品链接</label>
                                    <input type="text" name="external_url" class="form-control" value="<?php echo htmlspecialchars($editData['external_url'] ?? ''); ?>" placeholder="填写后前台产品详情优先跳转到此地址" <?php echo productFeatureDisabledAttr($productProFeature && $productFeatureConfig['external_link']); ?>>
                                    <small style="display:block;margin-top:8px;color:#94a3b8;"><?php echo ($productProFeature && $productFeatureConfig['external_link']) ? '开启后可将产品详情跳转到外部购买或展示页面。' : '当前授权或功能设置不可用，已保留入口但禁止设置。'; ?></small>
                                </div>
                                <div class="form-group" style="<?php echo productFeatureFieldStyle($productProFeature && $productPageConfig['main_video']); ?>">
                                    <label>主图视频</label>
                                    <div style="display:flex;gap:10px;align-items:center;">
                                        <input type="text" name="main_video_url" id="productVideoUrlInput" class="form-control" value="<?php echo htmlspecialchars($editData['main_video_url'] ?? ''); ?>" placeholder="视频地址，可上传本地 MP4" <?php echo productFeatureDisabledAttr($productProFeature && $productPageConfig['main_video']); ?>>
                                        <button type="button" class="btn btn-secondary" onclick="triggerProductVideoUpload()" <?php echo productFeatureDisabledAttr($productProFeature && $productPageConfig['main_video']); ?>>上传视频</button>
                                    </div>
                                    <input type="file" id="productVideoUpload" accept="video/*" style="display:none;" onchange="handleProductVideoUpload(this)" <?php echo productFeatureDisabledAttr($productProFeature && $productPageConfig['main_video']); ?>>
                                    <small id="productVideoUploadStatus" style="display:block;margin-top:8px;color:#94a3b8;"><?php echo ($productProFeature && $productPageConfig['main_video']) ? '支持 MP4/WebM/Ogg/Avi/Mov/Mkv/Wmv/Flv。' : '当前授权或页面设置不可用，已保留入口但禁止设置。'; ?></small>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-section">
                        <div class="form-section-header">价格与库存</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 htmlspecialchars($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 htmlspecialchars($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 htmlspecialchars($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 intval($editData['stock']); ?>" min="0"></div>
                            </div>
                            <div class="form-group">
                                <label>商品自定义规格</label>
                                <textarea name="specs_text" class="form-control" rows="4" placeholder="每行一个规格，例如：颜色:红色,蓝色&#10;尺寸:S,M,L"><?php echo htmlspecialchars(\Core\Lib\ProductSpec::toTextarea($editData['specs'] ?? '')); ?></textarea>
                                <small style="display:block;margin-top:8px;color:#94a3b8;">填写后前台购买时必须选择规格，订单和购物车会保存所选规格。</small>
                            </div>
                        </div>
                    </div>
                    <div class="form-section">
                        <div class="form-section-header">产品详情</div>
                        <div class="form-section-body product-ueditor-wrap">
                            <textarea id="product_content_editor" name="content" data-cms-ueditor data-height="460" aria-label="产品详情"><?php echo htmlspecialchars(isset($editData['content']) ? $editData['content'] : '', ENT_QUOTES, 'UTF-8'); ?></textarea>
                        </div>
                    </div>
                </div>
                <div>
                    <div class="form-section">
                        <div class="form-section-header">产品图片</div>
                        <div class="form-section-body">
                            <div class="form-group">
                                <div class="product-pictures-heading"><label>产品图库</label><span id="productPicturesCount">0 / 5</span></div>
                                <input type="hidden" name="litpic" id="litpicInput" value="<?php echo htmlspecialchars($productPictures ? $productPictures[0] : ''); ?>">
                                <div id="productPicturesList" class="product-pictures-list"></div>
                                <button type="button" id="productPicturesAddButton" class="btn btn-secondary product-pictures-add" onclick="document.getElementById('productPicturesFile').click()"><i data-lucide="images"></i> 添加图片</button>
                                <input type="file" id="productPicturesFile" accept="image/jpeg,image/png,image/gif,image/webp" multiple style="display:none;" onchange="handleProductPicturesUpload(this)">
                                <p id="productPicturesStatus" class="product-pictures-help">最多 5 张，第一张为主图；支持 JPG/PNG/GIF/WebP，单张不超过 5MB。</p>
                            </div>
                        </div>
                    </div>
                    <div class="form-section">
                        <div class="form-section-header">咨询按钮</div>
                        <div class="form-section-body">
                            <div class="form-group">
                                <label>咨询按钮方式</label>
                                <select name="consult_button_mode" class="form-control" id="productConsultModeSelect">
                                    <option value="pay" <?php echo ($editData['consult_button_mode'] ?? 'pay') === 'pay' ? 'selected' : ''; ?>>在线支付</option>
                                    <option value="phone" <?php echo ($editData['consult_button_mode'] ?? '') === 'phone' ? 'selected' : ''; ?>>电话咨询</option>
                                    <option value="wechat" <?php echo ($editData['consult_button_mode'] ?? '') === 'wechat' ? 'selected' : ''; ?>>添加微信二维码</option>
                                    <option value="email" <?php echo ($editData['consult_button_mode'] ?? '') === 'email' ? 'selected' : ''; ?>>邮箱</option>
                                </select>
                                <small style="display:block;margin-top:8px;color:#94a3b8;">单个产品可单独覆盖默认咨询方式，默认使用在线支付。</small>
                            </div>
                            <div class="form-group product-consult-mode-field" data-mode="phone">
                                <label>电话咨询号码</label>
                                <input type="text" name="consult_phone" class="form-control" value="<?php echo htmlspecialchars($editData['consult_phone'] ?? ''); ?>" placeholder="例如：400-888-8888">
                            </div>
                            <div class="form-group product-consult-mode-field" data-mode="wechat">
                                <label>微信二维码</label>
                                <div style="display:flex;gap:10px;align-items:center;">
                                    <input type="text" name="consult_wechat_qr" id="productSingleWechatQrInput" class="form-control" value="<?php echo htmlspecialchars($editData['consult_wechat_qr'] ?? ''); ?>" placeholder="微信二维码图片地址">
                                    <button type="button" class="btn btn-secondary" onclick="triggerProductSingleWechatQrUpload()">上传二维码</button>
                                </div>
                                <input type="file" id="productSingleWechatQrUpload" accept="image/*" style="display:none;" onchange="handleProductSingleWechatQrUpload(this)">
                                <small id="productSingleWechatQrStatus" style="display:block;margin-top:8px;color:#94a3b8;">上传后前台会优先使用该产品自己的二维码。</small>
                            </div>
                            <div class="form-group product-consult-mode-field" data-mode="email">
                                <label>咨询邮箱</label>
                                <input type="text" name="consult_email" class="form-control" value="<?php echo htmlspecialchars($editData['consult_email'] ?? ''); ?>" placeholder="例如：service@example.com">
                            </div>
                        </div>
                    </div>
                    <div class="form-section">
                        <div class="form-section-header">发布设置</div>
                        <div class="form-section-body">
                            <div class="form-group"><label>排序</label><input type="number" name="sort_order" class="form-control" value="<?php echo intval($editData['sort_order']); ?>" min="0"></div>
                            <div class="form-group">
                                <label style="display:flex;align-items:center;gap:12px;cursor:<?php echo $productAuthorizedFeature ? 'pointer' : 'not-allowed'; ?>;padding-top:8px;opacity:<?php echo $productAuthorizedFeature ? '1' : '0.6'; ?>;">
                                    <input type="checkbox" name="is_knowledge_paid" value="1" <?php echo !empty($editData['is_knowledge_paid']) ? 'checked' : ''; ?> id="paidToggle" style="display:none;" <?php echo productFeatureDisabledAttr($productAuthorizedFeature); ?>>
                                    <div id="paidSwitch" style="width:44px;height:24px;background:<?php echo !empty($editData['is_knowledge_paid']) ? '#f59e0b' : '#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 !empty($editData['is_knowledge_paid']) ? '23px' : '3px'; ?>;transition:all 0.2s;"></div></div>
                                    <span id="paidLabel" style="font-weight:500;color:<?php echo !empty($editData['is_knowledge_paid']) ? '#d97706' : '#64748b'; ?>;"><?php echo !empty($editData['is_knowledge_paid']) ? '知识付费产品' : '普通产品'; ?></span>
                                </label>
                                <small style="display:block;margin-top:8px;color:#94a3b8;"><?php echo $productAuthorizedFeature ? '开启后，前台产品详情需会员登录后才可查看完整内容。' : '当前授权不可用，已保留入口但禁止设置。'; ?></small>
                            </div>
                            <div class="form-group" style="<?php echo productFeatureFieldStyle($productProFeature && $productFeatureConfig['view_permission']); ?>">
                                <label>产品浏览权限</label>
                                <div class="article-group-checks">
                                    <?php foreach ($memberGroups as $group): ?>
                                    <label><input type="checkbox" name="view_group_ids[]" value="<?php echo intval($group['id']); ?>" <?php echo in_array(intval($group['id']), $viewGroupChecked, true) ? 'checked' : ''; ?> <?php echo productFeatureDisabledAttr($productProFeature && $productFeatureConfig['view_permission']); ?>> <?php echo htmlspecialchars($group['group_name']); ?></label>
                                    <?php endforeach; ?>
                                </div>
                                <small style="display:block;margin-top:8px;color:#94a3b8;"><?php echo ($productProFeature && $productFeatureConfig['view_permission']) ? '不勾选则登录会员均可查看；勾选后仅指定会员组可查看产品详情。' : '当前授权或功能设置不可用，已保留入口但禁止设置。'; ?></small>
                            </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 !empty($editData['status']) ? 'checked' : ''; ?> id="statusToggle" style="display:none;">
                                    <div id="statusSwitch" style="width:44px;height:24px;background:<?php echo !empty($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 !empty($editData['status']) ? '23px' : '3px'; ?>;transition:all 0.2s;"></div></div>
                                    <span id="statusLabel" style="font-weight:500;color:<?php echo !empty($editData['status']) ? '#10b981' : '#64748b'; ?>;"><?php echo !empty($editData['status']) ? '上架' : '下架'; ?></span>
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="form-section">
                        <div class="form-section-header">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" name="save_mode" value="draft" class="btn btn-secondary btn-lg">保存下架</button>
                <button type="submit" name="save_mode" value="publish" class="btn btn-success btn-lg">保存并上架</button>
                <a href="?act=product" class="btn btn-secondary btn-lg">取消</a>
            </div>
        </form>
    </div>
    <style>
    .article-group-checks{display:flex;gap:12px;flex-wrap:wrap;}
    .article-group-checks label{display:flex;align-items:center;gap:6px;padding:8px 10px;border:1px solid #e2e8f0;border-radius:10px;background:#f8fafc;font-size:12px;color:#475569;cursor:pointer;}
    .product-pictures-heading{display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;}
    .product-pictures-heading label{margin:0;}
    .product-pictures-heading span{color:#64748b;font-size:12px;}
    .product-pictures-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;margin-bottom:12px;}
    .product-picture-item{position:relative;aspect-ratio:1/1;overflow:hidden;border:1px solid #e2e8f0;border-radius:6px;background:#f8fafc;}
    .product-picture-item.is-main{border:2px solid #2563eb;}
    .product-picture-item img{display:block;width:100%;height:100%;object-fit:cover;}
    .product-picture-badge{position:absolute;top:6px;left:6px;padding:3px 7px;border-radius:4px;background:#2563eb;color:#fff;font-size:11px;line-height:1.4;}
    .product-picture-actions{position:absolute;right:6px;bottom:6px;left:6px;display:flex;gap:6px;}
    .product-picture-actions button{flex:1;min-height:28px;padding:0 6px;border:0;border-radius:4px;background:rgba(15,23,42,.82);color:#fff;font-size:11px;cursor:pointer;}
    .product-picture-actions .remove{flex:0 0 28px;background:rgba(220,38,38,.9);}
    .product-pictures-empty{grid-column:1/-1;padding:28px 12px;border:1px dashed #cbd5e1;border-radius:6px;color:#94a3b8;text-align:center;background:#f8fafc;}
    .product-pictures-add{width:100%;display:flex;align-items:center;justify-content:center;gap:7px;}
    .product-pictures-add svg{width:16px;height:16px;}
    .product-pictures-help{margin:8px 0 0;color:#94a3b8;font-size:11px;line-height:1.6;}
    </style>
    <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';
        }
    });
    var paidToggle = document.getElementById('paidToggle');
    if (paidToggle) {
        paidToggle.addEventListener('change', function() {
            var sw = document.getElementById('paidSwitch');
            var lb = document.getElementById('paidLabel');
            if (this.checked) {
                sw.style.background = '#f59e0b';
                sw.querySelector('div').style.left = '23px';
                lb.textContent = '知识付费产品';
                lb.style.color = '#d97706';
            } else {
                sw.style.background = '#cbd5e1';
                sw.querySelector('div').style.left = '3px';
                lb.textContent = '普通产品';
                lb.style.color = '#64748b';
            }
        });
    }
    var productPictures = <?php echo json_encode(array_values($productPictures), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    function renderProductPictures() {
        var list = document.getElementById('productPicturesList');
        var count = document.getElementById('productPicturesCount');
        var addButton = document.getElementById('productPicturesAddButton');
        list.innerHTML = '';
        count.textContent = productPictures.length + ' / 5';
        addButton.disabled = productPictures.length >= 5;
        if (!productPictures.length) {
            var empty = document.createElement('div');
            empty.className = 'product-pictures-empty';
            empty.textContent = '暂未添加产品图片';
            list.appendChild(empty);
            return;
        }
        productPictures.forEach(function(url, index) {
            var item = document.createElement('div');
            item.className = 'product-picture-item' + (index === 0 ? ' is-main' : '');
            var image = document.createElement('img');
            image.src = url;
            image.alt = '产品图片 ' + (index + 1);
            item.appendChild(image);
            if (index === 0) {
                var badge = document.createElement('span');
                badge.className = 'product-picture-badge';
                badge.textContent = '主图';
                item.appendChild(badge);
            }
            var actions = document.createElement('div');
            actions.className = 'product-picture-actions';
            if (index > 0) {
                var mainButton = document.createElement('button');
                mainButton.type = 'button';
                mainButton.textContent = '设为主图';
                mainButton.onclick = function() { setProductMainPicture(index); };
                actions.appendChild(mainButton);
            }
            var removeButton = document.createElement('button');
            removeButton.type = 'button';
            removeButton.className = 'remove';
            removeButton.title = '删除图片';
            removeButton.textContent = '×';
            removeButton.onclick = function() { removeProductPicture(index); };
            actions.appendChild(removeButton);
            item.appendChild(actions);
            list.appendChild(item);
        });
    }
    function syncProductPictures() {
        productPictures = productPictures.filter(function(url, index, all) {
            return url && all.indexOf(url) === index;
        }).slice(0, 5);
        document.getElementById('picturesInput').value = JSON.stringify(productPictures);
        document.getElementById('litpicInput').value = productPictures.length ? productPictures[0] : '';
        renderProductPictures();
    }
    function setProductMainPicture(index) {
        if (index <= 0 || index >= productPictures.length) return;
        productPictures.unshift(productPictures.splice(index, 1)[0]);
        syncProductPictures();
    }
    function removeProductPicture(index) {
        productPictures.splice(index, 1);
        syncProductPictures();
    }
    function handleProductPicturesUpload(input) {
        var files = Array.prototype.slice.call(input.files || []);
        var remaining = 5 - productPictures.length;
        var status = document.getElementById('productPicturesStatus');
        if (!files.length) return;
        if (remaining <= 0) {
            alert('产品图片最多添加5张');
            input.value = '';
            return;
        }
        if (files.length > remaining) {
            alert('本次最多还能添加' + remaining + '张图片');
            files = files.slice(0, remaining);
        }
        files = files.filter(function(file) {
            if (file.size > 5 * 1024 * 1024) {
                alert(file.name + ' 超过5MB，已跳过');
                return false;
            }
            return true;
        });
        function uploadNext(index) {
            if (index >= files.length) {
                input.value = '';
                status.textContent = '最多 5 张，第一张为主图；支持 JPG/PNG/GIF/WebP，单张不超过 5MB。';
                return;
            }
            var file = files[index];
            var formData = new FormData();
            formData.append('file', file);
            formData.append('csrf_token', '<?php echo rawurlencode(getAdminCsrfToken()); ?>');
            status.textContent = '正在上传 ' + (index + 1) + ' / ' + files.length + '：' + file.name;
            fetch('?act=upload', {method: 'POST', body: formData})
                .then(function(response) { return response.json(); })
                .then(function(data) {
                    if (data.code !== 200 || !data.data || !data.data.url) {
                        throw new Error(data.msg || '上传失败');
                    }
                    productPictures.push(data.data.url);
                    syncProductPictures();
                    uploadNext(index + 1);
                })
                .catch(function(error) {
                    alert(file.name + '：' + error.message);
                    uploadNext(index + 1);
                });
        }
        uploadNext(0);
    }
    function triggerProductVideoUpload() {
        var input = document.getElementById('productVideoUpload');
        if (!input || input.disabled) return;
        input.click();
    }
    function syncProductConsultModeFields() {
        var select = document.getElementById('productConsultModeSelect');
        if (!select) return;
        var mode = select.value;
        document.querySelectorAll('.product-consult-mode-field').forEach(function(field){
            field.style.display = field.getAttribute('data-mode') === mode ? 'block' : 'none';
        });
    }
    function removeLegacyProductField(fieldName) {
        var input = document.querySelector('[name="' + fieldName + '"]');
        if (!input) return;
        input.value = '';
        input.removeAttribute('list');
        var group = input.closest('.form-group');
        if (group) {
            group.remove();
        }
    }
    function removeLegacyProductFields() {
        ['product_code', 'param_spec', 'param_material', 'param_color', 'param_brand', 'unit'].forEach(removeLegacyProductField);
    }
    function attachProductFieldSuggestions(fieldName, options) {
    }
    function initProductFieldSuggestions() {
        attachProductFieldSuggestions('product_code', ['P-1001', 'P-1002', 'P-1003', 'P-2001', 'P-2002']);
        attachProductFieldSuggestions('param_spec', ['标准款', '小型', '中型', '大型', '定制款']);
        attachProductFieldSuggestions('param_material', ['304不锈钢', '316不锈钢', '铝合金', '碳钢', 'ABS塑料']);
        attachProductFieldSuggestions('param_color', ['白色', '黑色', '银色', '灰色', '蓝色']);
        attachProductFieldSuggestions('param_brand', ['芋头品牌', 'OEM', 'ODM', '品牌A', '品牌B']);
        attachProductFieldSuggestions('unit', ['个', '件', '台', '套', '箱']);
    }
    function triggerProductSingleWechatQrUpload() {
        var input = document.getElementById('productSingleWechatQrUpload');
        if (!input) return;
        input.click();
    }
    function handleProductSingleWechatQrUpload(input) {
        var file = input.files && input.files[0];
        var status = document.getElementById('productSingleWechatQrStatus');
        if (!file) return;
        if (file.size > 5 * 1024 * 1024) {
            alert('二维码图片不能超过5MB');
            input.value = '';
            return;
        }
        status.textContent = '正在上传二维码：' + file.name;
        var formData = new FormData();
        formData.append('file', file);
        formData.append('csrf_token', '<?php echo rawurlencode(getAdminCsrfToken()); ?>');
        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('productSingleWechatQrInput').value = d.data.url;
                    status.textContent = '上传成功';
                } else {
                    status.textContent = '上传失败';
                    alert(d.msg || '上传失败');
                }
            } else {
                status.textContent = '上传失败';
            }
            input.value = '';
        };
        xhr.send(formData);
    }
    function handleProductVideoUpload(input) {
        var file = input.files && input.files[0];
        var status = document.getElementById('productVideoUploadStatus');
        if (!file) return;
        status.textContent = '正在上传视频：' + file.name;
        var formData = new FormData();
        formData.append('file', file);
        formData.append('upload_type', 'video');
        formData.append('csrf_token', '<?php echo rawurlencode(getAdminCsrfToken()); ?>');
        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('productVideoUrlInput').value = d.data.url;
                    status.textContent = '上传成功';
                } else {
                    status.textContent = '上传失败';
                    alert(d.msg || '视频上传失败');
                }
            } else {
                status.textContent = '上传失败';
            }
            input.value = '';
        };
        xhr.send(formData);
    }
    var productConsultModeSelect = document.getElementById('productConsultModeSelect');
    if (productConsultModeSelect) {
        productConsultModeSelect.addEventListener('change', syncProductConsultModeFields);
        syncProductConsultModeFields();
    }
    renderProductPictures();
    removeLegacyProductFields();
    </script>
    <?php
}
?>
