<?php
// DB-Zugangsdaten
$host = 'localhost';
$user = 'kd54698_cloud';
$pass = 'w3r24asd!!!';
$db   = 'kd54698_cloud';

// Backup-Verzeichnis
$backupDir = __DIR__ . '/backups/';
if (!is_dir($backupDir)) {
    mkdir($backupDir, 0777, true);
}

// Dateiname mit Zeitstempel
$date = date('Y-m-d_H-i-s');
$backupFile = $backupDir . "backup_{$db}_{$date}.sql";

// Verbindung zur Datenbank aufbauen
$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
    die("Verbindung fehlgeschlagen: " . $conn->connect_error);
}
$conn->set_charset("utf8mb4");

// Tabellen abrufen
$tables = [];
$result = $conn->query("SHOW TABLES");
while ($row = $result->fetch_row()) {
    $tables[] = $row[0];
}

// Backup-Inhalt vorbereiten
$backupContent = "-- Backup von $db am $date\n\n";

foreach ($tables as $table) {
    // CREATE TABLE Statement
    $create = $conn->query("SHOW CREATE TABLE `$table`")->fetch_assoc();
    $backupContent .= "DROP TABLE IF EXISTS `$table`;\n" . $create['Create Table'] . ";\n\n";

    // Daten einfügen
    $rows = $conn->query("SELECT * FROM `$table`");
    while ($row = $rows->fetch_assoc()) {
        $values = array_map(function ($value) use ($conn) {
            return is_null($value) ? 'NULL' : "'" . $conn->real_escape_string($value) . "'";
        }, array_values($row));

        $backupContent .= "INSERT INTO `$table` VALUES (" . implode(", ", $values) . ");\n";
    }
    $backupContent .= "\n\n";
}

// Datei speichern
file_put_contents($backupFile, $backupContent);
echo "Backup erfolgreich erstellt: " . basename($backupFile);

// Dateiinformationen erfassen
$filesizeKB = round(filesize($backupFile) / 1024); // Größe in KB
$createdAt = date('Y-m-d H:i:s');
$filename = basename($backupFile);

// Backup-Datensatz in Datenbank speichern
$stmt = $conn->prepare("INSERT INTO db_backups (filename, filesize_kb, created_at) VALUES (?, ?, ?)");
$stmt->bind_param("sis", $filename, $filesizeKB, $createdAt);
$stmt->execute();
$stmt->close();

$conn->close();
?>
