<?php
declare(strict_types=1);

$config = require __DIR__ . '/config.php';
require_once __DIR__ . '/lib.php';

use function PasswortTool\auth_test;
use function PasswortTool\change_password;
use function PasswortTool\csrf_token;
use function PasswortTool\csrf_valid;
use function PasswortTool\enforce_https;
use function PasswortTool\hash_password;
use function PasswortTool\h;
use function PasswortTool\log_line;
use function PasswortTool\policy_violations;
use function PasswortTool\restore_backup;
use function PasswortTool\send_notification;
use function PasswortTool\send_security_headers;
use function PasswortTool\start_secure_session;
use function PasswortTool\user_exists;
use function PasswortTool\valid_mail_user;
use function PasswortTool\with_lock;

enforce_https($config);
send_security_headers();
start_secure_session();

$errors = [];
$success = false;
$email = '';

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $email = trim((string)($_POST['email'] ?? ''));
    // Passwörter existieren nur in diesen lokalen Variablen — nie in Session, Log oder HTML.
    $current = (string)($_POST['alt'] ?? '');
    $new     = (string)($_POST['neu'] ?? '');
    $confirm = (string)($_POST['neu2'] ?? '');

    if (!csrf_valid($_POST['csrf'] ?? null)) {
        http_response_code(400);
        $errors[] = 'Ungültiges Formular-Token. Bitte die Seite neu laden und erneut absenden.';
    } elseif ($email === '' || $current === '' || $new === '' || $confirm === '') {
        // Kein doveadm-Aufruf bei leeren Feldern
        $errors[] = 'Bitte alle Felder ausfüllen.';
    } elseif (!valid_mail_user($email, $config)) {
        // wird von fail2ban mitgezählt
        log_line($config, 'FAIL', $email, 'invalid-email');
        $errors[] = 'Aktuelles Passwort ist falsch.';
    } else {
        // Policy zuerst: bei Verstoß kein doveadm-Aufruf, kein Schreibzugriff
        $errors = policy_violations($new, $confirm, $config);
        if ($new === $current) {
            $errors[] = 'Das neue Passwort darf nicht dem aktuellen Passwort entsprechen.';
        }
        if ($errors === []) {
            $exists = user_exists($config['passwd_file'], $email);
            $auth = $exists ? auth_test($config, $email, $current) : ['ok' => false, 'reachable' => true];
            if (!$exists || !$auth['ok']) {
                if ($exists && !$auth['reachable']) {
                    log_line($config, 'ERROR', $email, 'doveadm-not-reachable');
                    $errors[] = 'Der Authentifizierungsdienst ist derzeit nicht erreichbar. Es wurde nichts geändert.';
                } else {
                    // Identische Meldung für unbekannten Benutzer und falsches Passwort (keine User-Enumeration).
                    // Jeder Fehlversuch landet mit ip= in der Logdatei -> fail2ban bannt nach maxretry.
                    log_line($config, 'FAIL', $email, $exists ? 'wrong-password' : 'unknown-user');
                    $errors[] = 'Aktuelles Passwort ist falsch.';
                }
            } else {
                $hash = hash_password($config, $new);
                if ($hash === null) {
                    log_line($config, 'ERROR', $email, 'hash-generation-failed');
                    $errors[] = 'Das neue Passwort konnte nicht verarbeitet werden. Es wurde nichts geändert.';
                } else {
                    // Schreiben + Verifikation + ggf. Rollback unter einem Lock
                    try {
                        $res = with_lock($config, static function () use ($config, $email, $hash, $new): array {
                            $backup = change_password($config, $email, $hash);
                            $verify = auth_test($config, $email, $new);
                            if (!$verify['ok']) {
                                restore_backup($config, $backup);
                                return ['ok' => false, 'reachable' => $verify['reachable']];
                            }
                            return ['ok' => true, 'reachable' => true];
                        });
                    } catch (RuntimeException $e) {
                        log_line($config, 'ERROR', $email, 'write-failed: ' . $e->getMessage());
                        $res = ['ok' => false, 'reachable' => true, 'write_error' => $e->getMessage()];
                    }
                    if (!$res['ok']) {
                        if (isset($res['write_error'])) {
                            $errors[] = 'Das Passwort konnte nicht gespeichert werden (' . $res['write_error'] . '). Bitte Administrator kontaktieren.';
                        } elseif (!$res['reachable']) {
                            log_line($config, 'ERROR', $email, 'doveadm-not-reachable-after-write');
                            $errors[] = 'Verifikation nach dem Wechsel nicht möglich. Bitte Administrator kontaktieren.';
                        } else {
                            log_line($config, 'ROLLBACK', $email, 'verify-failed');
                            $errors[] = 'Die Verifikation nach dem Wechsel ist fehlgeschlagen. Die Änderung wurde rückgängig gemacht.';
                        }
                    } else {
                        log_line($config, 'SUCCESS', $email, 'password-changed');
                        send_notification($config, $email);
                        // Session-Fixierung vermeiden: ID und CSRF-Token nach Erfolg erneuern
                        session_regenerate_id(true);
                        $_SESSION['csrf'] = bin2hex(random_bytes(32));
                        $success = true;
                        $email = '';
                    }
                }
            }
        }
    }
}

$token = csrf_token();
$min = (int)$config['min_password_length'];
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mail-Passwort ändern</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main class="card">
<h1>Mail-Passwort ändern</h1>
<?php if ($success): ?>
<p class="ok">Dein Passwort wurde erfolgreich geändert. Eine Bestätigung geht an deine E-Mail-Adresse.</p>
<p><a href="">Zurück zum Formular</a></p>
<?php else: ?>
<?php if ($errors !== []): ?>
<ul class="errors">
<?php foreach ($errors as $e): ?><li><?= h($e) ?></li><?php endforeach; ?>
</ul>
<?php endif; ?>
<form method="post" action="">
<input type="hidden" name="csrf" value="<?= h($token) ?>">
<label>E-Mail-Adresse
  <input type="email" name="email" required autocomplete="username" value="<?= h($email) ?>">
</label>
<label>Aktuelles Passwort
  <input type="password" name="alt" required autocomplete="current-password">
</label>
<label>Neues Passwort
  <input type="password" name="neu" required autocomplete="new-password">
</label>
<label>Neues Passwort (Wiederholung)
  <input type="password" name="neu2" required autocomplete="new-password">
</label>
<p class="hint">Anforderungen an das neue Passwort: mindestens <?= $min ?> Zeichen, mindestens ein Buchstabe, mindestens eine Ziffer und mindestens ein Sonderzeichen. Es muss sich vom aktuellen Passwort unterscheiden.</p>
<button type="submit">Passwort ändern</button>
</form>
<?php endif; ?>
</main>
</body>
</html>
