<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| Fidelity Performance Report
|--------------------------------------------------------------------------
|
| Required files in this directory:
|
| dbconn.php
| report-functions.php
| columns.json
| report-ui.css
| report-ui.js
|
| dbconn.php must create:
| $pdo
|
*/

/* -------------------------------------------------------------------------
 * Bootstrap
 * ---------------------------------------------------------------------- */

define('APP_NAME', 'fid');

require_once __DIR__ . '/dbconn.php';
require_once __DIR__ . '/report-functions.php';

$columnsJsonPath = __DIR__ . '/columns.json';

$reportCssUrl = 'report-ui.css';
$reportJsUrl  = 'report-ui.js';

$reportPagePath = 'fid.perf.php';

/* -------------------------------------------------------------------------
 * Report Defaults
 * ---------------------------------------------------------------------- */

/*
 * Dropdown values:
 *
 * all       = oldest available Fidelity record through newest record
 * this_year = January 1 of newest-record year through newest record
 * 1,3,5...  = newest record minus selected calendar years
 */
$allowedRanges = [
    'all'       => 'All data',
    'this_year' => 'This year',
    '1'         => '1 year',
    '3'         => '3 years',
    '5'         => '5 years',
    '7'         => '7 years',
    '10'        => '10 years',
    '15'        => '15 years'
];

$defaultRange = '3';

/*
 * A beginning value below this amount is considered unavailable for
 * return/CAGR calculations.
 */
$minimumStartingValue = 1.00;

/* -------------------------------------------------------------------------
 * Validate PDO Connection
 * ---------------------------------------------------------------------- */

if (!isset($pdo) || !($pdo instanceof PDO)) {
    die(
        'Database configuration error: dbconn.php did not create a valid PDO connection.'
    );
}

/* -------------------------------------------------------------------------
 * Load columns.json
 * ---------------------------------------------------------------------- */

try {
    $columnsFile = report_load_json($columnsJsonPath);
} catch (Throwable $e) {
    die(
        'Unable to load columns.json: '
        . report_h($e->getMessage())
    );
}

if (
    empty($columnsFile['table']) ||
    $columnsFile['table'] !== 'fidelity' ||
    empty($columnsFile['columns']) ||
    !is_array($columnsFile['columns'])
) {
    die('Invalid columns.json configuration for the fidelity report.');
}

$reportableColumns = report_get_reportable_columns(
    $columnsFile['columns']
);

if (count($reportableColumns) === 0) {
    die('No reportable columns were found in columns.json.');
}

$columnsByCategory = report_group_columns_by_category(
    $reportableColumns
);

$defaultFields = report_get_default_columns(
    $reportableColumns
);

if (count($defaultFields) === 0) {
    die('No default report fields were defined in columns.json.');
}

/* -------------------------------------------------------------------------
 * Read URL/Form Settings
 * ---------------------------------------------------------------------- */

/*
 * Main date range dropdown.
 *
 * Examples:
 * fid.perf.php?range=all
 * fid.perf.php?range=this_year
 * fid.perf.php?range=3
 */
$selectedRange = isset($_GET['range'])
    ? (string)$_GET['range']
    : $defaultRange;

if (!array_key_exists($selectedRange, $allowedRanges)) {
    $selectedRange = $defaultRange;
}

/*
 * Needed only when selectedRange is numeric.
 */
$selectedYears = ctype_digit($selectedRange)
    ? (int)$selectedRange
    : 0;

/*
 * Filter submitted checkbox fields through the JSON allowlist.
 */
$selectedFields = report_filter_requested_columns(
    $_GET['fields'] ?? null,
    $reportableColumns,
    $defaultFields
);

$hideUnavailable = isset($_GET['hide_unavailable'])
    && $_GET['hide_unavailable'] === '1';

$activeTab = isset($_GET['tab']) && $_GET['tab'] === 'settings'
    ? 'settings'
    : 'report';

/*
 * Custom range mode is used only from Customize Report.
 */
$dateMode = isset($_GET['date_mode']) && $_GET['date_mode'] === 'custom'
    ? 'custom'
    : 'period';

$customBeginDate = isset($_GET['begin_date'])
    ? trim((string)$_GET['begin_date'])
    : '';

$customEndDate = isset($_GET['end_date'])
    ? trim((string)$_GET['end_date'])
    : '';

$customBeginObject = report_get_date($customBeginDate);
$customEndObject   = report_get_date($customEndDate);

$customDateError = '';

if ($dateMode === 'custom') {
    if (!$customBeginObject || !$customEndObject) {
        $customDateError = 'Choose valid beginning and ending dates.';
        $dateMode = 'period';
    } elseif ($customBeginObject > $customEndObject) {
        $customDateError = 'Beginning date must be on or before ending date.';
        $dateMode = 'period';
    }
}

/*
 * $selectedFields has already been filtered against the JSON allowlist.
 * It is safe to use as a list of SQL identifiers.
 */
$fieldList = implode(', ', $selectedFields);

/* -------------------------------------------------------------------------
 * Query Fidelity Data
 * ---------------------------------------------------------------------- */

try {
    /*
     * Get full table date boundaries and connection diagnostics.
     */
    $stmtBounds = $pdo->query("
        SELECT
            MIN(fidCurDate) AS minFidCurDate,
            MAX(fidCurDate) AS maxFidCurDate,
            COUNT(*) AS totalRows,
            DATABASE() AS currentDatabase,
            @@hostname AS mysqlHost
        FROM fidelity
        WHERE fidCurDate IS NOT NULL
    ");

    $debug = $stmtBounds->fetch(PDO::FETCH_ASSOC);

    if (
        !$debug ||
        empty($debug['minFidCurDate']) ||
        empty($debug['maxFidCurDate'])
    ) {
        die('No dated records were found in the fidelity table.');
    }

    $oldestAvailableDate = new DateTimeImmutable(
        $debug['minFidCurDate']
    );

    $latestAvailableDate = new DateTimeImmutable(
        $debug['maxFidCurDate']
    );

    /*
     * Determine report ending record.
     *
     * Standard range mode:
     *   Always use newest table record.
     *
     * Custom date mode:
     *   Use newest record on/before the entered ending date.
     */
    $usingOldestEndRecord = false;

    if ($dateMode === 'custom') {
        $endCutoff = $customEndObject->format('Y-m-d');

        $stmtEnd = $pdo->prepare("
            SELECT {$fieldList}, fidCurDate, fidId
            FROM fidelity
            WHERE fidCurDate < DATE_ADD(:endCutoff, INTERVAL 1 DAY)
            ORDER BY fidCurDate DESC, fidId DESC
            LIMIT 1
        ");

        $stmtEnd->execute([
            ':endCutoff' => $endCutoff
        ]);

        $valEnd = $stmtEnd->fetch(PDO::FETCH_ASSOC);

        /*
         * If user selected an ending date before all available records,
         * still produce a report using the oldest available record.
         */
        if (!$valEnd) {
            $stmtOldestEnd = $pdo->query("
                SELECT {$fieldList}, fidCurDate, fidId
                FROM fidelity
                WHERE fidCurDate IS NOT NULL
                ORDER BY fidCurDate ASC, fidId ASC
                LIMIT 1
            ");

            $valEnd = $stmtOldestEnd->fetch(PDO::FETCH_ASSOC);
            $usingOldestEndRecord = true;
        }
    } else {
        $valEnd = $pdo->query("
            SELECT {$fieldList}, fidCurDate, fidId
            FROM fidelity
            WHERE fidCurDate IS NOT NULL
            ORDER BY fidCurDate DESC, fidId DESC
            LIMIT 1
        ")->fetch(PDO::FETCH_ASSOC);
    }

    if (!$valEnd) {
        die('No usable ending record was found in the fidelity table.');
    }

    $actualEndDate = new DateTimeImmutable($valEnd['fidCurDate']);

    /*
     * Determine beginning cutoff.
     */
    if ($dateMode === 'custom') {
        /*
         * Exact beginning date selected in Customize Report.
         */
        $beginCutoff = $customBeginObject->format('Y-m-d');

    } elseif ($selectedRange === 'all') {
        /*
         * All data begins at the oldest actual fidelity record.
         */
        $beginCutoff = $oldestAvailableDate->format('Y-m-d');

    } elseif ($selectedRange === 'this_year') {
        /*
         * This year begins January 1 of the ending record's year.
         *
         * Example:
         * End record: 2026-09-10
         * Start cutoff: 2026-01-01
         */
        $beginCutoff = $actualEndDate->format('Y') . '-01-01';

    } else {
        /*
         * Numeric period: latest ending record minus 1/3/5/7/10/15 years.
         */
        $beginCutoff = $actualEndDate
            ->sub(new DateInterval('P' . $selectedYears . 'Y'))
            ->format('Y-m-d');
    }

    /*
     * Beginning record is newest record on or before beginning cutoff.
     *
     * DATE_ADD(..., INTERVAL 1 DAY) allows the complete cutoff date,
     * regardless of the time part in fidCurDate.
     */
    $stmtBegin = $pdo->prepare("
        SELECT {$fieldList}, fidCurDate, fidId
        FROM fidelity
        WHERE fidCurDate < DATE_ADD(:beginCutoff, INTERVAL 1 DAY)
        ORDER BY fidCurDate DESC, fidId DESC
        LIMIT 1
    ");

    $stmtBegin->execute([
        ':beginCutoff' => $beginCutoff
    ]);

    $valBegin = $stmtBegin->fetch(PDO::FETCH_ASSOC);

    /*
     * Fallback:
     * If requested start is before all available data, select the oldest
     * available record and continue the report.
     */
    $usingOldestBeginRecord = false;

    if (!$valBegin) {
        $stmtOldestBegin = $pdo->query("
            SELECT {$fieldList}, fidCurDate, fidId
            FROM fidelity
            WHERE fidCurDate IS NOT NULL
            ORDER BY fidCurDate ASC, fidId ASC
            LIMIT 1
        ");

        $valBegin = $stmtOldestBegin->fetch(PDO::FETCH_ASSOC);

        if (!$valBegin) {
            die('No usable beginning record was found in the fidelity table.');
        }

        $usingOldestBeginRecord = true;
    }

} catch (PDOException $e) {
    die('Database error: ' . report_h($e->getMessage()));
}

/* -------------------------------------------------------------------------
 * Actual Time Period for CAGR
 * ---------------------------------------------------------------------- */

$actualBeginDate = new DateTimeImmutable($valBegin['fidCurDate']);
$actualEndDate   = new DateTimeImmutable($valEnd['fidCurDate']);

$daysBetween = (int)$actualBeginDate
    ->diff($actualEndDate)
    ->format('%a');

$yearsActual = $daysBetween / 365.25;

/*
 * Avoid division by zero for a same-day report.
 */
if ($yearsActual <= 0) {
    $yearsActual = 0.000001;
}

$actualBeginLabel = $actualBeginDate->format('Y-m-d');
$actualEndLabel   = $actualEndDate->format('Y-m-d');

/*
 * Populate default custom inputs when opening Customize Report.
 */
if ($customBeginDate === '') {
    $customBeginDate = $actualEndDate
        ->sub(new DateInterval('P3Y'))
        ->format('Y-m-d');
}

if ($customEndDate === '') {
    $customEndDate = $actualEndDate->format('Y-m-d');
}

/* -------------------------------------------------------------------------
 * Build Table Rows
 * ---------------------------------------------------------------------- */

$reportRows = [];

foreach ($selectedFields as $field) {
    $fieldConfig = $reportableColumns[$field];

    $vBegin = (float)($valBegin[$field] ?? 0);
    $vEnd   = (float)($valEnd[$field] ?? 0);

    /*
     * Do not calculate return/CAGR from a $0 or near-$0 beginning amount.
     */
    $noBeginningData = $vBegin < $minimumStartingValue;

    if ($noBeginningData) {
        $totReturn = null;
        $totReturnPct = null;
        $cagr = null;
    } else {
        $totReturn = $vEnd - $vBegin;

        $totReturnPct = ($totReturn / $vBegin) * 100;

        $cagr = report_calculate_cagr(
            $vBegin,
            $vEnd,
            $yearsActual
        );
    }

    /*
     * Optional hide-unavailable filter.
     */
    if ($hideUnavailable && $noBeginningData) {
        continue;
    }

    $reportRows[] = [
        'name' => $field,
        'category' => (string)($fieldConfig['category'] ?? ''),
        'title' => (string)($fieldConfig['title'] ?? $field),
        'description' => (string)($fieldConfig['description'] ?? ''),
        'vBegin' => $vBegin,
        'vEnd' => $vEnd,
        'noBeginningData' => $noBeginningData,
        'totReturn' => $totReturn,
        'totReturnPct' => $totReturnPct,
        'cagr' => $cagr,
        'returnClass' => report_return_class($totReturn),
        'cagrClass' => report_return_class($cagr)
    ];
}

/* -------------------------------------------------------------------------
 * Preserve Settings in Report / Settings URLs
 * ---------------------------------------------------------------------- */

$baseUrlState = [
    'range' => $selectedRange,
    'fields' => $selectedFields,
    'hide_unavailable' => $hideUnavailable ? '1' : null,
    'date_mode' => $dateMode,
    'begin_date' => $customBeginDate,
    'end_date' => $customEndDate
];

$reportUrl = report_build_url(
    $reportPagePath,
    array_merge($baseUrlState, [
        'tab' => 'report'
    ])
);

$settingsUrl = report_build_url(
    $reportPagePath,
    array_merge($baseUrlState, [
        'tab' => 'settings'
    ])
);

$defaultUrl = report_build_url(
    $reportPagePath,
    [
        'range' => $defaultRange,
        'fields' => $defaultFields,
        'date_mode' => 'period',
        'tab' => 'report'
    ]
);

?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Fidelity Performance Report</title>

<link rel="stylesheet" href="<?= report_h($reportCssUrl) ?>">
<script src="<?= report_h($reportJsUrl) ?>" defer></script>
</head>

<body>
<div class="report-wrap">

    <h1 class="report-title">Fidelity Performance Report</h1>

    <p class="report-subtitle">
        Account balances, total return, percentage return, and annualized CAGR.
    </p>

    <nav class="report-tabs" aria-label="Fidelity report navigation">
        <a
            class="report-tab-link <?= $activeTab === 'report' ? 'active' : '' ?>"
            href="<?= report_h($reportUrl) ?>"
        >
            Report
        </a>

        <a
            class="report-tab-link <?= $activeTab === 'settings' ? 'active' : '' ?>"
            href="<?= report_h($settingsUrl) ?>"
        >
            Customize Report
        </a>
    </nav>

    <?php if ($activeTab === 'settings'): ?>

        <div class="report-card">
            <h2 class="report-heading">Customize Fidelity Report</h2>

            <form
                id="report-settings-form"
                method="get"
                action="<?= report_h($reportPagePath) ?>"
            >
                <input type="hidden" name="tab" value="report">

                <div class="report-settings-grid">

                    <section class="report-settings-section">
                        <h3>Date Range</h3>

                        <p class="report-help">
                            Select a standard date period or use a custom start
                            and end date.
                        </p>

                        <div class="report-check-row">
                            <input
                                type="radio"
                                id="date-mode-period"
                                name="date_mode"
                                value="period"
                                <?= $dateMode === 'period' ? 'checked' : '' ?>
                            >

                            <label for="date-mode-period">
                                Use report period
                            </label>
                        </div>

                        <div class="report-form-row" style="margin: 10px 0 16px 23px;">
                            <label for="range">Period:</label>

                            <select name="range" id="range">
                                <?php foreach ($allowedRanges as $rangeValue => $rangeLabel): ?>
                                    <option
                                        value="<?= report_h($rangeValue) ?>"
                                        <?= $rangeValue === $selectedRange ? 'selected' : '' ?>
                                    >
                                        <?= report_h($rangeLabel) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="report-check-row">
                            <input
                                type="radio"
                                id="date-mode-custom"
                                name="date_mode"
                                value="custom"
                                <?= $dateMode === 'custom' ? 'checked' : '' ?>
                            >

                            <label for="date-mode-custom">
                                Use custom date range
                            </label>
                        </div>

                        <div class="report-date-grid">
                            <div>
                                <label for="begin-date">Beginning date:</label><br>

                                <input
                                    class="report-date-input"
                                    type="date"
                                    id="begin-date"
                                    name="begin_date"
                                    min="<?= report_h($oldestAvailableDate->format('Y-m-d')) ?>"
                                    max="<?= report_h($latestAvailableDate->format('Y-m-d')) ?>"
                                    value="<?= report_h($customBeginDate) ?>"
                                >
                            </div>

                            <div>
                                <label for="end-date">Ending date:</label><br>

                                <input
                                    class="report-date-input"
                                    type="date"
                                    id="end-date"
                                    name="end_date"
                                    min="<?= report_h($oldestAvailableDate->format('Y-m-d')) ?>"
                                    max="<?= report_h($latestAvailableDate->format('Y-m-d')) ?>"
                                    value="<?= report_h($customEndDate) ?>"
                                >
                            </div>
                        </div>

                        <?php if ($customDateError !== ''): ?>
                            <p class="report-help" style="color: #b3261e; margin-top: 12px;">
                                <?= report_h($customDateError) ?>
                                The report has fallen back to the selected period.
                            </p>
                        <?php endif; ?>
                    </section>

                    <section class="report-settings-section">
                        <h3>Accounts and Totals</h3>

                        <p class="report-help">
                            Choose the Fidelity columns to show.
                            <span id="selected-field-count">0 selected</span>
                        </p>

                        <div class="report-actions" style="margin: 0 0 14px;">
                            <button
                                type="button"
                                id="select-all-fields"
                                class="report-button secondary"
                            >
                                Select All
                            </button>

                            <button
                                type="button"
                                id="clear-all-fields"
                                class="report-button secondary"
                            >
                                Clear All
                            </button>
                        </div>

                        <?php foreach ($columnsByCategory as $category => $columns): ?>
                            <h4><?= report_h($category) ?></h4>

                            <div class="report-checkbox-list">
                                <?php foreach ($columns as $columnName => $column): ?>
                                    <div class="report-checkbox-block">
                                        <div class="report-check-row">
                                            <input
                                                type="checkbox"
                                                id="field-<?= report_h($columnName) ?>"
                                                name="fields[]"
                                                value="<?= report_h($columnName) ?>"
                                                <?= in_array(
                                                    $columnName,
                                                    $selectedFields,
                                                    true
                                                ) ? 'checked' : '' ?>
                                            >

                                            <label for="field-<?= report_h($columnName) ?>">
                                                <?= report_h(
                                                    (string)($column['title'] ?? $columnName)
                                                ) ?>

                                                <span class="report-column-code">
                                                    (<?= report_h($columnName) ?>)
                                                </span>
                                            </label>
                                        </div>

                                        <?php if (!empty($column['description'])): ?>
                                            <div class="report-column-description">
                                                <?= report_h(
                                                    (string)$column['description']
                                                ) ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endforeach; ?>
                    </section>

                </div>

                <section class="report-settings-section">
                    <h3>Display Options</h3>

                    <div class="report-check-row">
                        <input
                            type="checkbox"
                            id="hide-unavailable"
                            name="hide_unavailable"
                            value="1"
                            <?= $hideUnavailable ? 'checked' : '' ?>
                        >

                        <label for="hide-unavailable">
                            Hide rows with no beginning data available
                        </label>
                    </div>

                    <p class="report-help" style="margin: 10px 0 0;">
                        An account with a starting balance lower than
                        <?= report_h(report_money($minimumStartingValue)) ?>
                        displays as unavailable and has no return or CAGR
                        calculation.
                    </p>
                </section>

                <div class="report-actions">
                    <button type="submit" class="report-button">
                        Apply Settings and Run Report
                    </button>

                    <a
                        href="<?= report_h($defaultUrl) ?>"
                        class="report-button secondary"
                    >
                        Reset to Defaults
                    </a>
                </div>
            </form>
        </div>

    <?php else: ?>

        <div class="report-card">
            <form
                method="get"
                action="<?= report_h($reportPagePath) ?>"
                class="report-form-row"
            >
                <input type="hidden" name="tab" value="report">
                <input type="hidden" name="date_mode" value="period">

                <?php foreach ($selectedFields as $field): ?>
                    <input
                        type="hidden"
                        name="fields[]"
                        value="<?= report_h($field) ?>"
                    >
                <?php endforeach; ?>

                <?php if ($hideUnavailable): ?>
                    <input type="hidden" name="hide_unavailable" value="1">
                <?php endif; ?>

                <label for="quick-range">Report period:</label>

                <select name="range" id="quick-range">
                    <?php foreach ($allowedRanges as $rangeValue => $rangeLabel): ?>
                        <option
                            value="<?= report_h($rangeValue) ?>"
                            <?= $rangeValue === $selectedRange ? 'selected' : '' ?>
                        >
                            <?= report_h($rangeLabel) ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <button type="submit" class="report-button">
                    Run Report
                </button>

                <a
                    href="<?= report_h($settingsUrl) ?>"
                    class="report-button secondary"
                >
                    Customize Report
                </a>
            </form>
        </div>

        <?php if ($usingOldestBeginRecord): ?>
            <div class="report-notice">
                No Fidelity record exists on or before the requested start
                date of <strong><?= report_h($beginCutoff) ?></strong>.
                The report uses the oldest available record:
                <strong><?= report_h($valBegin['fidCurDate']) ?></strong>.
            </div>
        <?php endif; ?>

        <?php if ($usingOldestEndRecord): ?>
            <div class="report-notice">
                No Fidelity record exists on or before the requested ending
                date. The report uses the oldest available record:
                <strong><?= report_h($valEnd['fidCurDate']) ?></strong>.
            </div>
        <?php endif; ?>

        <div class="report-card">
            <dl class="report-record-grid">
                <dt>Selected date range:</dt>
                <dd>
                    <?= $dateMode === 'custom'
                        ? 'Custom: ' . report_h($customBeginDate)
                            . ' through ' . report_h($customEndDate)
                        : report_h($allowedRanges[$selectedRange]) ?>
                </dd>

                <dt>Requested beginning cutoff:</dt>
                <dd><?= report_h($beginCutoff) ?></dd>

                <dt>Actual beginning record:</dt>
                <dd>
                    <?= report_h($valBegin['fidCurDate']) ?>
                    &nbsp; (fidId <?= report_h($valBegin['fidId']) ?>)
                </dd>

                <dt>Actual ending record:</dt>
                <dd>
                    <?= report_h($valEnd['fidCurDate']) ?>
                    &nbsp; (fidId <?= report_h($valEnd['fidId']) ?>)
                </dd>

                <dt>Actual CAGR period:</dt>
                <dd>
                    <?= report_h(report_number($yearsActual, 3)) ?> years
                    / <?= report_h($daysBetween) ?> days
                </dd>

                <dt>Selected columns:</dt>
                <dd><?= report_h(implode(', ', $selectedFields)) ?></dd>

                <dt>Unavailable rows:</dt>
                <dd><?= $hideUnavailable ? 'Hidden' : 'Shown' ?></dd>
            </dl>
        </div>

        <div class="report-card">
            <?php if (count($reportRows) === 0): ?>
                <p class="report-empty-message">
                    No report rows match the selected settings. Either all
                    selected accounts have no available beginning data and
                    unavailable rows are hidden, or no report columns were
                    selected.
                </p>
            <?php else: ?>
                <table class="report-table">
                    <thead>
                        <tr>
                            <th>Account</th>
                            <th><?= report_h($actualBeginLabel) ?></th>
                            <th><?= report_h($actualEndLabel) ?></th>
                            <th>totReturn</th>
                            <th>totReturn %</th>
                            <th>CAGR</th>
                        </tr>
                    </thead>

                    <tbody>
                    <?php foreach ($reportRows as $row): ?>
                        <tr>
                            <td title="<?= report_h($row['description']) ?>">
                                <?= report_h($row['title']) ?>

                                <span class="report-column-code">
                                    (<?= report_h($row['name']) ?>)
                                </span>
                            </td>

                            <td class="<?= $row['noBeginningData']
                                ? 'report-no-data'
                                : '' ?>">
                                <?= $row['noBeginningData']
                                    ? 'No data available before '
                                        . report_h($actualBeginLabel)
                                    : report_h(report_money($row['vBegin'])) ?>
                            </td>

                            <td>
                                <?= report_h(report_money($row['vEnd'])) ?>
                            </td>

                            <td class="<?= report_h($row['returnClass']) ?>">
                                <?= $row['totReturn'] === null
                                    ? 'N/A'
                                    : report_h(
                                        report_money($row['totReturn'])
                                    ) ?>
                            </td>

                            <td class="<?= report_h($row['returnClass']) ?>">
                                <?= $row['totReturnPct'] === null
                                    ? 'N/A'
                                    : report_h(
                                        report_percent($row['totReturnPct'])
                                    ) ?>
                            </td>

                            <td class="<?= report_h($row['cagrClass']) ?>">
                                <?= $row['cagr'] === null
                                    ? 'N/A'
                                    : report_h(
                                        report_percent($row['cagr'])
                                    ) ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>

    <?php endif; ?>

    <details class="report-card report-debug">
        <summary>Database diagnostic information</summary>

        <pre><?= report_h(
            'Database:      ' . ($debug['currentDatabase'] ?? '') . PHP_EOL .
            'MySQL host:    ' . ($debug['mysqlHost'] ?? '') . PHP_EOL .
            'Oldest record: ' . ($debug['minFidCurDate'] ?? '') . PHP_EOL .
            'Latest record: ' . ($debug['maxFidCurDate'] ?? '') . PHP_EOL .
            'Total rows:    ' . ($debug['totalRows'] ?? '')
        ) ?></pre>
    </details>

</div>
</body>
</html>
