<?php
requireAdmin();

// ========== 正常页面显示 ==========
$page = isset($_GET['p']) ? intval($_GET['p']) : 1;
$perpage = 15;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

$where = "1=1";
if ($search) {
    $search = $db->escape($search);
    $where .= " AND (version LIKE '%$search%' OR content LIKE '%$search%')";
}

$total_result = $db->query("SELECT COUNT(*) as cnt FROM changelog WHERE $where");
$total = $total_result->fetch_assoc()['cnt'];
$offset = ($page - 1) * $perpage;

$logs = $db->fetchAll("
    SELECT * FROM changelog 
    WHERE $where 
    ORDER BY release_date DESC, id DESC 
    LIMIT $offset, $perpage
");

// 获取编辑数据
$edit_log = null;
if (isset($_GET['edit'])) {
    $edit_log = $db->fetchOne("SELECT * FROM changelog WHERE id = " . intval($_GET['edit']));
}
?>

<div class="changelog-manager">
    <div class="page-header">
        <h2>更新日志管理</h2>
        <button class="btn btn-primary" id="showAddModalBtn">+ 添加更新日志</button>
    </div>
    
    <!-- 搜索栏 -->
    <div class="search-bar">
        <form method="GET">
            <input type="hidden" name="page" value="changelog">
            <input type="text" name="search" placeholder="搜索版本号/内容" value="<?php echo htmlspecialchars($search); ?>">
            <button type="submit" class="btn btn-primary">搜索</button>
            <?php if ($search): ?>
                <a href="?page=changelog" class="btn btn-secondary">清空</a>
            <?php endif; ?>
        </form>
    </div>
    
    <div class="table-wrapper">
        <table class="data-table" id="changelogTable">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>版本号</th>
                    <th>发布日期</th>
                    <th>更新内容</th>
                    <th>重要</th>
                    <th>状态</th>
                    <th>操作</th>
                </thead>
            <tbody>
                <?php if (empty($logs)): ?>
                    <tr><td colspan="7" style="text-align: center; padding: 60px;">暂无更新日志</td></tr>
                <?php else: ?>
                    <?php foreach ($logs as $log): ?>
                        <tr id="log-row-<?php echo $log['id']; ?>">
                            <td style="text-align: center;"><?php echo $log['id']; ?></td>
                            <td><strong>v<?php echo htmlspecialchars($log['version']); ?></strong></td>
                            <td><?php echo $log['release_date']; ?></td>
                            <td style="max-width: 400px;"><?php echo nl2br(htmlspecialchars(mb_substr($log['content'], 0, 100))); ?></td>
                            <td><?php echo $log['is_featured'] ? '⭐ 重要' : '-'; ?></td>
                            <td>
                                <span class="status-badge status-<?php echo $log['status'] ? 'active' : 'inactive'; ?>" id="status-badge-<?php echo $log['id']; ?>">
                                    <?php echo $log['status'] ? '显示' : '隐藏'; ?>
                                </span>
                            </td>
                            <td class="action-buttons">
                                <button class="action-btn edit-btn" data-id="<?php echo $log['id']; ?>" data-version="<?php echo htmlspecialchars($log['version']); ?>" data-date="<?php echo $log['release_date']; ?>" data-content="<?php echo htmlspecialchars($log['content']); ?>" data-featured="<?php echo $log['is_featured']; ?>" data-status="<?php echo $log['status']; ?>">✏️ 编辑</button>
                                <button class="action-btn toggle-status-btn" data-id="<?php echo $log['id']; ?>" data-status="<?php echo $log['status']; ?>">
                                    <?php echo $log['status'] ? '🔴 隐藏' : '🟢 显示'; ?>
                                </button>
                                <button class="action-btn delete-btn" data-id="<?php echo $log['id']; ?>">🗑️ 删除</button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <?php if ($total > $perpage): ?>
        <div class="pagination">
            <?php for ($i = 1; $i <= ceil($total / $perpage); $i++): ?>
                <a href="?page=changelog&p=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>" class="page-link <?php echo $i == $page ? 'active' : ''; ?>"><?php echo $i; ?></a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
</div>

<!-- 添加/编辑弹窗 -->
<div id="logModal" class="modal" style="display: none;">
    <div class="modal-content" style="max-width: 600px;">
        <div class="modal-header">
            <h3 id="modalTitle">添加更新日志</h3>
            <span class="close">&times;</span>
        </div>
        <form id="logForm">
            <input type="hidden" name="id" id="log_id" value="">
            <div class="modal-body">
                <div class="form-row">
                    <div class="form-group" style="flex:1">
                        <label>版本号 *</label>
                        <input type="text" name="version" id="log_version" required placeholder="例如：1.0.1">
                    </div>
                    <div class="form-group" style="flex:1">
                        <label>发布日期 *</label>
                        <input type="date" name="release_date" id="log_date" required value="<?php echo date('Y-m-d'); ?>">
                    </div>
                </div>
                <div class="form-group">
                    <label>更新内容 *</label>
                    <textarea name="content" id="log_content" rows="8" required placeholder="每条更新一行，例如：&#10;✨ 新增资源下载功能&#10;🐛 修复授权验证问题&#10;🎨 优化界面样式"></textarea>
                    <small>支持 Markdown 格式，每条更新一行</small>
                </div>
                <div class="form-group">
                    <label>
                        <input type="checkbox" name="is_featured" id="log_featured" value="1">
                        ⭐ 标记为重要更新
                    </label>
                </div>
                <div class="form-group">
                    <label>状态</label>
                    <select name="status" id="log_status">
                        <option value="1">显示</option>
                        <option value="0">隐藏</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary cancel-btn">取消</button>
                <button type="submit" class="btn btn-primary">保存</button>
            </div>
        </form>
    </div>
</div>

<style>
.changelog-manager .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}
.search-bar {
    margin-bottom: 20px;
}
.search-bar form {
    display: flex;
    gap: 10px;
    max-width: 400px;
}
.search-bar input {
    flex: 1;
    padding: 8px 12px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    background: var(--bg-primary);
}
.table-wrapper {
    overflow-x: auto;
    background: var(--bg-primary);
    border-radius: 12px;
    border: 1px solid var(--border-color);
}
.data-table {
    width: 100%;
    border-collapse: collapse;
    min-width: 700px;
}
.data-table th {
    padding: 12px;
    text-align: left;
    font-weight: 600;
    font-size: 13px;
    color: var(--text-secondary);
    background: var(--bg-secondary);
    border-bottom: 1px solid var(--border-color);
}
.data-table td {
    padding: 12px;
    border-bottom: 1px solid var(--border-color);
    font-size: 13px;
    vertical-align: middle;
}
.data-table tr:hover {
    background: var(--bg-secondary);
}
.status-badge {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}
.status-active {
    background: #d1fae5;
    color: #065f46;
}
.status-inactive {
    background: #fee2e2;
    color: #991b1b;
}
.action-buttons {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}
.action-btn {
    background: none;
    border: 1px solid var(--border-color);
    padding: 4px 10px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 12px;
    transition: all 0.2s;
    text-decoration: none;
    color: var(--text-primary);
}
.action-btn:hover {
    border-color: var(--primary-color);
    background: var(--primary-light);
}
.delete-btn:hover {
    border-color: var(--danger-color);
    color: var(--danger-color);
    background: #fee2e2;
}
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
}
.modal-content {
    background: var(--bg-primary);
    border-radius: 16px;
    width: 90%;
    max-width: 600px;
}
.modal-header {
    padding: 18px 24px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.modal-header h3 {
    font-size: 18px;
    font-weight: 600;
    margin: 0;
}
.close {
    cursor: pointer;
    font-size: 24px;
    line-height: 1;
}
.modal-body {
    padding: 24px;
}
.modal-footer {
    padding: 16px 24px;
    border-top: 1px solid var(--border-color);
    display: flex;
    gap: 12px;
    justify-content: flex-end;
}
.form-row {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;
}
.form-group {
    margin-bottom: 16px;
}
.form-group label {
    display: block;
    margin-bottom: 6px;
    font-weight: 500;
    font-size: 14px;
}
.form-group input,
.form-group select,
.form-group textarea {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    font-size: 14px;
    background: var(--bg-primary);
}
.form-group textarea {
    resize: vertical;
    font-family: monospace;
}
.form-group small {
    display: block;
    margin-top: 4px;
    font-size: 12px;
    color: var(--text-muted);
}
.btn-primary {
    background: var(--primary-color);
    color: white;
    border: none;
    padding: 8px 20px;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
}
.btn-primary:hover {
    background: var(--primary-hover);
}
.btn-secondary {
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    padding: 8px 20px;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
}
.loading-spinner {
    display: inline-block;
    width: 14px;
    height: 14px;
    border: 2px solid #fff;
    border-radius: 50%;
    border-top-color: transparent;
    animation: spin 0.6s linear infinite;
    margin-right: 6px;
    vertical-align: middle;
}
@keyframes spin {
    to { transform: rotate(360deg); }
}
.pagination {
    display: flex;
    gap: 8px;
    justify-content: center;
    margin-top: 20px;
}
.page-link {
    padding: 6px 12px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    text-decoration: none;
    color: var(--text-primary);
}
.page-link.active {
    background: var(--primary-color);
    color: white;
}
</style>

<script>
(function() {
    // 获取元素
    const modal = document.getElementById('logModal');
    const form = document.getElementById('logForm');
    
    function openModal(editData) {
        const titleEl = document.getElementById('modalTitle');
        const idEl = document.getElementById('log_id');
        const versionEl = document.getElementById('log_version');
        const dateEl = document.getElementById('log_date');
        const contentEl = document.getElementById('log_content');
        const featuredEl = document.getElementById('log_featured');
        const statusEl = document.getElementById('log_status');
        
        if (!titleEl) return;
        
        if (editData) {
            titleEl.innerText = '编辑更新日志';
            if (idEl) idEl.value = editData.id || '';
            if (versionEl) versionEl.value = editData.version || '';
            if (dateEl) dateEl.value = editData.release_date || '';
            if (contentEl) contentEl.value = editData.content || '';
            if (featuredEl) featuredEl.checked = editData.is_featured == 1;
            if (statusEl) statusEl.value = editData.status || 1;
        } else {
            titleEl.innerText = '添加更新日志';
            if (idEl) idEl.value = '';
            if (versionEl) versionEl.value = '';
            if (dateEl) dateEl.value = '<?php echo date('Y-m-d'); ?>';
            if (contentEl) contentEl.value = '';
            if (featuredEl) featuredEl.checked = false;
            if (statusEl) statusEl.value = '1';
        }
        if (modal) modal.style.display = 'flex';
    }
    
    function closeModal() {
        if (modal) modal.style.display = 'none';
    }
    
    // 显示添加弹窗
    const addBtn = document.getElementById('showAddModalBtn');
    if (addBtn) {
        addBtn.addEventListener('click', function() { openModal(null); });
    }
    
    // 编辑按钮
    document.querySelectorAll('.edit-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            openModal({
                id: this.dataset.id,
                version: this.dataset.version,
                release_date: this.dataset.date,
                content: this.dataset.content,
                is_featured: parseInt(this.dataset.featured),
                status: parseInt(this.dataset.status)
            });
        });
    });
    
    // 关闭弹窗
    document.querySelectorAll('.close, .cancel-btn').forEach(function(btn) {
        btn.addEventListener('click', closeModal);
    });
    
    // 保存表单
    if (form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn ? submitBtn.innerHTML : '保存';
            
            if (submitBtn) {
                submitBtn.innerHTML = '<span class="loading-spinner"></span> 保存中...';
                submitBtn.disabled = true;
            }
            
            fetch('/api/changelog_save.php', {
                method: 'POST',
                body: formData
            })
            .then(function(res) { return res.json(); })
            .then(function(data) {
                if (data.success) {
                    if (window.showToast) window.showToast(data.message, 'success');
                    setTimeout(function() { location.reload(); }, 1000);
                } else {
                    if (window.showToast) window.showToast(data.message || '操作失败', 'error');
                }
                if (submitBtn) {
                    submitBtn.innerHTML = originalText;
                    submitBtn.disabled = false;
                }
                closeModal();
            })
            .catch(function(err) {
                console.error('错误:', err);
                if (window.showToast) window.showToast('网络错误', 'error');
                if (submitBtn) {
                    submitBtn.innerHTML = originalText;
                    submitBtn.disabled = false;
                }
                closeModal();
            });
        });
    }
    
    // 状态切换
    document.querySelectorAll('.toggle-status-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            const id = this.dataset.id;
            const currentStatus = parseInt(this.dataset.status);
            const newStatus = currentStatus === 1 ? 0 : 1;
            const originalText = this.innerHTML;
            
            this.innerHTML = '<span class="loading-spinner"></span> 处理中...';
            this.disabled = true;
            
            fetch('/api/changelog_toggle_status.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'id=' + id + '&status=' + newStatus
            })
            .then(function(res) { return res.json(); })
            .then(function(data) {
                if (data.success) {
                    var statusSpan = document.getElementById('status-badge-' + id);
                    if (statusSpan) {
                        if (newStatus === 1) {
                            statusSpan.className = 'status-badge status-active';
                            statusSpan.innerHTML = '显示';
                            btn.innerHTML = '🔴 隐藏';
                            btn.dataset.status = '1';
                        } else {
                            statusSpan.className = 'status-badge status-inactive';
                            statusSpan.innerHTML = '隐藏';
                            btn.innerHTML = '🟢 显示';
                            btn.dataset.status = '0';
                        }
                    }
                    if (window.showToast) window.showToast('状态已更新', 'success');
                } else {
                    if (window.showToast) window.showToast(data.message || '操作失败', 'error');
                }
                btn.innerHTML = originalText;
                btn.disabled = false;
            })
            .catch(function(err) {
                console.error('错误:', err);
                if (window.showToast) window.showToast('网络错误', 'error');
                btn.innerHTML = originalText;
                btn.disabled = false;
            });
        });
    });
    
    // 删除
    document.querySelectorAll('.delete-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            if (!confirm('确定删除此更新日志吗？此操作不可恢复。')) return;
            
            var id = this.dataset.id;
            var row = document.getElementById('log-row-' + id);
            var originalText = this.innerHTML;
            this.innerHTML = '<span class="loading-spinner"></span> 删除中...';
            this.disabled = true;
            
            fetch('/api/changelog_delete.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'id=' + id
            })
            .then(function(res) { return res.json(); })
            .then(function(data) {
                if (data.success) {
                    if (row) row.remove();
                    if (window.showToast) window.showToast('删除成功', 'success');
                    if (document.querySelectorAll('#changelogTable tbody tr').length === 0) {
                        location.reload();
                    }
                } else {
                    if (window.showToast) window.showToast(data.message || '删除失败', 'error');
                    btn.innerHTML = originalText;
                    btn.disabled = false;
                }
            })
            .catch(function(err) {
                console.error('错误:', err);
                if (window.showToast) window.showToast('网络错误', 'error');
                btn.innerHTML = originalText;
                btn.disabled = false;
            });
        });
    });
    
    // 点击模态框背景关闭
    if (modal) {
        modal.addEventListener('click', function(e) {
            if (e.target === modal) closeModal();
        });
    }
})();
</script>