<?php //ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
// finance_reports_data.php — self-contained report generator

// === CONFIG / CONNECTION ===
if (!empty($_REQUEST['tenant'])) {
    if (file_exists('../../../../' . $_REQUEST['tenant'] . '/config.php')) {
        require_once('../../../../' . $_REQUEST['tenant'] . '/config.php');
    }
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

// Helpers (client/broker/agent names etc.) – local include
require_once('../finance_functions.php');

// === INPUTS ===
$typeKey  = trim($_REQUEST['type']  ?? '');
$startStr = trim($_REQUEST['start'] ?? '');
$endStr   = trim($_REQUEST['end']   ?? '');

// === DATE PARSING (robust, DMY -> Unix) ===
if (!function_exists('fr_parse_dmy_to_unix')) {
    function fr_parse_dmy_to_unix(string $dmy): int
    {
        $dmy = trim($dmy);
        if ($dmy === '') return 0;

        $dmy = str_replace('/', '-', $dmy);
        $parts = explode('-', $dmy);
        if (count($parts) !== 3) return 0;

        [$d, $m, $y] = $parts;
        $d = (int)$d;
        $m = (int)$m;
        $y = (int)$y;

        if ($y < 100) {
            $y += 2000;
        }

        return (int)strtotime(sprintf('%04d-%02d-%02d 00:00:00', $y, $m, $d));
    }
}

$startUnix = fr_parse_dmy_to_unix($startStr);
$endUnix   = fr_parse_dmy_to_unix($endStr);

// Make end inclusive (end-of-day)
if ($endUnix > 0) {
    $endUnix += 86399;
}

// If both fail, treat as "all dates"
if ($startUnix === 0 && $endUnix === 0) {
    $startUnix = 0;
    $endUnix   = PHP_INT_MAX;
}

// === RANGE CHECK HELPER ===
if (!function_exists('fr_in_range')) {
    function fr_in_range(int $ts, int $start, int $end): bool
    {
        if ($start === 0 && $end === PHP_INT_MAX) return true;
        return ($ts >= $start && $ts <= $end);
    }
}

// === SAFETY ===
if (empty($GLOBALS['con'])) {
    echo '<div class="alert alert-danger">Database connection not available.</div>';
    exit;
}

// === LOCAL HELPERS ===
if (!function_exists('fr_format_money')) {
    function fr_format_money($value): string {
        $v = (float)$value;
        return '£' . number_format($v, 2);
    }
}

if (!function_exists('fr_parse_totals')) {
    function fr_parse_totals(string $totals): array {
        $parts = explode('|', $totals);
        $net = isset($parts[0]) ? (float)str_replace([',', ' '], '', $parts[0]) : 0.0;
        $vat = isset($parts[1]) ? (float)str_replace([',', ' '], '', $parts[1]) : 0.0;
        return [$net, $vat];
    }
}

if (!function_exists('fr_invoice_status_label')) {
    function fr_invoice_status_label(int $status): string {
        switch ($status) {
            case 1: return 'Unpaid';
            case 2: return 'Reminder';
            case 3: return 'Paid';
            case 4: return 'Refund';
            case 5: return 'Archived';
            default: return 'Unknown';
        }
    }
}

if (!function_exists('fr_safe_client_name')) {
    function fr_safe_client_name($id): string {
        if (function_exists('getClientName')) {
            return getClientName($id);
        }
        return (string)$id;
    }
}

// === TYPE MAP ===
$label = '';
switch ($typeKey) {
    case 'inv_paid':
        $label = 'Invoices – Paid';
        break;
    case 'inv_outstanding':
        $label = 'Invoices – Outstanding';
        break;
    case 'inv_all':
        $label = 'Invoices – All';
        break;
    case 'outgoings':
        $label = 'Expenses / Outgoings';
        break;
    case 'outgoings_by_category':
        $label = 'Expenses – By Category';
        break;
    case 'receipts':
        $label = 'Receipts';
        break;
    case 'receipts_by_category':
        $label = 'Receipts – By Payee';
        break;
    case 'vat_in':
        $label = 'VAT – Income (Receipts)';
        break;
    case 'vat_out':
        $label = 'VAT – Outgoing (Expenses)';
        break;
    default:
        $label = 'Unknown report type';
        break;
}

// === TOTALS ===
$nTotal = 0.0;  // net
$vTotal = 0.0;  // vat

?>
<p id="exportTitle" class="lead reportHeader noporint">
    <?php echo htmlspecialchars($label); ?> for the period
    <strong><?php echo $startStr !== '' ? htmlspecialchars($startStr) : 'All dates'; ?></strong>
    to
    <strong><?php echo $endStr !== '' ? htmlspecialchars($endStr) : 'All dates'; ?></strong>
</p>
<div id="expenseData">


    <?php
    // === ROUTE BY TYPE ===
    switch ($typeKey) {

        // -----------------------
        // INVOICES – PAID
        // -----------------------
        case 'inv_paid':
            ?>
    <table class="table table-striped table-hover table-sm align-middle">
        <thead class="table-dark">
            <tr>
                <th>Invoice #</th>
                <th>Client</th>
                <th>Date</th>
                <th>Due</th>
                <th>Status</th>
                <th class="text-end">Net</th>
                <th class="text-end">VAT</th>
                <th class="text-end">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php
                $stmt = $GLOBALS['con']->prepare("
                    SELECT invNo, client, date, date_due, status, totals
                    FROM invoices
                    WHERE status = 3
                    ORDER BY date ASC, invNo ASC
                ");
                $stmt->execute();
                $res = $stmt->get_result();
                $stmt->close();

                $hasRows = false;
                while ($row = $res->fetch_assoc()) {
                    $ts = (int)$row['date'];
                    if (!fr_in_range($ts, $startUnix, $endUnix)) continue;

                    $hasRows = true;
                    [$net, $vat] = fr_parse_totals($row['totals']);
                    $total = $net + $vat;
                    $nTotal += $net;
                    $vTotal += $vat;
                    ?>
            <tr>
                <td><?php echo sprintf('%06d', (int)$row['invNo']); ?></td>
                <td><?php echo htmlspecialchars(fr_safe_client_name($row['client'])); ?></td>
                <td><?php echo date('d-m-Y', $ts); ?></td>
                <td><?php echo $row['date_due'] ? date('d-m-Y', (int)$row['date_due']) : '-'; ?></td>
                <td><?php echo htmlspecialchars(fr_invoice_status_label((int)$row['status'])); ?></td>
                <td class="text-end"><?php echo fr_format_money($net); ?></td>
                <td class="text-end"><?php echo fr_format_money($vat); ?></td>
                <td class="text-end"><?php echo fr_format_money($total); ?></td>
            </tr>
            <?php
                }
                if (!$hasRows) {
                    echo '<tr><td colspan="8" class="text-center text-muted">No invoices found in this range.</td></tr>';
                }
                ?>
        </tbody>
    </table>
    <?php
            break;

        // -----------------------
        // INVOICES – OUTSTANDING
        // -----------------------
        case 'inv_outstanding':
            ?>
    <table class="table table-striped table-hover table-sm align-middle">
        <thead class="table-dark">
            <tr>
                <th>Invoice #</th>
                <th>Client</th>
                <th>Date</th>
                <th>Due</th>
                <th>Status</th>
                <th class="text-end">Net</th>
                <th class="text-end">VAT</th>
                <th class="text-end">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php
                $stmt = $GLOBALS['con']->prepare("
                    SELECT invNo, client, date, date_due, status, totals
                    FROM invoices
                    WHERE status IN (1, 2)
                    ORDER BY date ASC, invNo ASC
                ");
                $stmt->execute();
                $res = $stmt->get_result();
                $stmt->close();

                $hasRows = false;
                while ($row = $res->fetch_assoc()) {
                    $ts = (int)$row['date'];
                    if (!fr_in_range($ts, $startUnix, $endUnix)) continue;

                    $hasRows = true;
                    [$net, $vat] = fr_parse_totals($row['totals']);
                    $total = $net + $vat;
                    $nTotal += $net;
                    $vTotal += $vat;
                    ?>
            <tr>
                <td><?php echo sprintf('%06d', (int)$row['invNo']); ?></td>
                <td><?php echo htmlspecialchars(fr_safe_client_name($row['client'])); ?></td>
                <td><?php echo date('d-m-Y', $ts); ?></td>
                <td><?php echo $row['date_due'] ? date('d-m-Y', (int)$row['date_due']) : '-'; ?></td>
                <td><?php echo htmlspecialchars(fr_invoice_status_label((int)$row['status'])); ?></td>
                <td class="text-end"><?php echo fr_format_money($net); ?></td>
                <td class="text-end"><?php echo fr_format_money($vat); ?></td>
                <td class="text-end"><?php echo fr_format_money($total); ?></td>
            </tr>
            <?php
                }
                if (!$hasRows) {
                    echo '<tr><td colspan="8" class="text-center text-muted">No invoices found in this range.</td></tr>';
                }
                ?>
        </tbody>
    </table>
    <?php
            break;

        // -----------------------
        // INVOICES – ALL
        // -----------------------
        case 'inv_all':
            ?>
    <table class="table table-striped table-hover table-sm align-middle">
        <thead class="table-dark">
            <tr>
                <th>Invoice #</th>
                <th>Client</th>
                <th>Date</th>
                <th>Due</th>
                <th>Status</th>
                <th class="text-end">Net</th>
                <th class="text-end">VAT</th>
                <th class="text-end">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php
                $stmt = $GLOBALS['con']->prepare("
                    SELECT invNo, client, date, date_due, status, totals
                    FROM invoices
                    ORDER BY date ASC, invNo ASC
                ");
                $stmt->execute();
                $res = $stmt->get_result();
                $stmt->close();

                $hasRows = false;
                while ($row = $res->fetch_assoc()) {
                    $ts = (int)$row['date'];
                    if (!fr_in_range($ts, $startUnix, $endUnix)) continue;

                    $hasRows = true;
                    [$net, $vat] = fr_parse_totals($row['totals']);
                    $total = $net + $vat;
                    $nTotal += $net;
                    $vTotal += $vat;
                    ?>
            <tr>
                <td><?php echo sprintf('%06d', (int)$row['invNo']); ?></td>
                <td><?php echo htmlspecialchars(fr_safe_client_name($row['client'])); ?></td>
                <td><?php echo date('d-m-Y', $ts); ?></td>
                <td><?php echo $row['date_due'] ? date('d-m-Y', (int)$row['date_due']) : '-'; ?></td>
                <td><?php echo htmlspecialchars(fr_invoice_status_label((int)$row['status'])); ?></td>
                <td class="text-end"><?php echo fr_format_money($net); ?></td>
                <td class="text-end"><?php echo fr_format_money($vat); ?></td>
                <td class="text-end"><?php echo fr_format_money($total); ?></td>
            </tr>
            <?php
                }
                if (!$hasRows) {
                    echo '<tr><td colspan="8" class="text-center text-muted">No invoices found in this range.</td></tr>';
                }
                ?>
        </tbody>
    </table>
    <?php
            break;

        // -----------------------
        // OUTGOINGS (EXPENSES)
        // -----------------------
        case 'outgoings':
            ?>
    <table class="table table-striped table-hover table-sm align-middle">
        <thead class="table-dark">
            <tr>
                <th>ID</th>
                <th>Date</th>
                <th>Employee</th>
                <th>Type</th>
                <th>Description</th>
                <th class="text-end">Net</th>
                <th class="text-end">VAT</th>
                <th class="text-end">Total</th>
                <th>Payment type</th>
            </tr>
        </thead>
        <tbody>
            <?php
                $stmt = $GLOBALS['con']->prepare("
                    SELECT id, employee, `type`, `desc`, `date`, totals, payment_type
                    FROM expenses
                    ORDER BY `date` ASC, id ASC
                ");
                $stmt->execute();
                $res = $stmt->get_result();
                $stmt->close();

                $hasRows = false;
                while ($row = $res->fetch_assoc()) {
                    $ts = (int)$row['date'];
                    if (!fr_in_range($ts, $startUnix, $endUnix)) continue;

                    $hasRows = true;
                    [$net, $vat] = fr_parse_totals($row['totals']);
                    $total = $net + $vat;
                    $nTotal += $net;
                    $vTotal += $vat;
                    ?>
            <tr>
                <td><?php echo (int)$row['id']; ?></td>
                <td><?php echo date('d-m-Y', $ts); ?></td>
                <td><?php echo htmlspecialchars($row['employee']); ?></td>
                <td><?php echo htmlspecialchars($row['type']); ?></td>
                <td><?php echo htmlspecialchars($row['desc']); ?></td>
                <td class="text-end"><?php echo fr_format_money($net); ?></td>
                <td class="text-end"><?php echo fr_format_money($vat); ?></td>
                <td class="text-end"><?php echo fr_format_money($total); ?></td>
                <td><?php echo htmlspecialchars($row['payment_type']); ?></td>
            </tr>
            <?php
                }
                if (!$hasRows) {
                    echo '<tr><td colspan="9" class="text-center text-muted">No expenses found in this range.</td></tr>';
                }
                ?>
        </tbody>
    </table>
    <?php
            break;

        // -----------------------
        // OUTGOINGS BY CATEGORY (payment_type = 'Expenses', grouped by type)
        // -----------------------
        case 'outgoings_by_category':
            $byType = [];

            $stmt = $GLOBALS['con']->prepare("
                SELECT id, employee, `type`, `desc`, `date`, totals, payment_type
                FROM expenses
                WHERE payment_type = 'Expenses'
                ORDER BY `type` ASC, `date` ASC, id ASC
            ");
            $stmt->execute();
            $res = $stmt->get_result();
            $stmt->close();

            while ($row = $res->fetch_assoc()) {
                $ts = (int)$row['date'];
                if (!fr_in_range($ts, $startUnix, $endUnix)) continue;

                $typeName = $row['type'] ?: 'Uncategorised';
                [$net, $vat] = fr_parse_totals($row['totals']);

                if (!isset($byType[$typeName])) {
                    $byType[$typeName] = [];
                }
                $byType[$typeName][] = [
                    'id'           => (int)$row['id'],
                    'date'         => $ts,
                    'employee'     => $row['employee'],
                    'desc'         => $row['desc'],
                    'payment_type' => $row['payment_type'],
                    'net'          => $net,
                    'vat'          => $vat,
                    'total'        => $net + $vat,
                ];

                $nTotal += $net;
                $vTotal += $vat;
            }

            if (!empty($byType)) {
                ksort($byType, SORT_NATURAL | SORT_FLAG_CASE);
            }

            if (empty($byType)) {
                echo '<div class="alert alert-info">No expenses with payment type "Expenses" found in the selected range.</div>';
            } else {
                foreach ($byType as $typeName => $rows) {
                    $typeNet   = 0.0;
                    $typeVat   = 0.0;
                    $typeTotal = 0.0;

                    echo '<h5 class="mt-3 mb-2">' . htmlspecialchars($typeName) . '</h5>';
                    ?>
    <table class="table table-striped table-hover table-sm align-middle mb-3">
        <thead class="table-dark">
            <tr>
                <th>ID</th>
                <th>Date</th>
                <th>Employee</th>
                <th>Description</th>
                <th class="text-end">Net</th>
                <th class="text-end">VAT</th>
                <th class="text-end">Total</th>
                <th>Payment type</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($rows as $row):
                            $typeNet   += $row['net'];
                            $typeVat   += $row['vat'];
                            $typeTotal += $row['total']; ?>
            <tr>
                <td><?php echo $row['id']; ?></td>
                <td><?php echo date('d-m-Y', $row['date']); ?></td>
                <td><?php echo htmlspecialchars($row['employee']); ?></td>
                <td><?php echo htmlspecialchars($row['desc']); ?></td>
                <td class="text-end"><?php echo fr_format_money($row['net']); ?></td>
                <td class="text-end"><?php echo fr_format_money($row['vat']); ?></td>
                <td class="text-end"><?php echo fr_format_money($row['total']); ?></td>
                <td><?php echo htmlspecialchars($row['payment_type']); ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot class="table-dark">
            <tr>
                <th colspan="4" class="text-end">
                    Subtotal for <?php echo htmlspecialchars($typeName); ?>:
                </th>
                <th class="text-end"><?php echo fr_format_money($typeNet); ?></th>
                <th class="text-end"><?php echo fr_format_money($typeVat); ?></th>
                <th class="text-end"><?php echo fr_format_money($typeTotal); ?></th>
                <th></th>
            </tr>
        </tfoot>
    </table>
    <?php
                }
            }
            break;

        // -----------------------
        // RECEIPTS
        // -----------------------
        case 'receipts':
            ?>
    <table class="table table-striped table-hover table-sm align-middle">
        <thead class="table-dark">
            <tr>
                <th>ID</th>
                <th>Date</th>
                <th>Payee</th>
                <th>Details</th>
                <th class="text-end">Net</th>
                <th class="text-end">VAT</th>
                <th class="text-end">Total</th>
                <th>Method</th>
                <th>Invoices</th>
            </tr>
        </thead>
        <tbody>
            <?php
                $stmt = $GLOBALS['con']->prepare("
                    SELECT id, payee, details, `date`, totals, method, invoice
                    FROM receipts
                    ORDER BY `date` ASC, id ASC
                ");
                $stmt->execute();
                $res = $stmt->get_result();
                $stmt->close();

                $hasRows = false;
                while ($row = $res->fetch_assoc()) {
                    $ts = (int)$row['date'];
                    if (!fr_in_range($ts, $startUnix, $endUnix)) continue;

                    $hasRows = true;
                    [$net, $vat] = fr_parse_totals($row['totals']);
                    $total = $net + $vat;
                    $nTotal += $net;
                    $vTotal += $vat;
                    ?>
            <tr>
                <td><?php echo (int)$row['id']; ?></td>
                <td><?php echo date('d-m-Y', $ts); ?></td>
                <td><?php echo htmlspecialchars($row['payee']); ?></td>
                <td><?php echo htmlspecialchars($row['details']); ?></td>
                <td class="text-end"><?php echo fr_format_money($net); ?></td>
                <td class="text-end"><?php echo fr_format_money($vat); ?></td>
                <td class="text-end"><?php echo fr_format_money($total); ?></td>
                <td><?php echo htmlspecialchars($row['method']); ?></td>
                <td><?php echo htmlspecialchars($row['invoice']); ?></td>
            </tr>
            <?php
                }
                if (!$hasRows) {
                    echo '<tr><td colspan="9" class="text-center text-muted">No receipts found in this range.</td></tr>';
                }
                ?>
        </tbody>
    </table>
    <?php
            break;

        // -----------------------
        // RECEIPTS BY CATEGORY (payee)
        // -----------------------
        case 'receipts_by_category':
            $payees = [];
            $stmt = $GLOBALS['con']->prepare("
                SELECT payee, `date`, totals
                FROM receipts
            ");
            $stmt->execute();
            $res = $stmt->get_result();
            $stmt->close();

            while ($row = $res->fetch_assoc()) {
                $ts = (int)$row['date'];
                if (!fr_in_range($ts, $startUnix, $endUnix)) continue;

                $key = $row['payee'] ?: 'Unspecified';
                [$net, $vat] = fr_parse_totals($row['totals']);
                if (!isset($payees[$key])) {
                    $payees[$key] = ['net' => 0.0, 'vat' => 0.0];
                }
                $payees[$key]['net'] += $net;
                $payees[$key]['vat'] += $vat;
                $nTotal += $net;
                $vTotal += $vat;
            }
            ?>
    <table class="table table-striped table-hover table-sm align-middle">
        <thead class="table-dark">
            <tr>
                <th>Payee</th>
                <th class="text-end">Net</th>
                <th class="text-end">VAT</th>
                <th class="text-end">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php
                if (empty($payees)) {
                    echo '<tr><td colspan="4" class="text-center text-muted">No receipts found in this range.</td></tr>';
                } else {
                    ksort($payees, SORT_NATURAL | SORT_FLAG_CASE);
                    foreach ($payees as $payee => $vals) {
                        $total = $vals['net'] + $vals['vat']; ?>
            <tr>
                <td><?php echo htmlspecialchars($payee); ?></td>
                <td class="text-end"><?php echo fr_format_money($vals['net']); ?></td>
                <td class="text-end"><?php echo fr_format_money($vals['vat']); ?></td>
                <td class="text-end"><?php echo fr_format_money($total); ?></td>
            </tr>
            <?php }
                }
                ?>
        </tbody>
    </table>
    <?php
            break;

        // -----------------------
        // VAT – INCOME (from receipts)
        // -----------------------
        case 'vat_in':
            ?>
    <table class="table table-striped table-hover table-sm align-middle">
        <thead class="table-dark">
            <tr>
                <th>ID</th>
                <th>Date</th>
                <th>Payee</th>
                <th>Details</th>
                <th class="text-end">Net</th>
                <th class="text-end">VAT</th>
                <th class="text-end">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php
                $stmt = $GLOBALS['con']->prepare("
                    SELECT id, payee, details, `date`, totals
                    FROM receipts
                    ORDER BY `date` ASC, id ASC
                ");
                $stmt->execute();
                $res = $stmt->get_result();
                $stmt->close();

                $hasRows = false;
                while ($row = $res->fetch_assoc()) {
                    $ts = (int)$row['date'];
                    if (!fr_in_range($ts, $startUnix, $endUnix)) continue;

                    $hasRows = true;
                    [$net, $vat] = fr_parse_totals($row['totals']);
                    $total = $net + $vat;
                    $nTotal += $net;
                    $vTotal += $vat;
                    ?>
            <tr>
                <td><?php echo (int)$row['id']; ?></td>
                <td><?php echo date('d-m-Y', $ts); ?></td>
                <td><?php echo htmlspecialchars($row['payee']); ?></td>
                <td><?php echo htmlspecialchars($row['details']); ?></td>
                <td class="text-end"><?php echo fr_format_money($net); ?></td>
                <td class="text-end"><?php echo fr_format_money($vat); ?></td>
                <td class="text-end"><?php echo fr_format_money($total); ?></td>
            </tr>
            <?php
                }
                if (!$hasRows) {
                    echo '<tr><td colspan="7" class="text-center text-muted">No receipts found in this range.</td></tr>';
                }
                ?>
        </tbody>
    </table>
    <?php
            break;

        // -----------------------
        // VAT – OUTGOING (from expenses)
        // -----------------------
        case 'vat_out':
            ?>
    <table class="table table-striped table-hover table-sm align-middle">
        <thead class="table-dark">
            <tr>
                <th>ID</th>
                <th>Date</th>
                <th>Employee</th>
                <th>Type</th>
                <th>Description</th>
                <th class="text-end">Net</th>
                <th class="text-end">VAT</th>
                <th class="text-end">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php
                $stmt = $GLOBALS['con']->prepare("
                    SELECT id, employee, `type`, `desc`, `date`, totals
                    FROM expenses
                    ORDER BY `date` ASC, id ASC
                ");
                $stmt->execute();
                $res = $stmt->get_result();
                $stmt->close();

                $hasRows = false;
                while ($row = $res->fetch_assoc()) {
                    $ts = (int)$row['date'];
                    if (!fr_in_range($ts, $startUnix, $endUnix)) continue;

                    $hasRows = true;
                    [$net, $vat] = fr_parse_totals($row['totals']);
                    $total = $net + $vat;
                    $nTotal += $net;
                    $vTotal += $vat;
                    ?>
            <tr>
                <td><?php echo (int)$row['id']; ?></td>
                <td><?php echo date('d-m-Y', $ts); ?></td>
                <td><?php echo htmlspecialchars($row['employee']); ?></td>
                <td><?php echo htmlspecialchars($row['type']); ?></td>
                <td><?php echo htmlspecialchars($row['desc']); ?></td>
                <td class="text-end"><?php echo fr_format_money($net); ?></td>
                <td class="text-end"><?php echo fr_format_money($vat); ?></td>
                <td class="text-end"><?php echo fr_format_money($total); ?></td>
            </tr>
            <?php
                }
                if (!$hasRows) {
                    echo '<tr><td colspan="8" class="text-center text-muted">No expenses found in this range.</td></tr>';
                }
                ?>
        </tbody>
    </table>
    <?php
            break;

        default:
            echo '<div class="alert alert-warning">Unknown or unsupported report type.</div>';
            break;
    }

    // === SUMMARY BLOCK ===
    $summaryHtml = '';

    switch ($typeKey) {
        case 'inv_paid':
            $summaryHtml = '
<table class="vatBox table table-bordered table-sm" style="width:50%;">
<thead class="table-dark">
    <tr><th colspan="2">Report Totals</th></tr>
    </thead>
    <tbody>
    <tr><th>TOTAL VAT INPUT</th><th>' . fr_format_money($vTotal) . '</th></tr>
    <tr><td>CLAIM EXCLUDING VAT</td><td>' . fr_format_money($nTotal) . '</td></tr>
    </tbody>
</table>';
            break;

        case 'inv_outstanding':
            $summaryHtml = '
<table class="vatBox table table-bordered table-sm" style="width:50%;">
<thead class="table-dark">
    <tr><th colspan="2">Report Totals</th></tr>
     </thead>
    <tbody>
    <tr><th>TOTAL VAT INPUT</th><th>' . fr_format_money($vTotal) . '</th></tr>
    <tr><td>OUTSTANDING EXCLUDING VAT</td><td>' . fr_format_money($nTotal) . '</td></tr>
    </tbody>
</table>';
            break;

        case 'outgoings':
        case 'outgoings_by_category':
            $summaryHtml = '
<table class="vatBox table table-bordered table-sm" style="width:50%;">
<thead class="table-dark">
    <tr><th colspan="2">Report Totals</th></tr>
     </thead>
    <tbody>
    <tr><th>TOTAL VAT OUT (EXPENSES)</th><th>' . fr_format_money($vTotal) . '</th></tr>
    <tr><td>OUTGOINGS EXCLUDING VAT</td><td>' . fr_format_money($nTotal) . '</td></tr>
    </tbody>
</table>';
            break;

        case 'receipts':
        case 'receipts_by_category':
        case 'vat_in':
            $summaryHtml = '
<table class="vatBox table table-bordered table-sm" style="width:50%;">
<thead class="table-dark">
    <tr><th colspan="2">Report Totals</th></tr>
     </thead>
    <tbody>
    <tr><th>TOTAL VAT IN (RECEIPTS)</th><th>' . fr_format_money($vTotal) . '</th></tr>
    <tr><td>INCOME EXCLUDING VAT</td><td>' . fr_format_money($nTotal) . '</td></tr>
     </tbody>
</table>';
            break;

        case 'vat_out':
            $summaryHtml = '
<table class="vatBox table table-bordered table-sm" style="width:50%;">
<thead class="table-dark">
    <tr><th colspan="2">Report Totals</th></tr>
     </thead>
    <tbody>
    <tr><th>TOTAL VAT OUT (EXPENSES)</th><th>' . fr_format_money($vTotal) . '</th></tr>
    <tr><td>OUTGOINGS EXCLUDING VAT</td><td>' . fr_format_money($nTotal) . '</td></tr>
     </tbody>
</table>';
            break;
    }
    ?>

    <div class="clearfix my-3"></div>
    <?php echo $summaryHtml; ?>
</div>