<?php

require_once __DIR__ . '/functions.php';

$pdo = app_db_pdo();
$pendingUserId = saas_pending_tenant_user_id();
if ($pendingUserId === null) {
    header('Location: login.php');
    exit;
}

$errors = [];
$memberships = saas_list_user_memberships($pdo, $pendingUserId);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    app_require_csrf();

    $tenantId = isset($_POST['tenant_id']) ? (int)$_POST['tenant_id'] : 0;
    $identity = $tenantId > 0 ? saas_identity_for_user_tenant($pdo, $pendingUserId, $tenantId) : null;

    if ($identity === null) {
        $errors[] = 'Dieser Mandant ist für dein Konto nicht verfügbar.';
    } else {
        saas_session_login($identity);
        header('Location: konto.php');
        exit;
    }
}

include 'header.php';
include 'headerline.php';
include 'nav.php';
?>

<section id="banner">
    <div class="content">
        <h2>Mandant auswählen</h2>

        <?php if ($errors !== []): ?>
            <div class="hint-box error">
                <?php foreach ($errors as $error): ?>
                    <p><?php echo saas_html($error); ?></p>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php if ($memberships === []): ?>
            <div class="hint-box error"><p>Für dieses Konto ist kein aktiver Mandant verfügbar.</p></div>
        <?php else: ?>
            <form method="post" action="mandant-auswahl.php">
                <?php echo app_csrf_field(); ?>
                <div class="row">
                    <div class="col-12">
                        <label for="tenant_id">Mandant</label>
                        <select name="tenant_id" id="tenant_id" required>
                            <?php foreach ($memberships as $membership): ?>
                                <option value="<?php echo saas_html($membership['tenant_id']); ?>">
                                    <?php echo saas_html($membership['tenant_name']); ?>
                                    (<?php echo saas_html($membership['role']); ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <ul class="actions">
                    <li><button type="submit">Weiter</button></li>
                    <li><a href="logout.php" class="button alt">Abbrechen</a></li>
                </ul>
            </form>
        <?php endif; ?>
    </div>
</section>

<?php include 'footer.php'; ?>
