<?php
$page_title = "Database Backup";
require_once 'header.php';

$db = Database::getInstance()->connect();

// Handle backup creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_backup'])) {
    try {
        $backup_name = $POST['backup_name'] ?? 'backup' . date('Y-m-d_H-i-s');
        $backup_type = $_POST['backup_type'] ?? 'full';
        $include_structure = isset($_POST['include_structure']);
        $include_data = isset($_POST['include_data']);
        $compress = isset($_POST['compress']);
        
        // Get database connection details
        $host = DB_HOST;
        $user = DB_USER;
        $pass = DB_PASS;
        $dbname = DB_NAME;
        
        // Create backup directory if it doesn't exist
        $backup_dir = '../backups/';
        if (!is_dir($backup_dir)) {
            mkdir($backup_dir, 0755, true);
        }
        
        // Generate filename
        $filename = $backup_name . '.sql';
        if ($compress) {
            $filename .= '.gz';
        }
        $filepath = $backup_dir . $filename;
        
        // Get tables to backup
        $tables_stmt = $db->query("SHOW TABLES");
        $tables = $tables_stmt->fetchAll(PDO::FETCH_COLUMN);
        
        $backup_content = "-- " . SITE_NAME . " Database Backup\n";
        $backup_content .= "-- Generated: " . date('Y-m-d H:i:s') . "\n";
        $backup_content .= "-- Backup Type: " . ucfirst($backup_type) . "\n";
        $backup_content .= "-- Database: " . $dbname . "\n\n";
        $backup_content .= "SET FOREIGN_KEY_CHECKS=0;\n\n";
        
        foreach ($tables as $table) {
            // Skip certain tables for partial backups
            if ($backup_type == 'essential' && in_array($table, ['activity_logs', 'login_attempts'])) {
                continue;
            }
            
            if ($include_structure) {
                // Get table structure
                $create_stmt = $db->query("SHOW CREATE TABLE $table");
                $create_row = $create_stmt->fetch();
                $backup_content .= "--\n-- Table structure for table $table\n--\n\n";
                $backup_content .= "DROP TABLE IF EXISTS $table;\n";
                $backup_content .= $create_row[1] . ";\n\n";
            }
            
            if ($include_data) {
                // Get table data
                $data_stmt = $db->query("SELECT * FROM $table");
                $row_count = $data_stmt->rowCount();
                
                if ($row_count > 0) {
                    $backup_content .= "--\n-- Dumping data for table $table\n--\n\n";
                    
                    // Get column names
                    $columns_stmt = $db->query("SHOW COLUMNS FROM $table");
                    $columns = $columns_stmt->fetchAll(PDO::FETCH_COLUMN);
                    
                    while ($row = $data_stmt->fetch(PDO::FETCH_ASSOC)) {
                        $values = [];
                        foreach ($columns as $column) {
                            if (isset($row[$column])) {
                                $values[] = $db->quote($row[$column]);
                            } else {
                                $values[] = 'NULL';
                            }
                        }
                        $backup_content .= "INSERT INTO $table (" . implode(', ', $columns) . ") VALUES (" . implode(', ', $values) . ");\n";
                    }
                    $backup_content .= "\n";
                }
            }
        }
        
        $backup_content .= "SET FOREIGN_KEY_CHECKS=1;\n";
        
        // Write to file
        if ($compress) {
            file_put_contents('compress.zlib://' . $filepath, $backup_content);
        } else {
            file_put_contents($filepath, $backup_content);
        }
        
        // Log the backup
        $log_stmt = $db->prepare("
            INSERT INTO activity_logs (admin_id, action, details)
            VALUES (?, 'backup_create', ?)
        ");
        
        $log_details = [
            'filename' => $filename,
            'size' => filesize($filepath),
            'type' => $backup_type,
            'compressed' => $compress
        ];
        
        $log_stmt->execute([$_SESSION['admin_id'], json_encode($log_details)]);
        
        $success = "Backup created successfully! File: " . $filename;
        
    } catch (Exception $e) {
        $error = "Failed to create backup: " . $e->getMessage();
    }
}

// Handle backup restoration
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['restore_backup'])) {
    $backup_file = $_POST['backup_file'];
    $filepath = '../backups/' . $backup_file;
    
    if (!file_exists($filepath)) {
        $error = "Backup file not found";
    } else {
        try {
            $db->beginTransaction();
            
            // Read backup file
            if (pathinfo($filepath, PATHINFO_EXTENSION) == 'gz') {
                $content = gzdecode(file_get_contents($filepath));
            } else {
                $content = file_get_contents($filepath);
            }
            
            // Split into individual queries
            $queries = explode(";\n", $content);
            
            foreach ($queries as $query) {
                $query = trim($query);
                if (!empty($query) && !str_starts_with($query, '--')) {
                    $db->exec($query);
                }
            }
            
            // Log the restoration
            $log_stmt = $db->prepare("
                INSERT INTO activity_logs (admin_id, action, details)
                VALUES (?, 'backup_restore', ?)
            ");
            
            $log_stmt->execute([
                $_SESSION['admin_id'],
                json_encode(['filename' => $backup_file, 'size' => filesize($filepath)])
            ]);
            
            $db->commit();
            $success = "Backup restored successfully!";
            
        } catch (Exception $e) {
            $db->rollBack();
            $error = "Failed to restore backup: " . $e->getMessage();
        }
    }
}

// Handle backup deletion
if (isset($_GET['delete'])) {
    $filename = basename($_GET['delete']);
    $filepath = '../backups/' . $filename;
    
    if (file_exists($filepath) && unlink($filepath)) {
        // Log the deletion
        $log_stmt = $db->prepare("
            INSERT INTO activity_logs (admin_id, action, details)
            VALUES (?, 'backup_delete', ?)
        ");
        
        $log_stmt->execute([$_SESSION['admin_id'], json_encode(['filename' => $filename])]);
        
        $success = "Backup file deleted successfully!";
    } else {
        $error = "Failed to delete backup file";
    }
}

// Get existing backups
$backup_dir = '../backups/';
$backups = [];
if (is_dir($backup_dir)) {
    $files = scandir($backup_dir);
    foreach ($files as $file) {
        if ($file != '.' && $file != '..' && (str_ends_with($file, '.sql') || str_ends_with($file, '.sql.gz'))) {
            $filepath = $backup_dir . $file;
            $backups[] = [
                'name' => $file,
                'size' => filesize($filepath),
                'modified' => filemtime($filepath),
                'type' => str_ends_with($file, '.gz') ? 'compressed' : 'sql'
            ];
        }
    }
    
    // Sort by modification time (newest first)
    usort($backups, function($a, $b) {
        return $b['modified'] <=> $a['modified'];
    });
}

// Get database stats
$db_stats_sql = "
    SELECT 
        (SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE()) as table_count,
        ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) as total_size_mb,
        (SELECT COUNT(*) FROM users) as user_count,
        (SELECT COUNT(*) FROM transactions) as transaction_count,
        (SELECT COUNT(*) FROM investments) as investment_count
    FROM information_schema.tables 
    WHERE table_schema = DATABASE()
";

$db_stats_stmt = $db->query($db_stats_sql);
$db_stats = $db_stats_stmt->fetch();

// Get backup statistics
$backup_stats = [
    'total_backups' => count($backups),
    'total_size' => array_sum(array_column($backups, 'size')),
    'oldest_backup' => !empty($backups) ? min(array_column($backups, 'modified')) : null,
    'newest_backup' => !empty($backups) ? max(array_column($backups, 'modified')) : null
];
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="mb-6">
        <h1 class="text-2xl font-bold">Database Backup & Restore</h1>
        <p class="text-gray-600">Create, restore, and manage database backups</p>
    </div>

    <!-- Messages -->
    <?php if (isset($error)): ?>
    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
        <?php echo $error; ?>
    </div>
    <?php endif; ?>
    
    <?php if (isset($success)): ?>
    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
        <?php echo $success; ?>
    </div>
    <?php endif; ?>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Database Size</p>
                    <h3 class="text-2xl font-bold"><?php echo number_format($db_stats['total_size_mb'], 2); ?> MB</h3>
                </div>
                <i class="fas fa-database text-purple-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Tables</p>
                    <h3 class="text-2xl font-bold text-blue-600"><?php echo number_format($db_stats['table_count']); ?></h3>
                </div>
                <i class="fas fa-table text-blue-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Backups</p>
                    <h3 class="text-2xl font-bold text-green-600"><?php echo number_format($backup_stats['total_backups']); ?></h3>
                </div>
                <i class="fas fa-save text-green-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Backup Storage</p>
                    <h3 class="text-2xl font-bold"><?php echo number_format($backup_stats['total_size'] / 1024 / 1024, 2); ?> MB</h3>
                </div>
                <i class="fas fa-hdd text-yellow-500 text-2xl"></i>
            </div>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- Create Backup Form -->
        <div class="bg-white rounded-xl shadow p-6">
            <h3 class="text-lg font-bold mb-4">Create New Backup</h3>
            <form method="POST" action="" class="space-y-6">
                <div>
                    <label class="block text-gray-700 font-medium mb-2">Backup Name</label>
                    <input type="text" name="backup_name" 
                           value="backup_<?php echo date('Y-m-d_H-i-s'); ?>"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                    <p class="text-sm text-gray-500 mt-1">Optional custom name for the backup file</p>
                </div>
                
                <div>
                    <label class="block text-gray-700 font-medium mb-2">Backup Type</label>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <label class="flex items-center p-4 border rounded-lg cursor-pointer hover:bg-gray-50">
                            <input type="radio" name="backup_type" value="full" checked class="mr-3">
                            <div>
                                <p class="font-medium">Full Backup</p>
                                <p class="text-sm text-gray-500">All tables</p>
                            </div>
                        </label>
                        
                        <label class="flex items-center p-4 border rounded-lg cursor-pointer hover:bg-gray-50">
                            <input type="radio" name="backup_type" value="essential" class="mr-3">
                            <div>
                                <p class="font-medium">Essential Only</p>
                                <p class="text-sm text-gray-500">Exclude logs</p>
                            </div>
                        </label>
                        
                        <label class="flex items-center p-4 border rounded-lg cursor-pointer hover:bg-gray-50">
                            <input type="radio" name="backup_type" value="custom" class="mr-3">
                            <div>
                                <p class="font-medium">Custom</p>
                                <p class="text-sm text-gray-500">Select tables</p>
                            </div>
                        </label>
                    </div>
                </div>
                
                <div>
                    <label class="block text-gray-700 font-medium mb-2">Backup Options</label>
                    <div class="space-y-3">
                        <label class="flex items-center">
                            <input type="checkbox" name="include_structure" checked class="mr-3">
                            <span class="text-gray-700">Include table structure</span>
                        </label>
                        
                        <label class="flex items-center">
                            <input type="checkbox" name="include_data" checked class="mr-3">
                            <span class="text-gray-700">Include table data</span>
                        </label>
                        
                        <label class="flex items-center">
                            <input type="checkbox" name="compress" checked class="mr-3">
                            <span class="text-gray-700">Compress backup (GZIP)</span>
                        </label>
                    </div>
                </div>
                
                <div id="customTables" class="hidden">
                    <label class="block text-gray-700 font-medium mb-2">Select Tables</label>
                    <div class="grid grid-cols-2 md:grid-cols-3 gap-2 max-h-40 overflow-y-auto p-4 border rounded-lg">
                        <?php
                        $tables_stmt = $db->query("SHOW TABLES");
                        while ($table = $tables_stmt->fetch(PDO::FETCH_COLUMN)):
                        ?>
                        <label class="flex items-center">
                            <input type="checkbox" name="custom_tables[]" value="<?php echo $table; ?>" checked class="mr-2">
                            <span class="text-sm"><?php echo $table; ?></span>
                        </label>
                        <?php endwhile; ?>
                    </div>
                </div>
                
                <div class="border-t pt-6">
                    <button type="submit" name="create_backup" 
                            class="w-full bg-gradient-to-r from-purple-600 to-blue-600 text-white font-bold py-3 px-4 rounded-lg hover:opacity-90">
                        <i class="fas fa-save mr-2"></i>Create Backup
                    </button>
                </div>
            </form>
        </div>

        <!-- Restore Backup Form -->
        <div class="bg-white rounded-xl shadow p-6">
            <h3 class="text-lg font-bold mb-4">Restore Backup</h3>
            <form method="POST" action="" class="space-y-6" id="restoreForm">
                <div>
                    <label class="block text-gray-700 font-medium mb-2">Select Backup File</label>
                    <select name="backup_file" required
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        <option value="">Select a backup file</option>
                        <?php foreach ($backups as $backup): ?>
                        <option value="<?php echo htmlspecialchars($backup['name']); ?>">
                            <?php echo htmlspecialchars($backup['name']); ?>
                            (<?php echo date('Y-m-d H:i', $backup['modified']); ?>, 
                            <?php echo number_format($backup['size'] / 1024, 2); ?> KB)
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <?php if (empty($backups)): ?>
                    <p class="text-sm text-gray-500 mt-2">No backup files found</p>
                    <?php endif; ?>
                </div>
                
                <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                    <div class="flex items-center">
                        <i class="fas fa-exclamation-triangle text-red-500 text-xl mr-3"></i>
                        <div>
                            <p class="font-bold text-red-700">Warning</p>
                            <p class="text-sm text-red-600">Restoring a backup will overwrite ALL current data. This action cannot be undone!</p>
                        </div>
                    </div>
                </div>
                
                <div>
                    <label class="block text-gray-700 font-medium mb-2">Verification</label>
                    <input type="text" id="confirmText" 
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg"
                           placeholder="Type 'RESTORE' to confirm">
                </div>
                
                <div class="border-t pt-6">
                    <button type="submit" name="restore_backup" 
                            class="w-full bg-red-600 text-white font-bold py-3 px-4 rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed"
                            id="restoreButton" disabled>
                        <i class="fas fa-redo mr-2"></i>Restore Backup
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Existing Backups -->
    <div class="mt-6 bg-white rounded-xl shadow">
        <div class="p-6 border-b">
            <h3 class="text-lg font-bold">Existing Backups</h3>
            <p class="text-sm text-gray-600"><?php echo count($backups); ?> backup files found</p>
        </div>
        
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="p-4 text-left">File Name</th>
                        <th class="p-4 text-left">Size</th>
                        <th class="p-4 text-left">Type</th>
                        <th class="p-4 text-left">Modified</th>
                        <th class="p-4 text-left">Age</th>
                        <th class="p-4 text-left">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php foreach ($backups as $backup): 
                        $age = time() - $backup['modified'];
                        $age_days = floor($age / (60 * 60 * 24));
                        
                        $age_color = $age_days > 30 ? 'text-red-600' : 
                                    ($age_days > 7 ? 'text-yellow-600' : 'text-green-600');
                    ?>
                    <tr class="hover:bg-gray-50">
                        <td class="p-4">
                            <p class="font-medium">
                                <i class="fas fa-file-<?php echo $backup['type'] == 'compressed' ? 'archive' : 'code'; ?> mr-2"></i>
                                <?php echo htmlspecialchars($backup['name']); ?>
                            </p>
                        </td>
                        <td class="p-4">
                            <p class="font-mono"><?php echo number_format($backup['size'] / 1024, 2); ?> KB</p>
                        </td>
                        <td class="p-4">
                            <span class="px-2 py-1 rounded-full text-xs font-semibold 
                                <?php echo $backup['type'] == 'compressed' ? 'bg-blue-100 text-blue-800' : 'bg-gray-100 text-gray-800'; ?>">
                                <?php echo ucfirst($backup['type']); ?>
                            </span>
                        </td>
                        <td class="p-4">
                            <p><?php echo date('Y-m-d', $backup['modified']); ?></p>
                            <p class="text-sm text-gray-500"><?php echo date('H:i:s', $backup['modified']); ?></p>
                        </td>
                        <td class="p-4">
                            <p class="<?php echo $age_color; ?>">
                                <?php 
                                if ($age_days > 0) {
                                    echo $age_days . ' day' . ($age_days > 1 ? 's' : '');
                                } else {
                                    $age_hours = floor($age / (60 * 60));
                                    echo $age_hours . ' hour' . ($age_hours > 1 ? 's' : '');
                                }
                                ?>
                            </p>
                        </td>
                        <td class="p-4">
                            <div class="flex space-x-2">
                                <button onclick="downloadBackup('<?php echo htmlspecialchars($backup['name']); ?>')" 
                                        class="text-blue-600 hover:text-blue-800">
                                    <i class="fas fa-download"></i>
                                </button>
                                <button onclick="viewBackup('<?php echo htmlspecialchars($backup['name']); ?>')" 
                                        class="text-green-600 hover:text-green-800">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <button onclick="deleteBackup('<?php echo htmlspecialchars($backup['name']); ?>')" 
                                        class="text-red-600 hover:text-red-800">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <?php if (empty($backups)): ?>
        <div class="p-8 text-center text-gray-500">
            <i class="fas fa-database text-4xl mb-4 text-gray-300"></i>
            <p class="text-lg">No backup files found</p>
            <p class="text-sm mt-2">Create your first backup using the form above</p>
        </div>
        <?php endif; ?>
    </div>

    <!-- Backup Settings -->
    <div class="mt-6 bg-white rounded-xl shadow p-6">
        <h3 class="text-lg font-bold mb-4">Backup Settings</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div class="space-y-3">
                <h4 class="font-semibold text-gray-700">Automated Backups</h4>
                <div class="space-y-2">
                    <label class="flex items-center">
                        <input type="checkbox" class="mr-2">
                        <span class="text-sm">Daily backups</span>
                    </label>
                    <label class="flex items-center">
                        <input type="checkbox" class="mr-2">
                        <span class="text-sm">Weekly backups</span>
                    </label>
                    <label class="flex items-center">
                        <input type="checkbox" class="mr-2">
                        <span class="text-sm">Monthly backups</span>
                    </label>
                </div>
            </div>
            
            <div class="space-y-3">
                <h4 class="font-semibold text-gray-700">Retention Policy</h4>
                <div class="space-y-2">
                    <div class="flex justify-between">
                        <span class="text-sm">Keep daily backups:</span>
                        <select class="text-sm border rounded px-2 py-1">
                            <option>7 days</option>
                            <option>14 days</option>
                            <option>30 days</option>
                        </select>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-sm">Keep weekly backups:</span>
                        <select class="text-sm border rounded px-2 py-1">
                            <option>4 weeks</option>
                            <option>8 weeks</option>
                            <option>12 weeks</option>
                        </select>
                    </div>
                </div>
            </div>
            
            <div class="space-y-3">
                <h4 class="font-semibold text-gray-700">Storage</h4>
                <div class="space-y-2">
                    <div class="flex justify-between">
                        <span class="text-sm">Max backup size:</span>
                        <span class="font-semibold">1 GB</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-sm">Current usage:</span>
                        <span class="font-semibold"><?php echo number_format($backup_stats['total_size'] / 1024 / 1024, 2); ?> MB</span>
                    </div>
                </div>
            </div>
            
            <div class="space-y-3">
                <h4 class="font-semibold text-gray-700">Quick Actions</h4>
                <div class="space-y-2">
                    <button onclick="createQuickBackup()" class="w-full bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700 text-sm">
                        Quick Backup
                    </button>
                    <button onclick="cleanOldBackups()" class="w-full bg-yellow-600 text-white py-2 rounded-lg hover:bg-yellow-700 text-sm">
                        Clean Old Backups
                    </button>
                    <button onclick="exportBackupList()" class="w-full bg-gray-600 text-white py-2 rounded-lg hover:bg-gray-700 text-sm">
                        Export List
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- View Backup Modal -->
<div id="backupModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-4xl">
            <div class="p-6 border-b">
                <h3 id="modalTitle" class="text-xl font-bold"></h3>
            </div>
            <div class="p-6 max-h-[70vh] overflow-y-auto">
                <pre id="backupContent" class="text-sm font-mono bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto"></pre>
            </div>
            <div class="p-6 border-t flex justify-between">
                <button onclick="closeModal()" 
                        class="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700">
                    Close
                </button>
                <button onclick="downloadCurrentBackup()" 
                        class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                    <i class="fas fa-download mr-2"></i>Download
                </button>
            </div>
        </div>
    </div>
</div>

<script>
let currentBackupFile = '';

// Show/hide custom tables selection
document.querySelectorAll('input[name="backup_type"]').forEach(radio => {
    radio.addEventListener('change', function() {
        document.getElementById('customTables').classList.add('hidden');
        if (this.value === 'custom') {
            document.getElementById('customTables').classList.remove('hidden');
        }
    });
});

// Enable/disable restore button based on confirmation
document.getElementById('confirmText').addEventListener('input', function() {
    document.getElementById('restoreButton').disabled = this.value !== 'RESTORE';
});

// Download backup
function downloadBackup(filename) {
    window.open(download-backup.php?file=${encodeURIComponent(filename)}, '_blank');
}

// View backup
function viewBackup(filename) {
    currentBackupFile = filename;
    
    $.ajax({
        url: '../api/view-backup.php',
        method: 'GET',
        data: { file: filename },
        success: function(response) {
            document.getElementById('modalTitle').textContent = 'Backup File: ' + filename;
            document.getElementById('backupContent').textContent = response;
            document.getElementById('backupModal').classList.remove('hidden');
        },
        error: function() {
            showNotification('Error loading backup file', 'error');
        }
    });
}

// Delete backup
function deleteBackup(filename) {
    if (confirm(Delete backup file: ${filename}?)) {
        window.location.href = ?delete=${encodeURIComponent(filename)};
    }
}

// Close modal
function closeModal() {
    document.getElementById('backupModal').classList.add('hidden');
}

// Download current backup from modal
function downloadCurrentBackup() {
    if (currentBackupFile) {
        downloadBackup(currentBackupFile);
    }
}

// Quick backup
function createQuickBackup() {
    if (confirm('Create a quick backup now?')) {
        $.ajax({
            url: '../api/quick-backup.php',
            method: 'POST',
            success: function(response) {
                const result = JSON.parse(response);
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) {
                    location.reload();
                }
            }
        });
    }
}

// Clean old backups
function cleanOldBackups() {
    if (confirm('Delete backups older than 30 days?')) {
        $.ajax({
            url: '../api/clean-backups.php',
            method: 'POST',
            data: { days: 30 },
            success: function(response) {
                const result = JSON.parse(response);
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) {
                    location.reload();
                }
            }
        });
    }
}

// Export backup list
function exportBackupList() {
    window.open('export-backup-list.php', '_blank');
}

// Auto-backup reminder
setTimeout(() => {
    const lastBackup = <?php echo $backup_stats['newest_backup'] ?? 0; ?>;
    const sevenDaysAgo = Date.now() / 1000 - (7 * 24 * 60 * 60);
    
    if (lastBackup < sevenDaysAgo) {
        if (confirm('No backup created in the last 7 days. Create one now?')) {
            createQuickBackup();
        }
    }
}, 5000); // Show after 5 seconds
</script>

<?php require_once 'footer.php'; ?>