<?php
/**
 * HuSNS - 数据备份后台页面
 */
$totalSize = 0;
$sqlCount = 0;
$zipCount = 0;
foreach ($backups as $b) {
    $totalSize += $b['size'];
    if ($b['type'] === 'sql') {
        $sqlCount++;
    } else {
        $zipCount++;
    }
}
$totalSizeText = $totalSize < 1024 * 1024 
    ? round($totalSize / 1024, 2) . ' KB' 
    : round($totalSize / 1024 / 1024, 2) . ' MB';
?>
<style>
.backup-page { max-width: 1200px; }
.backup-page .stats-row {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
    flex-wrap: wrap;
}
.backup-page .stats-row .stat-card {
    flex: 1;
    min-width: 140px;
}
.backup-page .stat-card {
    flex: 1;
    min-width: 180px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 20px;
    border-radius: 12px;
    color: #fff;
}
.backup-page .stat-card.warning {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}
.backup-page .stat-card.info {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}
.backup-page .stat-card .stat-num {
    font-size: 28px;
    font-weight: 700;
}
.backup-page .stat-card .stat-label {
    font-size: 13px;
    opacity: 0.9;
    margin-top: 5px;
}
.backup-page .backup-card {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.08);
    overflow: hidden;
    margin-bottom: 20px;
}
.backup-page .card-header {
    padding: 18px 24px;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fafafa;
}
.backup-page .card-header h3 {
    margin: 0;
    font-size: 16px;
    color: #2c3e50;
    font-weight: 600;
}
.backup-page .card-body {
    padding: 24px;
}
.backup-page .action-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 20px;
}
.backup-page .action-item {
    padding: 24px;
    border: 2px dashed #e0e0e0;
    border-radius: 10px;
    text-align: center;
    transition: all 0.3s;
}
.backup-page .action-item:hover {
    border-color: #667eea;
    background: #f8f9ff;
}
.backup-page .action-item h4 {
    margin: 12px 0 8px;
    color: #2c3e50;
}
.backup-page .action-item p {
    color: #7f8c8d;
    font-size: 13px;
    margin-bottom: 15px;
}
.backup-page .action-icon {
    font-size: 36px;
    margin-bottom: 8px;
}
.backup-page .btn {
    padding: 10px 20px;
    border-radius: 6px;
    border: none;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.2s;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}
.backup-page .btn-primary { background: #667eea; color: #fff; }
.backup-page .btn-primary:hover { background: #5a6fd6; }
.backup-page .btn-warning { background: #f39c12; color: #fff; }
.backup-page .btn-warning:hover { background: #e67e22; }
.backup-page .btn-success { background: #27ae60; color: #fff; }
.backup-page .btn-success:hover { background: #219a52; }
.backup-page .btn-danger { background: #e74c3c; color: #fff; }
.backup-page .btn-danger:hover { background: #c0392b; }
.backup-page .btn-default { background: #95a5a6; color: #fff; }
.backup-page .btn-default:hover { background: #7f8c8d; }
.backup-page .btn-sm { padding: 6px 12px; font-size: 12px; }
.backup-page .btn-lg { padding: 12px 28px; font-size: 15px; }
.backup-page .backup-list {
    list-style: none;
    padding: 0;
    margin: 0;
}
.backup-page .backup-item {
    display: flex;
    align-items: center;
    padding: 16px 24px;
    border-bottom: 1px solid #f5f5f5;
    transition: background 0.2s;
}
.backup-page .backup-item:last-child { border-bottom: none; }
.backup-page .backup-item:hover { background: #f8f9fa; }
.backup-page .backup-icon {
    width: 44px;
    height: 44px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    color: #fff;
    font-size: 18px;
}
.backup-page .backup-info { flex: 1; }
.backup-page .backup-name {
    font-weight: 600;
    color: #2c3e50;
    font-size: 14px;
}
.backup-page .backup-meta {
    font-size: 12px;
    color: #95a5a6;
    margin-top: 4px;
}
.backup-page .backup-actions {
    display: flex;
    gap: 8px;
}
.backup-page .empty-state {
    text-align: center;
    padding: 50px 20px;
    color: #95a5a6;
}
.backup-page .empty-state i {
    font-size: 56px;
    margin-bottom: 16px;
    display: block;
    color: #dcdcdc;
}
.backup-page .empty-state p { margin-bottom: 20px; }
.backup-page .alert-box {
    background: linear-gradient(135deg, #fff9e6 0%, #fff3cd 100%);
    border-left: 4px solid #ffc107;
    padding: 16px 20px;
    border-radius: 8px;
}
.backup-page .alert-box h4 {
    margin: 0 0 10px;
    color: #856404;
    font-size: 14px;
}
.backup-page .alert-box ul {
    margin: 0;
    padding-left: 20px;
    color: #856404;
    font-size: 13px;
}
.backup-page .alert-box li { margin-bottom: 5px; }
.backup-page .upload-area {
    border: 2px dashed #e0e0e0;
    border-radius: 8px;
    padding: 24px;
    text-align: center;
    transition: all 0.3s;
    margin-top: 12px;
}
.backup-page .upload-area:hover { border-color: #667eea; }
.backup-page .upload-area input[type="file"] { display: none; }
.backup-page .upload-area label {
    cursor: pointer;
    color: #667eea;
    font-weight: 600;
    font-size: 14px;
}
.backup-page .upload-area p {
    color: #95a5a6;
    font-size: 12px;
    margin-top: 8px;
}
.backup-page .setting-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 0;
    border-bottom: 1px solid #f5f5f5;
}
.backup-page .setting-row:last-child { border-bottom: none; }
.backup-page .setting-info h5 { margin: 0 0 4px; color: #2c3e50; font-size: 14px; }
.backup-page .setting-info p { margin: 0; font-size: 12px; color: #95a5a6; }
.backup-page select {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 13px;
    color: #2c3e50;
    background: #fff;
    cursor: pointer;
}
.backup-page .progress-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.6);
    display: none;
    justify-content: center;
    align-items: center;
    z-index: 9999;
}
.backup-page .progress-box {
    background: #fff;
    padding: 32px 48px;
    border-radius: 12px;
    text-align: center;
    min-width: 300px;
}
.backup-page .progress-box h4 { margin: 0 0 16px; color: #2c3e50; }
.backup-page .spinner {
    width: 48px;
    height: 48px;
    border: 4px solid #f3f3f3;
    border-top: 4px solid #667eea;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin: 0 auto 16px;
}
@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
</style>

<div class="backup-page">
    <!-- 统计卡片 -->
    <div class="stats-row">
        <div class="stat-card">
            <div class="stat-num"><?php echo count($backups); ?></div>
            <div class="stat-label">备份文件数</div>
        </div>
        <div class="stat-card warning">
            <div class="stat-num"><?php echo $totalSizeText; ?></div>
            <div class="stat-label">总占用空间</div>
        </div>
        <div class="stat-card" style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);">
            <div class="stat-num"><?php echo $sqlCount; ?></div>
            <div class="stat-label">数据库备份</div>
        </div>
        <div class="stat-card info">
            <div class="stat-num"><?php echo $zipCount; ?></div>
            <div class="stat-label">文件备份</div>
        </div>
    </div>
    
    <!-- 操作卡片 -->
    <div class="backup-card">
        <div class="card-header">
            <h3><i class="fa fa-cogs"></i> 备份操作</h3>
        </div>
        <div class="card-body">
            <div class="action-grid">
                <!-- 数据库备份 -->
                <div class="action-item">
                    <div class="action-icon" style="color: #667eea;">
                        <i class="fa fa-database"></i>
                    </div>
                    <h4>数据库备份</h4>
                    <p>备份 MySQL 数据库结构和数据（.sql 文件）</p>
                    <button class="btn btn-primary" onclick="createBackup('create')">
                        <i class="fa fa-download"></i> 备份数据库
                    </button>
                </div>
                
                <!-- 代码备份 -->
                <div class="action-item">
                    <div class="action-icon" style="color: #11998e;">
                        <i class="fa fa-code"></i>
                    </div>
                    <h4>代码备份</h4>
                    <p>备份项目代码和配置文件（不含上传文件）</p>
                    <button class="btn btn-success" onclick="createBackup('code')">
                        <i class="fa fa-file-code-o"></i> 备份代码
                    </button>
                </div>
                
                <!-- 上传文件备份 -->
                <div class="action-item">
                    <div class="action-icon" style="color: #f39c12;">
                        <i class="fa fa-image"></i>
                    </div>
                    <h4>上传文件备份</h4>
                    <p>备份用户上传的图片、视频等文件</p>
                    <button class="btn btn-warning" onclick="createBackup('uploads')">
                        <i class="fa fa-cloud-upload"></i> 备份上传
                    </button>
                </div>
                
                <!-- 完整备份 -->
                <div class="action-item" style="background: linear-gradient(135deg, #f5f7fa 0%, #e4e8ec 100%); border-color: #667eea;">
                    <div class="action-icon" style="color: #e74c3c;">
                        <i class="fa fa-archive"></i>
                    </div>
                    <h4>完整备份</h4>
                    <p>一次性备份代码、上传文件、数据库（推荐定期使用）</p>
                    <button class="btn btn-danger" onclick="createBackup('full')">
                        <i class="fa fa-rocket"></i> 完整备份
                    </button>
                </div>
                
                <!-- 上传恢复 -->
                <div class="action-item">
                    <div class="action-icon" style="color: #9b59b6;">
                        <i class="fa fa-upload"></i>
                    </div>
                    <h4>上传备份</h4>
                    <p>从本地上传 .sql 格式的备份文件并恢复到数据库。</p>
                    <form id="restoreForm" enctype="multipart/form-data" style="margin: 0;">
                        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                        <div class="upload-area">
                            <input type="file" name="file" id="sqlFile" accept=".sql" onchange="fileSelected(this)">
                            <label for="sqlFile">
                                <i class="fa fa-file-code-o"></i> 选择 SQL 文件
                            </label>
                            <p id="fileName">支持 .sql 格式，单文件建议不超过 100MB</p>
                        </div>
                        <button type="submit" class="btn btn-default" style="margin-top: 12px;" onclick="return confirm('恢复备份将覆盖当前数据库，确定继续吗？')">
                            <i class="fa fa-refresh"></i> 上传并恢复
                        </button>
                    </form>
                </div>
                
                <!-- 快速清理 -->
                <div class="action-item">
                    <div class="action-icon" style="color: #e74c3c;">
                        <i class="fa fa-trash-o"></i>
                    </div>
                    <h4>清理备份</h4>
                    <p>删除多余的旧备份文件，释放服务器空间。</p>
                    <div style="display: flex; gap: 8px; justify-content: center; flex-wrap: wrap;">
                        <button class="btn btn-danger btn-sm" onclick="cleanupBackups(3)">保留3个</button>
                        <button class="btn btn-danger btn-sm" onclick="cleanupBackups(5)">保留5个</button>
                        <button class="btn btn-danger btn-sm" onclick="cleanupBackups(10)">保留10个</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 备份列表 -->
    <div class="backup-card">
        <div class="card-header">
            <h3><i class="fa fa-folder-open"></i> 备份文件列表</h3>
            <span style="color: #95a5a6; font-size: 13px;">
                共 <?php echo count($backups); ?> 个备份（<?php echo $sqlCount; ?> 个数据库 / <?php echo $zipCount; ?> 个文件）
            </span>
        </div>
        <div class="card-body" style="padding: 0;">
            <?php if (!empty($backups)): ?>
            <ul class="backup-list">
                <?php foreach ($backups as $i => $backup): 
                    $isSql = ($backup['type'] === 'sql');
                    $isFull = strpos($backup['name'], 'fullbackup_') === 0;
                    $isCode = strpos($backup['name'], 'codebackup_') === 0;
                    $isUploads = strpos($backup['name'], 'uploads_') === 0;
                ?>
                <li class="backup-item">
                    <div class="backup-icon" style="<?php 
                        if ($isSql) echo 'background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);';
                        elseif ($isFull) echo 'background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);';
                        elseif ($isCode) echo 'background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);';
                        else echo 'background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%);';
                    ?>">
                        <?php if ($isSql): ?>
                        <i class="fa fa-database"></i>
                        <?php elseif ($isFull): ?>
                        <i class="fa fa-archive"></i>
                        <?php elseif ($isCode): ?>
                        <i class="fa fa-code"></i>
                        <?php else: ?>
                        <i class="fa fa-cloud"></i>
                        <?php endif; ?>
                    </div>
                    <div class="backup-info">
                        <div class="backup-name">
                            <?php echo htmlspecialchars($backup['name']); ?>
                            <?php if ($isSql): ?>
                            <span style="background: #667eea; color: #fff; padding: 1px 6px; border-radius: 4px; font-size: 10px; margin-left: 6px;">数据库</span>
                            <?php elseif ($isFull): ?>
                            <span style="background: #e74c3c; color: #fff; padding: 1px 6px; border-radius: 4px; font-size: 10px; margin-left: 6px;">完整</span>
                            <?php elseif ($isCode): ?>
                            <span style="background: #11998e; color: #fff; padding: 1px 6px; border-radius: 4px; font-size: 10px; margin-left: 6px;">代码</span>
                            <?php else: ?>
                            <span style="background: #f39c12; color: #fff; padding: 1px 6px; border-radius: 4px; font-size: 10px; margin-left: 6px;">上传</span>
                            <?php endif; ?>
                        </div>
                        <div class="backup-meta">
                            <i class="fa fa-hdd-o"></i> <?php echo $backup['size_text']; ?> &nbsp;|&nbsp;
                            <i class="fa fa-clock-o"></i> <?php echo $backup['created_at_text']; ?>
                            <?php if ($i === 0): ?>
                            <span style="background: #27ae60; color: #fff; padding: 2px 8px; border-radius: 10px; font-size: 11px; margin-left: 8px;">最新</span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="backup-actions">
                        <a href="<?php echo Helper::url('admin/backup/download?file=' . urlencode($backup['name'])); ?>" 
                           class="btn btn-sm btn-primary" download title="下载">
                            <i class="fa fa-download"></i>
                        </a>
                        <?php if ($isSql): ?>
                        <button class="btn btn-sm btn-warning" 
                                onclick="restoreFromFile('<?php echo htmlspecialchars($backup['name']); ?>')" title="恢复">
                            <i class="fa fa-refresh"></i>
                        </button>
                        <?php endif; ?>
                        <button class="btn btn-sm btn-danger" 
                                onclick="deleteBackup('<?php echo htmlspecialchars($backup['name']); ?>')" title="删除">
                            <i class="fa fa-trash"></i>
                        </button>
                    </div>
                </li>
                <?php endforeach; ?>
            </ul>
            <?php else: ?>
            <div class="empty-state">
                <i class="fa fa-database"></i>
                <p>暂无备份文件</p>
                <button class="btn btn-primary btn-lg" onclick="createBackup('full')">
                    <i class="fa fa-rocket"></i> 创建完整备份
                </button>
            </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- 提示信息 -->
    <div class="alert-box">
        <h4><i class="fa fa-info-circle"></i> 备份提示</h4>
        <ul>
            <li><strong>数据库备份</strong>：导出 MySQL 数据库结构和所有数据（.sql 文件），用于数据恢复</li>
            <li><strong>代码备份</strong>：打包项目源代码、配置、模板等文件（不含上传文件）</li>
            <li><strong>上传备份</strong>：备份用户上传的图片、视频等媒体文件</li>
            <li><strong>完整备份</strong>：一次性备份代码+上传+数据库，推荐定期使用（文件较大可能需要较长时间）</li>
            <li>恢复备份会覆盖当前所有数据，操作前请确保已下载重要数据</li>
            <li>备份文件保存在服务器的 backups 目录下，建议定期下载到本地保存</li>
            <li>完整备份需要服务器启用 ZipArchive 扩展</li>
        </ul>
    </div>
</div>

<!-- 加载动画 -->
<div class="progress-overlay" id="progressOverlay">
    <div class="progress-box">
        <div class="spinner"></div>
        <h4 id="progressText">处理中，请稍候...</h4>
    </div>
</div>

<script>
function showProgress(text) {
    $('#progressText').text(text);
    $('#progressOverlay').show();
}

function hideProgress() {
    $('#progressOverlay').hide();
}

function fileSelected(input) {
    var fileName = document.getElementById('fileName');
    if (input.files && input.files[0]) {
        fileName.textContent = '已选择: ' + input.files[0].name + ' (' + formatBytes(input.files[0].size) + ')';
    }
}

function formatBytes(bytes) {
    if (bytes === 0) return '0 B';
    var k = 1024;
    var sizes = ['B', 'KB', 'MB', 'GB'];
    var i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function createBackup(type) {
    var tips = {
        'create': '数据库',
        'code': '代码',
        'uploads': '上传文件',
        'full': '完整（代码+上传+数据库）'
    };
    var urlMap = {
        'create': '<?php echo Helper::url('admin/backup/create'); ?>',
        'code': '<?php echo Helper::url('admin/backup/code'); ?>',
        'uploads': '<?php echo Helper::url('admin/backup/uploads'); ?>',
        'full': '<?php echo Helper::url('admin/backup/full'); ?>'
    };
    
    if (!confirm('确定要创建 ' + tips[type] + ' 备份吗？\n\n此操作可能需要一些时间，请耐心等待。')) {
        return;
    }
    
    var progressText = {
        'create': '正在备份数据库，请稍候...',
        'code': '正在打包代码文件，请稍候...',
        'uploads': '正在打包上传文件，请稍候...',
        'full': '正在创建完整备份，请稍候...'
    };
    
    showProgress(progressText[type]);
    
    $.post(urlMap[type], {
        csrf_token: '<?php echo $_SESSION['csrf_token']; ?>'
    }, function(res) {
        hideProgress();
        if (res.success) {
            alert(tips[type] + '备份创建成功！');
            window.location.reload();
        } else {
            alert(tips[type] + '备份创建失败：' + res.message);
        }
    }, 'json').fail(function() {
        hideProgress();
        alert(tips[type] + '备份创建失败，请检查服务器配置。');
    });
}

function restoreFromFile(filename) {
    if (!confirm('确定要从备份文件 "' + filename + '" 恢复吗？\n\n这将覆盖当前所有数据，此操作不可逆！')) {
        return;
    }
    
    showProgress('正在恢复备份，请稍候...');
    
    $.post('<?php echo Helper::url('admin/backup/restore'); ?>', {
        filename: filename,
        csrf_token: '<?php echo $_SESSION['csrf_token']; ?>'
    }, function(res) {
        hideProgress();
        if (res.success) {
            alert('恢复成功！');
            window.location.reload();
        } else {
            alert('恢复失败：' + res.message);
        }
    }, 'json').fail(function() {
        hideProgress();
        alert('恢复失败，请检查备份文件格式。');
    });
}

function deleteBackup(filename) {
    if (!confirm('确定要删除备份文件 "' + filename + '" 吗？\n\n此操作不可恢复！')) {
        return;
    }
    
    $.post('<?php echo Helper::url('admin/backup/delete'); ?>', {
        filename: filename,
        csrf_token: '<?php echo $_SESSION['csrf_token']; ?>'
    }, function(res) {
        if (res.success) {
            alert('删除成功！');
            window.location.reload();
        } else {
            alert('删除失败：' + res.message);
        }
    }, 'json');
}

function cleanupBackups(keepCount) {
    if (!confirm('确定要清理备份文件吗？\n\n将只保留最新的 ' + keepCount + ' 个备份文件，其他将被删除！')) {
        return;
    }
    
    showProgress('正在清理备份文件，请稍候...');
    
    $.post('<?php echo Helper::url('admin/backup/cleanup'); ?>', {
        keep_count: keepCount,
        csrf_token: '<?php echo $_SESSION['csrf_token']; ?>'
    }, function(res) {
        hideProgress();
        if (res.success) {
            alert('清理完成！' + (res.deleted_count ? '\n已删除 ' + res.deleted_count + ' 个备份文件' : ''));
            window.location.reload();
        } else {
            alert('清理失败：' + res.message);
        }
    }, 'json').fail(function() {
        hideProgress();
        alert('清理失败，请重试。');
    });
}

$(function() {
    $('#restoreForm').submit(function(e) {
        e.preventDefault();
        
        var fileInput = document.getElementById('sqlFile');
        if (!fileInput.files || !fileInput.files[0]) {
            alert('请先选择要上传的 SQL 文件');
            return;
        }
        
        var file = fileInput.files[0];
        if (file.size > 100 * 1024 * 1024) {
            alert('文件过大，建议不超过 100MB');
            return;
        }
        
        if (!confirm('确定要上传并恢复备份吗？\n这将覆盖当前所有数据！')) {
            return;
        }
        
        showProgress('正在上传并恢复备份，请稍候...');
        
        var formData = new FormData(this);
        
        $.ajax({
            url: '<?php echo Helper::url('admin/backup/upload'); ?>',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(res) {
                hideProgress();
                if (res.success) {
                    alert('恢复成功！');
                    window.location.reload();
                } else {
                    alert('恢复失败：' + res.message);
                }
            },
            error: function(xhr) {
                hideProgress();
                alert('上传失败，请检查文件格式和大小');
            }
        });
    });
});
</script>
