<?php
ob_start();
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/header.php';
check_permission('editor');

// 处理POST请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add' || $action === 'edit') {
        $id = intval($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $slug = trim($_POST['slug'] ?? '');
        $type = $_POST['type'] ?? 'select';
        $options = $_POST['options'] ?? '';
        $sort_order = intval($_POST['sort_order'] ?? 0);
        
        // 自动生成slug
        if (empty($slug)) {
            $slug = generate_slug($name);
        }
        
        // 处理options（JSON格式）
        if (!empty($options)) {
            $options_array = explode("\n", $options);
            $options_array = array_map('trim', $options_array);
            $options_array = array_filter($options_array);
            $options = json_encode(array_values($options_array), JSON_UNESCAPED_UNICODE);
        } else {
            $options = null;
        }
        
        if ($id > 0) {
            // 编辑
            $sql = "UPDATE product_attributes SET name = ?, slug = ?, type = ?, options = ?, sort_order = ? WHERE id = ?";
            $stmt = $pdo->prepare($sql);
            $result = $stmt->execute([$name, $slug, $type, $options, $sort_order, $id]);
        } else {
            // 新增
            $sql = "INSERT INTO product_attributes (name, slug, type, options, sort_order) VALUES (?, ?, ?, ?, ?)";
            $stmt = $pdo->prepare($sql);
            $result = $stmt->execute([$name, $slug, $type, $options, $sort_order]);
        }
        
        if ($result) {
            echo json_encode(['success' => true, 'message' => '保存成功']);
        } else {
            echo json_encode(['success' => false, 'message' => '保存失败']);
        }
        exit;
    }
    
    if ($action === 'delete') {
        $id = intval($_POST['id'] ?? 0);
        
        $sql = "DELETE FROM product_attributes WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $result = $stmt->execute([$id]);
        
        if ($result) {
            // 同时删除产品属性值
            $sql = "DELETE FROM product_attribute_values WHERE attribute_id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$id]);
            
            echo json_encode(['success' => true, 'message' => '删除成功']);
        } else {
            echo json_encode(['success' => false, 'message' => '删除失败']);
        }
        exit;
    }
    
    if ($action === 'get') {
        $id = intval($_POST['id'] ?? 0);
        $sql = "SELECT * FROM product_attributes WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$id]);
        $attribute = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($attribute) {
            // 处理options显示
            if ($attribute['options']) {
                $options_array = json_decode($attribute['options'], true);
                $attribute['options_text'] = implode("\n", $options_array);
            } else {
                $attribute['options_text'] = '';
            }
            
            echo json_encode(['success' => true, 'data' => $attribute]);
        } else {
            echo json_encode(['success' => false, 'message' => '属性不存在']);
        }
        exit;
    }
}

// 获取所有属性
$sql = "SELECT * FROM product_attributes ORDER BY sort_order ASC, id ASC";
$stmt = $pdo->query($sql);
$attributes = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品属性管理 - 2026企业CMS</title>
    <link rel="stylesheet" href="style.css">
    <style>
        .attribute-list {
            margin: 20px 0;
        }
        
        .attribute-item {
            padding: 15px;
            margin: 10px 0;
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .attribute-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .attribute-name {
            font-weight: 500;
            font-size: 16px;
        }
        
        .attribute-slug {
            color: #6c757d;
            font-size: 12px;
        }
        
        .attribute-type {
            padding: 2px 8px;
            background: #667eea;
            color: white;
            border-radius: 3px;
            font-size: 12px;
        }
        
        .attribute-actions {
            display: flex;
            gap: 5px;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
        }
        
        .modal.active {
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 8px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
        }
        
        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .form-group textarea {
            min-height: 100px;
            resize: vertical;
        }
        
        .btn-group {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }
        
        .help-text {
            font-size: 12px;
            color: #6c757d;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    <?php include 'header.php'; ?>
    
    <div class="container">
        <?php include 'sidebar.php'; ?>
        
        <main class="main-content">
            <div class="page-header">
                <h1>产品属性管理</h1>
                <button class="btn btn-primary" onclick="openModal()">添加属性</button>
            </div>
            
            <div class="attribute-list">
                <?php if (empty($attributes)): ?>
                    <p>暂无属性，请点击"添加属性"创建。</p>
                <?php else: ?>
                    <?php foreach ($attributes as $attribute): ?>
                        <div class="attribute-item">
                            <div class="attribute-info">
                                <span class="attribute-name"><?php echo htmlspecialchars($attribute['name']); ?></span>
                                <span class="attribute-slug">/<?php echo htmlspecialchars($attribute['slug']); ?></span>
                                <span class="attribute-type"><?php echo $attribute['type']; ?></span>
                            </div>
                            <div class="attribute-actions">
                                <button class="btn btn-sm btn-secondary" onclick="editAttribute(<?php echo $attribute['id']; ?>)">编辑</button>
                                <button class="btn btn-sm btn-danger" onclick="deleteAttribute(<?php echo $attribute['id']; ?>, '<?php echo htmlspecialchars($attribute['name']); ?>')">删除</button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
            
            <div class="help-text">
                <p><strong>使用说明：</strong></p>
                <p>1. 属性用于产品多条件筛选（如品牌、价格、颜色等）</p>
                <p>2. "选项"用于select/multiselect/checkbox/radio类型，每行一个选项</p>
                <p>3. 价格区间类型会自动生成价格筛选条件</p>
                <p>4. 属性会在前台产品列表页显示为筛选条件</p>
            </div>
        </main>
    </div>
    
    <!-- 添加/编辑属性模态框 -->
    <div id="attributeModal" class="modal">
        <div class="modal-content">
            <h2 id="modalTitle">添加属性</h2>
            <form csrf_token="<?php echo csrf_input(); ?>"  id="attributeForm">
                <input type="hidden" id="attributeId" name="id" value="0">
                
                <div class="form-group">
                    <label for="attributeName">属性名称 *</label>
                    <input type="text" id="attributeName" name="name" required>
                </div>
                
                <div class="form-group">
                    <label for="attributeSlug">URL参数名</label>
                    <input type="text" id="attributeSlug" name="slug" placeholder="留空自动生成">
                    <small>用于URL参数：?<b>参数名</b>=值</small>
                </div>
                
                <div class="form-group">
                    <label for="attributeType">属性类型</label>
                    <select id="attributeType" name="type">
                        <option value="select">下拉选择（单选）</option>
                        <option value="multiselect">多选</option>
                        <option value="checkbox">复选框</option>
                        <option value="radio">单选按钮</option>
                        <option value="price_range">价格区间</option>
                        <option value="text">文本输入</option>
                        <option value="number">数字输入</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="attributeOptions">选项</label>
                    <textarea id="attributeOptions" name="options" placeholder="每行一个选项"></textarea>
                    <small>用于select/multiselect/checkbox/radio类型，每行一个选项。价格区间类型无需填写。</small>
                </div>
                
                <div class="form-group">
                    <label for="sortOrder">排序</label>
                    <input type="number" id="sortOrder" name="sort_order" value="0">
                </div>
                
                <div class="btn-group">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        // 打开模态框
        function openModal(id = 0) {
            document.getElementById('attributeModal').classList.add('active');
            
            if (id === 0) {
                // 添加
                document.getElementById('modalTitle').textContent = '添加属性';
                document.getElementById('attributeId').value = 0;
                document.getElementById('attributeForm').reset();
            }
        }
        
        // 关闭模态框
        function closeModal() {
            document.getElementById('attributeModal').classList.remove('active');
        }
        
        // 编辑属性
        function editAttribute(id) {
            fetch('', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'action=get&id=' + id
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('modalTitle').textContent = '编辑属性';
                    document.getElementById('attributeId').value = data.data.id;
                    document.getElementById('attributeName').value = data.data.name;
                    document.getElementById('attributeSlug').value = data.data.slug;
                    document.getElementById('attributeType').value = data.data.type;
                    document.getElementById('attributeOptions').value = data.data.options_text || '';
                    document.getElementById('sortOrder').value = data.data.sort_order;
                    
                    openModal();
                } else {
                    alert(data.message);
                }
            });
        }
        
        // 删除属性
        function deleteAttribute(id, name) {
            if (confirm('确定要删除属性「' + name + '」吗？')) {
                fetch('', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    body: 'action=delete&id=' + id
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    } else {
                        alert(data.message);
                    }
                });
            }
        }
        
        // 表单提交
        document.getElementById('attributeForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            formData.append('action', 'add');
            
            const id = document.getElementById('attributeId').value;
            if (id > 0) {
                formData.set('action', 'edit');
            }
            
            fetch('', {
                method: 'POST',
                body: new URLSearchParams(formData)
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    alert(data.message);
                }
            });
        });
        
        // 点击模态框外部关闭
        document.getElementById('attributeModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeModal();
            }
        });
    </script>
</body>
</html>
