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

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');
}

require_once('../finance_functions.php');

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

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);

if ($endUnix > 0) {
    $endUnix += 86399;
}

if ($startUnix === 0 && $endUnix === 0) {
    $startUnix = 0;
    $endUnix   = PHP_INT_MAX;
}

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);
    }
}

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

if (!function_exists('fr_format_money')) {
    function fr_format_money($value): string
    {
        return '£' . number_format((float)$value, 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;
    }
}

if (!function_exists('fr_render_footer_row')) {
    function fr_render_footer_row(int $labelColspan, float $net, float $vat, float $total, int $blankCols = 0, string $label = ''): void
    {
        echo '<tfoot>';
        echo '<tr class="table-dark">';
        echo '<th colspan="' . $labelColspan . '" class="text-end">' . htmlspecialchars($label) . '</th>';
        echo '<th class="text-end">' . fr_format_money($net) . '</th>';
        echo '<th class="text-end">' . fr_format_money($vat) . '</th>';
        echo '<th class="text-end">' . fr_format_money($total) . '</th>';
        for ($i = 0; $i < $blankCols; $i++) {
            echo '<th>&nbsp;</th>';
        }
        echo '</tr>';
        echo '</tfoot>';
    }
}

if (!function_exists('fr_render_summary_box')) {
    function fr_render_summary_box(string $heading, string $line2Label, float $vatTotal, float $netTotal): string
    {
        return '
<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>' . htmlspecialchars($heading) . '</th><th>' . fr_format_money($vatTotal) . '</th></tr>
        <tr><td>' . htmlspecialchars($line2Label) . '</td><td>' . fr_format_money($netTotal) . '</td></tr>
    </tbody>
</table>';
    }
}

$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 / Outgoings – 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;
}

$nTotal = 0.0;
$vTotal = 0.0;
?>
<p id="exportTitle" class="lead reportHeader">
    <?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
switch ($typeKey) {

    case 'inv_paid':
        ?>
        <table class="table table-striped table-hover table-sm align-middle finance-report-table">
            <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((string)$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 !empty($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>
            <?php
            if ($hasRows) {
                fr_render_footer_row(5, $nTotal, $vTotal, $nTotal + $vTotal);
            }
            ?>
        </table>
        <?php
        break;

    case 'inv_outstanding':
        ?>
        <table class="table table-striped table-hover table-sm align-middle finance-report-table">
            <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((string)$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 !empty($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>
            <?php
            if ($hasRows) {
                fr_render_footer_row(5, $nTotal, $vTotal, $nTotal + $vTotal);
            }
            ?>
        </table>
        <?php
        break;

    case 'inv_all':
        ?>
        <table class="table table-striped table-hover table-sm align-middle finance-report-table">
            <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((string)$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 !empty($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>
            <?php
            if ($hasRows) {
                fr_render_footer_row(5, $nTotal, $vTotal, $nTotal + $vTotal);
            }
            ?>
        </table>
        <?php
        break;

    case 'outgoings':
        ?>
        <table class="table table-striped table-hover table-sm align-middle finance-report-table">
            <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((string)$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((string)$row['employee']); ?></td>
                    <td><?php echo htmlspecialchars((string)$row['type']); ?></td>
                    <td><?php echo htmlspecialchars((string)$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((string)$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>
            <?php
            if ($hasRows) {
                fr_render_footer_row(5, $nTotal, $vTotal, $nTotal + $vTotal, 1);
            }
            ?>
        </table>
        <?php
        break;

    case 'outgoings_by_category':
        $rowsAll = [];
        $titles  = [];

        $stmt = $GLOBALS['con']->prepare("
            SELECT id, employee, payee, payment_type, code, type, `desc`, `date`, totals
            FROM expenses
            ORDER BY `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;
            }

            $code = trim((string)($row['code'] ?? ''));
            $type = trim((string)($row['type'] ?? ''));

            if ($code !== '') {
                $titles[$code] = true;
            }
            if ($type !== '') {
                $titles[$type] = true;
            }

            $row['_ts']   = $ts;
            $row['_code'] = $code;
            $row['_type'] = $type;
            $rowsAll[] = $row;
        }

        if (empty($titles)) {
            echo '<div class="alert alert-info">No expenses/outgoings found in the selected range.</div>';
            break;
        }

        $titleList = array_keys($titles);
        sort($titleList, SORT_NATURAL | SORT_FLAG_CASE);

        $byTitle = [];
        foreach ($titleList as $t) {
            $byTitle[$t] = [];
        }

        foreach ($rowsAll as $row) {
            $titleKey = '';

            if ($row['_code'] !== '' && isset($byTitle[$row['_code']])) {
                $titleKey = $row['_code'];
            } elseif ($row['_type'] !== '' && isset($byTitle[$row['_type']])) {
                $titleKey = $row['_type'];
            } else {
                continue;
            }

            $paymentType = trim((string)($row['payment_type'] ?? ''));
            $kind = (stripos($paymentType, 'outgoing') !== false || $paymentType === 'Outgoings') ? 'Outgoing' : 'Expense';

            [$net, $vat] = fr_parse_totals((string)$row['totals']);

            $byTitle[$titleKey][] = [
                'id'       => (int)$row['id'],
                'date'     => (int)$row['_ts'],
                'employee' => (string)($row['employee'] ?? ''),
                'payee'    => (string)($row['payee'] ?? ''),
                'desc'     => (string)($row['desc'] ?? ''),
                'kind'     => $kind,
                'net'      => $net,
                'vat'      => $vat,
                'total'    => $net + $vat,
            ];

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

        foreach ($titleList as $titleName) {
            $rows = $byTitle[$titleName];
            if (empty($rows)) {
                continue;
            }

            usort($rows, static function ($a, $b) {
                if ($a['date'] === $b['date']) {
                    return $a['id'] <=> $b['id'];
                }
                return $a['date'] <=> $b['date'];
            });

            $typeNet = 0.0;
            $typeVat = 0.0;
            $typeTotal = 0.0;

            echo '<h5 class="mt-3 mb-2">' . htmlspecialchars($titleName) . '</h5>';
            ?>
            <table class="table table-striped table-hover table-sm align-middle mb-3 finance-report-table">
                <thead class="table-dark">
                    <tr>
                        <th>ID</th>
                        <th>Date</th>
                        <th>Employee</th>
                        <th>Payee</th>
                        <th>Description</th>
                        <th>Type</th>
                        <th class="text-end">Net</th>
                        <th class="text-end">VAT</th>
                        <th class="text-end">Total</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($rows as $r): ?>
                    <?php
                    $typeNet += $r['net'];
                    $typeVat += $r['vat'];
                    $typeTotal += $r['total'];
                    ?>
                    <tr>
                        <td><?php echo $r['id']; ?></td>
                        <td><?php echo date('d-m-Y', $r['date']); ?></td>
                        <td><?php echo htmlspecialchars($r['employee']); ?></td>
                        <td><?php echo htmlspecialchars($r['payee']); ?></td>
                        <td><?php echo htmlspecialchars($r['desc']); ?></td>
                        <td><?php echo htmlspecialchars($r['kind']); ?></td>
                        <td class="text-end"><?php echo fr_format_money($r['net']); ?></td>
                        <td class="text-end"><?php echo fr_format_money($r['vat']); ?></td>
                        <td class="text-end"><?php echo fr_format_money($r['total']); ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
                <?php
                fr_render_footer_row(6, $typeNet, $typeVat, $typeTotal, 0, 'Subtotal for ' . $titleName);
                ?>
            </table>
            <?php
        }
        break;

    case 'receipts':
        ?>
        <table class="table table-striped table-hover table-sm align-middle finance-report-table">
            <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((string)$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((string)$row['payee']); ?></td>
                    <td><?php echo htmlspecialchars((string)$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((string)$row['method']); ?></td>
                    <td><?php echo htmlspecialchars((string)$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>
            <?php
            if ($hasRows) {
                fr_render_footer_row(4, $nTotal, $vTotal, $nTotal + $vTotal, 2);
            }
            ?>
        </table>
        <?php
        break;

    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 = trim((string)$row['payee']) !== '' ? (string)$row['payee'] : 'Unspecified';
            [$net, $vat] = fr_parse_totals((string)$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 finance-report-table">
            <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
            $hasRows = !empty($payees);
            if (!$hasRows) {
                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>
            <?php
            if ($hasRows) {
                fr_render_footer_row(1, $nTotal, $vTotal, $nTotal + $vTotal);
            }
            ?>
        </table>
        <?php
        break;

    case 'vat_in':
        ?>
        <table class="table table-striped table-hover table-sm align-middle finance-report-table">
            <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((string)$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((string)$row['payee']); ?></td>
                    <td><?php echo htmlspecialchars((string)$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>
            <?php
            if ($hasRows) {
                fr_render_footer_row(4, $nTotal, $vTotal, $nTotal + $vTotal);
            }
            ?>
        </table>
        <?php
        break;

    case 'vat_out':
        ?>
        <table class="table table-striped table-hover table-sm align-middle finance-report-table">
            <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((string)$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((string)$row['employee']); ?></td>
                    <td><?php echo htmlspecialchars((string)$row['type']); ?></td>
                    <td><?php echo htmlspecialchars((string)$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>
            <?php
            if ($hasRows) {
                fr_render_footer_row(5, $nTotal, $vTotal, $nTotal + $vTotal);
            }
            ?>
        </table>
        <?php
        break;

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

$summaryHtml = '';

switch ($typeKey) {
    case 'inv_paid':
        $summaryHtml = fr_render_summary_box('TOTAL VAT INPUT', 'CLAIM EXCLUDING VAT', $vTotal, $nTotal);
        break;

    case 'inv_outstanding':
        $summaryHtml = fr_render_summary_box('TOTAL VAT INPUT', 'OUTSTANDING EXCLUDING VAT', $vTotal, $nTotal);
        break;

    case 'inv_all':
        $summaryHtml = fr_render_summary_box('TOTAL VAT INPUT', 'INVOICES EXCLUDING VAT', $vTotal, $nTotal);
        break;

    case 'outgoings':
    case 'outgoings_by_category':
    case 'vat_out':
        $summaryHtml = fr_render_summary_box('TOTAL VAT OUT (EXPENSES)', 'OUTGOINGS EXCLUDING VAT', $vTotal, $nTotal);
        break;

    case 'receipts':
    case 'receipts_by_category':
    case 'vat_in':
        $summaryHtml = fr_render_summary_box('TOTAL VAT IN (RECEIPTS)', 'INCOME EXCLUDING VAT', $vTotal, $nTotal);
        break;
}
?>
    <div class="clearfix my-3"></div>
    <?php echo $summaryHtml; ?>
</div>