<?php
session_start();

// Konfiguration
define('DOMAINS_FILE', 'localdomains.conf');
define('USERNAME', 'admin');
define('PASSWORD', 'password123'); // In Produktion sollte dies gehasht werden!

// Hilfsfunktionen
function isLoggedIn() {
    return isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true;
}

function validateDomain($domain) {
    // Domain-Validierung
    $domain = trim($domain);
    if (empty($domain)) {
        return false;
    }
    
    // Basis-Validierung für Domain-Format
    return filter_var($domain, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) !== false;
}

function loadDomains() {
    if (!file_exists(DOMAINS_FILE)) {
        return [];
    }
    
    $domains = file(DOMAINS_FILE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    return array_filter(array_map('trim', $domains));
}

function saveDomains($domains) {

    // Alphabetische Sortierung vor dem Speichern
    sort($domains, SORT_STRING | SORT_FLAG_CASE); 
    exec ('touch disposable_email_blocklist.conf -d "-2 hours" disposable_email_blocklist.conf 2>&1',$output, $retval); 

    return file_put_contents(DOMAINS_FILE, implode("\n", $domains) . "\n");
}

function addDomain($domain) {
    if (!validateDomain($domain)) {
        return false;
    }
    
    $domains = loadDomains();
    if (in_array($domain, $domains)) {
        return false; // Domain bereits vorhanden
    }
    
    $domains[] = $domain;
    return saveDomains($domains);
}

function deleteDomain($domain) {
    $domains = loadDomains();
    $domains = array_filter($domains, function($d) use ($domain) {
        return $d !== $domain;
    });
    return saveDomains($domains);
}

function updateDomain($oldDomain, $newDomain) {
    if (!validateDomain($newDomain)) {
        return false;
    }
    
    $domains = loadDomains();
    $key = array_search($oldDomain, $domains);
    if ($key !== false) {
        $domains[$key] = $newDomain;
        return saveDomains($domains);
    }
    return false;
}

// Request-Verarbeitung
$message = '';
$error = '';

// Login-Verarbeitung
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'login':
            if ($_POST['username'] === USERNAME && $_POST['password'] === PASSWORD) {
                $_SESSION['logged_in'] = true;
                $message = 'Erfolgreich angemeldet!';
            } else {
                $error = 'Ungültige Anmeldedaten!';
            }
            break;
            
        case 'logout':
            session_destroy();
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit;
            break;
            
        case 'add':
            if (isLoggedIn()) {
                $domain = trim($_POST['domain']);
                if (addDomain($domain)) {
                    $message = "Domain '$domain' wurde erfolgreich hinzugefügt!";
                } else {
                    $error = "Fehler beim Hinzufügen der Domain '$domain'. Möglicherweise ungültig oder bereits vorhanden.";
                }
            }
            break;
            
        case 'delete':
            if (isLoggedIn() && isset($_POST['domain'])) {
                $domain = $_POST['domain'];
                if (deleteDomain($domain)) {
                    $message = "Domain '$domain' wurde erfolgreich gelöscht!";
                } else {
                    $error = "Fehler beim Löschen der Domain '$domain'.";
                }
            }
            break;
            
        case 'update':
            if (isLoggedIn() && isset($_POST['old_domain']) && isset($_POST['new_domain'])) {
                $oldDomain = $_POST['old_domain'];
                $newDomain = trim($_POST['new_domain']);
                if (updateDomain($oldDomain, $newDomain)) {
                    $message = "Domain wurde erfolgreich von '$oldDomain' zu '$newDomain' geändert!";
                } else {
                    $error = "Fehler beim Aktualisieren der Domain. Neue Domain möglicherweise ungültig.";
                }
            }
            break;
    }
}

$domains = isLoggedIn() ? loadDomains() : [];
?>

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lokale Blocklist</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        input[type="text"], input[type="password"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            box-sizing: border-box;
        }
        
        button {
            background: #007cba;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin-right: 10px;
        }
        
        button:hover {
            background: #005a87;
        }
        
        button.danger {
            background: #dc3545;
        }
        
        button.danger:hover {
            background: #c82333;
        }
        
        .message {
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
        }
        
        .success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .domain-list {
            margin-top: 30px;
        }
        
        .domain-item {
            background: #f8f9fa;
            padding: 15px;
            margin: 10px 0;
            border-radius: 5px;
            border: 1px solid #dee2e6;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .domain-name {
            font-family: monospace;
            font-size: 16px;
        }
        
        .actions {
            display: flex;
            gap: 10px;
        }
        
        .edit-form {
            display: none;
        }
        
        .stats {
            background: #e9ecef;
            padding: 10px;
            border-radius: 5px;
            margin: 20px 0;
        }
        
        .logout-btn {
            float: right;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Lokale Blocklist bearbeiten</h1>
        
        <?php if ($message): ?>
            <div class="message success"><?= htmlspecialchars($message) ?></div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="message error"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        
        <?php if (!isLoggedIn()): ?>
            <!-- Login-Formular -->
            <form method="POST">
                <input type="hidden" name="action" value="login">
                <div class="form-group">
                    <label for="username">Benutzername:</label>
                    <input type="text" id="username" name="username" required>
                </div>
                <div class="form-group">
                    <label for="password">Passwort:</label>
                    <input type="password" id="password" name="password" required>
                </div>
                <button type="submit">Anmelden</button>
            </form>
            
            <div class="message" style="margin-top: 20px; background: #cce5ff;">
                <strong>Demo-Zugangsdaten:</strong><br>
                Benutzername: admin<br>
                Passwort: password123
            </div>
            
        <?php else: ?>
            <!-- Logout-Button -->
            <form method="POST" style="display: inline;">
                <input type="hidden" name="action" value="logout">
                <button type="submit" class="logout-btn">Abmelden</button>
            </form>
            
            <div style="clear: both;"></div>
            
            <!-- Statistiken -->
            <div class="stats">
                <strong>Statistiken:</strong> <?= count($domains) ?> Domains verwaltet
            </div>
            
            <!-- Domain hinzufügen -->
            <h2>Neue Domain hinzufügen</h2>
            <form method="POST">
                <input type="hidden" name="action" value="add">
                <div class="form-group">
                    <label for="domain">Domain:</label>
                    <input type="text" id="domain" name="domain" placeholder="z.B. example.com" required>
                </div>
                <button type="submit">Domain hinzufügen</button>
            </form>
            
            <!-- Domain-Liste -->
            <div class="domain-list">
                <h2>Verwaltete Domains (<?= count($domains) ?>)</h2>
                
                <?php if (empty($domains)): ?>
                    <p>Keine Domains vorhanden. Fügen Sie eine Domain hinzu, um zu beginnen.</p>
                <?php else: ?>
                    <?php foreach ($domains as $domain): ?>
                        <div class="domain-item">
                            <span class="domain-name"><?= htmlspecialchars($domain) ?></span>
                            <div class="actions">
                                <button onclick="showEditForm('<?= htmlspecialchars($domain) ?>')">Bearbeiten</button>
                                <form method="POST" style="display: inline;" onsubmit="return confirm('Domain \'<?= htmlspecialchars($domain) ?>\' wirklich löschen?')">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="domain" value="<?= htmlspecialchars($domain) ?>">
                                    <button type="submit" class="danger">Löschen</button>
                                </form>
                            </div>
                        </div>
                        
                        <!-- Bearbeitungsformular (versteckt) -->
                        <div id="edit-<?= htmlspecialchars($domain) ?>" class="edit-form">
                            <form method="POST" style="margin-top: 10px;">
                                <input type="hidden" name="action" value="update">
                                <input type="hidden" name="old_domain" value="<?= htmlspecialchars($domain) ?>">
                                <div class="form-group">
                                    <label>Domain bearbeiten:</label>
                                    <input type="text" name="new_domain" value="<?= htmlspecialchars($domain) ?>" required>
                                </div>
                                <button type="submit">Speichern</button>
                                <button type="button" onclick="hideEditForm('<?= htmlspecialchars($domain) ?>')">Abbrechen</button>
                            </form>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
    
    <script>
        function showEditForm(domain) {
            document.getElementById('edit-' + domain).style.display = 'block';
        }
        
        function hideEditForm(domain) {
            document.getElementById('edit-' + domain).style.display = 'none';
        }
    </script>
</body>
</html>
