<?php
ob_start();
session_start();
include_once("../config.php");
include_once("../functions.php");

if (!check_login()) {
  header("Location: " . WEB_URL . "logout.php");
  die();
}

include_once(ROOT_PATH . 'partial/report_top_common.php');
include_once(ROOT_PATH . 'language/' . $lang_code_global . '/lang_fair_info_all.php');
include_once(ROOT_PATH . 'language/' . $lang_code_global . '/lang_common.php');
include_once(ROOT_PATH . 'library/helper.php');

$ams_helper = new ams_helper();

function e($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function human_date($s){
  $t = strtotime($s);
  return $t ? date("jS F, Y", $t) : $s;
}

/* ---------------------------------
   Capture & sanitize filters (GET)
----------------------------------*/
$get       = get_input_serilization();
$type      = isset($get['type']) ? trim($get['type']) : 'all';
$bid       = isset($get['bid']) ? (int)$get['bid'] : 0;              // block id
$uid       = isset($get['uid']) ? (int)$get['uid'] : 0;              // unit id
$tid       = isset($get['tid']) ? (int)$get['tid'] : 0;              // tenant id
$start_str = isset($get['startDate']) ? trim($get['startDate']) : ''; // compared against issue_date (string)
$end_str   = isset($get['endDate']) ? trim($get['endDate']) : '';     // compared against issue_date (string)
$rs        = isset($get['rs']) ? trim($get['rs']) : '';              // refund status (s_status): 1/2/3

/* ---------------------------------
   WHERE builder (shared)
----------------------------------*/
$common_where = " WHERE 1 ";
if ($type === 'query') {
  if ($bid > 0) $common_where .= " AND bid = {$bid} ";
  if ($uid > 0) $common_where .= " AND uid = {$uid} ";
  if ($tid > 0) $common_where .= " AND tid = {$tid} ";
  if ($rs !== '' && in_array($rs, ['1','2','3'], true)) $common_where .= " AND s_status = '{$rs}' ";
  if ($start_str !== '') $common_where .= " AND issue_date >= '" . mysqli_real_escape_string($link, $start_str) . "' ";
  if ($end_str   !== '') $common_where .= " AND issue_date <= '" . mysqli_real_escape_string($link, $end_str)   . "' ";
}

/* ---------------------------------
   Queries from the security deposit view
   - Cedi (rate_currency_id = 14)
   - Foreign currency (rate_currency_id = 15)
----------------------------------*/
$sql_cedi = "
  SELECT *
  FROM security_deposit_tenant_unit_view
  {$common_where}
  AND rate_currency_id = 14
  ORDER BY issue_date DESC, r_name ASC
";
$sql_fc = "
  SELECT *
  FROM security_deposit_tenant_unit_view
  {$common_where}
  AND rate_currency_id = 15
  ORDER BY issue_date DESC, r_name ASC
";

$rows_cedi = [];
$rows_fc   = [];

if ($res = $link->query($sql_cedi)) { while ($r = mysqli_fetch_assoc($res)) $rows_cedi[] = $r; }
if ($res = $link->query($sql_fc))   { while ($r = mysqli_fetch_assoc($res)) $rows_fc[]   = $r; }

/* ---------------------------------
   Helper totals
   NOTE: amount_withheld is NOT stored in DB.
         Compute as (amt_paid - amount_refunded) ONLY if s_status != 0.
         If s_status == 0, treat withheld as 0 for totals.
----------------------------------*/
function calc_totals($rows){
  $tot = [
    'paid' => 0.0,
    'balance' => 0.0,
    'total' => 0.0,
    'refunded' => 0.0,
    'withheld' => 0.0,
  ];
  foreach ($rows as $r){
    $rate      = (float)($r['rate'] ?? 0);
    $paid      = (float)($r['amt_paid'] ?? 0);
    $refunded  = (float)($r['amount_refunded'] ?? 0); // using column name from your current view
    $s_status  = isset($r['s_status']) ? (int)$r['s_status'] : 0;

    $balance   = $rate - $paid;
    $withheld  = ($s_status !== 0) ? ($paid - $refunded) : 0.0;

    $tot['paid']     += $paid;
    $tot['balance']  += $balance;
    $tot['total']    += $rate;
    $tot['refunded'] += $refunded;
    $tot['withheld'] += $withheld;
  }
  return $tot;
}
$tot_ghs = calc_totals($rows_cedi);
$tot_fc  = calc_totals($rows_fc);

/* ---------------------------------
   Currency symbols (fallbacks)
----------------------------------*/
$ghs_symbol = count($rows_cedi) ? (string)$rows_cedi[0]['rate_currency'] : '₵';
$fc_symbol  = count($rows_fc)   ? (string)$rows_fc[0]['rate_currency']   : '$';

/* ---------------------------------
   Section title builders
----------------------------------*/
function first_val($rows, $field, $fallback = ''){
  foreach ($rows as $r) {
    if (isset($r[$field]) && $r[$field] !== '') return $r[$field];
  }
  return $fallback;
}
function refund_label_from_rs($rs_code){
  if ($rs_code === '2') return 'Fully Refunded';
  if ($rs_code === '3') return 'Partially Refunded';
  if ($rs_code === '1') return 'Withheld';
  return null;
}
function build_section_title($base, $rows, $params){
  $bid       = $params['bid'];
  $uid       = $params['uid'];
  $tid       = $params['tid'];
  $start     = $params['start'];
  $end       = $params['end'];
  $rs        = $params['rs'];

  $prefix = refund_label_from_rs($rs);
  $title  = ($prefix ? ($prefix . ' ') : '') . $base;

  $bits = [];
  if ($bid > 0) {
    $block_name = first_val($rows, 'b_name', 'Block #'.$bid);
    $bits[] = "Block: {$block_name}";
  }
  if ($uid > 0) {
    $unit_no = first_val($rows, 'unit_no', 'Unit #'.$uid);
    $bits[] = "Unit: {$unit_no}";
  }
  if ($tid > 0) {
    $tenant_name = first_val($rows, 'r_name', 'Tenant #'.$tid);
    $bits[] = "Tenant: {$tenant_name}";
  }
  if ($start !== '' || $end !== '') {
    $range = ($start !== '' ? human_date($start) : '…') . ' - ' . ($end !== '' ? human_date($end) : '…');
    $bits[] = "Issue Date: {$range}";
  }
  if (!empty($bits)) $title .= ' — ' . implode(' | ', $bits);
  return $title;
}

$params = [
  'bid'   => $bid,
  'uid'   => $uid,
  'tid'   => $tid,
  'start' => $start_str,
  'end'   => $end_str,
  'rs'    => $rs,
];

$title_cedi = build_section_title('Cedi Currency Security Deposit Report', $rows_cedi, $params);
$title_fc   = build_section_title('Foreign Currency Security Deposit Report', $rows_fc, $params);

/* ---------------------------------
   Page <title> helper (top header)
----------------------------------*/
$filter_bits = [];
if ($type === 'query') {
  if ($bid) $filter_bits[] = "Block #{$bid}";
  if ($uid) $filter_bits[] = "Unit #{$uid}";
  if ($tid) $filter_bits[] = "Tenant #{$tid}";
  if ($rs !== '') {
    $map = ['1'=>'Withheld','2'=>'Fully Refunded','3'=>'Partially Refunded'];
    $filter_bits[] = "Refund: " . ($map[$rs] ?? 'Pending');
  }
  if ($start_str !== '' || $end_str !== '') {
    $rng = ($start_str !== '' ? human_date($start_str) : '…') . ' - ' . ($end_str !== '' ? human_date($end_str) : '…');
    $filter_bits[] = "Issue Date: {$rng}";
  }
}
$filter_title = $filter_bits ? (' — ' . e(implode(' | ', $filter_bits))) : '';
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title><?= e($building_name); ?> — Security Deposit Report<?= $filter_title; ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <?php include_once(ROOT_PATH . '/partial/header_script.php'); ?>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
  <style>
    :root{
      --bg:#f8fafc; --bg2:#eef2ff; --card:#fff;
      --ink:#0f172a; --ink2:#334155; --muted:#6b7280; --line:#e5e7eb;
      --brand:#2563eb; --ok:#16a34a; --warn:#d97706; --danger:#dc2626;
      --chip:#e2e8f0;
    }
    body, .box, .table, .btn, .label, .badge {
      font-family:'Inter',system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial;
      color:var(--ink2);
      -webkit-font-smoothing:antialiased;
      -moz-osx-font-smoothing:grayscale;
      font-weight:400;
    }

    h1, h2, h3, .box-title, strong, b, th { font-weight:600; }
    .content-header h1{
      font-weight:600;
      color:var(--ink);
      letter-spacing:.1px;
      display:flex; gap:10px; align-items:center;
      margin-bottom:8px;
    }

    .card{
      background:var(--card);
      border:1px solid var(--line);
      border-radius:14px;
      overflow:hidden;
      box-shadow:0 10px 28px rgba(2,6,23,.06);
      margin-bottom:16px;
    }
    .card-header{
      display:flex; align-items:center; justify-content:space-between; gap:12px;
      padding:12px 14px;
      background:linear-gradient(135deg,var(--bg),var(--bg2));
      border-bottom:1px solid var(--line);
    }
    .card-title{
      margin:0; font-weight:600;
      color:var(--ink); letter-spacing:.1px;
      font-size:16px;
      display:flex; gap:10px; align-items:center;
    }

    .btn{ border:none; font-weight:600; border-radius:10px; }
    .btn-compact{ padding:6px 10px !important; font-size:12px !important; line-height:1.25 !important; }
    .btn-primary{ background:var(--brand); color:#fff; }
    .btn-success{ background:var(--ok); color:#fff; }
    .btn-soft{ background:#fff; border:1px solid var(--line); color:var(--ink2); }
    .btn:hover{ filter:brightness(.97); }

    .table thead th{
      background:#f8fafc;
      color:var(--ink);
      font-weight:600;
      border-bottom:1px solid var(--line) !important;
      white-space:nowrap;
    }
    .table tbody td{ vertical-align:middle; font-weight:500; }
    .table tfoot th{ font-weight:600; color:var(--ink); }
    .table tfoot th span{ font-weight:600; }

    .chip{
      display:inline-flex; align-items:center; gap:6px;
      padding:3px 8px; border-radius:999px; border:1px solid var(--line);
      font-weight:600;
      font-size:11px;
      white-space:nowrap;
    }
    .chip.paid{ background:#ecfdf5; color:#065f46; border-color:#bbf7d0; }
    .chip.partial{ background:#fff7ed; color:#92400e; border-color:#fed7aa; }
    .chip.unpaid{ background:#fef2f2; color:#991b1b; border-color:#fecaca; }

    .print-fab{
      position:fixed; right:12px; top:12px; z-index:999;
      border-radius:999px; padding:8px 10px; box-shadow:0 10px 24px rgba(2,6,23,.12);
      font-weight:600;
    }

    @media print {
      .print-hide { display:none !important; }
      .card { box-shadow:none; border:1px solid #ddd; }
      .table thead th, .table tfoot th { color:#000; }
    }
  </style>
  <script>
    function printContent(area, title) {
      $("#" + area).printThis({ pageTitle: title });
    }
  </script>
</head>
<body>
<section class="content">

  <!-- Header -->
  <section class="content-header print-hide">
    <h1>
      <i class="fa fa-shield"></i> Security Deposit Report
      <span style="font-size:14px; font-weight:500; color:#64748b;"><?= $filter_title; ?></span>
    </h1>
    <ol class="breadcrumb">
      <li><a href="<?= WEB_URL ?>dashboard.php"><i class="fa fa-dashboard"></i><?= e($_data['home_breadcam']); ?></a></li>
      <li class="active"><?= e($_data['text_2'] ?? 'Reports'); ?></li>
      <li class="active">Security Deposit Report</li>
    </ol>
  </section>

  <!-- Printable wrapper -->
  <div id="printable">
    <div style="margin:20px 12px 50px 12px;">
      <input type="hidden" id="web_url" value="<?= WEB_URL; ?>" />

      <!-- Report top (logo/title/address/etc.) -->
      <?php include_once(ROOT_PATH . 'partial/report_top_title.php'); ?>

      <!-- Quick filters -->
      <div class="card print-hide">
        <div class="card-header">
          <h3 class="card-title"><i class="fa fa-filter"></i> Quick Filters</h3>
          <div class="filter-wrap" style="display:flex; gap:16px; flex-wrap:wrap; align-items:center;">
            <div>
              <div class="filter-label" style="font-size:12px; color:#6b7280; font-weight:600; text-transform:uppercase; letter-spacing:.2px;">Payment Status</div>
              <div class="filter-group" style="display:flex; gap:8px; flex-wrap:wrap; align-items:center;">
                <button class="btn btn-soft btn-compact pay-filter active" data-filter="all"><i class="fa fa-list"></i> All</button>
                <button class="btn btn-soft btn-compact pay-filter" data-filter="paid"><i class="fa fa-check-circle"></i> Paid</button>
                <button class="btn btn-soft btn-compact pay-filter" data-filter="partial"><i class="fa fa-adjust"></i> Partial</button>
                <button class="btn btn-soft btn-compact pay-filter" data-filter="unpaid"><i class="fa fa-exclamation-circle"></i> Unpaid</button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- CEDI REPORT -->
      <div id="print-cedi" class="card">
        <div class="card-header">
          <h3 class="card-title"><?= e($title_cedi); ?></h3>
          <div class="print-hide">
            <button class="btn btn-primary btn-compact" onclick="printContent('print-cedi','<?= e($title_cedi); ?>')"><i class="fa fa-print"></i> Print</button>
          </div>
        </div>
        <div class="box-body" style="padding:16px;">
          <div style="overflow:auto;">
            <table id="table-cedi" class="table table-bordered table-striped dt-responsive"
                   data-cur="<?= e($ghs_symbol); ?>">
              <thead>
                <tr>
                  <th>Tenant</th>
                  <th>Block</th>
                  <th>Unit</th>
                  <th>Amount Paid (<?= e($ghs_symbol); ?>)</th>
                  <th>Balance (<?= e($ghs_symbol); ?>)</th>
                  <th>Total Deposit (<?= e($ghs_symbol); ?>)</th>
                  <th>Amount Refunded (<?= e($ghs_symbol); ?>)</th>
                  <th>Amount Withheld (<?= e($ghs_symbol); ?>)</th>
                  <th>Payment Status</th>
                  <th>Issue Date</th>
                </tr>
              </thead>
              <tbody>
              <?php if (count($rows_cedi) === 0): ?>
                <tr><td colspan="10">No Data Available</td></tr>
              <?php else:
                foreach ($rows_cedi as $row):
                  $tenant   = $row['r_name'];
                  $block    = $row['b_name'];
                  $unit     = $row['unit_no'];
                  $rate     = (float)($row['rate'] ?? 0);
                  $paid     = (float)($row['amt_paid'] ?? 0);
                  $ref      = (float)($row['amount_refunded'] ?? 0);
                  $s_status = isset($row['s_status']) ? (int)$row['s_status'] : 0;

                  $bal      = $rate - $paid;
                  $withheld_num = ($s_status !== 0) ? ($paid - $ref) : 0.0;
                  $withheld_display = ($s_status !== 0) ? number_format($withheld_num, 2) : 'Pending';

                  // Payment status
                  if ($paid <= 0) { $p_key='unpaid';  $p_txt='Unpaid';  }
                  elseif ($paid < $rate) { $p_key='partial'; $p_txt='Partial'; }
                  else { $p_key='paid'; $p_txt='Paid'; }
              ?>
                <tr
                  data-status="<?= $p_key; ?>"
                  data-paid="<?= number_format($paid, 2, '.', ''); ?>"
                  data-balance="<?= number_format($bal, 2, '.', ''); ?>"
                  data-total="<?= number_format($rate, 2, '.', ''); ?>"
                  data-refunded="<?= number_format($ref, 2, '.', ''); ?>"
                  data-withheld="<?= number_format($withheld_num, 2, '.', ''); ?>"
                >
                  <td><?= e($tenant); ?></td>
                  <td><?= e($block); ?></td>
                  <td><?= e($unit); ?></td>
                  <td><?= number_format($paid, 2); ?></td>
                  <td><?= number_format($bal, 2); ?></td>
                  <td><?= number_format($rate, 2); ?></td>
                  <td><?= number_format($ref, 2); ?></td>
                  <td><?= $withheld_display; ?></td>
                  <td><span class="chip <?= $p_key; ?>"><?= $p_txt; ?></span></td>
                  <td><?= e($row['issue_date']); ?></td>
                </tr>
              <?php endforeach; endif; ?>
              </tbody>
              <tfoot>
                <tr>
                  <th colspan="3" style="text-align:right;">Totals:</th>
                  <th style="color:#1e40af;"><span id="cedi_paid_total"><?= $ghs_symbol . ' ' . number_format($tot_ghs['paid'], 2); ?></span></th>
                  <th style="color:#b91c1c;"><span id="cedi_balance_total"><?= $ghs_symbol . ' ' . number_format($tot_ghs['balance'], 2); ?></span></th>
                  <th style="color:#14532d;"><span id="cedi_total_total"><?= $ghs_symbol . ' ' . number_format($tot_ghs['total'], 2); ?></span></th>
                  <th style="color:#0e7490;"><span id="cedi_refunded_total"><?= $ghs_symbol . ' ' . number_format($tot_ghs['refunded'], 2); ?></span></th>
                  <th style="color:#78350f;"><span id="cedi_withheld_total"><?= $ghs_symbol . ' ' . number_format($tot_ghs['withheld'], 2); ?></span></th>
                  <th colspan="2">&nbsp;</th>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>
      </div>

      <!-- FOREIGN CURRENCY REPORT -->
      <div id="print-fc" class="card">
        <div class="card-header">
          <h3 class="card-title"><?= e($title_fc); ?></h3>
          <div class="print-hide">
            <button class="btn btn-primary btn-compact" onclick="printContent('print-fc','<?= e($title_fc); ?>')"><i class="fa fa-print"></i> Print</button>
          </div>
        </div>
        <div class="box-body" style="padding:16px;">
          <div style="overflow:auto;">
            <table id="table-fc" class="table table-bordered table-striped dt-responsive"
                   data-cur="<?= e($fc_symbol); ?>">
              <thead>
                <tr>
                  <th>Tenant</th>
                  <th>Block</th>
                  <th>Unit</th>
                  <th>Amount Paid (<?= e($fc_symbol); ?>)</th>
                  <th>Balance (<?= e($fc_symbol); ?>)</th>
                  <th>Total Deposit (<?= e($fc_symbol); ?>)</th>
                  <th>Amount Refunded (<?= e($fc_symbol); ?>)</th>
                  <th>Amount Withheld (<?= e($fc_symbol); ?>)</th>
                  <th>Payment Status</th>
                  <th>Issue Date</th>
                </tr>
              </thead>
              <tbody>
              <?php if (count($rows_fc) === 0): ?>
                <tr><td colspan="10">No Data Available</td></tr>
              <?php else:
                foreach ($rows_fc as $row):
                  $tenant   = $row['r_name'];
                  $block    = $row['b_name'];
                  $unit     = $row['unit_no'];
                  $rate     = (float)($row['rate'] ?? 0);
                  $paid     = (float)($row['amt_paid'] ?? 0);
                  $ref      = (float)($row['amount_refunded'] ?? 0);
                  $s_status = isset($row['s_status']) ? (int)$row['s_status'] : 0;

                  $bal      = $rate - $paid;
                  $withheld_num = ($s_status !== 0) ? ($paid - $ref) : 0.0;
                  $withheld_display = ($s_status !== 0) ? number_format($withheld_num, 2) : 'Pending';

                  if ($paid <= 0) { $p_key='unpaid';  $p_txt='Unpaid';  }
                  elseif ($paid < $rate) { $p_key='partial'; $p_txt='Partial'; }
                  else { $p_key='paid'; $p_txt='Paid'; }
              ?>
                <tr
                  data-status="<?= $p_key; ?>"
                  data-paid="<?= number_format($paid, 2, '.', ''); ?>"
                  data-balance="<?= number_format($bal, 2, '.', ''); ?>"
                  data-total="<?= number_format($rate, 2, '.', ''); ?>"
                  data-refunded="<?= number_format($ref, 2, '.', ''); ?>"
                  data-withheld="<?= number_format($withheld_num, 2, '.', ''); ?>"
                >
                  <td><?= e($tenant); ?></td>
                  <td><?= e($block); ?></td>
                  <td><?= e($unit); ?></td>
                  <td><?= number_format($paid, 2); ?></td>
                  <td><?= number_format($bal, 2); ?></td>
                  <td><?= number_format($rate, 2); ?></td>
                  <td><?= number_format($ref, 2); ?></td>
                  <td><?= $withheld_display; ?></td>
                  <td><span class="chip <?= $p_key; ?>"><?= $p_txt; ?></span></td>
                  <td><?= e($row['issue_date']); ?></td>
                </tr>
              <?php endforeach; endif; ?>
              </tbody>
              <tfoot>
                <tr>
                  <th colspan="3" style="text-align:right;">Totals:</th>
                  <th style="color:#1e40af;"><span id="fc_paid_total"><?= $fc_symbol . ' ' . number_format($tot_fc['paid'], 2); ?></span></th>
                  <th style="color:#b91c1c;"><span id="fc_balance_total"><?= $fc_symbol . ' ' . number_format($tot_fc['balance'], 2); ?></span></th>
                  <th style="color:#14532d;"><span id="fc_total_total"><?= $fc_symbol . ' ' . number_format($tot_fc['total'], 2); ?></span></th>
                  <th style="color:#0e7490;"><span id="fc_refunded_total"><?= $fc_symbol . ' ' . number_format($tot_fc['refunded'], 2); ?></span></th>
                  <th style="color:#78350f;"><span id="fc_withheld_total"><?= $fc_symbol . ' ' . number_format($tot_fc['withheld'], 2); ?></span></th>
                  <th colspan="2">&nbsp;</th>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>
      </div>

    </div>
  </div>

  <!-- Floating Print All Button -->
  <div class="print-hide">
    <a title="<?= e($_data['text_16'] ?? 'Print'); ?>" class="btn btn-success btn-compact print-fab"
       onclick="printContent('printable','Security Deposit Report<?= $filter_title; ?>')" href="javascript:void(0);">
      <i class="fa fa-print"></i>
    </a>
  </div>

</section>

<script>
  // Format with 2 decimals
  function fmt(n){
    return (n||0).toLocaleString(undefined,{minimumFractionDigits:2, maximumFractionDigits:2});
  }

  function sumVisible(tableSel){
    var t = document.querySelector(tableSel);
    var rows = t.querySelectorAll('tbody tr');
    var sum = {paid:0, bal:0, tot:0, ref:0, wth:0, cur:(t.dataset.cur||'')};
    rows.forEach(function(tr){
      if (tr.style.display === 'none') return;
      sum.paid += parseFloat(tr.dataset.paid     || '0');
      sum.bal  += parseFloat(tr.dataset.balance  || '0');
      sum.tot  += parseFloat(tr.dataset.total    || '0');
      sum.ref  += parseFloat(tr.dataset.refunded || '0');
      sum.wth  += parseFloat(tr.dataset.withheld || '0');
    });
    return sum;
  }

  function updateFooter(tableSel, ids){
    var s = sumVisible(tableSel);
    var pref = s.cur ? (s.cur + ' ') : '';
    document.getElementById(ids.paid).textContent     = pref + fmt(s.paid);
    document.getElementById(ids.balance).textContent  = pref + fmt(s.bal);
    document.getElementById(ids.total).textContent    = pref + fmt(s.tot);
    document.getElementById(ids.refunded).textContent = pref + fmt(s.ref);
    document.getElementById(ids.withheld).textContent = pref + fmt(s.wth);
  }

  // Payment-only quick filter
  var payFilter = 'all';

  function applyFilters(){
    document.querySelectorAll('.pay-filter').forEach(function(b){
      b.classList.toggle('active', b.getAttribute('data-filter')===payFilter);
    });

    ['#table-cedi','#table-fc'].forEach(function(sel){
      document.querySelectorAll(sel + ' tbody tr').forEach(function(tr){
        var st = (tr.getAttribute('data-status')||'').toLowerCase();
        var payMatch = (payFilter==='all') ? true : (st === payFilter);
        tr.style.display = payMatch ? '' : 'none';
      });
    });

    updateFooter('#table-cedi', {
      paid:'cedi_paid_total',
      balance:'cedi_balance_total',
      total:'cedi_total_total',
      refunded:'cedi_refunded_total',
      withheld:'cedi_withheld_total'
    });
    updateFooter('#table-fc', {
      paid:'fc_paid_total',
      balance:'fc_balance_total',
      total:'fc_total_total',
      refunded:'fc_refunded_total',
      withheld:'fc_withheld_total'
    });
  }

  // Wire up filter buttons
  document.querySelectorAll('.pay-filter').forEach(function(b){
    b.addEventListener('click', function(){ payFilter = this.getAttribute('data-filter'); applyFilters(); });
  });

  // Initial view
  applyFilters();
</script>
</body>
</html>
