<?php
/**
 * 2026企业CMS - 后台产品管理
 */
require_once __DIR__ . '/header.php';
$pageTitle = '产品管理';
$action = $_GET['action'] ?? 'list';
$id = intval($_GET['id'] ?? 0);

// 处理删除
if ($action === 'delete' && $id) {
    check_permission('editor');
    $p = db_query_one("SELECT `title` FROM `products` WHERE `id`=?",[$id]);
    db_exec("DELETE FROM `products` WHERE `id`=?", [$id]);
    // 同时删除产品属性值
    db_exec("DELETE FROM `product_attribute_values` WHERE `product_id`=?", [$id]);
    add_log('delete', 'products', '删除产品: ' . ($p['title'] ?? ''));
    header('Location: /admin/products.php?msg=' . urlencode('删除成功！'));
    exit;
}

// 处理保存
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save'])) {
    check_permission('editor');
    if (!csrf_validate($_POST['csrf_token'] ?? '')) { die('CSRF 验证失败'); }
    $title   = trim($_POST['title'] ?? '');
    $slug    = trim($_POST['slug'] ?? '');
    $summary = trim($_POST['summary'] ?? '');
    $content = $_POST['content'] ?? '';
    $price   = floatval($_POST['price'] ?? 0);
    $stock   = intval($_POST['stock'] ?? 0);
    $isHot   = intval($_POST['is_hot'] ?? 0);
    $isNew   = intval($_POST['is_new'] ?? 1);
    $status  = intval($_POST['status'] ?? 1);
    
    if (!$slug) $slug = generate_slug($title);
    

    // 自动处理重复 slug
    $original_slug = $slug;
    $counter = 2;
    while (true) {
        $sql = "SELECT COUNT(*) as cnt FROM `products` WHERE `slug` = ?";
        $params = [$slug];
        if ($action === 'edit' && $id) {
            $sql .= " AND `id` != ?";
            $params[] = $id;
        }
        $exist = db_query_one($sql, $params);
        if ($exist && $exist['cnt'] > 0) {
            $slug = $original_slug . '-' . $counter;
            $counter++;
        } else {
            break;
        }
    }

    $product_id = 0;
    
    if ($action === 'add') {
        db_exec(
            "INSERT INTO `products` (`title`,`slug`,`summary`,`content`,`price`,`stock`,`is_hot`,`is_new`,`status`) VALUES (?,?,?,?,?,?,?,?,?)",
            [$title, $slug, $summary, $content, $price, $stock, $isHot, $isNew, $status]
        );
        $product_id = $GLOBALS['pdo']->lastInsertId();
        add_log('add', 'products', '添加产品: ' . $title);
    } elseif ($action === 'edit' && $id) {
        db_exec(
            "UPDATE `products` SET `title`=?,`slug`=?,`summary`=?,`content`=?,`price`=?,`stock`=?,`is_hot`=?,`is_new`=?,`status`=? WHERE `id`=?",
            [$title, $slug, $summary, $content, $price, $stock, $isHot, $isNew, $status, $id]
        );
        $product_id = $id;
        add_log('edit', 'products', '编辑产品: ' . $title);
    }
    
    // 保存产品属性值
    if ($product_id > 0 && isset($_POST['attributes'])) {
        // 先删除旧的属性值
        db_exec("DELETE FROM `product_attribute_values` WHERE `product_id`=?", [$product_id]);
        
        // 插入新的属性值
        foreach ($_POST['attributes'] as $attr_id => $values) {
            $attr_id = intval($attr_id);
            
            // 如果是数组（多选），则插入多个值
            if (is_array($values)) {
                foreach ($values as $value) {
                    if (!empty($value)) {
                        db_exec(
                            "INSERT INTO `product_attribute_values` (`product_id`, `attribute_id`, `value`) VALUES (?, ?, ?)",
                            [$product_id, $attr_id, $value]
                        );
                    }
                }
            } else {
                // 单值
                if (!empty($values)) {
                    db_exec(
                        "INSERT INTO `product_attribute_values` (`product_id`, `attribute_id`, `value`) VALUES (?, ?, ?)",
                        [$product_id, $attr_id, $values]
                    );
                }
            }
        }
    }
    
    header('Location: /admin/products.php?msg=' . urlencode('保存成功！'));
    exit;
}

$product = [];
if ($action === 'edit' && $id) {
    $product = db_query_one("SELECT * FROM `products` WHERE `id`=?", [$id]);
    if (!$product) { header('Location: /admin/products.php'); exit; }
}
if ($action === 'add' || $action === 'edit'):
?>
<div class="page-header">
    <h2><?php echo $action==='add'?'添加产品':'编辑产品'; ?></h2>
    <a href="/admin/products.php" class="btn">← 返回列表</a>
</div>
<div class="form-card">
    <form method="post" action="">
        <input type="hidden" name="csrf_token" value="<?= csrf_generate() ?>">
        <div class="form-row">
            <div class="form-group" style="flex:2;">
                <label>产品名称 <span style="color:red;">*</span></label>
                <input type="text" name="title" value="<?php echo xss_clean($product['title'] ?? ''); ?>" required>
            </div>
            <div class="form-group">
                <label>URL别名</label>
                <input type="text" name="slug" value="<?php echo xss_clean($product['slug'] ?? ''); ?>" placeholder="自动生成">
            </div>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label>价格（元）</label>
                <input type="number" step="0.01" name="price" value="<?php echo $product['price'] ?? ''; ?>">
            </div>
            <div class="form-group">
                <label>库存</label>
                <input type="number" name="stock" value="<?php echo $product['stock'] ?? 0; ?>">
            </div>
        </div>
        <div class="form-group">
            <label>简介</label>
            <textarea name="summary" rows="3"><?php echo xss_clean($product['summary'] ?? ''); ?></textarea>
        </div>
        <div class="form-group">
            <label>详细描述</label>
            <textarea name="content" id="content-editor"><?php echo $product['content'] ?? ''; ?></textarea>
        </div>
        
        <!-- 产品属性值设置 -->
        <?php
        // 获取所有启用的属性
        $all_attributes = db_query("SELECT * FROM `product_attributes` WHERE `status`=1 ORDER BY `sort_order` ASC");
        if ($all_attributes):
        ?>
        <hr>
        <h3>产品属性</h3>
        <p class="help-text">设置产品的属性值，用于前台多条件筛选。</p>
        
        <?php foreach ($all_attributes as $attr): ?>
            <div class="form-group">
                <label><?php echo htmlspecialchars($attr['name']); ?></label>
                
                <?php
                // 获取当前产品的该属性值（编辑时）
                $current_values = [];
                if ($id > 0) {
                    $values = db_query("SELECT `value` FROM `product_attribute_values` WHERE `product_id`=? AND `attribute_id`=?", [$id, $attr['id']]);
                    $current_values = array_column($values, 'value');
                }
                
                $options = $attr['options'] ? json_decode($attr['options'], true) : [];
                ?>
                
                <?php if ($attr['type'] == 'select'): ?>
                    <!-- 下拉选择（单选） -->
                    <select name="attributes[<?php echo $attr['id']; ?>]">
                        <option value="">请选择</option>
                        <?php foreach ($options as $opt): ?>
                            <option value="<?php echo htmlspecialchars($opt); ?>" <?php echo in_array($opt, $current_values) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($opt); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    
                <?php elseif ($attr['type'] == 'multiselect' || $attr['type'] == 'checkbox'): ?>
                    <!-- 多选 -->
                    <div class="checkbox-group">
                        <?php foreach ($options as $opt): ?>
                            <label>
                                <input type="checkbox" name="attributes[<?php echo $attr['id']; ?>][]" value="<?php echo htmlspecialchars($opt); ?>" <?php echo in_array($opt, $current_values) ? 'checked' : ''; ?>>
                                <?php echo htmlspecialchars($opt); ?>
                            </label>
                        <?php endforeach; ?>
                    </div>
                    
                <?php elseif ($attr['type'] == 'radio'): ?>
                    <!-- 单选按钮 -->
                    <div class="radio-group">
                        <?php foreach ($options as $opt): ?>
                            <label>
                                <input type="radio" name="attributes[<?php echo $attr['id']; ?>]" value="<?php echo htmlspecialchars($opt); ?>" <?php echo in_array($opt, $current_values) ? 'checked' : ''; ?>>
                                <?php echo htmlspecialchars($opt); ?>
                            </label>
                        <?php endforeach; ?>
                    </div>
                    
                <?php elseif ($attr['type'] == 'text'): ?>
                    <!-- 文本输入 -->
                    <input type="text" name="attributes[<?php echo $attr['id']; ?>]" value="<?php echo htmlspecialchars($current_values[0] ?? ''); ?>">
                    
                <?php elseif ($attr['type'] == 'number'): ?>
                    <!-- 数字输入 -->
                    <input type="number" name="attributes[<?php echo $attr['id']; ?>]" value="<?php echo htmlspecialchars($current_values[0] ?? ''); ?>">
                    
                <?php elseif ($attr['type'] == 'price_range'): ?>
                    <!-- 价格区间（自动处理，无需设置） -->
                    <p class="help-text">价格区间自动根据价格字段生成，无需设置。</p>
                    
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
        <?php endif; ?>
        <!-- 产品属性值设置结束 -->
        
        <hr>
        <div class="form-row">
            <div class="form-group">
                <label><input type="checkbox" name="is_hot" value="1" <?php echo ($product['is_hot'] ?? 0)?'checked':''; ?>> 热销</label>
            </div>
            <div class="form-group">
                <label><input type="checkbox" name="is_new" value="1" <?php echo ($product['is_new'] ?? 1)?'checked':''; ?>> 新品</label>
            </div>
            <div class="form-group">
                <label>状态</label>
                <select name="status">
                    <option value="1" <?php echo ($product['status'] ?? 1)==1?'selected':''; ?>>上架</option>
                    <option value="0" <?php echo ($product['status'] ?? 1)==0?'selected':''; ?>>下架</option>
                </select>
            </div>
        </div>
        <div style="margin-top:30px;">
            <button type="submit" name="save" class="btn btn-primary" style="margin-right:10px;">保存</button>
            <a href="/admin/products.php" class="btn">取消</a>
        </div>
    </form>
</div>
<script src="https://cdn.ckeditor.com/4.22.1/full/ckeditor.js"></script>
<script>if(typeof CKEDITOR!=='undefined'){CKEDITOR.replace('content-editor');}</script>
<?php require_once __DIR__ . '/footer.php'; exit; endif;

// 产品列表
$page = max(1, intval($_GET['page'] ?? 1));
$pageSize = 12;
$total = db_count('products');
$offset = ($page - 1) * $pageSize;
$products = db_query("SELECT * FROM `products` ORDER BY `is_hot` DESC,`sort_order` ASC,`id` DESC LIMIT {$offset},{$pageSize}");
?>
<div class="page-header">
    <h2>产品管理</h2>
    <a href="/admin/products.php?action=add" class="btn btn-primary"><i class="fas fa-plus"></i> 添加产品</a>
</div>

<div class="table-wrapper">
    <table>
        <thead><tr><th>ID</th><th>产品名称</th><th>价格</th><th>库存</th><th>销量</th><th>状态</th><th>操作</th></tr></thead>
        <tbody>
            <?php foreach ($products as $p): ?>
            <tr>
                <td><?php echo $p['id']; ?></td>
                <td><a href="/product/<?php echo $p['slug']; ?>.html" target="_blank"><?php echo xss_clean(str_cut($p['title'], 30)); ?></a></td>
                <td style="color:#e74c3c;font-weight:bold;">¥<?php echo $p['price'] ?: '面议'; ?></td>
                <td><?php echo $p['stock']; ?></td>
                <td><?php echo $p['sales']; ?></td>
                <td>
                    <?php if ($p['is_hot']): ?><span class="badge badge-success">热销</span><?php endif; ?>
                    <?php if ($p['status']==1): ?><span class="badge badge-success">上架</span>
                    <?php else: ?><span class="badge badge-danger">下架</span>
                    <?php endif; ?>
                </td>
                <td class="actions">
                    <a href="/admin/products.php?action=edit&id=<?php echo $p['id']; ?>" class="btn btn-sm btn-primary">编辑</a>
                    <a href="javascript:void(0)" onclick="if(confirmDelete(<?php echo $p['id']; ?>,'<?php echo xss_clean($p['title']); ?>')){location.href='/admin/products.php?action=delete&id=<?php echo $p['id']; ?>'}" class="btn btn-sm btn-danger">删除</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php if ($total > $pageSize): $totalPage=ceil($total/$pageSize); ?>
<div class="pagination">
    <?php for ($i=1; $i<=$totalPage; $i++): ?><a href="/admin/products.php?page=<?php echo $i; ?>" <?php echo $i==$page?'class="current"':''; ?>><?php echo $i; ?></a><?php endfor; ?>
</div>
<?php endif; ?>
<?php require_once __DIR__ . '/footer.php'; ?>
