<?php /* sales/index.php */
$sym = setting('currency_symbol','Rs.');
$pmtConfig = [
  'paid'    => ['bg-success','','Paid'],
  'partial' => ['bg-warning text-dark','','Partial'],
  'unpaid'  => ['bg-danger','','Unpaid'],
];
$methodIcon = [
  'cash'=>'bi-cash-stack','card'=>'bi-credit-card-2-front',
  'mobile'=>'bi-phone','cheque'=>'bi-bank2',
  'bank_transfer'=>'bi-bank','credit'=>'bi-person-lines-fill',
];
$data     = $pagination['data'];
$lastPage = $pagination['pages'];
$curPage  = $pagination['current'];
$perPage  = $pagination['perPage'];
?>

<style>
.sl-hero{
  background:#0f172a;
  border-radius:14px;padding:20px 26px;color:#fff;margin-bottom:18px;
  border:1px solid #1e293b;
  box-shadow:0 4px 20px rgba(0,0,0,.15);
}
.sl-hero .page-title{font-size:1.2rem;font-weight:800;letter-spacing:-.01em;margin-bottom:3px;
  display:flex;align-items:center;gap:10px}
.sl-hero .page-meta{font-size:.78rem;color:#94a3b8;display:flex;align-items:center;gap:6px;flex-wrap:wrap}
.sl-hero .page-meta .sep{color:#334155}
.sl-hero .hero-btn{border-radius:10px;font-weight:600;font-size:.82rem;padding:7px 16px;
  display:inline-flex;align-items:center;gap:6px;text-decoration:none;transition:all .15s}
.sl-hero .btn-primary-dash{background:#3b82f6;color:#fff;border:none}
.sl-hero .btn-primary-dash:hover{background:#2563eb;color:#fff;transform:translateY(-1px)}
.sl-hero .btn-ghost{background:transparent;color:#94a3b8;border:1px solid #334155}
.sl-hero .btn-ghost:hover{background:#1e293b;color:#fff;border-color:#475569}
.kpi-pill{border-radius:10px;padding:12px 14px;text-align:center}
.kpi-pill .val{font-size:1.3rem;font-weight:900;line-height:1}
.kpi-pill .lbl{font-size:.65rem;text-transform:uppercase;letter-spacing:.05em;opacity:.8;margin-top:2px}
.sl-table th{font-size:.7rem;padding:8px 10px;white-space:nowrap}
.sl-table td{font-size:.78rem;padding:7px 10px;vertical-align:middle}
.sl-table tr:hover td{background:#f8fafc}
.chq-badge{display:inline-flex;align-items:center;gap:3px;padding:2px 7px;
  border-radius:20px;font-size:.62rem;font-weight:700}
.pay-method-icon{font-size:.9rem}
.print-only{display:none}

/* ── Print / PDF ─────────────────────────────────────── */
@media print {
  @page{size:A4 portrait;margin:12mm 10mm 14mm 10mm}

  .no-print,.sl-hero,.kpi-pill,.card.mb-3:first-of-type,
  .pagination,.btn,.hero-btn,.btn-ghost,.btn-primary-dash,
  form,.alert:not(.alert-print){display:none!important}

  .print-only{display:block!important}
  .print-header-block{display:block!important}

  html,body{background:#fff!important;font-size:9pt;color:#111;font-family:Arial,sans-serif}

  .card{border:1px solid #ccc!important;box-shadow:none!important;
    break-inside:avoid;margin-bottom:6pt!important;border-radius:3px!important}
  .card-header{background:#1e3a8a!important;color:#fff!important;
    border-bottom:1px solid #ccc!important;padding:4pt 8pt!important;
    font-size:8.5pt!important;font-weight:700!important;
    print-color-adjust:exact;-webkit-print-color-adjust:exact}
  .card-body{padding:0!important}

  .table{font-size:8pt!important;border-collapse:collapse!important;width:100%!important}
  .table th,.table td{border:0.5pt solid #ddd!important;padding:3.5pt 5pt!important;vertical-align:middle!important}
  .table thead th{background:#0f2557!important;color:#fff!important;
    font-weight:700!important;font-size:7.5pt!important;
    text-transform:uppercase!important;
    print-color-adjust:exact;-webkit-print-color-adjust:exact}
  .table tfoot td{background:#e8edf5!important;font-weight:700!important;
    print-color-adjust:exact;-webkit-print-color-adjust:exact}
  .table-responsive,[style*="overflow"],[style*="max-height"]{
    overflow:visible!important;max-height:none!important;height:auto!important}
  .table{width:100%!important;table-layout:auto!important}

  .badge{border:1pt solid #999!important;padding:1pt 4pt!important;
    font-size:7pt!important;border-radius:3px!important;
    print-color-adjust:exact;-webkit-print-color-adjust:exact}
  .bg-success{background:#166534!important;color:#fff!important}
  .bg-danger {background:#991b1b!important;color:#fff!important}
  .bg-warning{background:#92400e!important;color:#fff!important}

  .text-success{color:#166534!important}
  .text-danger {color:#991b1b!important}
  .text-primary{color:#1e40af!important}
  .text-muted  {color:#6b7280!important}
  .fw-bold,.fw-semibold{font-weight:700!important}

  a{color:inherit!important;text-decoration:none!important}
  .text-end{text-align:right!important}
  .text-center{text-align:center!important}
  .no-print-inline{display:none!important}
  .print-only-inline{display:inline!important}
}
.print-header-block{display:none}
@media print{.print-header-block{display:block!important;margin-bottom:8pt}}
</style>

<!-- PRINT-ONLY PDF HEADER -->
<div class="print-header-block">
  <table width="100%" cellpadding="0" cellspacing="0"
         style="padding-bottom:6pt;margin-bottom:4pt">
    <tr>
      <td style="width:55%;vertical-align:top">
        <div style="font-size:15pt;font-weight:900;color:#0f2557;line-height:1.1">
          <?=e(setting('shop_name','MJPOS'))?>
        </div>
        <?php if(setting('shop_address','')): ?>
        <div style="font-size:8pt;color:#475569;margin-top:2pt"><?=e(setting('shop_address',''))?></div>
        <?php endif; ?>
        <?php if(setting('shop_phone','')): ?>
        <div style="font-size:8pt;color:#475569;margin-top:1pt">
          Tel: <?=e(setting('shop_phone',''))?>
          <?php if(setting('shop_email','')): ?> &nbsp;|&nbsp; <?=e(setting('shop_email',''))?><?php endif;?>
        </div>
        <?php endif; ?>
      </td>
      <td style="width:45%;text-align:right;vertical-align:top">
        <div style="font-size:14pt;font-weight:900;color:#0f2557;text-transform:uppercase;letter-spacing:.02em">
          SALES LIST
          <span style="font-size:9pt;font-weight:700"> &mdash; <?=date('d M Y',strtotime($from))?> to <?=date('d M Y',strtotime($to))?></span>
        </div>
        <div style="font-size:7.5pt;color:#64748b;margin-top:3pt">
          Generated by: <strong><?=Auth::name()?></strong>
          &nbsp;&nbsp;|&nbsp;&nbsp;
          Date: <?=date('d M Y, H:i')?>
        </div>
      </td>
    </tr>
  </table>
  <div style="height:3pt;background:linear-gradient(90deg,#0f2557 0%,#1d4ed8 50%,#60a5fa 100%);
              margin-bottom:6pt;print-color-adjust:exact;-webkit-print-color-adjust:exact"></div>

  <!-- Print KPI summary -->
  <div style="display:flex;gap:0;border:1pt solid #0f2557;border-radius:3pt;
              overflow:hidden;margin-bottom:8pt">
    <div style="flex:1;padding:6pt 10pt;border-right:1pt solid #e2e8f0;
                text-align:center;background:#eff6ff">
      <div style="font-size:12pt;font-weight:900;color:#1d4ed8"><?=$sym?><?=number_format($summary['total'],2)?></div>
      <div style="font-size:6.5pt;text-transform:uppercase;color:#64748b;margin-top:2pt">
        Total Sales (<?=$summary['count']?> invoices)
      </div>
    </div>
    <div style="flex:1;padding:6pt 10pt;border-right:1pt solid #e2e8f0;
                text-align:center;background:#fef2f2">
      <div style="font-size:12pt;font-weight:900;color:#dc2626"><?=$sym?><?=number_format($summary['balance'],2)?></div>
      <div style="font-size:6.5pt;text-transform:uppercase;color:#64748b;margin-top:2pt">Outstanding Balance</div>
    </div>
    <div style="flex:1;padding:6pt 10pt;text-align:center;
                background:<?=$summary['balance']>0?'#fef2f2':'#f0fdf4'?>">
      <div style="font-size:12pt;font-weight:900;color:<?=$summary['balance']>0?'#dc2626':'#16a34a'?>">
        <?=$summary['total']>0?round($summary['paid']/$summary['total']*100,1):100?>%
      </div>
      <div style="font-size:6.5pt;text-transform:uppercase;color:#64748b;margin-top:2pt">Collection Rate</div>
    </div>
  </div>
</div>

<!-- Hero -->
<div class="sl-hero">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
    <div>
      <div class="page-title">
        <i class="bi bi-receipt" style="color:#3b82f6"></i>
        Sales List
      </div>
      <div class="page-meta">
        <i class="bi bi-calendar3" style="font-size:.7rem"></i>
        <?= date('d M Y', strtotime($from)) ?> – <?= date('d M Y', strtotime($to)) ?>
        <span class="sep">·</span>
        <i class="bi bi-file-text" style="font-size:.7rem"></i>
        <?= number_format($summary['count']) ?> invoice<?=$summary['count']!=1?'s':''?>
        <span class="sep">·</span>
        Total <span style="color:#f8fafc;font-weight:600"><?= $sym ?><?= number_format($summary['total'],2) ?></span>
        <?php if($summary['balance']>0):?>
        <span class="sep">·</span>
        <span style="color:#fbbf24">Due <?=$sym?><?=number_format($summary['balance'],2)?></span>
        <?php endif;?>
        <?php if($pendingCheques>0):?>
        <a href="<?=APP_URL?>/cheques/pending"
           style="background:#d97706;color:#fff;border-radius:20px;padding:1px 8px;
                  font-size:.65rem;font-weight:700;text-decoration:none">
          <i class="bi bi-hourglass-split me-1"></i><?=$pendingCheques?> cheque<?=$pendingCheques>1?'s':''?> pending
        </a>
        <?php endif;?>
      </div>
    </div>
    <div class="d-flex gap-2">
      <a href="<?= APP_URL ?>/pos" class="hero-btn btn-primary-dash">
        <i class="bi bi-plus-circle"></i>New Sale
      </a>
      <button onclick="window.print()" class="hero-btn btn-ghost">
        <i class="bi bi-printer"></i>Print
      </button>
    </div>
  </div>
</div>

<?= flashMessages() ?>

<!-- KPI Summary -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md">
    <div class="kpi-pill" style="background:#eff6ff;border:2px solid #3b82f6">
      <div class="val" style="color:#3b82f6">
        <?= $sym ?><?= number_format($summary['total'],0) ?>
      </div>
      <div class="lbl" style="color:#3b82f6">
        Total Sales (<?= number_format($summary['count']) ?>)
      </div>
    </div>
  </div>
  <div class="col-6 col-md">
    <div class="kpi-pill" style="background:#f0fdf4;border:2px solid #16a34a">
      <div class="val" style="color:#16a34a">
        <?= $sym ?><?= number_format($summary['paid'],0) ?>
      </div>
      <div class="lbl" style="color:#16a34a">Collected</div>
    </div>
  </div>
  <div class="col-6 col-md">
    <div class="kpi-pill" style="background:#ecfdf5;border:2px solid #0891b2">
      <?php
        $profit     = (float)($summary['gross_profit'] ?? 0);
        $total      = (float)$summary['total'];
        $margin     = $total > 0 ? round($profit / $total * 100, 1) : 0;
        $profitClr  = $profit > 0 ? '#0891b2' : '#dc2626';
        $profitBg   = $profit > 0 ? '#ecfdf5' : '#fef2f2';
        $profitBdr  = $profit > 0 ? '#0891b2' : '#dc2626';
      ?>
      <div class="val" style="color:<?=$profitClr?>">
        <?= $sym ?><?= number_format($profit, 0) ?>
      </div>
      <div class="lbl" style="color:<?=$profitClr?>">
        Gross Profit (<?= $margin ?>%)
      </div>
    </div>
  </div>
  <div class="col-6 col-md">
    <div class="kpi-pill" style="background:#fef2f2;border:2px solid #dc2626">
      <div class="val" style="color:#dc2626">
        <?= $sym ?><?= number_format($summary['balance'],0) ?>
      </div>
      <div class="lbl" style="color:#dc2626">Outstanding</div>
    </div>
  </div>
  <div class="col-6 col-md">
    <div class="kpi-pill" style="background:#fef9c3;border:2px solid #d97706">
      <div class="val" style="color:#d97706">
        <?= $summary['total']>0
            ? round($summary['paid']/$summary['total']*100,1).'%'
            : '0%' ?>
      </div>
      <div class="lbl" style="color:#d97706">Collection Rate</div>
    </div>
  </div>
</div>

<!-- Filters -->
<div class="card mb-3">
  <div class="card-body py-2">
    <form method="GET" action="<?= APP_URL ?>/sales"
          class="d-flex gap-2 flex-wrap align-items-end">
      <!-- Date range -->
      <div class="d-flex gap-1 align-items-center">
        <input type="date" name="from" class="form-control form-control-sm"
               value="<?= e($from) ?>" style="width:135px">
        <span class="text-muted small">to</span>
        <input type="date" name="to" class="form-control form-control-sm"
               value="<?= e($to) ?>" style="width:135px">
      </div>
      <!-- Search -->
      <div class="input-group input-group-sm" style="max-width:200px">
        <span class="input-group-text"><i class="bi bi-search"></i></span>
        <input type="text" name="search" class="form-control"
               placeholder="Invoice, customer…"
               value="<?= e($search) ?>">
      </div>
      <!-- Payment method filter -->
      <select name="method" class="form-select form-select-sm" style="max-width:130px">
        <option value="all" <?=($this->get('method','all')==='all')?'selected':''?>>All Methods</option>
        <option value="cash"         <?=($this->get('method','all')==='cash')?'selected':''?>> Cash</option>
        <option value="card"         <?=($this->get('method','all')==='card')?'selected':''?>> Card</option>
        <option value="mobile"       <?=($this->get('method','all')==='mobile')?'selected':''?>> Mobile</option>
        <option value="cheque"       <?=($this->get('method','all')==='cheque')?'selected':''?>> Cheque</option>
        <option value="bank_transfer"<?=($this->get('method','all')==='bank_transfer')?'selected':''?>> Bank</option>
        <option value="credit"       <?=($this->get('method','all')==='credit')?'selected':''?>> Credit</option>
      </select>
      <!-- Payment status -->
      <select name="pmt" class="form-select form-select-sm" style="max-width:120px">
        <option value="all"     <?=$pmtStatus==='all'?    'selected':''?>>All Status</option>
        <option value="paid"    <?=$pmtStatus==='paid'?   'selected':''?>> Paid</option>
        <option value="partial" <?=$pmtStatus==='partial'?'selected':''?>> Partial</option>
        <option value="unpaid"  <?=$pmtStatus==='unpaid'? 'selected':''?>> Unpaid</option>
      </select>
      <!-- Sale status -->
      <select name="status" class="form-select form-select-sm" style="max-width:130px">
        <option value="all"       <?=$status==='all'?      'selected':''?>>All Sales</option>
        <option value="completed" <?=$status==='completed'?'selected':''?>>Completed</option>
        <option value="cancelled" <?=$status==='cancelled'?'selected':''?>>Cancelled</option>
      </select>
      <!-- Cashier -->
      <?php if(!empty($cashiers)):?>
      <select name="cashier" class="form-select form-select-sm" style="max-width:140px">
        <option value="0">All Cashiers</option>
        <?php foreach($cashiers as $cs):?>
        <option value="<?=$cs['id']?>" <?=$cashierId==$cs['id']?'selected':''?>>
          <?=e($cs['name'])?>
        </option>
        <?php endforeach;?>
      </select>
      <?php endif;?>
      <button class="btn btn-secondary btn-sm fw-semibold">
        <i class="bi bi-funnel me-1"></i>Filter
      </button>
      <a href="<?= APP_URL ?>/sales" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-x-lg"></i>
      </a>
      <!-- Quick date shortcuts -->
      <div class="d-flex gap-1 ms-1">
        <?php
        $shortcuts = [
          'Today'       => [date('Y-m-d'), date('Y-m-d')],
          'Yesterday'   => [date('Y-m-d',strtotime('-1 day')), date('Y-m-d',strtotime('-1 day'))],
          'This Week'   => [date('Y-m-d',strtotime('monday this week')), date('Y-m-d')],
          'This Month'  => [date('Y-m-01'), date('Y-m-d')],
          'Last Month'  => [date('Y-m-01',strtotime('first day of last month')), date('Y-m-t',strtotime('last day of last month'))],
        ];
        foreach($shortcuts as $label=>[$f,$t]):
          $active = ($from===$f && $to===$t);
        ?>
        <a href="<?=APP_URL?>/sales?from=<?=$f?>&to=<?=$t?>"
           class="btn btn-sm <?=$active?'btn-primary':'btn-outline-secondary'?>">
          <?=$label?>
        </a>
        <?php endforeach;?>
      </div>
    </form>
  </div>
</div>

<!-- Sales Table -->
<div class="card">
  <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
    <span class="fw-semibold small"><i class="bi bi-table me-1"></i>Sales</span>
    <span class="badge bg-secondary">
      <?= number_format($summary['count']) ?> total &nbsp;·&nbsp;
      Page <?= $curPage ?>/<?= $lastPage ?>
    </span>
  </div>
  <div class="table-responsive">
    <table class="table table-sm table-hover mb-0 sl-table">
      <thead class="table-dark">
        <tr>
          <th class="ps-3">#</th>
          <th>Invoice</th>
          <th>Customer</th>
          <th>Cashier</th>
          <th class="text-center">Date & Time</th>
          <th class="text-center">Method</th>
          <th class="text-end">Total</th>
          <th class="text-end text-success">Paid</th>
          <th class="text-end">Balance / Change</th>
          <th class="text-center">Status</th>
          <th class="text-center">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php if(empty($data)):?>
        <tr>
          <td colspan="11" class="text-center text-muted py-5">
            <i class="bi bi-receipt d-block fs-2 mb-2 opacity-25"></i>
            No sales found for the selected filters.
          </td>
        </tr>
        <?php endif;?>

        <?php
        $rowNum = ($curPage - 1) * $perPage;
        foreach($data as $sale):
          $rowNum++;
          $pmt    = $pmtConfig[$sale['payment_status']] ?? ['bg-secondary','?','Unknown'];
          $chq    = $chequeMap[$sale['id']] ?? null;
          $isCancelled = $sale['status'] === 'cancelled';

          // Determine primary payment method from payment_status context
          $pm = 'cash'; // default
          // We can't easily get method per row without extra query, show from chequeMap
        ?>
        <tr class="<?= $isCancelled ? 'opacity-50' : '' ?>">
          <td class="ps-3 text-muted small"><?= $rowNum ?></td>

          <!-- Invoice -->
          <td>
            <a href="<?= APP_URL ?>/sales/view/<?= $sale['id'] ?>"
               class="fw-bold text-decoration-none text-primary">
              <?= e($sale['invoice_no']) ?>
            </a>
            <?php if($isCancelled):?>
            <span class="badge bg-danger ms-1" style="font-size:.55rem">Cancelled</span>
            <?php endif;?>
            <?php if($chq):
              $chqCls = ['pending'=>'bg-warning text-dark','cleared'=>'bg-success','bounced'=>'bg-danger'][$chq['cheque_status']]??'bg-secondary';
              $chqIcon= ['pending'=>'','cleared'=>'','bounced'=>''][$chq['cheque_status']]??'';
            ?>
            <span class="chq-badge <?=$chqCls?> mt-1 d-block">
              <i class="bi bi-bank2"></i>
              <?=$chqIcon?> CHQ <?=$chq['cheque_no']?:'#'?>
            </span>
            <?php endif;?>
          </td>

          <!-- Customer -->
          <td>
            <div class="fw-semibold"><?= e($sale['customer_name']) ?></div>
            <?php if($sale['customer_phone']):?>
            <div style="font-size:.65rem;color:#94a3b8"><?= e($sale['customer_phone']) ?></div>
            <?php endif;?>
          </td>

          <!-- Cashier -->
          <td class="text-muted small"><?= e($sale['cashier_name'] ?? '—') ?></td>

          <!-- Date -->
          <td class="text-center">
            <div class="small fw-semibold"><?= date('d M Y', strtotime($sale['sale_date'])) ?></div>
            <div style="font-size:.65rem;color:#94a3b8"><?= date('H:i', strtotime($sale['sale_date'])) ?></div>
          </td>

          <!-- Method -->
          <td class="text-center">
            <?php
            $saleMethods = $methodMap[$sale['id']] ?? ['cash'];
            $methIcons = [
              'cash'         => ['bi-cash-stack',          '#16a34a','Cash'],
              'card'         => ['bi-credit-card-2-front', '#3b82f6','Card'],
              'mobile'       => ['bi-phone',               '#7c3aed','Mobile'],
              'cheque'       => ['bi-bank2',               '#d97706','Cheque'],
              'bank_transfer'=> ['bi-building',            '#0891b2','Bank'],
              'credit'       => ['bi-person-lines-fill',   '#dc2626','Credit'],
            ];
            foreach($saleMethods as $sm):
              $mi = $methIcons[$sm] ?? ['bi-cash','#64748b', ucfirst($sm)];
            ?>
            <span class="d-inline-flex align-items-center gap-1 me-1"
                  style="font-size:.68rem;font-weight:700;color:<?=$mi[1]?>"
                  title="<?=$mi[2]?>">
              <i class="bi <?=$mi[0]?>"></i>
              <?=$mi[2]?>
            </span>
            <?php endforeach; ?>
          </td>

          <!-- Total -->
          <td class="text-end fw-bold"><?= $sym ?><?= number_format($sale['total'],2) ?></td>

          <!-- Paid -->
          <td class="text-end text-success fw-semibold">
            <?= $sym ?><?= number_format($sale['paid'],2) ?>
          </td>

          <!-- Balance -->
          <td class="text-end">
            <?php
            $balAmt   = (float)$sale['balance'];
            $paidAmt  = (float)$sale['paid'];
            $totalAmt = (float)$sale['total'];
            $change   = round($paidAmt - $totalAmt, 2);
            if ($balAmt > 0.01):
            ?>
            <span class="fw-bold" style="color:#dc2626">
              <?=$sym?><?=number_format($balAmt,2)?>
            </span>
            <?php elseif($change > 0.01): ?>
            <span style="color:#0891b2;font-size:.72rem">
              <i class="bi bi-arrow-left-right" style="font-size:.6rem"></i>
              <?=$sym?><?=number_format($change,2)?>
            </span>
            <?php else: ?>
            <span style="color:#16a34a;font-size:.82rem">
              <i class="bi bi-check-circle-fill"></i>
            </span>
            <?php endif;?>
          </td>

          <!-- Payment Status -->
          <td class="text-center">
            <span class="badge <?= $pmt[0] ?>" style="font-size:.65rem">
              <?= $pmt[1] ?> <?= $pmt[2] ?>
            </span>
          </td>

          <!-- Actions -->
          <td class="text-center">
            <div class="d-flex gap-1 justify-content-center">
              <a href="<?= APP_URL ?>/sales/view/<?= $sale['id'] ?>"
                 class="btn btn-sm btn-outline-primary py-0 px-2" title="View">
                <i class="bi bi-eye"></i>
              </a>
              <?php if($sale['balance'] > 0.01 && !$isCancelled && Auth::can('sales.create')):?>
              <a href="<?= APP_URL ?>/sales/payment/<?= $sale['id'] ?>"
                 class="btn btn-sm btn-outline-success py-0 px-2" title="Record Payment">
                <i class="bi bi-cash"></i>
              </a>
              <?php endif;?>
              <?php if(!$isCancelled && Auth::can('sales.delete')):?>
              <form method="POST" action="<?= APP_URL ?>/sales/cancel/<?= $sale['id'] ?>"
                    onsubmit="return confirm('Cancel invoice <?= e($sale['invoice_no']) ?>?')">
                <?= Auth::csrfField() ?>
                <button class="btn btn-sm btn-outline-danger py-0 px-1" title="Cancel">
                  <i class="bi bi-x-lg"></i>
                </button>
              </form>
              <?php endif;?>
            </div>
          </td>
        </tr>
        <?php endforeach;?>
      </tbody>

      <!-- Footer totals -->
      <?php if(!empty($data)):?>
      <tfoot class="table-secondary fw-bold" style="font-size:.75rem">
        <tr>
          <td colspan="6" class="ps-3">
            PAGE TOTAL (<?= count($data) ?> invoices)
          </td>
          <td class="text-end"><?=$sym?><?=number_format(array_sum(array_column($data,'total')),2)?></td>
          <td class="text-end text-muted">—</td>
          <td class="text-end <?= array_sum(array_column($data,'balance'))>0?'text-danger':'text-success' ?>">
            <?php
            $pageBalance = array_sum(array_column($data,'balance'));
            echo $pageBalance > 0 ? $sym.number_format($pageBalance,2) : ' Rs.0.00';
            ?>
          </td>
          <td colspan="2"></td>
        </tr>
      </tfoot>
      <?php endif;?>
    </table>
  </div>

  <!-- Pagination -->
  <?php if($lastPage > 1):?>
  <div class="card-footer d-flex justify-content-between align-items-center py-2">
    <span class="text-muted small">
      Page <?= $curPage ?> of <?= $lastPage ?>
      &nbsp;·&nbsp; <?= number_format($summary['count']) ?> total records
    </span>
    <nav>
      <ul class="pagination pagination-sm mb-0">
        <li class="page-item <?= $curPage<=1?'disabled':''?>">
          <a class="page-link" href="?<?= http_build_query(array_merge($_GET,['page'=>$curPage-1])) ?>">
            ‹ Prev
          </a>
        </li>
        <?php
        $range = range(max(1,$curPage-2), min($lastPage,$curPage+2));
        if($range[0]>1){ echo '<li class="page-item disabled"><span class="page-link">…</span></li>'; }
        foreach($range as $p):
        ?>
        <li class="page-item <?= $p===$curPage?'active':''?>">
          <a class="page-link"
             href="?<?= http_build_query(array_merge($_GET,['page'=>$p])) ?>">
            <?= $p ?>
          </a>
        </li>
        <?php endforeach;?>
        <?php if(end($range)<$lastPage){ echo '<li class="page-item disabled"><span class="page-link">…</span></li>'; }?>
        <li class="page-item <?= $curPage>=$lastPage?'disabled':''?>">
          <a class="page-link" href="?<?= http_build_query(array_merge($_GET,['page'=>$curPage+1])) ?>">
            Next ›
          </a>
        </li>
      </ul>
    </nav>
  </div>
  <?php endif;?>
</div>