<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Outstanding Balances Report';

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('money_fmt')) {
    function money_fmt($amount): string
    {
        return number_format((float)$amount, 2);
    }
}

if (!function_exists('outstanding_table_exists')) {
    function outstanding_table_exists(PDO $pdo, string $tableName): bool
    {
        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.tables
            WHERE table_schema = DATABASE()
              AND table_name = :table_name
        ");
        $stmt->execute([':table_name' => $tableName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

$errors = [];

$today = date('Y-m-d');
$dateAsAt = trim((string)($_GET['as_at'] ?? $today));
$selectedPropertyId = (int)($_GET['property_id'] ?? 0);
$selectedAgentId = (int)($_GET['agent_id'] ?? 0);
$selectedBucket = trim((string)($_GET['bucket'] ?? ''));
$showZeroBalances = (int)($_GET['show_zero'] ?? 0);

$allowedBuckets = ['', 'current', '1_30', '31_60', '61_90', '90_plus'];
if (!in_array($selectedBucket, $allowedBuckets, true)) {
    $selectedBucket = '';
}

if ($dateAsAt === '') {
    $dateAsAt = $today;
}
if (strtotime($dateAsAt) === false) {
    $errors[] = 'Invalid as-at date selected.';
}

$requiredTables = ['folios', 'orders', 'properties'];
foreach ($requiredTables as $table) {
    if (!outstanding_table_exists($pdo, $table)) {
        $errors[] = 'Required table missing: ' . $table;
    }
}

$properties = [];
$agents = [];

if (!$errors) {
    try {
        $properties = $pdo->query("
            SELECT id, name, code
            FROM properties
            WHERE is_active = 1
            ORDER BY name ASC
        ")->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $errors[] = 'Could not load properties: ' . $e->getMessage();
    }

    try {
        $agents = $pdo->query("
            SELECT id, firstname, lastname
            FROM agents
            ORDER BY firstname ASC, lastname ASC
        ")->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $agents = [];
    }
}

/*
  Important HY093 fix:
  Do NOT repeat the same named placeholder many times inside CASE/DATEDIFF.
  We safely quote the validated date once and inject it as a literal.
*/
$asAtSql = $pdo->quote($dateAsAt);

$ageSql = "
    DATEDIFF(
        $asAtSql,
        COALESCE(o.check_out, o.check_in, DATE(f.created_at), $asAtSql)
    )
";

$bucketSql = "
    CASE
        WHEN $ageSql <= 0 THEN 'current'
        WHEN $ageSql BETWEEN 1 AND 30 THEN '1_30'
        WHEN $ageSql BETWEEN 31 AND 60 THEN '31_60'
        WHEN $ageSql BETWEEN 61 AND 90 THEN '61_90'
        ELSE '90_plus'
    END
";

$where = " 1 = 1 ";
$params = [];

if ($selectedPropertyId > 0) {
    $where .= " AND o.property_id = :property_id ";
    $params[':property_id'] = $selectedPropertyId;
}

if ($selectedAgentId > 0) {
    $where .= " AND o.agent_id = :agent_id ";
    $params[':agent_id'] = $selectedAgentId;
}

if (!$showZeroBalances) {
    $where .= " AND f.balance > 0.00001 ";
}

if ($selectedBucket !== '') {
    $where .= " AND ($bucketSql) = :bucket ";
    $params[':bucket'] = $selectedBucket;
}

$summary = [
    'total_charges' => 0,
    'total_payments' => 0,
    'total_balance' => 0,
    'folio_count' => 0,
    'booking_count' => 0,
    'current_total' => 0,
    'days_1_30_total' => 0,
    'days_31_60_total' => 0,
    'days_61_90_total' => 0,
    'days_90_plus_total' => 0,
];

$rows = [];
$agentRows = [];
$propertyRows = [];

if (!$errors) {
    try {
        $stmt = $pdo->prepare("
            SELECT
                COALESCE(SUM(f.total_charges), 0) AS total_charges,
                COALESCE(SUM(f.total_payments), 0) AS total_payments,
                COALESCE(SUM(f.balance), 0) AS total_balance,
                COUNT(*) AS folio_count,
                COUNT(DISTINCT f.order_id) AS booking_count,

                COALESCE(SUM(CASE WHEN ($bucketSql) = 'current' THEN f.balance ELSE 0 END), 0) AS current_total,
                COALESCE(SUM(CASE WHEN ($bucketSql) = '1_30' THEN f.balance ELSE 0 END), 0) AS days_1_30_total,
                COALESCE(SUM(CASE WHEN ($bucketSql) = '31_60' THEN f.balance ELSE 0 END), 0) AS days_31_60_total,
                COALESCE(SUM(CASE WHEN ($bucketSql) = '61_90' THEN f.balance ELSE 0 END), 0) AS days_61_90_total,
                COALESCE(SUM(CASE WHEN ($bucketSql) = '90_plus' THEN f.balance ELSE 0 END), 0) AS days_90_plus_total
            FROM folios f
            LEFT JOIN orders o ON o.id = f.order_id
            LEFT JOIN properties p ON p.id = o.property_id
            WHERE $where
        ");
        $stmt->execute($params);
        $summary = array_merge($summary, $stmt->fetch(PDO::FETCH_ASSOC) ?: []);
    } catch (Throwable $e) {
        $errors[] = 'Could not load outstanding summary: ' . $e->getMessage();
    }
}

if (!$errors) {
    try {
        $stmt = $pdo->prepare("
            SELECT
                f.id AS folio_id,
                f.folio_no,
                f.folio_name,
                f.folio_type,
                f.total_charges,
                f.total_payments,
                f.balance,
                f.created_at,
                f.updated_at,
                o.id AS order_id,
                o.order_no,
                o.check_in,
                o.check_out,
                o.agent_id,
                p.name AS property_name,
                p.code AS property_code,
                TRIM(CONCAT(COALESCE(g.firstname,''), ' ', COALESCE(g.lastname,''))) AS guest_name,
                TRIM(CONCAT(COALESCE(a.firstname,''), ' ', COALESCE(a.lastname,''))) AS agent_name,
                COALESCE(o.check_out, o.check_in, DATE(f.created_at), $asAtSql) AS due_basis_date,
                $ageSql AS age_days,
                $bucketSql AS aging_bucket
            FROM folios f
            LEFT JOIN orders o ON o.id = f.order_id
            LEFT JOIN properties p ON p.id = o.property_id
            LEFT JOIN guests g ON g.id = o.guest_id
            LEFT JOIN agents a ON a.id = o.agent_id
            WHERE $where
            ORDER BY f.balance DESC, age_days DESC, p.name ASC, o.check_out ASC
            LIMIT 1500
        ");
        $stmt->execute($params);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $errors[] = 'Could not load outstanding detail: ' . $e->getMessage();
    }
}

if (!$errors) {
    try {
        $stmt = $pdo->prepare("
            SELECT
                COALESCE(NULLIF(TRIM(CONCAT(COALESCE(a.firstname,''), ' ', COALESCE(a.lastname,''))), ''), 'Direct / No Agent') AS agent_name,
                COUNT(*) AS folio_count,
                COUNT(DISTINCT f.order_id) AS booking_count,
                COALESCE(SUM(f.total_charges), 0) AS total_charges,
                COALESCE(SUM(f.total_payments), 0) AS total_payments,
                COALESCE(SUM(f.balance), 0) AS balance
            FROM folios f
            LEFT JOIN orders o ON o.id = f.order_id
            LEFT JOIN agents a ON a.id = o.agent_id
            LEFT JOIN properties p ON p.id = o.property_id
            WHERE $where
            GROUP BY agent_name
            ORDER BY balance DESC, agent_name ASC
        ");
        $stmt->execute($params);
        $agentRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $agentRows = [];
    }
}

if (!$errors) {
    try {
        $stmt = $pdo->prepare("
            SELECT
                COALESCE(p.name, 'No Property') AS property_name,
                COUNT(*) AS folio_count,
                COUNT(DISTINCT f.order_id) AS booking_count,
                COALESCE(SUM(f.total_charges), 0) AS total_charges,
                COALESCE(SUM(f.total_payments), 0) AS total_payments,
                COALESCE(SUM(f.balance), 0) AS balance
            FROM folios f
            LEFT JOIN orders o ON o.id = f.order_id
            LEFT JOIN properties p ON p.id = o.property_id
            WHERE $where
            GROUP BY property_name
            ORDER BY balance DESC, property_name ASC
        ");
        $stmt->execute($params);
        $propertyRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $propertyRows = [];
    }
}

$bucketLabels = [
    'current' => 'Current / Not Due',
    '1_30' => '1 - 30 Days',
    '31_60' => '31 - 60 Days',
    '61_90' => '61 - 90 Days',
    '90_plus' => '90+ Days',
];

$bucketRows = [
    ['bucket' => 'current', 'label' => $bucketLabels['current'], 'amount' => (float)$summary['current_total']],
    ['bucket' => '1_30', 'label' => $bucketLabels['1_30'], 'amount' => (float)$summary['days_1_30_total']],
    ['bucket' => '31_60', 'label' => $bucketLabels['31_60'], 'amount' => (float)$summary['days_31_60_total']],
    ['bucket' => '61_90', 'label' => $bucketLabels['61_90'], 'amount' => (float)$summary['days_61_90_total']],
    ['bucket' => '90_plus', 'label' => $bucketLabels['90_plus'], 'amount' => (float)$summary['days_90_plus_total']],
];

if (isset($_GET['export']) && $_GET['export'] === 'csv' && !$errors) {
    $filename = 'outstanding_report_' . date('Ymd_His') . '.csv';

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');

    $out = fopen('php://output', 'w');

    fputcsv($out, [
        'As At',
        'Property',
        'Booking',
        'Guest',
        'Agent',
        'Check In',
        'Check Out',
        'Folio No',
        'Folio Name',
        'Folio Type',
        'Charges',
        'Payments',
        'Balance',
        'Age Days',
        'Aging Bucket'
    ]);

    foreach ($rows as $row) {
        $property = trim((string)($row['property_name'] ?? ''));
        if (!empty($row['property_code'])) {
            $property .= ' (' . $row['property_code'] . ')';
        }

        fputcsv($out, [
            $dateAsAt,
            $property,
            $row['order_no'] ?: ('#' . $row['order_id']),
            trim((string)$row['guest_name']) ?: 'Guest',
            trim((string)$row['agent_name']) ?: 'Direct',
            $row['check_in'],
            $row['check_out'],
            $row['folio_no'],
            $row['folio_name'],
            $row['folio_type'],
            number_format((float)$row['total_charges'], 2, '.', ''),
            number_format((float)$row['total_payments'], 2, '.', ''),
            number_format((float)$row['balance'], 2, '.', ''),
            max(0, (int)$row['age_days']),
            $bucketLabels[$row['aging_bucket']] ?? $row['aging_bucket'],
        ]);
    }

    fclose($out);
    exit;
}

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50">
                <i class="bi bi-wallet2"></i> Debtors & Control
            </div>
            <div class="hero-title mt-2">Outstanding Balances Report</div>
            <div class="hero-subtitle mt-2">
                Track unpaid folio balances by booking, guest, agent, property and aging bucket.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="outstanding_report.php?<?php echo h(http_build_query(array_merge($_GET, ['export' => 'csv']))); ?>" class="btn btn-light">
                <i class="bi bi-download me-2"></i>Export CSV
            </a>
        </div>
    </div>
</div>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?>
                <li><?php echo h($err); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="card panel-card mb-4">
    <div class="card-body">
        <form method="get" class="row g-3 align-items-end">
            <div class="col-md-2">
                <label class="form-label">As At</label>
                <input type="date" name="as_at" class="form-control" value="<?php echo h($dateAsAt); ?>">
            </div>

            <div class="col-md-3">
                <label class="form-label">Property</label>
                <select name="property_id" class="form-select">
                    <option value="0">All properties</option>
                    <?php foreach ($properties as $property): ?>
                        <option value="<?php echo (int)$property['id']; ?>" <?php echo $selectedPropertyId === (int)$property['id'] ? 'selected' : ''; ?>>
                            <?php echo h($property['name']); ?> - <?php echo h($property['code']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-3">
                <label class="form-label">Agent</label>
                <select name="agent_id" class="form-select">
                    <option value="0">All agents / direct</option>
                    <?php foreach ($agents as $agent): ?>
                        <?php $agentName = trim(($agent['firstname'] ?? '') . ' ' . ($agent['lastname'] ?? '')); ?>
                        <option value="<?php echo (int)$agent['id']; ?>" <?php echo $selectedAgentId === (int)$agent['id'] ? 'selected' : ''; ?>>
                            <?php echo h($agentName !== '' ? $agentName : ('Agent #' . (int)$agent['id'])); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label">Aging Bucket</label>
                <select name="bucket" class="form-select">
                    <option value="">All buckets</option>
                    <?php foreach ($bucketLabels as $key => $label): ?>
                        <option value="<?php echo h($key); ?>" <?php echo $selectedBucket === $key ? 'selected' : ''; ?>>
                            <?php echo h($label); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-1">
                <label class="form-label">Zero</label>
                <select name="show_zero" class="form-select">
                    <option value="0" <?php echo $showZeroBalances === 0 ? 'selected' : ''; ?>>No</option>
                    <option value="1" <?php echo $showZeroBalances === 1 ? 'selected' : ''; ?>>Yes</option>
                </select>
            </div>

            <div class="col-md-1 d-grid">
                <button class="btn btn-primary">
                    <i class="bi bi-funnel"></i>
                </button>
            </div>
        </form>
    </div>
</div>

<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-2">
        <div class="metric-card">
            <div class="metric-icon bg-info-subtle text-info"><i class="bi bi-receipt"></i></div>
            <div>
                <div class="metric-label">Charges</div>
                <div class="metric-value"><?php echo money_fmt($summary['total_charges']); ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-2">
        <div class="metric-card">
            <div class="metric-icon bg-success-subtle text-success"><i class="bi bi-cash-stack"></i></div>
            <div>
                <div class="metric-label">Payments</div>
                <div class="metric-value"><?php echo money_fmt($summary['total_payments']); ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-2">
        <div class="metric-card">
            <div class="metric-icon bg-danger-subtle text-danger"><i class="bi bi-exclamation-circle"></i></div>
            <div>
                <div class="metric-label">Outstanding</div>
                <div class="metric-value"><?php echo money_fmt($summary['total_balance']); ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-2">
        <div class="metric-card">
            <div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-journal-text"></i></div>
            <div>
                <div class="metric-label">Folios</div>
                <div class="metric-value"><?php echo (int)$summary['folio_count']; ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-2">
        <div class="metric-card">
            <div class="metric-icon bg-secondary-subtle text-secondary"><i class="bi bi-briefcase"></i></div>
            <div>
                <div class="metric-label">Bookings</div>
                <div class="metric-value"><?php echo (int)$summary['booking_count']; ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-2">
        <div class="metric-card">
            <div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-clock-history"></i></div>
            <div>
                <div class="metric-label">90+ Days</div>
                <div class="metric-value"><?php echo money_fmt($summary['days_90_plus_total']); ?></div>
            </div>
        </div>
    </div>
</div>

<div class="row g-4">
    <div class="col-xl-5">
        <div class="card panel-card h-100">
            <div class="card-header">
                <h5 class="mb-0">Aging Summary</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Bucket</th>
                                <th class="text-end">Outstanding</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($bucketRows as $bucket): ?>
                                <?php
                                    $bucketParams = $_GET;
                                    unset($bucketParams['export']);
                                    $bucketParams['bucket'] = $bucket['bucket'];
                                ?>
                                <tr>
                                    <td>
                                        <a href="outstanding_report.php?<?php echo h(http_build_query($bucketParams)); ?>">
                                            <strong><?php echo h($bucket['label']); ?></strong>
                                        </a>
                                    </td>
                                    <td class="text-end fw-bold"><?php echo money_fmt($bucket['amount']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <th>Total</th>
                                <th class="text-end"><?php echo money_fmt($summary['total_balance']); ?></th>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-7">
        <div class="card panel-card h-100">
            <div class="card-header">
                <h5 class="mb-0">Outstanding by Agent</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Agent</th>
                                <th class="text-end">Bookings</th>
                                <th class="text-end">Folios</th>
                                <th class="text-end">Charges</th>
                                <th class="text-end">Payments</th>
                                <th class="text-end">Balance</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$agentRows): ?>
                                <tr><td colspan="6" class="text-center text-muted py-4">No outstanding agent balances.</td></tr>
                            <?php else: ?>
                                <?php foreach ($agentRows as $row): ?>
                                    <tr>
                                        <td><strong><?php echo h($row['agent_name']); ?></strong></td>
                                        <td class="text-end"><?php echo (int)$row['booking_count']; ?></td>
                                        <td class="text-end"><?php echo (int)$row['folio_count']; ?></td>
                                        <td class="text-end"><?php echo money_fmt($row['total_charges']); ?></td>
                                        <td class="text-end"><?php echo money_fmt($row['total_payments']); ?></td>
                                        <td class="text-end fw-bold"><?php echo money_fmt($row['balance']); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-12">
        <div class="card panel-card">
            <div class="card-header">
                <h5 class="mb-0">Outstanding by Property</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Property</th>
                                <th class="text-end">Bookings</th>
                                <th class="text-end">Folios</th>
                                <th class="text-end">Charges</th>
                                <th class="text-end">Payments</th>
                                <th class="text-end">Balance</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$propertyRows): ?>
                                <tr><td colspan="6" class="text-center text-muted py-4">No outstanding property balances.</td></tr>
                            <?php else: ?>
                                <?php foreach ($propertyRows as $row): ?>
                                    <tr>
                                        <td><strong><?php echo h($row['property_name']); ?></strong></td>
                                        <td class="text-end"><?php echo (int)$row['booking_count']; ?></td>
                                        <td class="text-end"><?php echo (int)$row['folio_count']; ?></td>
                                        <td class="text-end"><?php echo money_fmt($row['total_charges']); ?></td>
                                        <td class="text-end"><?php echo money_fmt($row['total_payments']); ?></td>
                                        <td class="text-end fw-bold"><?php echo money_fmt($row['balance']); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-12">
        <div class="card panel-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Outstanding Detail</h5>
                <span class="text-muted small">Showing latest 1,500 folios</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Property</th>
                                <th>Booking</th>
                                <th>Guest</th>
                                <th>Agent</th>
                                <th>Stay</th>
                                <th>Folio</th>
                                <th>Type</th>
                                <th class="text-end">Charges</th>
                                <th class="text-end">Payments</th>
                                <th class="text-end">Balance</th>
                                <th class="text-end">Age</th>
                                <th>Bucket</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$rows): ?>
                                <tr><td colspan="12" class="text-center text-muted py-4">No outstanding folios found.</td></tr>
                            <?php else: ?>
                                <?php foreach ($rows as $row): ?>
                                    <?php
                                    $propertyLabel = trim((string)($row['property_name'] ?? ''));
                                    if (!empty($row['property_code'])) {
                                        $propertyLabel .= ' (' . $row['property_code'] . ')';
                                    }
                                    $guestName = trim((string)($row['guest_name'] ?? ''));
                                    $agentName = trim((string)($row['agent_name'] ?? ''));
                                    $bucket = (string)($row['aging_bucket'] ?? '');
                                    ?>
                                    <tr>
                                        <td><?php echo h($propertyLabel ?: 'Not set'); ?></td>
                                        <td>
                                            <a href="/rooms/modules/payments/payments.php?order_id=<?php echo (int)$row['order_id']; ?>" class="booking-ref">
                                                <?php echo h($row['order_no'] ?: ('#' . $row['order_id'])); ?>
                                            </a>
                                        </td>
                                        <td><?php echo h($guestName ?: 'Guest'); ?></td>
                                        <td><?php echo h($agentName ?: 'Direct'); ?></td>
                                        <td>
                                            <div class="data-stack">
                                                <strong><?php echo h($row['check_in']); ?></strong>
                                                <small>to <?php echo h($row['check_out']); ?></small>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="data-stack">
                                                <strong><?php echo h($row['folio_no']); ?></strong>
                                                <small><?php echo h($row['folio_name']); ?></small>
                                            </div>
                                        </td>
                                        <td><?php echo h(ucwords(str_replace('_', ' ', (string)$row['folio_type']))); ?></td>
                                        <td class="text-end"><?php echo money_fmt($row['total_charges']); ?></td>
                                        <td class="text-end"><?php echo money_fmt($row['total_payments']); ?></td>
                                        <td class="text-end fw-bold"><?php echo money_fmt($row['balance']); ?></td>
                                        <td class="text-end"><?php echo max(0, (int)$row['age_days']); ?></td>
                                        <td>
                                            <span class="badge text-bg-light border">
                                                <?php echo h($bucketLabels[$bucket] ?? $bucket); ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

</div>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
