<?php
session_start();
include('../includes/config.php');

// Create backups directory if it doesn't exist
$backup_dir = '../backups/';
if (!file_exists($backup_dir)) {
    mkdir($backup_dir, 0755, true);
}

// Get list of backup files
$backup_files = array();
if (is_dir($backup_dir)) {
    $files = scandir($backup_dir);
    foreach ($files as $file) {
        if ($file != '.' && $file != '..' && pathinfo($file, PATHINFO_EXTENSION) == 'sql') {
            $filepath = $backup_dir . $file;
            $backup_files[] = array(
                'name' => $file,
                'path' => $filepath,
                'size' => formatSize(filesize($filepath)),
                'date' => date('Y-m-d H:i:s', filemtime($filepath))
            );
        }
    }
}

// Sort by date (newest first)
usort($backup_files, function($a, $b) {
    return strtotime($b['date']) - strtotime($a['date']);
});

if (count($backup_files) > 0) {
    foreach ($backup_files as $backup) {
        echo '<tr>';
        echo '<td>' . $backup['name'] . '</td>';
        echo '<td>' . $backup['date'] . '</td>';
        echo '<td>' . $backup['size'] . '</td>';
        echo '<td>';
        echo '<button class="btn btn-sm btn-primary me-2" onclick="downloadBackup(\'' . $backup['name'] . '\')">';
        echo '<i class="fas fa-download"></i>';
        echo '</button>';
        echo '<button class="btn btn-sm btn-danger" onclick="deleteBackup(\'' . $backup['name'] . '\')">';
        echo '<i class="fas fa-trash"></i>';
        echo '</button>';
        echo '</td>';
        echo '</tr>';
    }
} else {
    echo '<tr><td colspan="4" class="text-center py-20">No backup files found.</td></tr>';
}

function formatSize($bytes) {
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        return $bytes . ' bytes';
    } elseif ($bytes == 1) {
        return '1 byte';
    } else {
        return '0 bytes';
    }
}
?>