<?php

require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/app/ledger.php';

$pdo = app_db_pdo();
$saasUser = saas_current_user($pdo);
$hasAccess = false;
$tenantId = 0;
$tenantName = '';
$tenantSlug = '';

if ($saasUser !== null && saas_user_has_role(['owner', 'admin', 'treasurer'], $saasUser)) {
    $hasAccess = true;
    $tenantId = (int)$saasUser['tenant_id'];
    $tenantName = (string)$saasUser['tenant_name'];
    $tenantSlug = (string)$saasUser['tenant_slug'];
} elseif (checkKaffeelisteAdmin($conn, $mailadress)) {
    $defaultTenantSlug = getenv('M3_DEFAULT_TENANT_SLUG');
    $defaultTenantSlug = $defaultTenantSlug !== false && trim($defaultTenantSlug) !== ''
        ? trim($defaultTenantSlug)
        : 'default';
    $stmt = $pdo->prepare('SELECT id, name, slug FROM tenants WHERE slug = ? LIMIT 1');
    $stmt->execute([$defaultTenantSlug]);
    $tenant = $stmt->fetch();

    if ($tenant !== false) {
        $hasAccess = true;
        $tenantId = (int)$tenant['id'];
        $tenantName = (string)$tenant['name'];
        $tenantSlug = (string)$tenant['slug'];
    }
}

$year = ledger_current_year();
$tenantTotals = $hasAccess ? ledger_fetch_tenant_totals($pdo, $tenantId, $year) : ledger_empty_totals();
$participantSummaries = $hasAccess ? ledger_fetch_participant_summaries($pdo, $tenantId, [
    'active_only' => true,
    'year' => $year,
]) : [];
$recentEntries = $hasAccess ? ledger_fetch_recent_entries($pdo, $tenantId, ['limit' => 25]) : [];

function ledger_preview_money(int $cents): string
{
    return saas_format_money_cents($cents) . ' EUR';
}

function ledger_preview_entry_type(string $type): string
{
    if ($type === 'payment') {
        return 'Einzahlung';
    }

    if ($type === 'consumption') {
        return 'Kaffeeverbrauch';
    }

    return $type;
}

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

<section id="banner">
    <div class="content">
        <h2>Ledger Preview</h2>

        <?php if (!$hasAccess): ?>
            <div class="hint-box error"><p>Kein Zugriff.</p></div>
        <?php else: ?>
            <p>
                Read-only Vorschau aus <code>ledger_entries</code> für
                <?php echo saas_html($tenantName); ?>
                (<code><?php echo saas_html($tenantSlug); ?></code>).
                Die bestehenden App-Seiten schreiben weiterhin in die Legacy-Tabellen.
            </p>

            <h3>Tenant-Summen</h3>
            <table>
                <tr>
                    <th>Gesamteinzahlungen</th>
                    <th>Gesamtausgaben</th>
                    <th>Gesamtstriche</th>
                    <th>Aktueller Saldo</th>
                    <th>Einzahlungen <?php echo $year; ?></th>
                    <th>Ausgaben <?php echo $year; ?></th>
                    <th>Striche <?php echo $year; ?></th>
                </tr>
                <tr>
                    <td><?php echo ledger_preview_money($tenantTotals['total_payments_cents']); ?></td>
                    <td><?php echo ledger_preview_money($tenantTotals['total_costs_cents']); ?></td>
                    <td><?php echo number_format($tenantTotals['total_marks'], 0, ',', '.'); ?></td>
                    <td><?php echo ledger_preview_money($tenantTotals['balance_cents']); ?></td>
                    <td><?php echo ledger_preview_money($tenantTotals['year_payments_cents']); ?></td>
                    <td><?php echo ledger_preview_money($tenantTotals['year_costs_cents']); ?></td>
                    <td><?php echo number_format($tenantTotals['year_marks'], 0, ',', '.'); ?></td>
                </tr>
            </table>

            <h3>Aktive Teilnehmer</h3>
            <table>
                <tr>
                    <th>Name</th>
                    <th>E-Mail</th>
                    <th>Aktueller Stand</th>
                    <th>Gesamtausgaben</th>
                    <th>Gesamtstriche</th>
                    <th>Gesamteinzahlungen</th>
                    <th>Striche <?php echo $year; ?></th>
                </tr>
                <?php foreach ($participantSummaries as $summary): ?>
                    <tr>
                        <td><?php echo saas_html($summary['display_name']); ?></td>
                        <td><?php echo saas_html($summary['email'] ?? ''); ?></td>
                        <td><?php echo ledger_preview_money($summary['balance_cents']); ?></td>
                        <td><?php echo ledger_preview_money($summary['total_costs_cents']); ?></td>
                        <td><?php echo number_format($summary['total_marks'], 0, ',', '.'); ?></td>
                        <td><?php echo ledger_preview_money($summary['total_payments_cents']); ?></td>
                        <td><?php echo number_format($summary['year_marks'], 0, ',', '.'); ?></td>
                    </tr>
                <?php endforeach; ?>
            </table>

            <h3>Letzte Ledger-Buchungen</h3>
            <table>
                <tr>
                    <th>Datum</th>
                    <th>Teilnehmer</th>
                    <th>Typ</th>
                    <th>Betrag</th>
                    <th>Striche</th>
                    <th>Quelle</th>
                    <th>Legacy</th>
                </tr>
                <?php foreach ($recentEntries as $entry): ?>
                    <tr>
                        <td><?php echo saas_html($entry['booked_at']); ?></td>
                        <td><?php echo saas_html($entry['display_name']); ?></td>
                        <td><?php echo saas_html(ledger_preview_entry_type($entry['type'])); ?></td>
                        <td><?php echo ledger_preview_money($entry['amount_cents']); ?></td>
                        <td><?php echo $entry['marks_count'] !== null ? number_format($entry['marks_count'], 0, ',', '.') : ''; ?></td>
                        <td><?php echo saas_html($entry['source']); ?></td>
                        <td>
                            <?php
                            echo saas_html((string)($entry['legacy_table'] ?? ''));
                            if ($entry['legacy_id'] !== null) {
                                echo ' #' . (int)$entry['legacy_id'];
                            }
                            ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </table>
        <?php endif; ?>
    </div>
</section>

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