<?php
require_once __DIR__ . "/../config.php";
require_once __DIR__ . "/../includes/functions.php";

$error = "";

// Handle logout via POST + CSRF
if ($_SERVER['REQUEST_METHOD'] === "POST" && isset($_POST['logout'])) {
    if (!validateCsrfToken($_POST['csrf_token'] ?? "")) {
        $error = "Ungültiges Token. Bitte versuchen Sie es erneut.";
    } else {
        $_SESSION = [];
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(
                session_name(),
                "",
                time() - 42000,
                $params["path"],
                $params["domain"],
                $params["secure"],
                $params["httponly"],
            );
        }
        session_destroy();
        header("Location: login.php");
        exit();
    }
}

if ($_SERVER['REQUEST_METHOD'] === "POST") {
    // Validate CSRF token
    if (!validateCsrfToken($_POST['csrf_token'] ?? "")) {
        $error = "Ungültiges Token. Bitte versuchen Sie es erneut.";
    } else {
        if (isAdminLoginRateLimited()) {
            $error =
                "Zu viele fehlgeschlagene Anmeldeversuche. Bitte versuchen Sie es später erneut.";
        } else {
            $username = normalizeAdminUsername($_POST["username"] ?? "");
            $password = $_POST["password"] ?? "";

            $users = getAdminUsers();
            if (
                isset($users[$username]) &&
                password_verify($password, $users[$username])
            ) {
                clearAdminLoginRateLimitForCurrentIp();
                session_regenerate_id(true);
                $_SESSION["admin_logged_in"] = true;
                $_SESSION["admin_username"] = $username;
                logAccess("Admin login successful", ["username" => $username]);
                header("Location: index.php");
                exit();
            } else {
                recordAdminLoginFailure();
                logAccess("Admin login failed", ["username" => $username]);
                $error = "Benutzername oder Passwort falsch.";
            }
        }
    }
}

// Redirect if already logged in
if (isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in']) {
    header("Location: index.php");
    exit();
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Administration - <?php echo escape(SITE_FULL_NAME); ?></title>
    <link rel="stylesheet" href="<?php echo escape(
        SITE_URL,
    ); ?>/assets/css/style.css">
</head>
<body class="admin-page">
    <header class="site-header">
        <div class="container header-inner">
            <a class="brand" href="<?php echo escape(SITE_URL); ?>/index.php">
                <img class="brand-logo" src="<?php echo escape(
                    SITE_URL,
                ); ?>/assets/branding/stadt-freising-logo.png" alt="Wappen der Stadt Freising">
                <div class="brand-text">
                    <span class="brand-title"><?php echo escape(
                        SITE_NAME,
                    ); ?></span>
                    <span class="brand-subtitle"><?php echo escape(
                        SITE_SERVICE_HEADER,
                    ); ?></span>
                </div>
            </a>
            <a href="<?php echo escape(
                SITE_URL,
            ); ?>/index.php" class="btn btn-secondary">Zurück zu <?php echo escape(
    SITE_SERVICE_NAME,
); ?></a>
        </div>
    </header>
    <main>
        <div class="container container-narrow page-top-gap">
            <h2>Administration</h2>

            <?php if ($error): ?>
                <div class="alert alert-error">
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>

            <form method="POST" class="panel panel-lg">
                <?php echo csrfField(); ?>
                <div class="form-group">
                    <label for="username">Benutzername:</label>
                    <input type="text" id="username" name="username" required autofocus>
                </div>
                <div class="form-group">
                    <label for="password">Passwort:</label>
                    <input type="password" id="password" name="password" required>
                </div>
                <button type="submit" class="btn btn-block">Anmelden</button>
            </form>

            <div class="text-center mt-2">
                <a href="<?php echo escape(
                    SITE_URL,
                ); ?>/index.php">Zurück zu <?php echo escape(
    SITE_SERVICE_NAME,
); ?></a>
            </div>
        </div>
    </main>
</body>
</html>
