<?php
// Output buffering: any stray PHP notice/warning printed before our header()
// calls would otherwise corrupt the downloaded file or break the download
// entirely ("headers already sent"). Buffering + cleaning protects against this.
if (ob_get_level()) { ob_end_clean(); }
ob_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING & ~E_DEPRECATED);

require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/PdfHelper.php';
requireLogin();

$type   = $_GET['type']   ?? 'purchase';
$format = $_GET['format'] ?? 'csv';
$from   = $_GET['from']   ?? date('Y-m-01');
$to     = $_GET['to']     ?? date('Y-m-d');
$filtId = (int)($_GET['filter_id'] ?? 0);

// Clear any buffered output right before we send file headers
ob_end_clean();

/* ---- helpers ---- */
function outCSV($headers, $rows, $fname) {
    header('Content-Type: text/csv');
    header("Content-Disposition: attachment; filename=\"$fname\"");
    $fp = fopen('php://output','w');
    fputcsv($fp, $headers);
    foreach ($rows as $r) fputcsv($fp, array_values($r));
    fclose($fp); exit;
}
function outExcel($headers, $rows, $fname, $title) {
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment; filename=\"$fname\"");
    $n = count($headers);
    echo '<table border="1">';
    echo "<tr><th colspan=\"$n\"><b>".htmlspecialchars($title)."</b></th></tr>";
    echo '<tr>'.implode('', array_map(fn($h)=>'<th><b>'.htmlspecialchars($h).'</b></th>', $headers)).'</tr>';
    foreach ($rows as $r) {
        echo '<tr>';
        foreach (array_values($r) as $v) echo '<td>'.htmlspecialchars((string)($v??'')).'</td>';
        echo '</tr>';
    }
    echo '</table>'; exit;
}

/* ==============================================================
   PURCHASE REPORT
   ============================================================== */
if ($type === 'purchase') {
    $vf     = $filtId ? " AND p.vendor_id = $filtId" : '';
    $params = [$from, $to];

    $stmt = $pdo->prepare(
        "SELECT i.item_code, i.item_name,
                SUM(pi.qty) qty,
                AVG(pi.purchase_price) avg_price,
                SUM(pi.gst_amount) gst,
                SUM(pi.line_total) total
         FROM purchase_items pi
         JOIN purchases p ON p.id = pi.purchase_id
         JOIN items     i ON i.id = pi.item_id
         WHERE p.purchase_date BETWEEN ? AND ? $vf
         GROUP BY pi.item_id
         ORDER BY total DESC");
    $stmt->execute($params);
    $itemRows = $stmt->fetchAll();

    $stmt = $pdo->prepare(
        "SELECT v.vendor_code, v.vendor_name,
                COUNT(DISTINCT p.id) cnt,
                SUM(p.total_amount) subtotal,
                SUM(p.gst_amount) gst,
                SUM(p.grand_total) total,
                SUM(p.grand_total - p.paid_amount) outstanding
         FROM purchases p
         JOIN purchase_vendors v ON v.id = p.vendor_id
         WHERE p.purchase_date BETWEEN ? AND ? $vf
         GROUP BY p.vendor_id
         ORDER BY total DESC");
    $stmt->execute($params);
    $vendorRows = $stmt->fetchAll();

    $stmt = $pdo->prepare(
        "SELECT DATE_FORMAT(p.purchase_date,'%Y-%m-%d') d,
                COUNT(DISTINCT p.id) cnt,
                SUM(p.grand_total) total
         FROM purchases p
         WHERE p.purchase_date BETWEEN ? AND ? $vf
         GROUP BY d ORDER BY d");
    $stmt->execute($params);
    $dateRows = $stmt->fetchAll();

    if ($format === 'csv') {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="purchase_report_'.date('Ymd').'.csv"');
        $fp = fopen('php://output','w');
        fputcsv($fp, ['PURCHASE REPORT', 'Period: '.$from.' to '.$to]);
        fputcsv($fp, []);
        fputcsv($fp, ['--- ITEM-WISE ---']);
        fputcsv($fp, ['Item Code','Item Name','Qty Purchased','Avg Price','GST','Total Amount']);
        foreach ($itemRows as $r)
            fputcsv($fp, [$r['item_code'],$r['item_name'],$r['qty'],
                          number_format($r['avg_price'],2),
                          number_format($r['gst'],2),
                          number_format($r['total'],2)]);
        fputcsv($fp, []);
        fputcsv($fp, ['--- VENDOR-WISE ---']);
        fputcsv($fp, ['Vendor Code','Vendor Name','Orders','Subtotal','GST','Total','Outstanding']);
        foreach ($vendorRows as $r)
            fputcsv($fp, [$r['vendor_code'],$r['vendor_name'],$r['cnt'],
                          number_format($r['subtotal'],2),number_format($r['gst'],2),
                          number_format($r['total'],2),number_format($r['outstanding'],2)]);
        fputcsv($fp, []);
        fputcsv($fp, ['--- DATE-WISE ---']);
        fputcsv($fp, ['Date','Orders','Amount']);
        foreach ($dateRows as $r)
            fputcsv($fp, [$r['d'], $r['cnt'], number_format($r['total'],2)]);
        fclose($fp); exit;
    }

    if ($format === 'excel') {
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="purchase_report_'.date('Ymd').'.xls"');
        echo '<table border="1">';
        echo '<tr><th colspan="7"><b>Purchase Report: '.htmlspecialchars($from).' to '.htmlspecialchars($to).'</b></th></tr>';
        echo '<tr><th colspan="7" style="background:#eee"><b>Item-wise</b></th></tr>';
        foreach (['Item Code','Item Name','Qty','Avg Price','GST','Total'] as $h)
            echo '<th><b>'.htmlspecialchars($h).'</b></th>';
        echo '</tr>';
        foreach ($itemRows as $r)
            echo '<tr><td>'.htmlspecialchars($r['item_code']).'</td><td>'.htmlspecialchars($r['item_name']).'</td>'
                .'<td align="right">'.$r['qty'].'</td>'
                .'<td align="right">'.number_format($r['avg_price'],2).'</td>'
                .'<td align="right">'.number_format($r['gst'],2).'</td>'
                .'<td align="right">'.number_format($r['total'],2).'</td></tr>';
        echo '<tr><td colspan="7"></td></tr>';
        echo '<tr><th colspan="7" style="background:#eee"><b>Vendor-wise</b></th></tr>';
        echo '<tr>';
        foreach (['Code','Vendor Name','Orders','Subtotal','GST','Total','Outstanding'] as $h)
            echo '<th><b>'.htmlspecialchars($h).'</b></th>';
        echo '</tr>';
        foreach ($vendorRows as $r)
            echo '<tr><td>'.htmlspecialchars($r['vendor_code']).'</td><td>'.htmlspecialchars($r['vendor_name']).'</td>'
                .'<td align="right">'.$r['cnt'].'</td>'
                .'<td align="right">'.number_format($r['subtotal'],2).'</td>'
                .'<td align="right">'.number_format($r['gst'],2).'</td>'
                .'<td align="right">'.number_format($r['total'],2).'</td>'
                .'<td align="right">'.number_format($r['outstanding'],2).'</td></tr>';
        echo '<tr><td colspan="7"></td></tr>';
        echo '<tr><th colspan="3" style="background:#eee"><b>Date-wise</b></th></tr>';
        echo '<tr><th>Date</th><th>Orders</th><th>Amount</th></tr>';
        foreach ($dateRows as $r)
            echo '<tr><td>'.htmlspecialchars($r['d']).'</td><td align="right">'.$r['cnt'].'</td>'
                .'<td align="right">'.number_format($r['total'],2).'</td></tr>';
        echo '</table>'; exit;
    }

    if ($format === 'pdf') {
        $totalItems   = array_sum(array_column($itemRows,'total'));
        $totalVendors = array_sum(array_column($vendorRows,'total'));
        ob_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Purchase Report</title>
<style>
body{font-family:Arial,Helvetica,sans-serif;font-size:11px;margin:20px;color:#2B2A28;}
h2{color:#1D4E4A;margin:0 0 2px;font-size:18px;}
h3{color:#1D4E4A;font-size:13px;margin:14px 0 4px;}
.meta{color:#75716A;font-size:10px;margin-bottom:12px;}
.summary{display:flex;gap:28px;background:#F6F4EF;padding:10px 14px;border-radius:6px;margin-bottom:14px;}
.s .lbl{font-size:9px;text-transform:uppercase;letter-spacing:1px;color:#75716A;}
.s .val{font-size:15px;font-weight:bold;color:#1D4E4A;}
table{width:100%;border-collapse:collapse;margin-bottom:18px;font-size:10px;}
th{background:#1D4E4A;color:#fff;padding:5px 7px;text-align:left;}
td{padding:4px 7px;border-bottom:1px solid #E0DBCE;}
tr:nth-child(even) td{background:#FBFAF6;}
.num{text-align:right;}
.red{color:#A32D2D;}
</style>
</head>
<body>
<h2>Purchase Report</h2>
<div class="meta">Period: <?= htmlspecialchars($from) ?> to <?= htmlspecialchars($to) ?> &nbsp;&bull;&nbsp; Generated: <?= date('d-M-Y h:i A') ?></div>
<div class="summary">
    <div class="s"><div class="lbl">Total Purchase Value</div><div class="val">Rs. <?= number_format($totalItems,2) ?></div></div>
    <div class="s"><div class="lbl">Item Lines</div><div class="val"><?= count($itemRows) ?></div></div>
    <div class="s"><div class="lbl">Vendors</div><div class="val"><?= count($vendorRows) ?></div></div>
</div>

<h3>Item-wise Purchases</h3>
<table>
<thead><tr><th>Item Code</th><th>Item Name</th><th>Qty</th><th>Avg Price</th><th>GST</th><th>Total</th></tr></thead>
<tbody>
<?php foreach ($itemRows as $r): ?>
<tr>
    <td><?= htmlspecialchars($r['item_code']) ?></td>
    <td><?= htmlspecialchars($r['item_name']) ?></td>
    <td class="num"><?= $r['qty'] ?></td>
    <td class="num">Rs. <?= number_format($r['avg_price'],2) ?></td>
    <td class="num">Rs. <?= number_format($r['gst'],2) ?></td>
    <td class="num"><b>Rs. <?= number_format($r['total'],2) ?></b></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

<h3>Vendor-wise Purchases</h3>
<table>
<thead><tr><th>Code</th><th>Vendor Name</th><th>Orders</th><th>Subtotal</th><th>GST</th><th>Total</th><th>Outstanding</th></tr></thead>
<tbody>
<?php foreach ($vendorRows as $r): ?>
<tr>
    <td><?= htmlspecialchars($r['vendor_code']) ?></td>
    <td><?= htmlspecialchars($r['vendor_name']) ?></td>
    <td class="num"><?= $r['cnt'] ?></td>
    <td class="num">Rs. <?= number_format($r['subtotal'],2) ?></td>
    <td class="num">Rs. <?= number_format($r['gst'],2) ?></td>
    <td class="num"><b>Rs. <?= number_format($r['total'],2) ?></b></td>
    <td class="num <?= $r['outstanding']>0?'red':'' ?>">Rs. <?= number_format($r['outstanding'],2) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

<h3>Date-wise Trend</h3>
<table>
<thead><tr><th>Date</th><th>Orders</th><th>Amount</th></tr></thead>
<tbody>
<?php foreach ($dateRows as $r): ?>
<tr>
    <td><?= date('d-M-Y', strtotime($r['d'])) ?></td>
    <td class="num"><?= $r['cnt'] ?></td>
    <td class="num">Rs. <?= number_format($r['total'],2) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
<?php
        $html = ob_get_clean();
        PdfHelper::output($html, 'purchase_report_' . date('Ymd') . '.pdf');
    }
}

/* ==============================================================
   SALES REPORT
   ============================================================== */
if ($type === 'sales') {
    $cf     = $filtId ? " AND i.customer_id = $filtId" : '';
    $params = [$from, $to];

    $stmt = $pdo->prepare(
        "SELECT c.customer_code, c.customer_name,
                COUNT(*) cnt,
                SUM(i.grand_total) total,
                SUM(i.paid_amount) paid
         FROM invoices i
         JOIN sale_vendors c ON c.id = i.customer_id
         WHERE i.invoice_date BETWEEN ? AND ? AND i.invoice_type='sale' $cf
         GROUP BY i.customer_id ORDER BY total DESC");
    $stmt->execute($params);
    $custRows = $stmt->fetchAll();

    $stmt = $pdo->prepare(
        "SELECT it.item_code, it.item_name,
                SUM(ii.qty) qty,
                SUM(ii.line_total) total
         FROM invoice_items ii
         JOIN invoices i  ON i.id  = ii.invoice_id
         JOIN items    it ON it.id = ii.item_id
         WHERE i.invoice_date BETWEEN ? AND ? AND i.invoice_type='sale' $cf
         GROUP BY ii.item_id ORDER BY total DESC");
    $stmt->execute($params);
    $itemRows = $stmt->fetchAll();

    $stmt = $pdo->prepare(
        "SELECT DATE_FORMAT(i.invoice_date,'%Y-%m-%d') d,
                COUNT(*) cnt,
                SUM(i.grand_total) total
         FROM invoices i
         WHERE i.invoice_date BETWEEN ? AND ? AND i.invoice_type='sale' $cf
         GROUP BY d ORDER BY d");
    $stmt->execute($params);
    $dateRows = $stmt->fetchAll();

    $totalSales = array_sum(array_column($custRows,'total'));
    $totalPaid  = array_sum(array_column($custRows,'paid'));

    if ($format === 'csv') {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="sales_report_'.date('Ymd').'.csv"');
        $fp = fopen('php://output','w');
        fputcsv($fp, ['SALES REPORT', 'Period: '.$from.' to '.$to]);
        fputcsv($fp, []);
        fputcsv($fp, ['--- CUSTOMER-WISE ---']);
        fputcsv($fp, ['Code','Customer Name','Invoices','Total','Paid','Outstanding']);
        foreach ($custRows as $r)
            fputcsv($fp, [$r['customer_code'],$r['customer_name'],$r['cnt'],
                          number_format($r['total'],2),number_format($r['paid'],2),
                          number_format($r['total']-$r['paid'],2)]);
        fputcsv($fp, []);
        fputcsv($fp, ['--- ITEM-WISE ---']);
        fputcsv($fp, ['Item Code','Item Name','Qty Sold','Amount']);
        foreach ($itemRows as $r)
            fputcsv($fp, [$r['item_code'],$r['item_name'],$r['qty'],number_format($r['total'],2)]);
        fputcsv($fp, []);
        fputcsv($fp, ['--- DATE-WISE ---']);
        fputcsv($fp, ['Date','Invoices','Amount']);
        foreach ($dateRows as $r)
            fputcsv($fp, [$r['d'],$r['cnt'],number_format($r['total'],2)]);
        fclose($fp); exit;
    }

    if ($format === 'excel') {
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="sales_report_'.date('Ymd').'.xls"');
        echo '<table border="1">';
        echo '<tr><th colspan="6"><b>Sales Report: '.htmlspecialchars($from).' to '.htmlspecialchars($to).'</b></th></tr>';
        echo '<tr><th colspan="6" style="background:#eee"><b>Customer-wise</b></th></tr>';
        echo '<tr><th>Code</th><th>Customer</th><th>Invoices</th><th>Total</th><th>Paid</th><th>Outstanding</th></tr>';
        foreach ($custRows as $r)
            echo '<tr><td>'.htmlspecialchars($r['customer_code']).'</td><td>'.htmlspecialchars($r['customer_name']).'</td>'
                .'<td align="right">'.$r['cnt'].'</td>'
                .'<td align="right">'.number_format($r['total'],2).'</td>'
                .'<td align="right">'.number_format($r['paid'],2).'</td>'
                .'<td align="right">'.number_format($r['total']-$r['paid'],2).'</td></tr>';
        echo '<tr><td colspan="6"></td></tr>';
        echo '<tr><th colspan="4" style="background:#eee"><b>Item-wise</b></th></tr>';
        echo '<tr><th>Code</th><th>Item Name</th><th>Qty</th><th>Amount</th></tr>';
        foreach ($itemRows as $r)
            echo '<tr><td>'.htmlspecialchars($r['item_code']).'</td><td>'.htmlspecialchars($r['item_name']).'</td>'
                .'<td align="right">'.$r['qty'].'</td>'
                .'<td align="right">'.number_format($r['total'],2).'</td></tr>';
        echo '<tr><td colspan="6"></td></tr>';
        echo '<tr><th colspan="3" style="background:#eee"><b>Date-wise</b></th></tr>';
        echo '<tr><th>Date</th><th>Invoices</th><th>Amount</th></tr>';
        foreach ($dateRows as $r)
            echo '<tr><td>'.htmlspecialchars($r['d']).'</td><td align="right">'.$r['cnt'].'</td>'
                .'<td align="right">'.number_format($r['total'],2).'</td></tr>';
        echo '</table>'; exit;
    }

    if ($format === 'pdf') {
        ob_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sales Report</title>
<style>
body{font-family:Arial,Helvetica,sans-serif;font-size:11px;margin:20px;color:#2B2A28;}
h2{color:#1D4E4A;margin:0 0 2px;font-size:18px;}
h3{color:#1D4E4A;font-size:13px;margin:14px 0 4px;}
.meta{color:#75716A;font-size:10px;margin-bottom:12px;}
.summary{display:flex;gap:28px;background:#F6F4EF;padding:10px 14px;border-radius:6px;margin-bottom:14px;}
.s .lbl{font-size:9px;text-transform:uppercase;letter-spacing:1px;color:#75716A;}
.s .val{font-size:15px;font-weight:bold;color:#1D4E4A;}
table{width:100%;border-collapse:collapse;margin-bottom:18px;font-size:10px;}
th{background:#1D4E4A;color:#fff;padding:5px 7px;text-align:left;}
td{padding:4px 7px;border-bottom:1px solid #E0DBCE;}
tr:nth-child(even) td{background:#FBFAF6;}
.num{text-align:right;}
.green{color:#3B6D11;}.red{color:#A32D2D;}
</style>
</head>
<body>
<h2>Sales Report</h2>
<div class="meta">Period: <?= htmlspecialchars($from) ?> to <?= htmlspecialchars($to) ?> &nbsp;&bull;&nbsp; Generated: <?= date('d-M-Y h:i A') ?></div>
<div class="summary">
    <div class="s"><div class="lbl">Total Sales</div><div class="val">Rs. <?= number_format($totalSales,2) ?></div></div>
    <div class="s"><div class="lbl">Received</div><div class="val" style="color:#3B6D11;">Rs. <?= number_format($totalPaid,2) ?></div></div>
    <div class="s"><div class="lbl">Outstanding</div><div class="val" style="color:#A32D2D;">Rs. <?= number_format($totalSales-$totalPaid,2) ?></div></div>
    <div class="s"><div class="lbl">Customers</div><div class="val"><?= count($custRows) ?></div></div>
</div>

<h3>Customer-wise Sales</h3>
<table>
<thead><tr><th>Code</th><th>Customer</th><th>#</th><th>Total</th><th>Paid</th><th>Outstanding</th></tr></thead>
<tbody>
<?php foreach ($custRows as $r): $bal = $r['total'] - $r['paid']; ?>
<tr>
    <td><?= htmlspecialchars($r['customer_code']) ?></td>
    <td><?= htmlspecialchars($r['customer_name']) ?></td>
    <td class="num"><?= $r['cnt'] ?></td>
    <td class="num"><b>Rs. <?= number_format($r['total'],2) ?></b></td>
    <td class="num green">Rs. <?= number_format($r['paid'],2) ?></td>
    <td class="num <?= $bal>0?'red':'' ?>">Rs. <?= number_format($bal,2) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

<h3>Item-wise Sales</h3>
<table>
<thead><tr><th>Code</th><th>Item Name</th><th>Qty Sold</th><th>Amount</th></tr></thead>
<tbody>
<?php foreach ($itemRows as $r): ?>
<tr>
    <td><?= htmlspecialchars($r['item_code']) ?></td>
    <td><?= htmlspecialchars($r['item_name']) ?></td>
    <td class="num"><?= $r['qty'] ?></td>
    <td class="num"><b>Rs. <?= number_format($r['total'],2) ?></b></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

<h3>Date-wise Sales</h3>
<table>
<thead><tr><th>Date</th><th>Invoices</th><th>Amount</th></tr></thead>
<tbody>
<?php foreach ($dateRows as $r): ?>
<tr>
    <td><?= date('d-M-Y', strtotime($r['d'])) ?></td>
    <td class="num"><?= $r['cnt'] ?></td>
    <td class="num">Rs. <?= number_format($r['total'],2) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
<?php
        $html = ob_get_clean();
        PdfHelper::output($html, 'sales_report_' . date('Ymd') . '.pdf');
    }
}

/* ==============================================================
   CASH FLOW REPORT
   ============================================================== */
if ($type === 'cashflow') {
    $stmt = $pdo->prepare(
        "SELECT p.*, u.name as user_name
         FROM payments p
         LEFT JOIN users u ON u.id = p.created_by
         WHERE DATE(p.payment_date) BETWEEN ? AND ?
         ORDER BY p.payment_date DESC");
    $stmt->execute([$from, $to]);
    $rows = $stmt->fetchAll();

    $inflow  = array_sum(array_map(fn($r) => $r['payment_type']==='inflow'  ? $r['amount'] : 0, $rows));
    $outflow = array_sum(array_map(fn($r) => $r['payment_type']==='outflow' ? $r['amount'] : 0, $rows));
    $net     = $inflow - $outflow;

    $hdrs = ['Date/Time','Type','Party','Reference','Amount','Mode','Marked By'];
    $flat = array_map(fn($r) => [
        $r['payment_date'],
        $r['payment_type'],
        $r['party_name'] ?? '',
        ucfirst($r['reference_type'] ?? '') . ' #' . ($r['reference_id'] ?? ''),
        number_format($r['amount'],2),
        $r['payment_mode'] ?? '',
        $r['user_name'] ?? ''
    ], $rows);

    if ($format === 'csv') {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="cashflow_report_'.date('Ymd').'.csv"');
        $fp = fopen('php://output','w');
        fputcsv($fp, ['CASH FLOW REPORT','Period: '.$from.' to '.$to]);
        fputcsv($fp, ['Total Inflow','Total Outflow','Net Cash Flow']);
        fputcsv($fp, [number_format($inflow,2), number_format($outflow,2), number_format($net,2)]);
        fputcsv($fp, []);
        fputcsv($fp, $hdrs);
        foreach ($flat as $r) fputcsv($fp, $r);
        fclose($fp); exit;
    }

    if ($format === 'excel') {
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="cashflow_report_'.date('Ymd').'.xls"');
        $n = count($hdrs);
        echo '<table border="1">';
        echo "<tr><th colspan=\"$n\"><b>Cash Flow Report: ".htmlspecialchars($from).' to '.htmlspecialchars($to)."</b></th></tr>";
        echo "<tr><td colspan=\"$n\" style=\"background:#eee\"><b>Summary</b></td></tr>";
        echo '<tr><td><b>Inflow</b></td><td align="right">'.number_format($inflow,2).'</td>'
            .'<td><b>Outflow</b></td><td align="right">'.number_format($outflow,2).'</td>'
            .'<td><b>Net</b></td><td align="right">'.number_format($net,2).'</td>'
            .'<td></td></tr>';
        echo "<tr><td colspan=\"$n\"></td></tr>";
        echo '<tr>'.implode('',array_map(fn($h)=>'<th><b>'.htmlspecialchars($h).'</b></th>',$hdrs)).'</tr>';
        foreach ($flat as $r) {
            echo '<tr>';
            foreach ($r as $v) echo '<td>'.htmlspecialchars((string)$v).'</td>';
            echo '</tr>';
        }
        echo '</table>'; exit;
    }

    if ($format === 'pdf') {
        ob_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cash Flow Report</title>
<style>
body{font-family:Arial,Helvetica,sans-serif;font-size:11px;margin:20px;color:#2B2A28;}
h2{color:#1D4E4A;margin:0 0 2px;font-size:18px;}
.meta{color:#75716A;font-size:10px;margin-bottom:12px;}
.summary{display:flex;gap:32px;background:#F6F4EF;padding:10px 14px;border-radius:6px;margin-bottom:14px;}
.s .lbl{font-size:9px;text-transform:uppercase;letter-spacing:1px;color:#75716A;}
.s .val{font-size:16px;font-weight:bold;}
table{width:100%;border-collapse:collapse;font-size:10px;}
th{background:#1D4E4A;color:#fff;padding:5px 7px;text-align:left;}
td{padding:4px 7px;border-bottom:1px solid #E0DBCE;}
tr:nth-child(even) td{background:#FBFAF6;}
.num{text-align:right;}
.in{color:#3B6D11;font-weight:bold;}
.out{color:#A32D2D;font-weight:bold;}
</style>
</head>
<body>
<h2>Cash Flow Report</h2>
<div class="meta">Period: <?= htmlspecialchars($from) ?> to <?= htmlspecialchars($to) ?> &nbsp;&bull;&nbsp; Generated: <?= date('d-M-Y h:i A') ?></div>
<div class="summary">
    <div class="s">
        <div class="lbl">Total Inflow (Received)</div>
        <div class="val" style="color:#3B6D11;">Rs. <?= number_format($inflow,2) ?></div>
    </div>
    <div class="s">
        <div class="lbl">Total Outflow (Paid)</div>
        <div class="val" style="color:#A32D2D;">Rs. <?= number_format($outflow,2) ?></div>
    </div>
    <div class="s">
        <div class="lbl">Net Cash Flow</div>
        <div class="val" style="color:<?= $net>=0?'#3B6D11':'#A32D2D' ?>;">Rs. <?= number_format($net,2) ?></div>
    </div>
    <div class="s">
        <div class="lbl">Transactions</div>
        <div class="val"><?= count($rows) ?></div>
    </div>
</div>
<table>
<thead>
<tr>
    <th>Date/Time</th><th>Type</th><th>Party</th><th>Reference</th>
    <th>Amount</th><th>Mode</th><th>Marked By</th>
</tr>
</thead>
<tbody>
<?php foreach ($rows as $r): $in = ($r['payment_type']==='inflow'); ?>
<tr>
    <td><?= date('d-M-Y h:i A', strtotime($r['payment_date'])) ?></td>
    <td class="<?= $in?'in':'out' ?>"><?= strtoupper($r['payment_type']) ?></td>
    <td><?= htmlspecialchars($r['party_name'] ?? '') ?></td>
    <td><?= htmlspecialchars(ucfirst($r['reference_type']??'').' #'.($r['reference_id']??'')) ?></td>
    <td class="num <?= $in?'in':'out' ?>"><?= $in?'+':'-' ?>Rs. <?= number_format($r['amount'],2) ?></td>
    <td><?= htmlspecialchars($r['payment_mode'] ?? '') ?></td>
    <td><?= htmlspecialchars($r['user_name'] ?? '') ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
<?php
        $html = ob_get_clean();
        PdfHelper::output($html, 'cashflow_report_' . date('Ymd') . '.pdf');
    }
}
