<?php
session_start(); // Sitzung starten, um die Authentifizierung zu verwalten

// Überprüfen, ob das Passwort gesendet wurde und korrekt ist
if (isset($_POST['password']) && $_POST['password'] === 'demo') {
    $_SESSION['authenticated'] = true; // Authentifizierung erfolgreich, Sitzungsvariable setzen
}

// Überprüfen, ob der Benutzer bereits authentifiziert ist, sonst das Passwort-Eingabeformular anzeigen
if (!isset($_SESSION['authenticated']) || !$_SESSION['authenticated']) {
    echo '
    <!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Passwortschutz</title>
    <style>
        /* Globales CSS */
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            margin-top: 100px;
        }

        h1 {
            text-align: center;
            color: #333;
        }

        form {
            text-align: center;
            margin-top: 20px;
        }

        input[type="password"] {
            padding: 10px;
            width: 100%;
            margin-top: 10px;
            box-sizing: border-box;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        input[type="submit"] {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
            margin-top: 10px;
        }

        input[type="submit"]:hover {
            background-color: #45a049;
        }

        /* Popup-Overlay */
        #overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
        }

        #password-popup {
            background-color: #333;
            padding: 20px;
            border-radius: 5px;
            color: #fff;
        }

        /* Ende des CSS */
    </style>
</head>
<body>

<div class="container">
    <h1>Passwortschutz</h1>

    <!-- Popup-Overlay und Passwort-Formular -->
    <div id="overlay">
        <div id="password-popup">
            <form action="" method="post">
                <label for="password">Passwort:</label><br>
                <input type="password" id="password" name="password"><br>
                <input type="submit" value="Einloggen">
            </form>
        </div>
    </div>

    <!-- JavaScript für das Schließen des Popups bei Klick außerhalb des Formulars -->
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            var overlay = document.getElementById("overlay");
            overlay.addEventListener("click", function(event) {
                if (event.target === overlay) {
                    overlay.style.display = "none";
                }
            });
        });
    </script>
</div>

</body>
</html>';
    exit; // Die Ausführung hier stoppen, damit der Rest der Seite nicht angezeigt wird, bis das Passwort korrekt eingegeben wurde
}

// Datenbankverbindung herstellen
include_once 'config/config.php';
include_once 'log.php'; // Logdatei einbinden

// Backup durchführen und direkt verschlüsseln
if (isset($_POST['backup'])) {
    $timestamp = date('Y-m-d_H-i-s'); // Eindeutiger Zeitstempel für die Dateinamen
    $backup_file = "backup/backup_$timestamp.sql"; // Backup-Datei im "backup/"-Ordner speichern
    $command = "mysqldump -u $username -p$password $database > $backup_file";
    exec($command);

    // Backup erfolgreich erstellt
    if (file_exists($backup_file)) {
        // Backup-Datei verschlüsseln
        $encryption_key = "2Tj&wuWCUeMrSD%tWS%2fv&vDQdFTeUQ"; // Geheimen Schlüssel für die Verschlüsselung
        $input_file = $backup_file; // Backup-Datei, die verschlüsselt werden soll
        $output_file = "backup/encrypted_backup_$timestamp.txt"; // Verschlüsselte Ausgabedatei

        // Verschlüsselungsalgorithmus und Modus (z.B. AES-256-CBC)
        $encryption_algorithm = 'aes-256-cbc';

        // Initialisierungsvektor für die Verschlüsselung (zufällig generieren oder festlegen)
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($encryption_algorithm));

        // Verschlüsselung durchführen
        if ($encrypted_data = openssl_encrypt(file_get_contents($input_file), $encryption_algorithm, $encryption_key, 0, $iv)) {
            // Initialisierungsvektor (IV) der verschlüsselten Datei hinzufügen
            $encrypted_data_with_iv = $iv . $encrypted_data;
            
            // Verschlüsselte Daten in Ausgabedatei schreiben
            file_put_contents($output_file, $encrypted_data_with_iv);

            // Erfolgreiche Meldung mit Download-Link anzeigen
            $download_button = "<a href='$output_file' download class='download-button'>Download Backup</a>";
            echo "<script>alert('Backup erfolgreich erstellt und verschlüsselt: Download Backup');</script>";

            // Ereignis protokollieren
            logEvent('Backup erstellt und verschlüsselt', 'Backup', "Backup-Datei: $backup_file");
        } else {
            echo "Fehler beim Erstellen und Verschlüsseln des Backups.";
        }
    } else {
        echo "Fehler beim Erstellen des Backups.";
    }
}

// Wiederherstellung durchführen
if (isset($_POST['restore'])) {
    if (isset($_FILES['restore_file'])) {
        $restore_file = $_FILES['restore_file']['tmp_name'];

        // Backup-Datei entschlüsseln, bevor die Wiederherstellung durchgeführt wird
        $encryption_key = "2Tj&wuWCUeMrSD%tWS%2fv&vDQdFTeUQ"; // Geheimer Schlüssel für die Verschlüsselung
        $encryption_algorithm = 'aes-256-cbc';
        $iv_size = openssl_cipher_iv_length($encryption_algorithm);
        $encrypted_data_with_iv = file_get_contents($restore_file);
        $iv = substr($encrypted_data_with_iv, 0, $iv_size);
        $encrypted_data = substr($encrypted_data_with_iv, $iv_size);
        $restored_data = openssl_decrypt($encrypted_data, $encryption_algorithm, $encryption_key, 0, $iv);

        // Temporäre Datei für die Wiederherstellung erstellen
        $temp_restore_file = 'temp_restore.sql';
        file_put_contents($temp_restore_file, $restored_data);

        // Wiederherstellung durchführen
        $command = "mysql -u $username -p$password $database < $temp_restore_file";
        exec($command);
        echo "<script>alert('Wiederherstellung erfolgreich abgeschlossen.');</script>";

        // Ereignis protokollieren
        logEvent('Wiederherstellung durchgeführt', 'Wiederherstellung', "Wiederhergestellte Datei: $restore_file");

        // Temporäre Datei löschen
        unlink($temp_restore_file);
    } else {
        echo "Datei für die Wiederherstellung nicht hochgeladen.";
    }
}

// Wiederherstellung aus ausgewähltem Backup durchführen
if (isset($_POST['restore_from_selected'])) {
    $selected_backup = $_POST['selected_backup'];

    // Wiederherstellung durchführen
    $command = "mysql -u $username -p$password $database < $selected_backup";
    exec($command);
    echo "<script>alert('Wiederherstellung erfolgreich abgeschlossen.');</script>";

    // Ereignis protokollieren
    logEvent('Wiederherstellung ausgewähltes Backup durchgeführt', 'Wiederherstellung', "Ausgewählte Backup-Datei: $selected_backup");
}

// Liste der letzten 10 Backups generieren
$backup_files = glob('backup/encrypted_backup_*.txt'); // Nur nach verschlüsselten Backups suchen
$backup_files = array_slice($backup_files, -10); // Die letzten 10 Backups auswählen

?>


<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Backup und Wiederherstellung</title>
    <style>
       /* Header CSS */
        body {
            background-color: aliceblue;
        }

        .header {
            background-color: #333;
            color: #fff;
            padding: 20px 0;
        }

        .header-container {
            width: 80%;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            margin: 0;
        }

        .header nav ul {
            list-style-type: none;
            margin: 0;
            padding: 0;
        }

        .header nav ul li {
            display: inline;
            margin-right: 20px;
        }

        .header nav ul li:last-child {
            margin-right: 0;
        }

        .header nav ul li a {
            color: #fff;
            text-decoration: none;
        }

        /* Container CSS */
        .container {
            width: 80%;
            margin: 0 auto;
            padding: 20px;
            background-color: #333;
            color: #fff;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            margin-top: 40px;
        }

        h1, h2 {
            text-align: center;
        }

        form {
            text-align: center;
            margin-top: 20px;
        }

        input[type="submit"] {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        input[type="submit"]:hover {
            background-color: #45a049;
        }

        input[type="file"] {
            display: block;
            margin: 10px auto;
        }

        .download-button {
            display: block;
            margin-top: 20px;
            text-align: center;
            text-decoration: none;
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
        }

        .download-button:hover {
            background-color: #45a049;
        }

        /* Backup List Styles */
        .backup-list {
            list-style: none;
            padding: 0;
            margin: 20px 0;
        }

        .backup-list li {
            background-color: #fff;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .backup-list li a {
            color: #333;
            text-decoration: none;
            font-weight: bold;
        }

        .backup-list li form {
            display: inline;
        }

        .backup-list li input[type="submit"] {
            background-color: #45a049;
            color: #fff;
            padding: 5px 10px;
            margin-left: 10px;
            transition: background-color 0.3s;
        }

        .backup-list li input[type="submit"]:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>
    <header class="header">
        <div class="header-container">
            <h1>Materialverwaltung</h1>
            <nav>
                <ul>
                    <li><a href="index.php">Home</a></li>
                    <li><a href="add_material_form.php">Artikel hinzufügen</a></li>
                    <li><a href="article_overview.php">Artikel Übersicht</a></li>
					<li><a href="Material_chrome.zip">chrome Erweiterung</a></li>
                    <li><a href="backup_restore.php">Backup</a></li>
                </ul>
            </nav>
        </div>
    </header>

    <div class="container">
        <h1>Backup und Wiederherstellung</h1>

        <h2>Backup erstellen</h2>
        <form action="" method="post">
            <input type="submit" name="backup" value="Backup erstellen">
        </form>

        <?php if (isset($download_button)) echo $download_button; ?> 

        <h2>Wiederherstellung durchführen</h2>
        <form action="" method="post" enctype="multipart/form-data">
            <input type="file" name="restore_file" accept=".txt">
            <input type="submit" name="restore" value="Wiederherstellung durchführen">
        </form>

        <!-- Backup-Liste -->
    <h2>Letzte 10 verschlüsselte Backups</h2>
    <ul class="backup-list">
        <?php foreach ($backup_files as $file): ?>
            <li>
                <a href="<?php echo $file; ?>"><?php echo basename($file); ?></a>
                <form action="" method="post">
                    <input type="hidden" name="selected_backup" value="<?php echo $file; ?>">
                    <input type="submit" name="restore_from_selected" value="Wiederherstellen">
                </form>
            </li>
        <?php endforeach; ?>
    </ul>

    </div>
</body>
</html>