<?php

require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/app/platform-admin.php';
require_once __DIR__ . '/app/billing.php';

$pdo = app_db_pdo();
$user = app_require_platform_admin($pdo);

$tenants = app_backoffice_fetch_tenants($pdo);
$billingPlans = billing_plans();

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

<section id="banner">
    <div class="content">
        <h2>Back-Office</h2>
        <p>Nur für Betreiber-Admins sichtbar: Übersicht aller Mandanten, unabhängig von deren eigener Mitgliedschaft.
        Jeder Zugriff wird im Audit-Log des jeweiligen Mandanten protokolliert.</p>

        <table>
            <tr>
                <th>Kunde</th>
                <th>Kürzel</th>
                <th>Status</th>
                <th>Tarif</th>
                <th>Erstellt</th>
                <th>Teilnehmer (aktiv/gesamt)</th>
                <th>Saldensumme</th>
                <th></th>
            </tr>
            <?php foreach ($tenants as $tenant): ?>
                <?php $tenantRequiredPlan = billing_required_plan_code((int)$tenant['active_participant_count']); ?>
                <tr>
                    <td><?php echo saas_html($tenant['name']); ?></td>
                    <td><?php echo saas_html($tenant['slug']); ?></td>
                    <td><?php echo saas_html($tenant['status']); ?></td>
                    <td>
                        <?php echo saas_html($billingPlans[$tenant['plan_code']]['label'] ?? $tenant['plan_code']); ?>
                        <?php if ($tenantRequiredPlan !== $tenant['plan_code']): ?>
                            <br><small>benötigt: <?php echo saas_html($billingPlans[$tenantRequiredPlan]['label'] ?? $tenantRequiredPlan); ?></small>
                        <?php endif; ?>
                    </td>
                    <td><?php echo (int)$tenant['active_participant_count']; ?> / <?php echo (int)$tenant['participant_count']; ?></td>
                    <td><?php echo saas_html(saas_format_money_cents((int)$tenant['balance_cents'])); ?> €</td>
                    <td><a href="backoffice-mandant.php?tenant_id=<?php echo (int)$tenant['id']; ?>" class="button">Ansehen</a></td>
                </tr>
            <?php endforeach; ?>
        </table>
    </div>
</section>

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