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

$pageTitle = "Bestellung abschließen";
$cartItems = getCartItemsDetailed();
$organizations = getOrganizations(true);
$errors = [];

if (empty($cartItems)) {
    header("Location: cart.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === "POST" && isset($_POST['create_order'])) {
    // Validate CSRF token
    if (!validateCsrfToken($_POST['csrf_token'] ?? "")) {
        $errors[] = "Ungültiges Token. Bitte versuchen Sie es erneut.";
    } else {
        $validator = new Validator($_POST);

        $validator
            ->required("customer_name", "Name")
            ->minLength("customer_name", 2, "Name")
            ->maxLength("customer_name", 100, "Name")
            ->required("customer_email", "E-Mail-Adresse")
            ->email("customer_email", "E-Mail-Adresse")
            ->maxLength("customer_email", 255, "E-Mail-Adresse")
            ->required("organization_id", "Organisation")
            ->maxLength("comment", 1000, "Kommentar");

        // Validate organization exists
        $organizationId = $_POST['organization_id'] ?? "";
        $organizations = getOrganizations(true);
        $validOrgIds = array_column($organizations, "id");

        if (!in_array($organizationId, $validOrgIds, true)) {
            $validator->addError("Die gewählte Organisation ist ungültig.");
        }

        if (!$validator->isValid()) {
            $errors = array_merge($errors, $validator->getErrors());
        } elseif (!checkoutRateLimitWouldAllow()) {
            $errors[] =
                "Zu viele Bestellversuche von dieser Verbindung. Bitte versuchen Sie es später erneut.";
        } else {
            $customerName = trim($_POST['customer_name']);
            $customerEmail = trim(strtolower($_POST['customer_email']));
            $comment = trim($_POST['comment'] ?? "");

            $result = createOrder(
                $customerName,
                $customerEmail,
                $organizationId,
                $comment,
                buildOrderItemsFromCart(),
            );

            if (!$result["success"]) {
                $errors[] = $result["message"];
            } else {
                checkoutRateLimitTryConsume();
                clearCart();
                logAccess("Order created", [
                    "order_id" => $result["order"]["id"],
                    "customer" => $customerEmail,
                ]);
                header(
                    "Location: order-success.php?id=" .
                        urlencode($result["order"]["id"]),
                );
                exit();
            }
        }
    }
}

include __DIR__ . "/includes/header.php";
?>

<h2>Bestellung abschließen</h2>

<?php if (!empty($errors)): ?>
    <div class="alert alert-error">
        <ul class="list-indent">
            <?php foreach ($errors as $error): ?>
                <li><?php echo escape($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="checkout-grid">
    <div>
        <h3>Ihre Auswahl</h3>

        <?php foreach ($cartItems as $cartItem): ?>
            <div class="panel panel-compact">
                <strong><?php echo escape(
                    $cartItem["product"]["name"],
                ); ?></strong><br>
                <?php if ($cartItem["size"] !== ""): ?>
                    Größe: <?php echo escape($cartItem["size"]); ?><br>
                <?php endif; ?>
                <?php if ($cartItem["availability_label"] !== ""): ?>
                    Lieferhinweis: <?php echo escape(
                        $cartItem["availability_label"],
                    ); ?>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>

    <div>
        <h3>Bestelldaten</h3>
        <form method="POST">
            <div class="form-group">
                <label for="customer_name">Name *</label>
                <input type="text" id="customer_name" name="customer_name" required value="<?php echo isset(
                    $_POST['customer_name'],
                )
                    ? escape($_POST['customer_name'])
                    : ""; ?>">
            </div>

            <div class="form-group">
                <label for="customer_email">E-Mail-Adresse *</label>
                <input type="email" id="customer_email" name="customer_email" required value="<?php echo isset(
                    $_POST['customer_email'],
                )
                    ? escape($_POST['customer_email'])
                    : ""; ?>">
            </div>

            <div class="form-group">
                <label for="organization_id">Organisation *</label>
                <select id="organization_id" name="organization_id" required>
                    <option value="">Bitte wählen</option>
                    <?php foreach ($organizations as $organization): ?>
                        <option value="<?php echo escape(
                            $organization["id"],
                        ); ?>" <?php echo isset($_POST['organization_id']) &&
$_POST['organization_id'] === $organization["id"]
    ? "selected"
    : ""; ?>>
                            <?php echo escape($organization["label"]); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group">
                <label for="comment">Kommentar</label>
                <textarea id="comment" name="comment" rows="5"><?php echo isset(
                    $_POST['comment'],
                )
                    ? escape($_POST['comment'])
                    : ""; ?></textarea>
            </div>

            <div class="alert alert-info">
                Nach dem Absenden wird die Bestellung direkt an die Gerätewarte weitergeleitet.
            </div>

            <?php echo csrfField(); ?>

            <button type="submit" name="create_order" class="btn btn-block">Bestellung absenden</button>
        </form>

        <div class="mt-2">
            <a href="cart.php" class="btn btn-secondary">Zurück zum Warenkorb</a>
        </div>
    </div>
</div>

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