<?php
/**
 * Finance reports - enhanced with charts, member giving, trends
 */

require_once __DIR__ . '/../../includes/settings.php';

$start = trim($_GET['start'] ?? date('Y-m-01'));
$end = trim($_GET['end'] ?? date('Y-m-d'));
$reportType = trim($_GET['type'] ?? 'summary');
$pledgeYear = (int) ($_GET['year'] ?? date('Y'));
if ($pledgeYear < 2000 || $pledgeYear > 2100) {
    $pledgeYear = (int) date('Y');
}

// Validate date range
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $start) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $end)) {
    $start = date('Y-m-01');
    $end = date('Y-m-d');
}

// Persist selected funds for Fund Summary chart using settings
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['form_section'] ?? '') === 'summary_fund_filter') {
    $ids = isset($_POST['summary_fund_ids']) && is_array($_POST['summary_fund_ids'])
        ? array_filter(array_map('intval', $_POST['summary_fund_ids']))
        : [];
    $value = $ids ? implode(',', $ids) : '';
    setSetting('finance_summary_fund_ids', $value);
    header('Location: ' . BASE_PATH . '/finance/reports?type=summary&start=' . urlencode($start) . '&end=' . urlencode($end));
    exit;
}

// Read selected funds (comma-separated ids); empty = all
$summaryFundIdsSetting = getSetting('finance_summary_fund_ids', '');
$summaryFundIds = array_values(array_filter(array_map('intval', $summaryFundIdsSetting !== '' ? explode(',', $summaryFundIdsSetting) : [])));

// Fund Summary Report
$stmt = $pdo->prepare("
    SELECT f.id, f.name, COALESCE(SUM(t.amount), 0) AS total, COUNT(t.id) AS tx_count
    FROM funds f
    LEFT JOIN transactions t ON t.fund_id = f.id 
        AND t.transaction_date BETWEEN ? AND ?
    GROUP BY f.id
    ORDER BY f.name
");
$stmt->execute([$start, $end]);
$byFund = $stmt->fetchAll();

$stmt = $pdo->prepare("SELECT COALESCE(SUM(amount), 0) AS grand_total FROM transactions WHERE transaction_date BETWEEN ? AND ?");
$stmt->execute([$start, $end]);
$grandTotal = (float) $stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM transactions WHERE transaction_date BETWEEN ? AND ?");
$stmt->execute([$start, $end]);
$totalTransactions = (int) $stmt->fetchColumn();
$avgTransaction = $totalTransactions > 0 ? $grandTotal / $totalTransactions : 0;

// Member Giving Report (only for personal funds)
try {
    $memberGivingSql = "
        SELECT m.id, CONCAT(m.first_name, ' ', m.last_name) AS member_name,
               COALESCE(SUM(t.amount), 0) AS total, COUNT(t.id) AS tx_count
        FROM members m
        INNER JOIN transactions t ON t.member_id = m.id
        INNER JOIN funds f ON t.fund_id = f.id
        WHERE t.transaction_date BETWEEN ? AND ?
          AND COALESCE(f.is_personal, 0) = 1
        GROUP BY m.id
        ORDER BY total DESC
        LIMIT 50
    ";
    $stmt = $pdo->prepare($memberGivingSql);
    $stmt->execute([$start, $end]);
    $memberGiving = $stmt->fetchAll();
} catch (PDOException $e) {
    $memberGiving = [];
}

// Monthly Trends (last 12 months)
$monthlyTrends = [];
for ($i = 11; $i >= 0; $i--) {
    $monthStart = date('Y-m-01', strtotime("-$i months"));
    $monthEnd = date('Y-m-t', strtotime("-$i months"));
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(amount), 0) FROM transactions WHERE transaction_date BETWEEN ? AND ?");
    $stmt->execute([$monthStart, $monthEnd]);
    $monthTotal = (float) $stmt->fetchColumn();
    $monthlyTrends[] = [
        'month' => date('M Y', strtotime($monthStart)),
        'total' => $monthTotal
    ];
}

// Fund Comparison (last 6 months)
$fundComparison = [];
$funds = $pdo->query('SELECT id, name FROM funds ORDER BY name')->fetchAll();
$months = [];
for ($i = 5; $i >= 0; $i--) {
    $months[] = date('M Y', strtotime("-$i months"));
}
// Pledge vs giving (by member and year)
$pledgeVsGiven = [];
try {
    $pledgeStart = $pledgeYear . '-01-01';
    $pledgeEnd = $pledgeYear . '-12-31';
    $byMemberPledge = [];
    $stmt = $pdo->prepare("
        SELECT p.member_id,
               CONCAT(m.first_name, ' ', m.last_name) AS member_name,
               COALESCE(SUM(p.amount), 0) AS pledged
        FROM pledges p
        JOIN members m ON m.id = p.member_id
        WHERE p.pledge_year = ?
        GROUP BY p.member_id, m.first_name, m.last_name
    ");
    $stmt->execute([$pledgeYear]);
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $byMemberPledge[(int) $row['member_id']] = [
            'member_name' => $row['member_name'],
            'pledged' => (float) $row['pledged'],
        ];
    }
    // Giving by member for the year
    $stmt = $pdo->prepare("
        SELECT t.member_id,
               CONCAT(m.first_name, ' ', m.last_name) AS member_name,
               COALESCE(SUM(t.amount), 0) AS given
        FROM transactions t
        JOIN members m ON m.id = t.member_id
        WHERE t.member_id IS NOT NULL AND t.transaction_date BETWEEN ? AND ?
        GROUP BY t.member_id, m.first_name, m.last_name
    ");
    $stmt->execute([$pledgeStart, $pledgeEnd]);
    $seenMemberIds = [];
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $mid = (int) $row['member_id'];
        $seenMemberIds[] = $mid;
        $given = (float) $row['given'];
        $pledged = isset($byMemberPledge[$mid]) ? $byMemberPledge[$mid]['pledged'] : 0;
        $name = isset($byMemberPledge[$mid]) ? $byMemberPledge[$mid]['member_name'] : $row['member_name'];
        $pledgeVsGiven[] = [
            'member_id' => $mid,
            'member_name' => $name,
            'pledged' => $pledged,
            'given' => $given,
            'difference' => $given - $pledged,
        ];
    }
    // Add members who pledged but have no transactions this year
    foreach ($byMemberPledge as $mid => $info) {
        if (!in_array($mid, $seenMemberIds)) {
            $pledgeVsGiven[] = [
                'member_id' => $mid,
                'member_name' => $info['member_name'],
                'pledged' => $info['pledged'],
                'given' => 0,
                'difference' => -$info['pledged'],
            ];
        }
    }
    usort($pledgeVsGiven, function ($a, $b) {
        return strcmp($a['member_name'], $b['member_name']);
    });
} catch (PDOException $e) {
    // pledges table may not exist
}

foreach ($funds as $fund) {
    $fundData = ['name' => $fund['name'], 'months' => []];
    for ($i = 5; $i >= 0; $i--) {
        $monthStart = date('Y-m-01', strtotime("-$i months"));
        $monthEnd = date('Y-m-t', strtotime("-$i months"));
        $stmt = $pdo->prepare("SELECT COALESCE(SUM(amount), 0) FROM transactions WHERE fund_id = ? AND transaction_date BETWEEN ? AND ?");
        $stmt->execute([$fund['id'], $monthStart, $monthEnd]);
        $fundData['months'][] = (float) $stmt->fetchColumn();
    }
    $fundComparison[] = $fundData;
}

// ── Final Report: standalone printable page ───────────────────────────────
if ($reportType === 'final') {
    $allowed = ['summary', 'members', 'trends', 'comparison', 'pledge'];
    $sections = [];
    if (isset($_GET['sections']) && is_array($_GET['sections'])) {
        foreach ($_GET['sections'] as $s) {
            if (in_array($s, $allowed, true)) $sections[] = $s;
        }
    }
    if (empty($sections)) $sections = ['summary'];
    $orgName = defined('SITE_FULL_NAME') ? SITE_FULL_NAME : 'Presbyterian Church of Ghana';
    $periodLabel = date('j M Y', strtotime($start)) . ' – ' . date('j M Y', strtotime($end));
    ?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Financial Report – <?= htmlspecialchars($periodLabel) ?></title>
<style>
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:'Segoe UI',Arial,sans-serif;font-size:13px;color:#111;background:#fff;padding:2cm 2.2cm;}
@page{size:A4 portrait;margin:1.8cm 2cm;}
.fr-cover{text-align:center;padding-bottom:1.2rem;margin-bottom:1.4rem;border-bottom:2px solid #1e3a5f;}
.fr-cover h1{font-size:1.4rem;font-weight:700;color:#1e3a5f;letter-spacing:.01em;}
.fr-cover .fr-sub{font-size:0.85rem;color:#555;margin-top:.3rem;}
.fr-cover .fr-meta{display:flex;justify-content:center;gap:2rem;margin-top:.75rem;font-size:0.8rem;color:#444;}
.fr-meta span strong{display:block;font-size:0.7rem;text-transform:uppercase;letter-spacing:.05em;color:#888;margin-bottom:.1rem;}
.fr-section{margin-bottom:2rem;page-break-inside:avoid;}
.fr-section h2{font-size:1rem;font-weight:700;color:#1e3a5f;padding:.5rem 0;border-bottom:1.5px solid #dce3ee;margin-bottom:.75rem;text-transform:uppercase;letter-spacing:.04em;}
.fr-stats{display:flex;gap:1rem;margin-bottom:.85rem;flex-wrap:wrap;}
.fr-stat{flex:1;min-width:120px;background:#f4f7fb;border-radius:5px;padding:.55rem .75rem;}
.fr-stat .lbl{font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;color:#64748b;margin-bottom:.15rem;}
.fr-stat .val{font-size:1.1rem;font-weight:700;color:#1e293b;}
table{width:100%;border-collapse:collapse;font-size:12.5px;}
thead th{background:#1e3a5f;color:#fff;padding:.4rem .65rem;text-align:left;font-weight:600;font-size:.7rem;text-transform:uppercase;letter-spacing:.04em;}
thead th.r{text-align:right;}
tbody tr:nth-child(even){background:#f8fafc;}
tbody td{padding:.38rem .65rem;border-bottom:1px solid #e8edf3;}
tbody td.r{text-align:right;}
tfoot th{padding:.4rem .65rem;background:#e8edf3;font-weight:700;border-top:2px solid #b0bfd4;}
tfoot th.r{text-align:right;}
.fr-no-data{font-size:.85rem;color:#888;padding:.5rem 0;}
.fr-print-bar{display:flex;gap:.75rem;justify-content:flex-end;margin-bottom:1.5rem;}
.fr-print-bar button{padding:.45rem 1.1rem;border:none;border-radius:5px;font-size:.85rem;cursor:pointer;font-family:inherit;}
.fr-btn-print{background:#1e3a5f;color:#fff;}
.fr-btn-close{background:#e5e7eb;color:#374151;}
@media print{.fr-print-bar{display:none!important;}}
</style>
</head>
<body>
<div class="fr-print-bar">
    <button class="fr-btn-close" onclick="window.close()">Close</button>
    <button class="fr-btn-print" onclick="window.print()">&#128438; Print / Save PDF</button>
</div>
<div class="fr-cover">
    <h1><?= htmlspecialchars($orgName) ?></h1>
    <div class="fr-sub">Financial Report</div>
    <div class="fr-meta">
        <span><strong>Period</strong><?= htmlspecialchars($periodLabel) ?></span>
        <span><strong>Generated</strong><?= date('j M Y, g:i A') ?></span>
    </div>
</div>

<?php if (in_array('summary', $sections)): ?>
<div class="fr-section">
    <h2>Fund Summary</h2>
    <div class="fr-stats">
        <div class="fr-stat"><div class="lbl">Total Income</div><div class="val">GH&#8373;&nbsp;<?= number_format($grandTotal, 2) ?></div></div>
        <div class="fr-stat"><div class="lbl">Transactions</div><div class="val"><?= number_format($totalTransactions) ?></div></div>
        <div class="fr-stat"><div class="lbl">Average / Transaction</div><div class="val">GH&#8373;&nbsp;<?= number_format($avgTransaction, 2) ?></div></div>
    </div>
    <table>
        <thead><tr><th>Fund</th><th class="r">Transactions</th><th class="r">Total (GH&#8373;)</th><th class="r">% of Total</th></tr></thead>
        <tbody>
        <?php foreach ($byFund as $row):
            $pct = $grandTotal > 0 ? ($row['total'] / $grandTotal) * 100 : 0; ?>
        <tr><td><?= htmlspecialchars($row['name']) ?></td><td class="r"><?= (int)$row['tx_count'] ?></td><td class="r"><?= number_format((float)$row['total'], 2) ?></td><td class="r"><?= number_format($pct, 1) ?>%</td></tr>
        <?php endforeach; ?>
        </tbody>
        <tfoot><tr><th>Grand Total</th><th class="r"><?= number_format($totalTransactions) ?></th><th class="r"><?= number_format($grandTotal, 2) ?></th><th class="r">100%</th></tr></tfoot>
    </table>
</div>
<?php endif; ?>

<?php if (in_array('members', $sections)): ?>
<div class="fr-section">
    <h2>Member Giving</h2>
    <?php if (empty($memberGiving)): ?>
    <p class="fr-no-data">No member giving data for this period.</p>
    <?php else: ?>
    <div class="fr-stats">
        <div class="fr-stat"><div class="lbl">Contributing Members</div><div class="val"><?= count($memberGiving) ?></div></div>
        <div class="fr-stat"><div class="lbl">Total Giving</div><div class="val">GH&#8373;&nbsp;<?= number_format(array_sum(array_column($memberGiving, 'total')), 2) ?></div></div>
    </div>
    <table>
        <thead><tr><th>Member</th><th class="r">Transactions</th><th class="r">Total (GH&#8373;)</th></tr></thead>
        <tbody>
        <?php foreach ($memberGiving as $m): ?>
        <tr><td><?= htmlspecialchars($m['member_name']) ?></td><td class="r"><?= (int)$m['tx_count'] ?></td><td class="r"><?= number_format((float)$m['total'], 2) ?></td></tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>
</div>
<?php endif; ?>

<?php if (in_array('trends', $sections)): ?>
<div class="fr-section">
    <h2>Monthly Income Trends (Last 12 Months)</h2>
    <?php
    $tTotals = array_column($monthlyTrends, 'total');
    $tAvg = count($tTotals) ? array_sum($tTotals) / count($tTotals) : 0;
    ?>
    <div class="fr-stats">
        <div class="fr-stat"><div class="lbl">Monthly Average</div><div class="val">GH&#8373;&nbsp;<?= number_format($tAvg, 2) ?></div></div>
        <div class="fr-stat"><div class="lbl">Highest Month</div><div class="val">GH&#8373;&nbsp;<?= number_format(max($tTotals ?: [0]), 2) ?></div></div>
        <div class="fr-stat"><div class="lbl">Lowest Month</div><div class="val">GH&#8373;&nbsp;<?= number_format(min($tTotals ?: [0]), 2) ?></div></div>
    </div>
    <table>
        <thead><tr><th>Month</th><th class="r">Total (GH&#8373;)</th></tr></thead>
        <tbody>
        <?php foreach ($monthlyTrends as $trend): ?>
        <tr><td><?= htmlspecialchars($trend['month']) ?></td><td class="r"><?= number_format($trend['total'], 2) ?></td></tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php endif; ?>

<?php if (in_array('comparison', $sections)): ?>
<div class="fr-section">
    <h2>Fund Comparison (Last 6 Months)</h2>
    <table>
        <thead>
            <tr><th>Fund</th><?php foreach ($months as $m): ?><th class="r"><?= htmlspecialchars($m) ?></th><?php endforeach; ?><th class="r">6-Month Total</th></tr>
        </thead>
        <tbody>
        <?php foreach ($fundComparison as $fund): ?>
        <tr>
            <td><?= htmlspecialchars($fund['name']) ?></td>
            <?php foreach ($fund['months'] as $mt): ?><td class="r"><?= number_format($mt, 2) ?></td><?php endforeach; ?>
            <td class="r" style="font-weight:600;"><?= number_format(array_sum($fund['months']), 2) ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php endif; ?>

<?php if (in_array('pledge', $sections)): ?>
<div class="fr-section">
    <h2>Pledge vs Giving – <?= $pledgeYear ?></h2>
    <?php if (empty($pledgeVsGiven)): ?>
    <p class="fr-no-data">No pledge data for <?= $pledgeYear ?>.</p>
    <?php else: ?>
    <table>
        <thead><tr><th>Member</th><th class="r">Pledged (GH&#8373;)</th><th class="r">Given (GH&#8373;)</th><th class="r">Difference</th></tr></thead>
        <tbody>
        <?php foreach ($pledgeVsGiven as $row): ?>
        <tr>
            <td><?= htmlspecialchars($row['member_name']) ?></td>
            <td class="r"><?= number_format($row['pledged'], 2) ?></td>
            <td class="r"><?= number_format($row['given'], 2) ?></td>
            <td class="r" style="color:<?= $row['difference'] >= 0 ? '#16a34a' : '#dc2626' ?>;"><?= ($row['difference'] >= 0 ? '+' : '') . number_format($row['difference'], 2) ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>
</div>
<?php endif; ?>

<script>window.addEventListener('load', function(){ window.print(); });</script>
</body></html>
<?php
    exit;
}
// ── End final report ──────────────────────────────────────────────────────

$pageTitle = 'Finance Reports';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="header">
    <h1>Finance Reports</h1>
    <div class="header-actions">
        <button type="button" id="final-report-btn" class="btn btn-primary">Generate Report</button>
        <button type="button" onclick="window.print()" class="btn">Print Report</button>
        <a href="<?= BASE_PATH ?>/finance">Back to Finance</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<div class="card">
    <div class="print-header" style="display: none;">
        <h2 style="margin: 0 0 0.5rem 0;"><?= htmlspecialchars(ucfirst($reportType)) ?> Report</h2>
        <p style="margin: 0; color: #666; font-size: 0.875rem;">
            <?= htmlspecialchars(SITE_FULL_NAME) ?><br>
            Period: <?= date('M j, Y', strtotime($start)) ?> - <?= date('M j, Y', strtotime($end)) ?><br>
            Generated: <?= date('M j, Y g:i A') ?>
        </p>
    </div>
    
    <div class="filter-bar" style="margin-bottom: 1.5rem;">
        <form method="get" style="display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap;">
            <input type="hidden" name="type" value="<?= htmlspecialchars($reportType) ?>">
            <label>From</label>
            <input type="date" name="start" value="<?= htmlspecialchars($start) ?>">
            <label>To</label>
            <input type="date" name="end" value="<?= htmlspecialchars($end) ?>">
            <button type="submit" class="btn btn-sm">Apply</button>
        </form>
    </div>

    <div class="reports-nav" style="display: flex; gap: 0.5rem; border-bottom: 1px solid var(--border, #e5e7eb); margin-bottom: 1.5rem; align-items: center; justify-content: space-between; flex-wrap: wrap;">
        <div style="display: flex; gap: 0.5rem; flex-wrap: wrap;">
            <a href="?type=summary&start=<?= urlencode($start) ?>&end=<?= urlencode($end) ?>" 
               class="report-tab <?= $reportType === 'summary' ? 'active' : '' ?>">Fund Summary</a>
            <a href="?type=members&start=<?= urlencode($start) ?>&end=<?= urlencode($end) ?>" 
               class="report-tab <?= $reportType === 'members' ? 'active' : '' ?>">Member Giving</a>
            <a href="?type=trends&start=<?= urlencode($start) ?>&end=<?= urlencode($end) ?>" 
               class="report-tab <?= $reportType === 'trends' ? 'active' : '' ?>">Trends</a>
            <a href="?type=comparison&start=<?= urlencode($start) ?>&end=<?= urlencode($end) ?>"
               class="report-tab <?= $reportType === 'comparison' ? 'active' : '' ?>">Fund Comparison</a>
            <a href="?type=pledge&year=<?= $pledgeYear ?>"
               class="report-tab <?= $reportType === 'pledge' ? 'active' : '' ?>">Pledge vs giving</a>
        </div>
    </div>

    <?php if ($reportType === 'pledge'): ?>
    <!-- Pledge vs Giving Report -->
    <div class="filter-bar" style="margin-bottom: 1rem;">
        <form method="get" style="display: flex; gap: 0.5rem; align-items: center;">
            <input type="hidden" name="type" value="pledge">
            <label>Year:</label>
            <select name="year" onchange="this.form.submit()">
                <?php for ($y = date('Y'); $y >= date('Y') - 10; $y--): ?>
                <option value="<?= $y ?>" <?= $pledgeYear === $y ? 'selected' : '' ?>><?= $y ?></option>
                <?php endfor; ?>
            </select>
        </form>
    </div>
    <?php if (empty($pledgeVsGiven)): ?>
    <p class="text-muted">No pledge data for <?= $pledgeYear ?>. <a href="<?= BASE_PATH ?>/finance/pledges">Add pledges</a>.</p>
    <?php else: ?>
    <table>
        <thead>
            <tr>
                <th>Member</th>
                <th>Year</th>
                <th style="text-align: right;">Pledged</th>
                <th style="text-align: right;">Given</th>
                <th style="text-align: right;">Difference</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($pledgeVsGiven as $row): ?>
            <tr>
                <td><a href="<?= BASE_PATH ?>/members/view/<?= (int) $row['member_id'] ?>"><?= htmlspecialchars($row['member_name']) ?></a></td>
                <td><?= $pledgeYear ?></td>
                <td style="text-align: right;">GH&#8373; <?= number_format($row['pledged'], 2) ?></td>
                <td style="text-align: right;">GH&#8373; <?= number_format($row['given'], 2) ?></td>
                <td style="text-align: right;">GH&#8373; <?= number_format($row['difference'], 2) ?><?= $row['difference'] >= 0 ? '' : ' (short)' ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <p><a href="<?= BASE_PATH ?>/finance/pledges">Manage pledges</a></p>
    <?php endif; ?>

    <?php elseif ($reportType === 'summary'): ?>
    <!-- Fund Summary Report -->
    <div class="report-summary-stats" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 1.5rem;">
        <div style="padding: 1rem; background: #f8fafc; border-radius: 6px;">
            <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.25rem;">Total Income</div>
            <div style="font-size: 1.5rem; font-weight: 600; color: #1e293b;">GH&#8373; <?= number_format($grandTotal, 2) ?></div>
        </div>
        <div style="padding: 1rem; background: #f8fafc; border-radius: 6px;">
            <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.25rem;">Transactions</div>
            <div style="font-size: 1.5rem; font-weight: 600; color: #1e293b;"><?= number_format($totalTransactions) ?></div>
        </div>
        <div style="padding: 1rem; background: #f8fafc; border-radius: 6px;">
            <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.25rem;">Average</div>
            <div style="font-size: 1.5rem; font-weight: 600; color: #1e293b;">GH&#8373; <?= number_format($avgTransaction, 2) ?></div>
        </div>
    </div>
    <div class="filter-bar" style="margin-bottom: 0.75rem; display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: center; justify-content: space-between;">
        <p class="text-muted" style="margin: 0; font-size: 0.875rem;">
            Use the chart legend to toggle offerings on and off.
        </p>
        <button type="button" class="btn btn-sm btn-secondary" id="summary-fund-filter-btn">
            Choose offerings…
        </button>
    </div>

    <div class="charts-container" style="margin-bottom: 2rem;">
        <div class="chart-wrapper">
            <h3 style="margin-top: 0; margin-bottom: 1rem;">Fund Totals</h3>
            <div style="position: relative; height: 400px; width: 100%;">
                <canvas id="fundBarChart"></canvas>
            </div>
        </div>
    </div>

    <table>
        <thead>
            <tr>
                <th>Fund</th>
                <th style="text-align: right;">Transactions</th>
                <th style="text-align: right;">Total</th>
                <th style="text-align: right;">% of Total</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($byFund as $row): 
                $percentage = $grandTotal > 0 ? ($row['total'] / $grandTotal) * 100 : 0;
            ?>
            <tr>
                <td><?= htmlspecialchars($row['name']) ?></td>
                <td style="text-align: right;"><?= (int)$row['tx_count'] ?></td>
                <td style="text-align: right;">GH&#8373; <?= number_format((float)$row['total'], 2) ?></td>
                <td style="text-align: right;"><?= number_format($percentage, 1) ?>%</td>
            </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot>
            <tr>
                <th>Grand Total</th>
                <th style="text-align: right;"><?= number_format($totalTransactions) ?></th>
                <th style="text-align: right;">GH&#8373; <?= number_format($grandTotal, 2) ?></th>
                <th style="text-align: right;">100%</th>
            </tr>
        </tfoot>
    </table>

    <?php elseif ($reportType === 'members'): ?>
    <!-- Member Giving Report -->
    <?php if (empty($memberGiving)): ?>
    <p class="text-muted">No member giving data available for this period. Member giving is tracked for personal offerings (e.g. tithes).</p>
    <?php else: ?>
    <div class="report-summary-stats" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 1.5rem;">
        <div style="padding: 1rem; background: #f8fafc; border-radius: 6px;">
            <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.25rem;">Total Members</div>
            <div style="font-size: 1.5rem; font-weight: 600; color: #1e293b;"><?= count($memberGiving) ?></div>
        </div>
        <div style="padding: 1rem; background: #f8fafc; border-radius: 6px;">
            <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.25rem;">Total Giving</div>
            <div style="font-size: 1.5rem; font-weight: 600; color: #1e293b;">GH&#8373; <?= number_format(array_sum(array_column($memberGiving, 'total')), 2) ?></div>
        </div>
    </div>

    <div style="margin-bottom: 2rem;">
        <h3 style="margin-top: 0; margin-bottom: 1rem;">Top Givers</h3>
        <div style="position: relative; height: 400px; width: 100%;">
            <canvas id="memberBarChart"></canvas>
        </div>
    </div>

    <table>
        <thead>
            <tr>
                <th>Member</th>
                <th style="text-align: right;">Transactions</th>
                <th style="text-align: right;">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($memberGiving as $m): ?>
            <tr>
                <td><?= htmlspecialchars($m['member_name']) ?></td>
                <td style="text-align: right;"><?= (int)$m['tx_count'] ?></td>
                <td style="text-align: right;">GH&#8373; <?= number_format((float)$m['total'], 2) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>

    <?php elseif ($reportType === 'trends'): ?>
    <!-- Trends Report -->
    <div class="report-summary-stats" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 1.5rem;">
        <div style="padding: 1rem; background: #f8fafc; border-radius: 6px;">
            <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.25rem;">Average Monthly</div>
            <div style="font-size: 1.5rem; font-weight: 600; color: #1e293b;">GH&#8373; <?= number_format(array_sum(array_column($monthlyTrends, 'total')) / max(count($monthlyTrends), 1), 2) ?></div>
        </div>
        <div style="padding: 1rem; background: #f8fafc; border-radius: 6px;">
            <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.25rem;">Highest Month</div>
            <div style="font-size: 1.5rem; font-weight: 600; color: #1e293b;">GH&#8373; <?= number_format(max(array_column($monthlyTrends, 'total')), 2) ?></div>
        </div>
        <div style="padding: 1rem; background: #f8fafc; border-radius: 6px;">
            <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.25rem;">Lowest Month</div>
            <div style="font-size: 1.5rem; font-weight: 600; color: #1e293b;">GH&#8373; <?= number_format(min(array_column($monthlyTrends, 'total')), 2) ?></div>
        </div>
    </div>

    <div style="margin-bottom: 2rem;">
        <h3 style="margin-top: 0; margin-bottom: 1rem;">Monthly Income Trends (Last 12 Months)</h3>
        <div style="position: relative; height: 400px; width: 100%;">
            <canvas id="trendsLineChart"></canvas>
        </div>
    </div>

    <table>
        <thead>
            <tr>
                <th>Month</th>
                <th style="text-align: right;">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($monthlyTrends as $trend): ?>
            <tr>
                <td><?= htmlspecialchars($trend['month']) ?></td>
                <td style="text-align: right;">GH&#8373; <?= number_format($trend['total'], 2) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <?php elseif ($reportType === 'comparison'): ?>
    <!-- Fund Comparison Report -->
    <div style="margin-bottom: 2rem;">
        <h3 style="margin-top: 0; margin-bottom: 1rem;">Fund Performance Comparison (Last 6 Months)</h3>
        <div style="position: relative; height: 400px; width: 100%;">
            <canvas id="comparisonChart"></canvas>
        </div>
    </div>

    <table>
        <thead>
            <tr>
                <th>Fund</th>
                <?php foreach ($months as $month): ?>
                <th style="text-align: right;"><?= htmlspecialchars($month) ?></th>
                <?php endforeach; ?>
                <th style="text-align: right;">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($fundComparison as $fund): ?>
            <tr>
                <td><?= htmlspecialchars($fund['name']) ?></td>
                <?php foreach ($fund['months'] as $monthTotal): ?>
                <td style="text-align: right;">GH&#8373; <?= number_format($monthTotal, 2) ?></td>
                <?php endforeach; ?>
                <td style="text-align: right; font-weight: 600;">GH&#8373; <?= number_format(array_sum($fund['months']), 2) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
window.addEventListener('DOMContentLoaded', function() {
    var fundData = <?= json_encode(array_map(function($f) { return ['id' => (int)$f['id'], 'name' => $f['name'], 'total' => (float)$f['total']]; }, $byFund)) ?>;
    var memberData = <?= json_encode(array_map(function($m) { return ['name' => $m['member_name'], 'total' => (float)$m['total']]; }, array_slice($memberGiving, 0, 10))) ?>;
    var trendsData = <?= json_encode($monthlyTrends) ?>;
    var comparisonData = <?= json_encode($fundComparison) ?>;
    var months = <?= json_encode($months) ?>;
    var selectedSummaryFundIds = <?= json_encode($summaryFundIds) ?>;

    // Colors
    var colors = ['#2563eb', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#06b6d4', '#84cc16'];

    <?php if ($reportType === 'summary'): ?>
    // Fund Bar Chart with legend per offering (one dataset per fund)
    var barCtx = document.getElementById('fundBarChart');
    if (barCtx) {
        var barDatasets = fundData
            .filter(function(f) {
                if (!selectedSummaryFundIds || !selectedSummaryFundIds.length) return true;
                return selectedSummaryFundIds.indexOf(f.id) !== -1;
            })
            .map(function(f, idx) {
            return {
                label: f.name,
                data: [f.total],
                backgroundColor: colors[idx % colors.length]
            };
        });
        new Chart(barCtx, {
            type: 'bar',
            data: {
                labels: ['Total'],
                datasets: barDatasets
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                aspectRatio: 1.6,
                scales: {
                    x: {
                        beginAtZero: true,
                        ticks: {
                            maxTicksLimit: 8,
                            font: { size: 11 },
                            callback: function(value) {
                                return 'GH₵ ' + value.toLocaleString('en-US', {minimumFractionDigits: 0, maximumFractionDigits: 0});
                            }
                        }
                    },
                    y: {
                        ticks: {
                            font: { size: 11 }
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: true,
                        position: 'bottom',
                        labels: { padding: 12, boxWidth: 12, font: { size: 11 } }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.dataset.label + ': GH₵ ' + context.parsed.y.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                            }
                        }
                    }
                }
            }
        });
    }
    <?php endif; ?>

    <?php if ($reportType === 'members' && !empty($memberGiving)): ?>
    // Member Bar Chart
    var memberCtx = document.getElementById('memberBarChart');
    if (memberCtx) {
        new Chart(memberCtx, {
            type: 'bar',
            data: {
                labels: memberData.map(m => m.name.length > 20 ? m.name.substring(0, 20) + '...' : m.name),
                datasets: [{
                    label: 'Total Giving (GH₵)',
                    data: memberData.map(m => m.total),
                    backgroundColor: colors[1]
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                aspectRatio: 1.5,
                indexAxis: 'y',
                scales: {
                    x: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return 'GH₵ ' + value.toLocaleString('en-US', {minimumFractionDigits: 0, maximumFractionDigits: 0});
                            }
                        }
                    }
                },
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return 'GH₵ ' + context.parsed.x.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                            }
                        }
                    }
                }
            }
        });
    }
    <?php endif; ?>

    <?php if ($reportType === 'trends'): ?>
    // Trends Line Chart
    var trendsCtx = document.getElementById('trendsLineChart');
    if (trendsCtx) {
        new Chart(trendsCtx, {
            type: 'line',
            data: {
                labels: trendsData.map(t => t.month),
                datasets: [{
                    label: 'Monthly Income (GH₵)',
                    data: trendsData.map(t => t.total),
                    borderColor: colors[0],
                    backgroundColor: colors[0] + '20',
                    fill: true,
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                aspectRatio: 2,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return 'GH₵ ' + value.toLocaleString('en-US', {minimumFractionDigits: 0, maximumFractionDigits: 0});
                            }
                        }
                    }
                },
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: { padding: 15, boxWidth: 12 }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return 'GH₵ ' + context.parsed.y.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                            }
                        }
                    }
                }
            }
        });
    }
    <?php endif; ?>

    <?php if ($reportType === 'comparison'): ?>
    // Comparison Chart
    var compCtx = document.getElementById('comparisonChart');
    if (compCtx) {
        new Chart(compCtx, {
            type: 'line',
            data: {
                labels: months,
                datasets: comparisonData.map((fund, idx) => ({
                    label: fund.name,
                    data: fund.months,
                    borderColor: colors[idx % colors.length],
                    backgroundColor: colors[idx % colors.length] + '20',
                    fill: false,
                    tension: 0.4
                }))
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                aspectRatio: 2,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return 'GH₵ ' + value.toLocaleString('en-US', {minimumFractionDigits: 0, maximumFractionDigits: 0});
                            }
                        }
                    }
                },
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: { padding: 15, boxWidth: 12 }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.dataset.label + ': GH₵ ' + context.parsed.y.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                            }
                        }
                    }
                }
            }
        });
    }
    <?php endif; ?>

    // Modal for choosing which offerings to include in summary chart
    var summaryBtn = document.getElementById('summary-fund-filter-btn');
    var summaryModal = document.getElementById('summary-fund-filter-modal');
    if (summaryBtn && summaryModal) {
        var backdrop = summaryModal.querySelector('.modal-backdrop');
        var closeBtn = summaryModal.querySelector('[data-summary-fund-close]');
        summaryBtn.addEventListener('click', function() {
            summaryModal.hidden = false;
        });
        function closeModal() { summaryModal.hidden = true; }
        if (backdrop) backdrop.addEventListener('click', closeModal);
        if (closeBtn) closeBtn.addEventListener('click', closeModal);
    }
});
</script>

<style>
.report-tab {
    padding: 0.5rem 1rem;
    text-decoration: none;
    color: var(--text, #334155);
    border-bottom: 2px solid transparent;
    transition: all 0.2s;
}
.report-tab:hover {
    color: var(--primary, #2563eb);
    border-bottom-color: var(--primary, #2563eb);
}
.report-tab.active {
    color: var(--primary, #2563eb);
    border-bottom-color: var(--primary, #2563eb);
    font-weight: 600;
}

#summary-fund-filter-modal .modal-content {
    max-width: 480px;
    width: 95%;
    display: flex;
    flex-direction: column;
    max-height: 82vh;
    padding: 1.5rem;
}
#summary-fund-filter-modal .sff-header {
    margin-bottom: 0.25rem;
}
#summary-fund-filter-modal .sff-desc {
    font-size: 0.8125rem;
    color: var(--text-muted, #64748b);
    margin: 0 0 1rem;
    line-height: 1.5;
}
#summary-fund-filter-modal .sff-toggle-row {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding-bottom: 0.65rem;
    margin-bottom: 0.65rem;
    border-bottom: 1px solid var(--border, #e5e7eb);
    cursor: pointer;
    font-size: 0.875rem;
    font-weight: 600;
    color: var(--text, #1e293b);
    user-select: none;
}
#summary-fund-filter-modal .sff-toggle-row input[type="checkbox"] {
    width: 15px;
    height: 15px;
    flex-shrink: 0;
    margin: 0;
    cursor: pointer;
    accent-color: var(--primary, #2563eb);
}
#summary-fund-filter-modal .sff-scroll {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    margin: 0 -0.25rem;
    padding: 0 0.25rem;
}
#summary-fund-filter-modal .sff-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 0.1rem 0.5rem;
}
#summary-fund-filter-modal .sff-item {
    display: flex;
    align-items: center;
    gap: 0.45rem;
    padding: 0.3rem 0.4rem;
    border-radius: 5px;
    cursor: pointer;
    font-size: 0.875rem;
    color: var(--text, #1e293b);
    transition: background 0.12s;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
#summary-fund-filter-modal .sff-item:hover {
    background: var(--bg, #f1f5f9);
}
#summary-fund-filter-modal .sff-item input[type="checkbox"] {
    width: 14px;
    height: 14px;
    flex-shrink: 0;
    margin: 0;
    cursor: pointer;
    accent-color: var(--primary, #2563eb);
}
#summary-fund-filter-modal .sff-item span {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    pointer-events: none;
}
#summary-fund-filter-modal .sff-footer {
    margin-top: 1rem;
    padding-top: 0.75rem;
    border-top: 1px solid var(--border, #e5e7eb);
    display: flex;
    gap: 0.5rem;
    justify-content: flex-end;
}

/* Print Styles */
@media print {
    body {
        background: white;
    }
    
    .sidebar,
    .header-actions,
    .filter-bar,
    .reports-nav,
    button,
    .btn,
    a[href]:not(.print-link) {
        display: none !important;
    }
    
    .main {
        margin: 0;
        padding: 0;
        max-width: 100%;
    }
    
    .card {
        box-shadow: none;
        border: none;
        padding: 0;
        margin: 0;
        page-break-inside: avoid;
    }
    
    .header {
        margin-bottom: 1rem;
        padding-bottom: 0.5rem;
        border-bottom: 2px solid #000;
    }
    
    .header h1 {
        margin: 0;
        font-size: 1.5rem;
    }
    
    .header::after {
        content: "Period: <?= date('M j, Y', strtotime($start)) ?> - <?= date('M j, Y', strtotime($end)) ?>";
        display: block;
        margin-top: 0.5rem;
        font-size: 0.875rem;
        color: #666;
    }
    
    .print-header {
        display: block !important;
        margin-bottom: 1.5rem;
        padding-bottom: 1rem;
        border-bottom: 2px solid #000;
    }
    
    .print-header h2 {
        font-size: 1.25rem;
        margin-bottom: 0.5rem;
    }
    
    .report-summary-stats {
        page-break-inside: avoid;
        margin-bottom: 1rem;
    }
    
    /* Hide charts in print - show detailed tables instead */
    canvas,
    .chart-wrapper,
    div[style*="position: relative"][style*="height"],
    .charts-container {
        display: none !important;
    }
    
    /* Hide chart headings when chart is hidden */
    h3:has(+ div[style*="position: relative"]) {
        display: none !important;
    }
    
    /* Enhanced table styling for print */
    table {
        width: 100%;
        border-collapse: collapse;
        page-break-inside: auto;
        margin-bottom: 1.5rem;
        font-size: 0.875rem;
    }
    
    table thead {
        display: table-header-group;
        background-color: #f5f5f5;
    }
    
    table tbody tr {
        page-break-inside: avoid;
    }
    
    table tbody tr:nth-child(even) {
        background-color: #fafafa;
    }
    
    table th,
    table td {
        border: 1px solid #333;
        padding: 0.5rem 0.75rem;
        text-align: left;
    }
    
    table th {
        background-color: #e5e5e5 !important;
        font-weight: 700;
        color: #000;
    }
    
    table tfoot th {
        background-color: #d0d0d0 !important;
        font-weight: 700;
        border-top: 2px solid #000;
    }
    
    table td[style*="text-align: right"],
    table th[style*="text-align: right"] {
        text-align: right !important;
    }
    
    h2, h3 {
        page-break-after: avoid;
        margin-top: 1rem;
        margin-bottom: 0.5rem;
        font-size: 1.125rem;
    }
    
    @page {
        margin: 1.5cm;
        size: A4 landscape;
    }
    
    .table-wrap {
        overflow: visible;
    }
}
</style>

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

<?php if ($reportType === 'summary'): ?>
<div id="summary-fund-filter-modal" class="modal" role="dialog" aria-modal="true" aria-labelledby="summary-fund-filter-title" hidden>
    <div class="modal-backdrop"></div>
    <div class="modal-content">
        <div class="sff-header">
            <h2 id="summary-fund-filter-title" class="modal-heading" style="margin:0;">Choose offerings to show</h2>
        </div>
        <p class="sff-desc">Select which offerings appear in the Fund Totals chart.</p>
        <form method="post" style="flex:1;min-height:0;display:flex;flex-direction:column;">
            <input type="hidden" name="form_section" value="summary_fund_filter">
            <label class="sff-toggle-row">
                <input type="checkbox" id="summary-fund-all-toggle" <?= empty($summaryFundIds) ? 'checked' : '' ?>>
                <span>All offerings</span>
            </label>
            <div class="sff-scroll">
                <div class="sff-grid">
                    <?php foreach ($funds as $fund): ?>
                    <label class="sff-item">
                        <input type="checkbox" class="summary-fund-checkbox" name="summary_fund_ids[]" value="<?= (int)$fund['id'] ?>"
                            <?= (empty($summaryFundIds) || in_array((int)$fund['id'], $summaryFundIds, true)) ? 'checked' : '' ?>>
                        <span><?= htmlspecialchars($fund['name']) ?></span>
                    </label>
                    <?php endforeach; ?>
                </div>
            </div>
            <div class="sff-footer">
                <button type="submit" class="btn">Save</button>
                <button type="button" class="btn btn-ghost" data-summary-fund-close>Cancel</button>
            </div>
        </form>
        <script>
        (function() {
            var allToggle = document.getElementById('summary-fund-all-toggle');
            var checkboxes = document.querySelectorAll('.summary-fund-checkbox');
            if (!allToggle || !checkboxes.length) return;
            allToggle.addEventListener('change', function() {
                checkboxes.forEach(function(cb) { cb.checked = allToggle.checked; });
            });
            checkboxes.forEach(function(cb) {
                cb.addEventListener('change', function() {
                    var allChecked = Array.from(checkboxes).every(function(c) { return c.checked; });
                    allToggle.checked = allChecked;
                });
            });
        })();
        </script>
    </div>
</div>
<?php endif; ?>

<!-- Generate Final Report Modal -->
<div id="final-report-modal" class="modal" role="dialog" aria-modal="true" aria-labelledby="final-report-title" hidden>
    <div class="modal-backdrop" id="final-report-backdrop"></div>
    <div class="modal-content" style="max-width:460px;width:95%;">
        <h2 id="final-report-title" class="modal-heading" style="margin-bottom:0.25rem;">Generate Financial Report</h2>
        <p style="font-size:0.8125rem;color:var(--text-muted,#64748b);margin:0 0 1.25rem;">Choose a date range and sections to include. The report opens in a new window, ready to print or save as PDF.</p>

        <div style="display:flex;flex-direction:column;gap:1.1rem;">
            <div>
                <div style="font-size:0.8rem;font-weight:600;text-transform:uppercase;letter-spacing:.05em;color:var(--text-muted,#64748b);margin-bottom:0.5rem;">Date Range</div>
                <div style="display:flex;align-items:center;gap:0.5rem;flex-wrap:wrap;">
                    <label style="font-size:0.875rem;color:var(--text,#1e293b);">From</label>
                    <input type="date" id="fr-start" value="<?= htmlspecialchars($start) ?>" style="padding:0.4rem 0.6rem;border:1px solid #d1d5db;border-radius:5px;font-size:0.875rem;color:var(--text,#1e293b);background:#fff;">
                    <label style="font-size:0.875rem;color:var(--text,#1e293b);">To</label>
                    <input type="date" id="fr-end" value="<?= htmlspecialchars($end) ?>" style="padding:0.4rem 0.6rem;border:1px solid #d1d5db;border-radius:5px;font-size:0.875rem;color:var(--text,#1e293b);background:#fff;">
                </div>
            </div>

            <div>
                <div style="font-size:0.8rem;font-weight:600;text-transform:uppercase;letter-spacing:.05em;color:var(--text-muted,#64748b);margin-bottom:0.6rem;">Sections to include</div>
                <div id="fr-sections-list" style="display:flex;flex-direction:column;gap:0.25rem;">
                    <?php
                    $sectionOptions = [
                        'summary'    => 'Fund Summary — totals and breakdown by offering',
                        'members'    => 'Member Giving — individual giving breakdown',
                        'trends'     => 'Monthly Trends — last 12 months',
                        'comparison' => 'Fund Comparison — last 6 months side by side',
                        'pledge'     => 'Pledge vs Giving — ' . $pledgeYear,
                    ];
                    foreach ($sectionOptions as $val => $label):
                    ?>
                    <label style="display:flex;align-items:flex-start;gap:0.5rem;padding:0.45rem 0.55rem;border-radius:6px;cursor:pointer;transition:background .12s;">
                        <input type="checkbox" class="fr-section-cb" value="<?= $val ?>" <?= $val === 'summary' ? 'checked' : '' ?> style="width:14px;height:14px;margin-top:2px;flex-shrink:0;accent-color:var(--primary,#2563eb);">
                        <span style="font-size:0.875rem;color:var(--text,#1e293b);line-height:1.4;"><?= htmlspecialchars($label) ?></span>
                    </label>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <div style="margin-top:1.25rem;padding-top:0.85rem;border-top:1px solid var(--border,#e5e7eb);display:flex;gap:0.5rem;justify-content:flex-end;">
            <button type="button" id="fr-generate-btn" class="btn btn-primary">Open Report</button>
            <button type="button" id="fr-cancel-btn" class="btn btn-ghost">Cancel</button>
        </div>
    </div>
</div>

<style>
#fr-sections-list label:hover { background: var(--bg, #f1f5f9); }
</style>

<script>
(function() {
    var openBtn   = document.getElementById('final-report-btn');
    var modal     = document.getElementById('final-report-modal');
    var backdrop  = document.getElementById('final-report-backdrop');
    var cancelBtn = document.getElementById('fr-cancel-btn');
    var genBtn    = document.getElementById('fr-generate-btn');
    if (!openBtn || !modal) return;

    function openModal()  { modal.hidden = false; }
    function closeModal() { modal.hidden = true; }

    openBtn.addEventListener('click', openModal);
    cancelBtn.addEventListener('click', closeModal);
    backdrop.addEventListener('click', closeModal);
    document.addEventListener('keydown', function(e) { if (e.key === 'Escape' && !modal.hidden) closeModal(); });

    genBtn.addEventListener('click', function() {
        var start    = document.getElementById('fr-start').value;
        var end      = document.getElementById('fr-end').value;
        var checked  = document.querySelectorAll('.fr-section-cb:checked');
        var sections = Array.from(checked).map(function(cb) { return 'sections[]=' + encodeURIComponent(cb.value); });

        if (!sections.length) { alert('Please select at least one section.'); return; }
        if (!start || !end)   { alert('Please choose a date range.');          return; }

        var url = '<?= BASE_PATH ?>/finance/reports?type=final'
                + '&start=' + encodeURIComponent(start)
                + '&end='   + encodeURIComponent(end)
                + '&'       + sections.join('&');

        window.open(url, '_blank');
        closeModal();
    });
})();
</script>
