<?php
session_start();
require_once '../config.php';
require_once 'functions.php';

// 检查登录状态
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$message = '';
$message_type = '';

// 检查配置文件权限
$permission_check = check_config_permission();
if ($permission_check !== true) {
    $message = $permission_check;
    $message_type = 'danger';
}

// 添加自定义数据
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_data'])) {
    $var_name = safe_input($_POST['var_name']);
    $data_name = safe_input($_POST['data_name']);
    $data_type = safe_input($_POST['data_type']);
    $data_count = intval($_POST['data_count']);
    $order = safe_input($_POST['order']);
    $pages = $_POST['pages'] ?? [];
    $position = safe_input($_POST['position'] ?? 'sidebar');
    $post_ids = safe_input($_POST['post_ids'] ?? '');

    // 确保custom_data数组存在
    if (!isset($config['custom_data']) || !is_array($config['custom_data'])) {
        $config['custom_data'] = [];
    }

    $config['custom_data'][$var_name] = [
        'name' => $data_name,
        'data_type' => $data_type,
        'data_count' => $data_count,
        'order' => $order,
        'pages' => $pages,
        'position' => $position
    ];

    // 如果是指定文章类型，保存文章ID
    if ($data_type === 'specific_posts' && !empty($post_ids)) {
        $config['custom_data'][$var_name]['post_ids'] = $post_ids;
    }

    if (save_config($config)) {
        $message = '自定义数据添加成功！';
        $message_type = 'success';
    } else {
        $message = '自定义数据添加失败，请检查文件权限！';
        $message_type = 'danger';
    }
}

// 删除自定义数据
if (isset($_GET['delete'])) {
    $var_name = safe_input($_GET['delete']);
    if (isset($config['custom_data'][$var_name])) {
        unset($config['custom_data'][$var_name]);
        if (save_config($config)) {
            $message = '自定义数据删除成功！';
            $message_type = 'success';
        } else {
            $message = '自定义数据删除失败，请检查文件权限！';
            $message_type = 'danger';
        }
    } else {
        $message = '自定义数据不存在！';
        $message_type = 'danger';
    }
}

$page_title = '自定义数据';
?>
<?php include 'header.php'; ?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar.php'; ?>

        <div class="col-md-10 p-4">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2 class="mb-0">自定义数据调用</h2>
                <span class="badge bg-primary"><?php echo count($config['custom_data'] ?? []); ?> 个数据块</span>
            </div>

            <?php if ($message): ?>
            <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
                <?php echo $message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php endif; ?>

            <style>
                .usage-guide {
                    background: #f8f9fa;
                    border: 1px solid #e9ecef;
                    border-radius: 8px;
                    padding: 1.5rem;
                    margin: 1.5rem 0;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
                }
                .usage-guide h6 {
                    color: #2c3e50;
                    margin-bottom: 1rem;
                    font-weight: 600;
                    border-bottom: 2px solid #17a2b8;
                    padding-bottom: 0.5rem;
                }
                .code-example {
                    background: #2c3e50;
                    color: #ecf0f1;
                    padding: 1rem;
                    border-radius: 6px;
                    font-family: 'Courier New', monospace;
                    font-size: 0.85rem;
                    margin: 0.75rem 0;
                    border-left: 4px solid #17a2b8;
                }
                .data-card {
                    transition: transform 0.2s;
                    border: 1px solid #e9ecef;
                    border-radius: 10px;
                }
                .data-card:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
                }
            </style>

            <div class="row">
                <div class="col-md-6">
                    <div class="card data-card">
                        <div class="card-header bg-primary text-white">
                            <i class="bi bi-plus-circle"></i> 添加自定义数据
                        </div>
                        <div class="card-body">
                            <form method="POST">
                                <div class="mb-3">
                                    <label class="form-label">变量名称</label>
                                    <input type="text" class="form-control" name="var_name" placeholder="如: array1" required pattern="[a-zA-Z_][a-zA-Z0-9_]*" title="变量名必须以字母或下划线开头">
                                    <div class="form-text">在模板中使用 $array1 来调用这个数据</div>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">显示名称</label>
                                    <input type="text" class="form-control" name="data_name" placeholder="如: 热门文章" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">数据类型</label>
                                    <select class="form-select" name="data_type" id="dataType" required>
                                        <option value="latest_posts">最新文章</option>
                                        <option value="random_posts">随机文章</option>
                                        <option value="popular_posts">热门文章</option>
                                        <option value="specific_posts">指定文章</option>
                                        <option value="latest_comments">最新评论</option>
                                        <option value="categories">分类列表</option>
                                    </select>
                                </div>
                                <div class="mb-3 d-none" id="postIdsGroup">
                                    <label class="form-label">文章ID</label>
                                    <input type="text" class="form-control" name="post_ids" placeholder="如: 1,2,3,4,5">
                                    <div class="form-text">输入文章ID，用逗号分隔</div>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">显示数量</label>
                                    <input type="number" class="form-control" name="data_count" value="5" min="1" max="50" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">排序方式</label>
                                    <select class="form-select" name="order" required>
                                        <option value="DESC">倒序 (最新/最热在前)</option>
                                        <option value="ASC">正序 (最旧/最冷在前)</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">显示位置</label>
                                    <select class="form-select" name="position" required>
                                        <option value="sidebar">侧边栏</option>
                                        <option value="footer">底部</option>
                                        <option value="header">头部</option>
                                        <option value="custom">自定义位置</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">显示页面</label>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="pages[]" value="index" id="pageIndex" checked>
                                        <label class="form-check-label" for="pageIndex">首页</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="pages[]" value="category" id="pageCategory">
                                        <label class="form-check-label" for="pageCategory">分类页</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="pages[]" value="post" id="pagePost">
                                        <label class="form-check-label" for="pagePost">文章页</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="pages[]" value="search" id="pageSearch">
                                        <label class="form-check-label" for="pageSearch">搜索页</label>
                                    </div>
                                </div>
                                <button type="submit" name="add_data" class="btn btn-primary w-100">
                                    <i class="bi bi-check-lg"></i> 添加数据
                                </button>
                            </form>
                        </div>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="card data-card">
                        <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                            <span><i class="bi bi-database"></i> 自定义数据列表</span>
                            <span class="badge bg-light text-dark"><?php echo count($config['custom_data'] ?? []); ?> 个</span>
                        </div>
                        <div class="card-body">
                            <?php if (empty($config['custom_data'])): ?>
                            <div class="text-center py-4">
                                <i class="bi bi-database display-1 text-muted"></i>
                                <p class="text-muted mt-3">暂无自定义数据</p>
                            </div>
                            <?php else: ?>
                            <div class="list-group list-group-flush">
                                <?php foreach ($config['custom_data'] as $var_name => $data): ?>
                                <div class="list-group-item px-0">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div style="flex: 1;">
                                            <div class="d-flex align-items-center mb-1">
                                                <h6 class="mb-0 me-2"><?php echo $data['name']; ?></h6>
                                                <span class="badge bg-primary status-badge">{$<?php echo $var_name; ?>}</span>
                                            </div>
                                            <div class="row small text-muted">
                                                <div class="col-6">
                                                    <i class="bi bi-gear"></i> 类型: <?php echo $data['data_type']; ?>
                                                </div>
                                                <div class="col-6">
                                                    <i class="bi bi-list-ol"></i> 数量: <?php echo $data['data_count']; ?>
                                                </div>
                                                <div class="col-6">
                                                    <i class="bi bi-sort-down"></i> 排序: <?php echo $data['order']; ?>
                                                </div>
                                                <div class="col-6">
                                                    <i class="bi bi-pin-map"></i> 位置: <?php echo $data['position']; ?>
                                                </div>
                                            </div>
                                            <div class="mt-2">
                                                <small class="text-muted">
                                                    <i class="bi bi-file-earmark"></i> 
                                                    页面: <?php echo implode(', ', $data['pages'] ?? ['index']); ?>
                                                </small>
                                            </div>
                                        </div>
                                        <div class="ms-3">
                                            <a href="?delete=<?php echo $var_name; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('确定删除这个自定义数据吗？')">
                                                <i class="bi bi-trash"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 使用说明放在功能后面 -->
            <div class="usage-guide">
                <h6>📝 自定义数据使用说明</h6>
                <p><strong>模板调用方法：</strong></p>
                <div class="code-example">
                    {if $array1}<br>
                    &nbsp;&nbsp;&lt;div class="custom-data"&gt;<br>
                    &nbsp;&nbsp;&nbsp;&nbsp;&lt;h3&gt;{$array1.name}&lt;/h3&gt;<br>
                    &nbsp;&nbsp;&nbsp;&nbsp;&lt;ul&gt;<br>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{foreach $array1.data as $item}<br>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;li&gt;&lt;a href="{$item.url}"&gt;{$item.title}&lt;/a&gt;&lt;/li&gt;<br>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{/foreach}<br>
                    &nbsp;&nbsp;&nbsp;&nbsp;&lt;/ul&gt;<br>
                    &nbsp;&nbsp;&lt;/div&gt;<br>
                    {/if}
                </div>
                <p><strong>数据类型说明：</strong></p>
                <div class="row">
                    <div class="col-md-6">
                        <ul class="list-unstyled">
                            <li><i class="bi bi-clock text-primary"></i> <strong>最新文章</strong> - 按发布时间排序</li>
                            <li><i class="bi bi-shuffle text-info"></i> <strong>随机文章</strong> - 随机显示文章</li>
                            <li><i class="bi bi-fire text-danger"></i> <strong>热门文章</strong> - 按浏览量排序</li>
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <ul class="list-unstyled">
                            <li><i class="bi bi-pin text-warning"></i> <strong>指定文章</strong> - 显示指定ID的文章</li>
                            <li><i class="bi bi-chat-dots text-success"></i> <strong>最新评论</strong> - 显示最新评论</li>
                            <li><i class="bi bi-folder text-secondary"></i> <strong>分类列表</strong> - 显示所有分类</li>
                        </ul>
                    </div>
                </div>
                <p><strong>显示位置：</strong></p>
                <ul>
                    <li><strong>侧边栏</strong> - 在侧边栏显示数据块</li>
                    <li><strong>底部</strong> - 在页面底部显示数据块</li>
                    <li><strong>头部</strong> - 在页面头部显示数据块</li>
                    <li><strong>自定义位置</strong> - 需要手动在模板中调用</li>
                </ul>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdmirror.com/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.getElementById('dataType').addEventListener('change', function() {
    const type = this.value;
    const postIdsGroup = document.getElementById('postIdsGroup');

    if (type === 'specific_posts') {
        postIdsGroup.classList.remove('d-none');
    } else {
        postIdsGroup.classList.add('d-none');
    }
});

// 初始化显示状态
document.addEventListener('DOMContentLoaded', function() {
    const type = document.getElementById('dataType').value;
    const postIdsGroup = document.getElementById('postIdsGroup');
    
    if (type === 'specific_posts') {
        postIdsGroup.classList.remove('d-none');
    }
});
</script>
</body>
</html>