<?php


session_start();
include __DIR__ . '/../../includes/db.php';
include __DIR__ . '/../../includes/header.php';
include __DIR__ . '/../../includes/nav.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$user_id = $_SESSION['user_id'];


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

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

// Wenn Backup manuell ausgelöst wurde
if (isset($_POST['do_backup'])) {
    $backupDir = __DIR__ . '/backups/';
    if (!is_dir($backupDir)) {
        mkdir($backupDir, 0777, true);
    }

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

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

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

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

        $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";
    }

    file_put_contents($backupFile, $backupContent);

    // Backup in Tabelle eintragen
    $filename = basename($backupFile);
    $filesizeKB = round(filesize($backupFile) / 1024);
    $createdAt = date('Y-m-d H:i:s');

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

    $successMessage = "Backup erfolgreich erstellt: $filename";
}

// Backups aus Datenbank laden
$result = $conn->query("SELECT * FROM db_backups ORDER BY created_at DESC");
?>

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <title>Datenbank-Backups</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { padding: 8px 12px; border: 1px solid #ccc; text-align: left; }
        th { background-color: #f2f2f2; }
        a.download { text-decoration: none; color: #007BFF; }
        a.download:hover { text-decoration: underline; }
        .success { padding: 10px; background-color: #d4edda; border: 1px solid #c3e6cb; color: #155724; margin-bottom: 15px; }
        .btn { background-color: #007BFF; color: white; padding: 10px 16px; border: none; cursor: pointer; border-radius: 4px; }
        .btn:hover { background-color: #0056b3; }
    </style>
</head>
<body>
    <h1>Datenbank-Backups</h1>

    <?php if (isset($successMessage)): ?>
        <div class="success"><?php echo htmlspecialchars($successMessage); ?></div>
    <?php endif; ?>

    <form method="post">
        <button class="btn" type="submit" name="do_backup">Backup jetzt erstellen</button>
    </form>

    <table>
        <thead>
            <tr>
                <th>Dateiname</th>
                <th>Größe (KB)</th>
                <th>Erstellt am</th>
                <th>Download</th>
            </tr>
        </thead>
        <tbody>
            <?php while ($row = $result->fetch_assoc()): ?>
                <tr>
                    <td><?php echo htmlspecialchars($row['filename']); ?></td>
                    <td><?php echo $row['filesize_kb']; ?></td>
                    <td><?php echo $row['created_at']; ?></td>
                    <td><a class="download" href="backups/<?php echo urlencode($row['filename']); ?>" download>Herunterladen</a></td>
                </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</body>
</html>

<?php $conn->close(); ?>

<?php include '../../includes/footer.php'; ?>
