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

// Check admin login
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    header("Location: login.php");
    exit();
}

$pageTitle = "Admins verwalten";
$message = "";
$messageType = "";

function isValidAdminPasswordInput($password)
{
    return is_string($password) && strlen($password) >= 8;
}

$adminAccounts = getAdminAccounts();

function isValidAdminEmailInput($email)
{
    return isValidAdminEmail($email);
}

if ($_SERVER['REQUEST_METHOD'] === "POST") {
    // Validate CSRF token
    if (!validateCsrfToken($_POST['csrf_token'] ?? "")) {
        $message = "Ungültiges Token. Bitte versuchen Sie es erneut.";
        $messageType = "error";
    } else {
        if (isset($_POST['add_admin'])) {
            $username = normalizeAdminUsername($_POST['username'] ?? "");
            $description = normalizeAdminDescription(
                $_POST['description'] ?? "",
            );
            $email = normalizeAdminEmail($_POST['email'] ?? "");
            $password = $_POST['password'] ?? "";
            $passwordConfirm = $_POST['password_confirm'] ?? "";

            if (!isValidAdminUsername($username)) {
                $message =
                    "Ungültiger Benutzername. Erlaubt: 3-50 Zeichen (Buchstaben, Zahlen, Punkt, Unterstrich, Bindestrich).";
                $messageType = "error";
            } elseif (isset($adminAccounts[$username])) {
                $message = "Dieser Benutzername existiert bereits.";
                $messageType = "error";
            } elseif (!isValidAdminDescription($description)) {
                $message = "Beschreibung ist erforderlich (max. 120 Zeichen).";
                $messageType = "error";
            } elseif (!isValidAdminEmailInput($email)) {
                $message = "Gültige E-Mail ist erforderlich.";
                $messageType = "error";
            } elseif (!isValidAdminPasswordInput($password)) {
                $message = "Passwort muss mindestens 8 Zeichen lang sein.";
                $messageType = "error";
            } elseif ($password !== $passwordConfirm) {
                $message = "Passwort und Bestätigung stimmen nicht überein.";
                $messageType = "error";
            } else {
                $adminAccounts[$username] = [
                    "password_hash" => password_hash(
                        $password,
                        PASSWORD_BCRYPT,
                    ),
                    "description" => $description,
                    "email" => $email,
                ];
                if (saveAdminAccounts($adminAccounts)) {
                    logAccess("Admin added admin account", [
                        "username" => $username,
                        "description" => $description,
                    ]);
                    $message = "Admin wurde erfolgreich angelegt.";
                    $messageType = "success";
                } else {
                    $message = "Admin konnte nicht gespeichert werden.";
                    $messageType = "error";
                }
            }
        }

        if (isset($_POST['update_description'])) {
            $targetUsername = normalizeAdminUsername(
                $_POST['target_username'] ?? "",
            );
            $description = normalizeAdminDescription(
                $_POST['description'] ?? "",
            );
            $email = normalizeAdminEmail($_POST['email'] ?? "");

            if (!isset($adminAccounts[$targetUsername])) {
                $message = "Admin nicht gefunden.";
                $messageType = "error";
            } elseif (!isValidAdminDescription($description)) {
                $message = "Beschreibung ist erforderlich (max. 120 Zeichen).";
                $messageType = "error";
            } elseif (!isValidAdminEmailInput($email)) {
                $message = "Gültige E-Mail ist erforderlich.";
                $messageType = "error";
            } else {
                $adminAccounts[$targetUsername]["description"] = $description;
                $adminAccounts[$targetUsername]["email"] = $email;
                if (saveAdminAccounts($adminAccounts)) {
                    logAccess("Admin updated admin description", [
                        "username" => $targetUsername,
                    ]);
                    $message = "Beschreibung und E-Mail wurden aktualisiert.";
                    $messageType = "success";
                } else {
                    $message = "Änderungen konnten nicht gespeichert werden.";
                    $messageType = "error";
                }
            }
        }

        if (isset($_POST['change_password'])) {
            $targetUsername = normalizeAdminUsername(
                $_POST['target_username'] ?? "",
            );
            $newPassword = $_POST['new_password'] ?? "";
            $newPasswordConfirm = $_POST['new_password_confirm'] ?? "";

            if (!isset($adminAccounts[$targetUsername])) {
                $message = "Admin nicht gefunden.";
                $messageType = "error";
            } elseif (!isValidAdminPasswordInput($newPassword)) {
                $message = "Passwort muss mindestens 8 Zeichen lang sein.";
                $messageType = "error";
            } elseif ($newPassword !== $newPasswordConfirm) {
                $message = "Passwort und Bestätigung stimmen nicht überein.";
                $messageType = "error";
            } else {
                $adminAccounts[$targetUsername][
                    "password_hash"
                ] = password_hash($newPassword, PASSWORD_BCRYPT);
                if (saveAdminAccounts($adminAccounts)) {
                    logAccess("Admin changed admin password", [
                        "username" => $targetUsername,
                    ]);
                    $message = "Passwort wurde aktualisiert.";
                    $messageType = "success";
                } else {
                    $message = "Passwort konnte nicht gespeichert werden.";
                    $messageType = "error";
                }
            }
        }

        if (isset($_POST['delete_admin'])) {
            $targetUsername = normalizeAdminUsername(
                $_POST['target_username'] ?? "",
            );

            if (!isset($adminAccounts[$targetUsername])) {
                $message = "Admin nicht gefunden.";
                $messageType = "error";
            } elseif (
                $targetUsername ===
                normalizeAdminUsername($_SESSION['admin_username'] ?? "")
            ) {
                $message = "Sie können Ihr eigenes Admin-Konto nicht löschen.";
                $messageType = "error";
            } else {
                unset($adminAccounts[$targetUsername]);
                if (!saveAdminAccounts($adminAccounts)) {
                    $message = "Admin konnte nicht gelöscht werden.";
                    $messageType = "error";
                    $adminAccounts = getAdminAccounts();
                } else {
                    logAccess("Admin deleted admin account", [
                        "username" => $targetUsername,
                    ]);

                    $message = "Admin wurde gelöscht.";
                    $messageType = "success";
                }
            }
        }

        $adminAccounts = getAdminAccounts();
    }
}

$currentAdmin = isset($_SESSION['admin_username'])
    ? normalizeAdminUsername($_SESSION['admin_username'])
    : "";
$changeUsername = normalizeAdminUsername($_GET['change'] ?? "");
$selectedChangeUser = null;
$editDescriptionUsername = normalizeAdminUsername(
    $_GET['edit_description'] ?? "",
);
$selectedDescriptionUser = null;

if ($changeUsername !== "") {
    if (!isset($adminAccounts[$changeUsername])) {
        if ($message === "") {
            $message = "Ausgewählter Admin wurde nicht gefunden.";
            $messageType = "error";
        }
    } else {
        $selectedChangeUser = $changeUsername;
    }
}

if ($editDescriptionUsername !== "") {
    if (!isset($adminAccounts[$editDescriptionUsername])) {
        if ($message === "") {
            $message = "Ausgewählter Admin wurde nicht gefunden.";
            $messageType = "error";
        }
    } else {
        $selectedDescriptionUser = $editDescriptionUsername;
    }
}

ksort($adminAccounts);

$bodyClass = "admin-page";
include __DIR__ . "/../includes/header.php";
?>

<div class="admin-header">
    <h2>Admins verwalten</h2>
    <div>
        <a href="index.php" class="btn btn-secondary">Zurück zum Dashboard</a>
    </div>
</div>

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

<div class="panel">
    <p><strong>Eingeloggt als:</strong> <?php echo htmlspecialchars(
        $currentAdmin !== "" ? $currentAdmin : "Unbekannt",
    ); ?></p>
</div>

<div class="panel">
    <h3>Neuen Admin anlegen</h3>
    <form method="POST">
        <?php echo csrfField(); ?>
        <div class="form-group">
            <label for="username">Benutzername *</label>
            <input type="text" id="username" name="username" required maxlength="50" pattern="[A-Za-z0-9][A-Za-z0-9._-]{2,49}" placeholder="z.B. max.mustermann">
        </div>
        <div class="form-group">
                <label for="description">Beschreibung *</label>
                <input type="text" id="description" name="description" required maxlength="120" placeholder="z.B. Kassierer, Shop-Team">
            </div>
            <div class="form-group">
                <label for="email">E-Mail *</label>
                <input type="email" id="email" name="email" required maxlength="190" placeholder="z.B. max.mustermann@example.org">
            </div>
            <div class="form-group">
                <label for="password">Passwort (mind. 8 Zeichen) *</label>
                <input type="password" id="password" name="password" required minlength="8">
        </div>
        <div class="form-group">
            <label for="password_confirm">Passwort bestätigen *</label>
            <input type="password" id="password_confirm" name="password_confirm" required minlength="8">
        </div>
        <button type="submit" name="add_admin" class="btn">Admin anlegen</button>
    </form>
</div>

<div class="panel">
    <h3>Admin-Liste</h3>
    <div class="table-responsive">
        <table class="responsive-table">
            <thead>
                <tr>
                    <th>Benutzername</th>
                    <th>Beschreibung</th>
                    <th>E-Mail</th>
                    <th>Aktionen</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($adminAccounts as $username => $account): ?>
                <tr>
                    <td data-label="Benutzername">
                        <strong><?php echo htmlspecialchars(
                            $username,
                        ); ?></strong>
                        <?php if ($username === $currentAdmin): ?>
                            <span class="status status-open status-self">Du</span>
                        <?php endif; ?>
                    </td>
                    <td data-label="Beschreibung">
                        <?php echo htmlspecialchars($account["description"]); ?>
                    </td>
                    <td data-label="E-Mail">
                        <?php echo htmlspecialchars($account["email"]); ?>
                    </td>
                    <td data-label="Aktionen">
                        <a href="admins.php?edit_description=<?php echo urlencode(
                            $username,
                        ); ?>" class="btn btn-small btn-secondary">Profil ändern</a>
                        <a href="admins.php?change=<?php echo urlencode(
                            $username,
                        ); ?>" class="btn btn-small btn-secondary">Passwort ändern</a>
                        <?php if ($username !== $currentAdmin): ?>
                        <form method="POST" class="inline-form" onsubmit="return confirm('Admin wirklich löschen?');">
                            <?php echo csrfField(); ?>
                            <input type="hidden" name="target_username" value="<?php echo htmlspecialchars(
                                $username,
                            ); ?>">
                            <button type="submit" name="delete_admin" class="btn btn-small">Löschen</button>
                        </form>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php if ($selectedDescriptionUser !== null): ?>
    <div class="panel">
        <h3>Profil ändern: <?php echo htmlspecialchars(
            $selectedDescriptionUser,
        ); ?></h3>
        <form method="POST">
            <?php echo csrfField(); ?>
            <input type="hidden" name="target_username" value="<?php echo htmlspecialchars(
                $selectedDescriptionUser,
            ); ?>">
            <div class="form-group">
                <label for="description_edit">Beschreibung *</label>
                <input type="text" id="description_edit" name="description" maxlength="120" required value="<?php echo htmlspecialchars(
                    $adminAccounts[$selectedDescriptionUser]["description"],
                ); ?>">
            </div>
            <div class="form-group">
                <label for="email_edit">E-Mail *</label>
                <input type="email" id="email_edit" name="email" maxlength="190" required value="<?php echo htmlspecialchars(
                    $adminAccounts[$selectedDescriptionUser]["email"],
                ); ?>">
            </div>
            <button type="submit" name="update_description" class="btn">Profil speichern</button>
            <a href="admins.php" class="btn btn-secondary">Abbrechen</a>
        </form>
    </div>
<?php endif; ?>

<?php if ($selectedChangeUser !== null): ?>
    <div class="panel">
        <h3>Passwort ändern: <?php echo htmlspecialchars(
            $selectedChangeUser,
        ); ?></h3>
        <form method="POST">
            <?php echo csrfField(); ?>
            <input type="hidden" name="target_username" value="<?php echo htmlspecialchars(
                $selectedChangeUser,
            ); ?>">
            <div class="form-group">
                <label for="new_password">Neues Passwort (mind. 8 Zeichen) *</label>
                <input type="password" id="new_password" name="new_password" required minlength="8">
            </div>
            <div class="form-group">
                <label for="new_password_confirm">Neues Passwort bestätigen *</label>
                <input type="password" id="new_password_confirm" name="new_password_confirm" required minlength="8">
            </div>
            <button type="submit" name="change_password" class="btn">Passwort speichern</button>
            <a href="admins.php" class="btn btn-secondary">Abbrechen</a>
        </form>
    </div>
<?php endif; ?>

<?php include __DIR__ . "/../includes/footer.php"; ?>
