<?php
require_once __DIR__ . '/../MPHX/common.php';

$user = check_user();
$bt = $DB->get_row("SELECT * FROM `bt` WHERE `id`='{$user['btid']}'");
?>

<link rel="stylesheet" href="/static/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/css/all.min.css">
<link rel="stylesheet" href="css/style.css?v=20260220_3">

<script src="/static/js/jquery.min.js"></script>

<style>
    html, body { overflow-y: auto; }
    .page-container { padding: 15px; }
    .page-title { font-size: 16px; color: #202124; margin-bottom: 15px; display: flex; align-items: center; gap: 8px; }
    .btn-group .btn { border-radius: 4px !important; }
    .btn-group .btn.active { background-color: #188038; border-color: #188038; color: #fff; }
    .filter-btn.active { background-color: #188038 !important; border-color: #188038 !important; color: #fff !important; }
    .backup-list {
        padding: 0;
    }
    .backup-item {
        padding: 12px 15px;
        border-bottom: 1px solid #e8eaed;
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 12px;
    }
    .backup-item:last-child {
        border-bottom: none;
    }
    .backup-info {
        flex: 1;
        min-width: 0;
    }
    .backup-info h4 {
        margin: 0 0 6px 0;
        color: #202124;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 8px;
        min-width: 0;
    }
    .backup-info .backup-name {
        min-width: 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #1a73e8;
        font-weight: 600;
    }
    .backup-info .status-badge {
        display: inline-block;
        padding: 2px 8px;
        border-radius: 10px;
        font-size: 11px;
        font-weight: 600;
        flex-shrink: 0;
    }
    .backup-info .status-badge.success {
        background: #e6f4ea;
        color: #137333;
    }
    .backup-info .status-badge.pending {
        background: #fef7e0;
        color: #f9ab00;
    }
    .backup-info .status-badge.failed {
        background: #fce8e6;
        color: #c5221f;
    }
    .backup-info .details {
        color: #5f6368;
        font-size: 12px;
        margin-top: 4px;
        display: flex;
        flex-wrap: wrap;
        gap: 8px 16px;
    }
    .backup-info .details div {
        margin: 0;
        white-space: nowrap;
    }
    .backup-info .details i {
        width: 14px;
        margin-right: 4px;
    }
    .backup-actions {
        display: flex;
        gap: 6px;
        flex-shrink: 0;
    }
    .backup-actions .btn-success {
        background: #188038;
        border-color: #188038;
        color: #fff;
    }
    .backup-actions .btn-success:hover {
        background: #137333;
        border-color: #137333;
        color: #fff;
    }
    .backup-actions .btn-danger {
        background: #c5221f;
        border-color: #c5221f;
        color: #fff;
    }
    .backup-actions .btn-danger:hover {
        background: #a50e0e;
        border-color: #a50e0e;
        color: #fff;
    }
    .backup-actions .btn {
        padding: 6px 12px;
        font-size: 12px;
    }
    .backup-actions .btn:active { transform: translateY(1px); }
    .empty-state {
        text-align: center;
        padding: 40px 20px;
        color: #5f6368;
    }
    .empty-state i {
        font-size: 48px;
        margin-bottom: 15px;
        color: #ccc;
    }
    .empty-state h3 {
        margin: 0 0 8px 0;
        font-size: 16px;
        color: #202124;
    }
    .empty-state p {
        margin: 0;
        font-size: 13px;
    }
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.5);
        z-index: 1000;
        align-items: center;
        justify-content: center;
    }
    .modal.show {
        display: flex;
    }
    .modal-content {
        background: #fff;
        border-radius: 8px;
        width: 90%;
        max-width: 500px;
        max-height: 90vh;
        overflow-y: auto;
    }
    .modal-header {
        padding: 15px 20px;
        border-bottom: 1px solid #e8eaed;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .modal-header h3 {
        margin: 0;
        color: #202124;
        font-size: 16px;
    }
    .modal-close {
        background: none;
        border: none;
        font-size: 20px;
        cursor: pointer;
        color: #5f6368;
    }
    .modal-body {
        padding: 15px 20px;
    }
    .form-group {
        margin-bottom: 12px;
    }
    .form-group label {
        display: block;
        margin-bottom: 4px;
        color: #202124;
        font-weight: 500;
        font-size: 13px;
    }
    .form-group input,
    .form-group select {
        width: 100%;
        padding: 8px 10px;
        border: 1px solid #e8eaed;
        border-radius: 6px;
        font-size: 13px;
        box-sizing: border-box;
    }
    .form-group input:focus,
    .form-group select:focus {
        outline: none;
        border-color: #188038;
    }
    .form-group .help-text {
        color: #5f6368;
        font-size: 12px;
        margin-top: 3px;
    }
    .modal-footer {
        padding: 12px 20px;
        border-top: 1px solid #e8eaed;
        display: flex;
        justify-content: flex-end;
        gap: 8px;
    }
    .alert {
        padding: 10px 12px;
        border-radius: 4px;
        margin-bottom: 12px;
        font-size: 13px;
    }
    .alert-success {
        background: #e6f4ea;
        color: #137333;
        border: 1px solid #ceead6;
    }
    .alert-danger {
        background: #fce8e6;
        color: #c5221f;
        border: 1px solid #fad2cf;
    }
    .loading {
        text-align: center;
        padding: 30px;
    }
    .loading i {
        font-size: 24px;
        color: #188038;
        margin-bottom: 10px;
    }
    .loading p {
        color: #5f6368;
        margin: 0;
        font-size: 13px;
    }

    @media (max-width: 768px) {
        .page-container { padding: 12px; }

        .page-header h2 { font-size: 18px !important; }
        .page-header p { font-size: 12px !important; }

        .backup-toolbar { flex-wrap: wrap; gap: 10px; }
        .backup-toolbar > div { max-width: 100%; }

        .btn-group { overflow-x: auto; -webkit-overflow-scrolling: touch; }
        .btn-group::-webkit-scrollbar { display: none; }

        .filter-btn { min-height: 36px; padding: 6px 12px !important; white-space: nowrap; }

        .backup-item { flex-direction: column; align-items: stretch; }
        .backup-info h4 { width: 100%; }
        .backup-info .details { gap: 6px 10px; }
        .backup-info .details div { white-space: normal; }

        .backup-actions { width: 100%; display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; }
        .backup-actions .btn { width: 100%; min-height: 38px; padding: 8px 10px; font-size: 12px; border-radius: 8px; }
        .backup-actions .btn i { margin-right: 6px; font-size: 13px; }
    }
</style>

<div id="alertContainer"></div>

<div class="content-area page-container">
    <div class="page-header" style="margin-bottom: 15px;">
        <h2 style="font-size: 18px; margin: 0;"><i class="fas fa-archive"></i> 备份管理</h2>
        <p style="font-size: 13px; color: #5f6368; margin: 5px 0 0 0;">管理您的网站备份文件</p>
    </div>
    
    <div class="backup-toolbar d-flex justify-content-between align-items-center mb-3" style="margin-bottom: 12px;">
    <div>
        <!-- 备份类型筛选标签 -->
        <div class="btn-group" role="group" style="display: flex; gap: 4px;">
            <button type="button" class="btn btn-sm btn-outline-secondary filter-btn active" data-filter="all" style="padding: 4px 12px; font-size: 12px;">全部</button>
            <button type="button" class="btn btn-sm btn-outline-secondary filter-btn" data-filter="database" style="padding: 4px 12px; font-size: 12px;">数据库</button>
            <button type="button" class="btn btn-sm btn-outline-secondary filter-btn" data-filter="files" style="padding: 4px 12px; font-size: 12px;">文件</button>
        </div>
    </div>
    <button type="button" class="btn btn-primary btn-sm" data-action="show-create-backup" style="padding: 6px 14px; font-size: 13px;">
        <i class="fas fa-plus"></i> 创建备份
    </button>
</div>

<div class="backup-list" id="backupList">
    <div class="loading">
        <i class="fas fa-spinner fa-spin"></i>
        <p>加载中...</p>
    </div>
</div>

<div class="modal" id="createModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3><?php echo L('create_backup', 'backup'); ?></h3>
            <button type="button" class="modal-close" data-action="close-modal" data-target="createModal">&times;</button>
        </div>
        <div class="modal-body">
            <div class="form-group">
                <label for="backupName">备份名称</label>
                <input type="text" id="backupName" placeholder="自动生成，可修改">
            </div>
            <div class="form-group">
                <label for="backupType">备份类型 *</label>
                <select id="backupType">
                    <option value="database">数据库备份</option>
                    <option value="files">文件备份</option>
                </select>
                <div class="help-text">选择要备份的内容</div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-action="close-modal" data-target="createModal">取消</button>
            <button type="button" class="btn btn-primary" data-action="create-backup">创建</button>
        </div>
    </div>
</div>
<script>
function showAlert(message, type) {
    var alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    var alertHtml = '<div class="alert ' + alertClass + '">' + message + '</div>';
    $('#alertContainer').html(alertHtml);
    setTimeout(function() {
        $('#alertContainer').html('');
    }, 3000);
}

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

var currentFilter = 'all';

function loadBackups() {
    $('#backupList').html('<div class="loading"><i class="fas fa-spinner fa-spin"></i><p>加载中...</p></div>');
    
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: {
            egn: 'getbackups'
        },
        dataType: 'json',
        success: function(data) {
            if (data.code === 'success') {
                renderBackups(data.backups);
            } else {
                $('#backupList').html('<div class="empty-state"><i class="fas fa-exclamation-circle"></i><h3>' + '<?php echo L('loading_failed', 'logs'); ?>' + '</h3><p>' + data.code + '</p></div>');
            }
        },
        error: function(xhr, status, error) {
            console.log('AJAX Error:', status, error);
            console.log('Response:', xhr.responseText);
            $('#backupList').html('<div class="empty-state"><i class="fas fa-exclamation-circle"></i><h3>' + '<?php echo L('loading_failed', 'logs'); ?>' + '</h3><p><?php echo L('refresh', 'common'); ?></p></div>');
        }
    });
}

function renderBackups(backups) {
    // 根据筛选类型过滤备份
    if (currentFilter !== 'all') {
        backups = backups.filter(function(backup) {
            return backup.backup_type === currentFilter;
        });
    }
    
    if (backups.length === 0) {
        var emptyMessage = currentFilter === 'all' ? '您还没有创建任何备份' : '暂无' + (currentFilter === 'database' ? '数据库' : '文件') + '备份';
        $('#backupList').html('<div class="empty-state"><i class="fas fa-download"></i><h3>' + '<?php echo L('no_data', 'common'); ?>' + '</h3><p>' + emptyMessage + '</p></div>');
        return;
    }
    
    var html = '';
    backups.forEach(function(backup) {
        var statusText = '';
        var statusClass = '';
        
        switch(backup.status) {
            case 'success':
                statusText = '成功';
                statusClass = 'success';
                break;
            case 'pending':
                statusText = '备份中';
                statusClass = 'pending';
                break;
            case 'failed':
                statusText = '失败';
                statusClass = 'failed';
                break;
        }
        
        var typeText = '';
        switch(backup.backup_type) {
            case 'database':
                typeText = '数据库备份';
                break;
            case 'files':
                typeText = '文件备份';
                break;
        }
        
        html += '<div class="backup-item">';
        html += '<div class="backup-info">';
        html += '<h4><span class="backup-name" title="' + backup.backup_name + '">' + backup.backup_name + '</span><span class="status-badge ' + statusClass + '">' + statusText + '</span></h4>';
        html += '<div class="details">';
        html += '<div><i class="fas fa-archive"></i> 类型：' + typeText + '</div>';
        html += '<div><i class="fas fa-hdd"></i> 大小：' + formatFileSize(backup.backup_size) + '</div>';
        html += '<div><i class="fas fa-calendar"></i> 创建：' + backup.create_time + '</div>';
        if (backup.error_message) {
            html += '<div><i class="fas fa-exclamation-triangle"></i> 错误信息：' + backup.error_message + '</div>';
        }
        html += '</div>';
        html += '</div>';
        html += '<div class="backup-actions">';
        if (backup.status === 'success') {
            html += '<button type="button" class="btn btn-success backup-action" data-action="download" data-id="' + backup.id + '"><i class="fas fa-download"></i> 下载</button>';
        html += '<button type="button" class="btn btn-success backup-action" data-action="restore" data-id="' + backup.id + '" data-type="' + backup.backup_type + '"><i class="fas fa-upload"></i> 恢复</button>';
        }
        html += '<button type="button" class="btn btn-danger backup-action" data-action="delete" data-id="' + backup.id + '"><i class="fas fa-trash"></i> 删除</button>';
        html += '</div>';
        html += '</div>';
    });
    
    $('#backupList').html(html);
}

function showCreateModal() {
    try {
        $('#backupName').val(buildDefaultBackupName($('#backupType').val()));
    } catch (e) {}
    $('#createModal').addClass('show');
}

function closeModal(modalId) {
    $('#' + modalId).removeClass('show');
}

function createBackup() {
    var backupName = ($('#backupName').val() || '').trim();
    var backupType = $('#backupType').val();

    if (!backupName) {
        backupName = buildDefaultBackupName(backupType);
        $('#backupName').val(backupName);
    }
    
    closeModal('createModal');
    
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: {
            egn: 'createbackup',
            backup_name: backupName,
            backup_type: backupType
        },
        dataType: 'json',
        success: function(data) {
            if (data.code === 'success') {
                showAlert('备份创建成功', 'success');
                loadBackups();
            } else {
                showAlert(data.code, 'error');
            }
        },
        error: function(xhr, status, error) {
            console.log('AJAX Error:', status, error);
            console.log('Response:', xhr.responseText);
            showAlert('创建失败，请重试', 'error');
        }
    });
}

function pad2(n) {
    return (n < 10 ? '0' : '') + n;
}

function buildDefaultBackupName(type) {
    var now = new Date();
    var yyyy = now.getFullYear();
    var mm = pad2(now.getMonth() + 1);
    var dd = pad2(now.getDate());
    var hh = pad2(now.getHours());
    var mi = pad2(now.getMinutes());
    var ss = pad2(now.getSeconds());
    var prefix = (type === 'database') ? '数据库备份' : '文件备份';
    return yyyy + '-' + mm + '-' + dd + '_' + hh + '-' + mi + '-' + ss + '_' + prefix;
}

function downloadBackup(id) {
    window.open('ajax.php?egn=downloadbackup&id=' + id, '_blank');
}

function restoreBackup(id, type) {
    var msg = '确定要恢复此备份吗？恢复操作将覆盖现有数据，请谨慎操作！';
    if (type === 'database') {
        msg = '确定要将此备份导入到您的数据库吗？此操作会覆盖/修改现有数据库数据，请谨慎操作！';
    } else if (type === 'files') {
        msg = '确定要恢复此文件备份吗？此操作会覆盖网站文件，请谨慎操作！';
    }
    if (!confirm(msg)) {
        return;
    }
    
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: {
            egn: 'restorebackup',
            id: id
        },
        dataType: 'json',
        success: function(data) {
            if (data && data.code === 'success') {
                showAlert(data.msg || '操作已提交', 'success');
                loadBackups();
                return;
            }
            showAlert((data && (data.msg || data.code)) ? (data.msg || data.code) : '操作失败', 'error');
        },
        error: function(xhr, status, error) {
            console.log('AJAX Error:', status, error);
            console.log('Response:', xhr.responseText);
            showAlert('恢复失败，请重试', 'error');
        }
    });
}

function deleteBackup(id) {
    if (!confirm('确定要删除此备份吗？删除后将无法恢复！')) {
        return;
    }
    
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: {
            egn: 'deletebackup',
            id: id
        },
        dataType: 'json',
        success: function(data) {
            if (data.code === 'success') {
                showAlert('备份删除成功', 'success');
                loadBackups();
            } else {
                showAlert(data.code, 'error');
            }
        },
        error: function(xhr, status, error) {
            console.log('AJAX Error:', status, error);
            console.log('Response:', xhr.responseText);
            showAlert('删除失败，请重试', 'error');
        }
    });
}

// 事件委托：备份操作
$(document).on('click', '.backup-action', function() {
    var action = $(this).data('action');
    var id = $(this).data('id');
    var type = $(this).data('type');
    if (!action || !id) return;
    switch(action) {
        case 'download':
            downloadBackup(id);
            break;
        case 'restore':
            restoreBackup(id, type);
            break;
        case 'delete':
            deleteBackup(id);
            break;
    }
});

// 事件代理：备份相关动作
$(document).on('click', 'button[data-action^="show-"]', function(e){
    var action = $(this).attr('data-action');
    switch(action) {
        case 'show-create-backup':
            showCreateModal(); break;
    }
});

// 备份类型筛选
$(document).on('click', '.filter-btn', function() {
    $('.filter-btn').removeClass('active btn-primary').addClass('btn-outline-secondary');
    $(this).removeClass('btn-outline-secondary').addClass('active btn-primary');
    currentFilter = $(this).data('filter');
    loadBackups();
});

// 事件代理：备份模态动作
$(document).on('click', '[data-action="close-modal"]', function(e){
    var target = $(this).attr('data-target');
    if (target) $('#' + target).removeClass('show');
});
$(document).on('click', '[data-action="create-backup"]', function(e){
    e.preventDefault();
    createBackup();
});

$(document).on('change', '#backupType', function(){
    var v = ($('#backupName').val() || '').trim();
    if (!v) {
        $('#backupName').val(buildDefaultBackupName($(this).val()));
    }
});

$(document).ready(function() {
    loadBackups();
});
</script>
