<?php
// backup_db.php
session_start();
include 'layouts/dbconn.php';

$backup_dir = 'backups/';
if (!is_dir($backup_dir)) {
    mkdir($backup_dir, 0755, true);
}

$include_data = isset($_POST['include_data']);
$compress = isset($_POST['compress']);
$filename = 'backup_' . date('Y-m-d_H-i-s') . '.sql';
$filepath = $backup_dir . $filename;

// Create backup command
$command = sprintf(
    'mysqldump --host=%s --user=%s --password=%s %s %s > %s',
    escapeshellarg($dbhost),
    escapeshellarg($dbuser),
    escapeshellarg($dbpass),
    $include_data ? '' : '--no-data',
    escapeshellarg($dbname),
    escapeshellarg($filepath)
);

exec($command, $output, $return_var);

if ($return_var === 0) {
    if ($compress) {
        $gz_filename = $filename . '.gz';
        $gz_filepath = $backup_dir . $gz_filename;
        $gz = gzopen($gz_filepath, 'w9');
        gzwrite($gz, file_get_contents($filepath));
        gzclose($gz);
        unlink($filepath);
        $filepath = $gz_filepath;
    }
    $_SESSION['success'] = 'Database backup created successfully';
} else {
    $_SESSION['error'] = 'Failed to create backup';
}

header('Location: settings.php');
exit;

function formatBytes($bytes) {
    $units = ['B', 'KB', 'MB', 'GB'];
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    return round($bytes, 2) . ' ' . $units[$pow];
}