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

if (empty($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit();
}

$pageTitle = "Einstellungen";
$message = "";
$messageType = "";

if ($_SERVER['REQUEST_METHOD'] === "POST" && isset($_POST['save_settings'])) {
    // Validate CSRF token
    if (!validateCsrfToken($_POST['csrf_token'] ?? "")) {
        $message = "Ungültiges Token. Bitte versuchen Sie es erneut.";
        $messageType = "error";
    } else {
        $settings = array_merge(getSystemSettings(), [
            "order_recipient_email" => $_POST['order_recipient_email'] ?? "",
            "attach_order_pdf_to_admin_email" => isset(
                $_POST['attach_order_pdf_to_admin_email'],
            ),
        ]);

        if (saveSystemSettings($settings)) {
            logAccess("Admin updated system settings");
            $message = "Einstellungen wurden gespeichert.";
            $messageType = "success";
        } else {
            $message = "Einstellungen konnten nicht gespeichert werden.";
            $messageType = "error";
        }
    }
}

$settings = getSystemSettings();

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

<div class="admin-header">
    <h2>Einstellungen</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 escape($messageType); ?>">
        <?php echo escape($message); ?>
    </div>
<?php endif; ?>

<div class="panel panel-lg">
    <form method="POST">
        <?php echo csrfField(); ?>
        <div class="form-group">
            <label for="order_recipient_email">Empfängeradresse für interne Bestellungen *</label>
            <input type="email" id="order_recipient_email" name="order_recipient_email" required value="<?php echo escape(
                $settings["order_recipient_email"],
            ); ?>">
        </div>

        <div class="form-group">
            <label class="checkbox-label">
                <input type="checkbox" name="attach_order_pdf_to_admin_email" value="1" <?php echo !empty(
                    $settings["attach_order_pdf_to_admin_email"]
                )
                    ? "checked"
                    : ""; ?>>
                PDF an interne Bestell-E-Mails anhängen
            </label>
        </div>

        <button type="submit" name="save_settings" class="btn">Speichern</button>
    </form>
</div>

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