<?php /* finance/account_ledger.php &mdash; Advanced Edition */
$sym    = setting('currency_symbol','Rs.');
$isCash = $account['account_type'] === 'cash';
$acClr  = $isCash ? '#16a34a' : '#1d4ed8';
$acBg   = $isCash ? '#f0fdf4' : '#eff6ff';
$acIcon = $isCash ? 'bi-cash-stack' : 'bi-bank';

// Compute stats from transactions
$totalIn  = array_sum(array_map(fn($t)=>in_array($t['txn_type'],['deposit','transfer_in'])?$t['amount']:0, $txns));
$totalOut = array_sum(array_map(fn($t)=>in_array($t['txn_type'],['withdrawal','transfer_out'])?$t['amount']:0, $txns));
$txnCount = count($txns);

// POS auto-deposits in this list
$posDeposits = array_filter($txns, fn($t)=>str_starts_with($t['note']??'','POS Sale:'));
$posTotalIn  = array_sum(array_column(iterator_to_array((function() use($posDeposits){foreach($posDeposits as $p){if(in_array($p['txn_type'],['deposit','transfer_in']))yield $p;}})(), false),'amount'));

$returnWithdrawals = array_filter($txns, fn($t)=>str_starts_with($t['note']??'','Sale Return:'));
?>
<style>
.al-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)}
.al-hero .page-title{font-size:1.2rem;font-weight:800;display:flex;align-items:center;gap:10px;margin-bottom:4px}
.al-hero .page-meta{font-size:.78rem;color:#94a3b8;display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.al-hero .sep{color:#334155}

.bal-card{border-radius:14px;padding:18px 20px;height:100%;border:2px solid transparent;
  transition:transform .15s,box-shadow .15s}
.bal-card:hover{transform:translateY(-2px);box-shadow:0 6px 18px rgba(0,0,0,.08)}
.bal-card .bv{font-size:1.5rem;font-weight:900;line-height:1;margin-bottom:4px}
.bal-card .bl{font-size:.63rem;text-transform:uppercase;letter-spacing:.07em;font-weight:700;opacity:.75}
.bal-card .bs{font-size:.72rem;margin-top:5px;opacity:.8}

.hero-btn{border-radius:10px;font-weight:600;font-size:.8rem;padding:8px 16px;
  display:inline-flex;align-items:center;gap:6px;transition:all .15s;border:none;cursor:pointer}

.txn-table th{font-size:.68rem;padding:8px 10px;white-space:nowrap}
.txn-table td{font-size:.76rem;padding:7px 10px;vertical-align:middle}
.txn-table tr:hover td{background:#fafbff}

.txn-badge{padding:3px 8px;border-radius:10px;font-size:.62rem;font-weight:700;
  display:inline-flex;align-items:center;gap:3px}
.source-tag{font-size:.6rem;padding:1px 6px;border-radius:8px;font-weight:700}

.date-btn{border-radius:8px;padding:4px 12px;font-size:.72rem;font-weight:600;
  border:1.5px solid #e2e8f0;background:#fff;color:#475569;text-decoration:none;transition:all .12s}
.date-btn.active,.date-btn:hover{background:#0f172a;color:#fff;border-color:#0f172a}

/* ── Print / PDF ─────────────────────────────────────── */
.print-only{display:none}
.print-header-block{display:none}

@media print {
  @page { size:A4 portrait; margin:12mm 10mm 14mm 10mm }

  /* ── Hide everything except ledger content ── */
  .no-print,.al-hero,.bal-card,.date-btn,
  .hero-btn,.modal,.modal-backdrop,
  .card.mb-3,                        /* filter card */
  .row.g-3.mb-4,                     /* KPI row */
  button,.btn,form,
  nav,header,.topbar,.sidebar,#sidebar{
    display:none!important
  }
  .print-only{display:block!important}
  .print-header-block{display:block!important;margin-bottom:8pt}

  /* ── Base reset ── */
  *,*::before,*::after{box-sizing:border-box!important}
  html,body{
    background:#fff!important;
    font-family:Arial,Helvetica,sans-serif!important;
    font-size:8.5pt!important;
    color:#111!important;
    margin:0!important;padding:0!important;
    width:100%!important;
    overflow:visible!important;
    height:auto!important;
  }

  /* ── Remove ALL overflow/scroll constraints ── */
  .table-responsive,
  .card-body,
  .card,
  div[style*="overflow"],
  div[style*="max-height"],
  div[style*="height"]{
    overflow:visible!important;
    max-height:none!important;
    height:auto!important;
  }

  /* ── Card ── */
  .card{
    border:1pt solid #ccc!important;
    box-shadow:none!important;
    break-inside:auto!important;
    margin:0!important;
    border-radius:3pt!important;
    width:100%!important;
  }
  .card-header{
    background:#1e3a8a!important;color:#fff!important;
    padding:4pt 8pt!important;font-size:8pt!important;font-weight:700!important;
    border-bottom:1pt solid #ccc!important;
    print-color-adjust:exact;-webkit-print-color-adjust:exact;
  }

  /* ── Table ── */
  .table,.txn-table{
    font-size:7.5pt!important;
    border-collapse:collapse!important;
    width:100%!important;
    table-layout:auto!important;
  }
  .txn-table th{
    font-size:7pt!important;
    padding:3.5pt 5pt!important;
    white-space:nowrap!important;
  }
  .txn-table td{
    font-size:7.5pt!important;
    padding:3pt 5pt!important;
    vertical-align:top!important;
    word-break:normal!important;
    overflow-wrap:break-word!important;
    max-width:0;
  }
  /* Reference cell &mdash; widest column, allow wrapping */
  .txn-table td:nth-child(3){
    white-space:normal!important;
    word-break:break-word!important;
    max-width:160pt!important;
  }
  /* Date, Type, In, Out, Balance, By &mdash; don't wrap */
  .txn-table td:nth-child(1),
  .txn-table td:nth-child(2),
  .txn-table td:nth-child(4),
  .txn-table td:nth-child(5),
  .txn-table td:nth-child(6),
  .txn-table td:nth-child(7){
    white-space:nowrap!important;
  }
  .txn-table thead th{
    background:#0f2557!important;color:#fff!important;
    print-color-adjust:exact;-webkit-print-color-adjust:exact;
  }
  .txn-table tbody tr{
    border-bottom:0.4pt solid #e2e8f0!important;
    page-break-inside:avoid!important;
  }
  .txn-table tfoot td{
    background:#e8edf5!important;font-weight:700!important;
    border-top:1.5pt solid #0f2557!important;
    print-color-adjust:exact;-webkit-print-color-adjust:exact;
  }
  /* code elements &mdash; don't break */
  .txn-table code{
    display:block!important;
    white-space:normal!important;
    word-break:break-all!important;
    background:#f1f5f9!important;
    padding:1pt 3pt!important;
    border-radius:2pt!important;
    font-size:6.5pt!important;
    margin-bottom:2pt!important;
    print-color-adjust:exact;-webkit-print-color-adjust:exact;
  }

  /* ── Column widths ── */
  .txn-table th:nth-child(1){ width:13% }   /* Date */
  .txn-table th:nth-child(2){ width:11% }   /* Type */
  .txn-table th:nth-child(3){ width:30% }   /* Reference */
  .txn-table th:nth-child(4){ width:12% }   /* In */
  .txn-table th:nth-child(5){ width:12% }   /* Out */
  .txn-table th:nth-child(6){ width:13% }   /* Balance */
  .txn-table th:nth-child(7){ width:9%  }   /* By */

  /* ── Badges ── */
  .txn-badge{
    font-size:6pt!important;padding:1pt 3pt!important;
    border-radius:2pt!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-info   {background:#155e75!important;color:#fff!important}
  .bg-warning{background:#92400e!important;color:#fff!important}
  .source-tag{
    font-size:5.5pt!important;padding:1pt 3pt!important;
    border:0.5pt solid #999!important;border-radius:2pt!important;
    display:inline-block!important;margin-top:2pt!important;
    print-color-adjust:exact;-webkit-print-color-adjust:exact;
  }

  /* ── Text ── */
  .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}
  code{
    background:#f1f5f9!important;padding:0 2pt!important;
    border-radius:2pt!important;font-size:6.5pt!important;
    print-color-adjust:exact;-webkit-print-color-adjust:exact;
  }

  /* ── No page break inside rows ── */
  tr{page-break-inside:avoid!important}
  thead{display:table-header-group!important}
  tfoot{display:table-footer-group!important}
}
</style>

<!-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
     PRINT-ONLY PDF HEADER
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ -->
<div class="print-header-block">
  <!-- Shop + Report title -->
  <table width="100%" cellpadding="0" cellspacing="0"
         style="padding-bottom:5pt;margin-bottom:4pt">
    <tr>
      <td style="width:55%;vertical-align:top">
        <div style="font-size:14pt;font-weight:900;color:#0f2557;line-height:1.1">
          <?=e(setting('shop_name','MJPOS'))?>
        </div>
        <?php if(setting('shop_address','')): ?>
        <div style="font-size:7.5pt;color:#475569;margin-top:1pt"><?=e(setting('shop_address',''))?></div>
        <?php endif;?>
        <?php if(setting('shop_phone','')): ?>
        <div style="font-size:7.5pt;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:13pt;font-weight:900;color:#0f2557;text-transform:uppercase">
          ACCOUNT LEDGER
        </div>
        <div style="font-size:10pt;font-weight:700;color:#1d4ed8;margin-top:2pt">
          <?=e($account['account_name'])?>
          <?php if(!$isCash && $account['bank_name']): ?>
          &mdash; <?=e($account['bank_name'])?>
          <?php endif;?>
        </div>
        <div style="font-size:7pt;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>

  <!-- Blue rule -->
  <div style="height:3pt;background:linear-gradient(90deg,#0f2557,#1d4ed8,#60a5fa);
              margin-bottom:6pt;print-color-adjust:exact;-webkit-print-color-adjust:exact"></div>

  <!-- Account summary KPI bar -->
  <div style="display:flex;gap:0;border:1pt solid #0f2557;border-radius:3pt;
              overflow:hidden;margin-bottom:8pt">
    <div style="flex:1.5;padding:6pt 10pt;background:<?=$acBg?>;border-right:1pt solid #e2e8f0;text-align:center">
      <div style="font-size:12pt;font-weight:900;color:<?=$acClr?>"><?=$sym?><?=number_format($account['current_balance'],2)?></div>
      <div style="font-size:6.5pt;text-transform:uppercase;color:#64748b;margin-top:1pt">Current Balance</div>
    </div>
    <div style="flex:1;padding:6pt 10pt;background:#f0fdf4;border-right:1pt solid #e2e8f0;text-align:center">
      <div style="font-size:11pt;font-weight:900;color:#16a34a"><?=$sym?><?=number_format($totalIn,2)?></div>
      <div style="font-size:6.5pt;text-transform:uppercase;color:#64748b;margin-top:1pt">Total In</div>
    </div>
    <div style="flex:1;padding:6pt 10pt;background:#fef2f2;border-right:1pt solid #e2e8f0;text-align:center">
      <div style="font-size:11pt;font-weight:900;color:#dc2626"><?=$sym?><?=number_format($totalOut,2)?></div>
      <div style="font-size:6.5pt;text-transform:uppercase;color:#64748b;margin-top:1pt">Total Out</div>
    </div>
    <div style="flex:1;padding:6pt 10pt;background:#eff6ff;text-align:center">
      <div style="font-size:11pt;font-weight:900;color:#1d4ed8"><?=$txnCount?></div>
      <div style="font-size:6.5pt;text-transform:uppercase;color:#64748b;margin-top:1pt">Transactions</div>
    </div>
  </div>

  <!-- Filter info if applied -->
  <?php if(($filterFrom??'') || ($filterTo??'') || ($filterType??'')): ?>
  <div style="font-size:7.5pt;color:#475569;margin-bottom:5pt;
              background:#f8fafc;border:0.5pt solid #e2e8f0;border-radius:3pt;padding:4pt 8pt">
    Filter applied:
    <?php if($filterFrom??''): ?>Period from <strong><?=date('d M Y',strtotime($filterFrom))?></strong><?php endif;?>
    <?php if($filterTo??''): ?> to <strong><?=date('d M Y',strtotime($filterTo))?></strong><?php endif;?>
    <?php if($filterType??''): ?> &nbsp;|&nbsp; Type: <strong><?=ucfirst(str_replace('_',' ',$filterType))?></strong><?php endif;?>
  </div>
  <?php endif;?>

  <!-- Account info line -->
  <div style="font-size:8pt;color:#0f172a;margin-bottom:4pt">
    <strong>Account:</strong> <?=e($account['account_name'])?>
    &nbsp;&nbsp;<strong>Type:</strong> <?=ucfirst($account['account_type'])?>
    <?php if(!$isCash): ?>
    &nbsp;&nbsp;<strong>Bank:</strong> <?=e($account['bank_name']??'')?>
    <?php if($account['account_number']??''): ?>
    &nbsp;&nbsp;<strong>A/C No:</strong> <span style="font-family:monospace"><?=e($account['account_number'])?></span>
    <?php endif;?>
    <?php endif;?>
    &nbsp;&nbsp;<strong>Opening:</strong> <?=$sym?><?=number_format($account['opening_balance'],2)?>
  </div>
</div>
<div class="al-hero">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
    <div>
      <div class="page-title">
        <i class="bi <?=$acIcon?>" style="color:<?=$isCash?'#6ee7b7':'#93c5fd'?>"></i>
        <?=e($account['account_name'])?>
        <span style="background:rgba(255,255,255,.12);font-size:.65rem;font-weight:600;
                     padding:2px 10px;border-radius:20px">
          <?=ucfirst($account['account_type'])?>
        </span>
      </div>
      <div class="page-meta">
        <?php if(!$isCash && $account['bank_name']): ?>
        <i class="bi bi-bank" style="font-size:.7rem"></i>
        <?=e($account['bank_name'])?>
        <?php if($account['account_number']): ?>
        <span class="sep">&middot;</span>
        <span style="font-family:monospace"><?=e($account['account_number'])?></span>
        <?php endif; ?>
        <span class="sep">&middot;</span>
        <?php endif; ?>
        <i class="bi bi-calendar3" style="font-size:.7rem"></i>
        <?=$txnCount?> transaction<?=$txnCount!=1?'s':''?>
      </div>
    </div>
    <div class="d-flex gap-2 flex-wrap">
      <a href="<?=APP_URL?>/finance/accounts" class="hero-btn"
         style="background:rgba(255,255,255,.1);color:#e2e8f0">
        <i class="bi bi-arrow-left"></i>Accounts
      </a>
      <button onclick="window.print()" class="hero-btn"
              style="background:#3b82f6;color:#fff">
        <i class="bi bi-printer"></i>Print / PDF
      </button>
      <?php if(Auth::can('accounts.manage')):?>
      <button onclick="openTxn('deposit')" class="hero-btn"
              style="background:#16a34a;color:#fff">
        <i class="bi bi-plus-circle"></i>Deposit
      </button>
      <button onclick="openTxn('withdrawal')" class="hero-btn"
              style="background:#dc2626;color:#fff">
        <i class="bi bi-dash-circle"></i>Withdraw
      </button>
      <?php if(!empty($otherAccounts)):?>
      <button onclick="openTransfer()" class="hero-btn"
              style="background:#0891b2;color:#fff">
        <i class="bi bi-arrow-left-right"></i>Transfer
      </button>
      <?php endif;?>
      <?php endif;?>
    </div>
  </div>
</div>

<?= flashMessages() ?>

<!-- ── Balance KPI Row ───────────────────────────────── -->
<div class="row g-3 mb-4">
  <div class="col-6 col-md-3">
    <div class="bal-card" style="background:<?=$acBg?>;border-color:<?=$acClr?>55">
      <div class="bl" style="color:<?=$acClr?>">Current Balance</div>
      <div class="bv" style="color:<?=$acClr?>"><?=$sym?><?=number_format($account['current_balance'],2)?></div>
      <div class="bs" style="color:<?=$acClr?>"><?=ucfirst($account['account_type'])?> account</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="bal-card" style="background:#f0fdf4;border-color:#86efac">
      <div class="bl text-success">Total In</div>
      <div class="bv text-success"><?=$sym?><?=number_format($totalIn,2)?></div>
      <div class="bs text-muted">All deposits + transfers in</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="bal-card" style="background:#fef2f2;border-color:#fca5a5">
      <div class="bl text-danger">Total Out</div>
      <div class="bv text-danger"><?=$sym?><?=number_format($totalOut,2)?></div>
      <div class="bs text-muted">All withdrawals + transfers out</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="bal-card" style="background:#eff6ff;border-color:#93c5fd">
      <div class="bl text-primary">POS Collections</div>
      <div class="bv text-primary"><?=$sym?><?=number_format($posTotalIn,2)?></div>
      <div class="bs text-muted">Auto-credited from POS sales</div>
    </div>
  </div>
</div>

<!-- ── Date Filter ────────────────────────────────────── -->
<div class="card mb-3">
  <div class="card-body py-2">
    <form method="GET" action="<?=APP_URL?>/finance/accounts/<?=$account['id']?>"
          class="d-flex gap-2 flex-wrap align-items-center">
      <input type="date" name="from" class="form-control form-control-sm"
             value="<?=e($filterFrom??'')?>" style="width:136px">
      <span class="text-muted small">to</span>
      <input type="date" name="to" class="form-control form-control-sm"
             value="<?=e($filterTo??'')?>" style="width:136px">
      <select name="type" class="form-select form-select-sm" style="width:150px">
        <option value="">All Types</option>
        <option value="deposit"      <?=($filterType??'')==='deposit'?     'selected':''?>> Deposits</option>
        <option value="withdrawal"   <?=($filterType??'')==='withdrawal'?  'selected':''?>> Withdrawals</option>
        <option value="transfer_in"  <?=($filterType??'')==='transfer_in'? 'selected':''?>> Transfer In</option>
        <option value="transfer_out" <?=($filterType??'')==='transfer_out'?'selected':''?>> Transfer Out</option>
      </select>
      <button class="btn btn-secondary btn-sm fw-semibold">
        <i class="bi bi-funnel me-1"></i>Filter
      </button>
      <a href="<?=APP_URL?>/finance/accounts/<?=$account['id']?>" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-x-lg"></i>
      </a>
      <?php foreach([
        'Today'      => [date('Y-m-d'),       date('Y-m-d')],
        'This Week'  => [date('Y-m-d',strtotime('monday')), date('Y-m-d')],
        'This Month' => [date('Y-m-01'),       date('Y-m-d')],
      ] as $lbl=>[$f,$t]):
        $act = (($filterFrom??'')===$f && ($filterTo??'')===$t);
      ?>
      <a href="?from=<?=$f?>&to=<?=$t?>" class="date-btn <?=$act?'active':''?>"><?=$lbl?></a>
      <?php endforeach;?>
    </form>
  </div>
</div>

<!-- ── Transaction 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-journal-text me-1"></i>
      Transaction Ledger &mdash; <?=e($account['account_name'])?>
    </span>
    <div class="d-flex align-items-center gap-2">
      <span class="badge bg-secondary"><?=$txnCount?> entries</span>
      <button onclick="window.print()" class="btn btn-sm btn-primary py-0 no-print"
              style="font-size:.72rem;border-radius:8px">
        <i class="bi bi-printer me-1"></i>Print / PDF
      </button>
    </div>
  </div>
  <div class="table-responsive">
    <table class="table table-sm table-hover mb-0 txn-table">
      <thead class="table-dark">
        <tr>
          <th class="ps-3" style="width:115px">Date / Time</th>
          <th class="text-center" style="width:130px">Type</th>
          <th>Reference / Note</th>
          <th class="text-end text-success" style="width:120px">In (+)</th>
          <th class="text-end text-danger" style="width:120px">Out (−)</th>
          <th class="text-end" style="width:130px">Balance</th>
          <th class="text-center" style="width:90px">By</th>
          <?php if(Auth::role()==='developer'):?>
          <th class="text-center no-print" style="width:60px"></th>
          <?php endif;?>
        </tr>
      </thead>
      <tbody>
        <?php if(empty($txns)):?>
        <tr><td colspan="7" class="text-center text-muted py-5">
          <i class="bi bi-journal-x d-block fs-2 mb-2 opacity-25"></i>
          No transactions yet.
        </td></tr>
        <?php endif;?>
        <?php
        $typeCfg = [
          'deposit'      => ['bg-success',          'bi-plus-circle',    'Deposit',      '#16a34a'],
          'withdrawal'   => ['bg-danger',            'bi-dash-circle',    'Withdrawal',   '#dc2626'],
          'transfer_in'  => ['bg-info text-dark',    'bi-arrow-down-left','Transfer In',  '#0891b2'],
          'transfer_out' => ['bg-warning text-dark', 'bi-arrow-up-right', 'Transfer Out', '#d97706'],
        ];
        foreach($txns as $t):
          $tc   = $typeCfg[$t['txn_type']] ?? ['bg-secondary','bi-dot',ucfirst($t['txn_type']),'#64748b'];
          $isIn = in_array($t['txn_type'], ['deposit','transfer_in'], true);

          // Detect source tag
          $src = '';
          $note = $t['note'] ?? '';
          if(str_starts_with($note,'POS Sale:'))       $src = [' POS','#1d4ed8','#eff6ff'];
          elseif(str_starts_with($note,'Sale Return:')) $src = [' Return','#dc2626','#fef2f2'];
          elseif($t['related_account_name']??false)     $src = [' Transfer','#0891b2','#f0f9ff'];
        ?>
        <tr>
          <td class="ps-3">
            <div class="fw-semibold" style="font-size:.77rem"><?=date('d M Y',strtotime($t['txn_date']))?></div>
            <div style="font-size:.62rem;color:#94a3b8"><?=date('H:i',strtotime($t['created_at']))?></div>
          </td>
          <td class="text-center">
            <span class="txn-badge <?=$tc[0]?>">
              <i class="bi <?=$tc[1]?>"></i><?=$tc[2]?>
            </span>
          </td>
          <td>
            <div style="display:flex;align-items:flex-start;gap:6px;flex-wrap:wrap">
              <div style="min-width:0;flex:1">
                <?php if($t['related_account_name']??false):?>
                <div class="fw-semibold" style="font-size:.73rem">
                  <?=$isIn?'From':'To'?>: <?=e($t['related_account_name'])?>
                </div>
                <?php endif;?>
                <?php if($t['reference']):?>
                <div>
                  <code style="font-size:.66rem;background:#f1f5f9;padding:1px 4px;border-radius:4px;display:inline-block">
                    <?=e($t['reference'])?>
                  </code>
                </div>
                <?php endif;?>
                <?php if($note):?>
                <div class="text-muted" style="font-size:.66rem;line-height:1.3"><?=e($note)?></div>
                <?php endif;?>
              </div>
              <?php if($src):?>
              <span class="source-tag flex-shrink-0"
                    style="background:<?=$src[2]?>;color:<?=$src[1]?>;border:1px solid <?=$src[1]?>33">
                <?=$src[0]?>
              </span>
              <?php endif;?>
            </div>
          </td>
          <!-- In -->
          <td class="text-end fw-bold">
            <?php if($isIn):?>
            <span style="color:#16a34a"><?=$sym?><?=number_format($t['amount'],2)?></span>
            <?php else:?>
            <span class="text-muted" style="opacity:.35">&mdash;</span>
            <?php endif;?>
          </td>
          <!-- Out -->
          <td class="text-end fw-bold">
            <?php if(!$isIn):?>
            <span style="color:#dc2626"><?=$sym?><?=number_format($t['amount'],2)?></span>
            <?php else:?>
            <span class="text-muted" style="opacity:.35">&mdash;</span>
            <?php endif;?>
          </td>
          <!-- Running balance -->
          <td class="text-end">
            <span class="fw-bold" style="color:<?=$t['balance_after']>=0?'#0f172a':'#dc2626'?>">
              <?=$sym?><?=number_format($t['balance_after'],2)?>
            </span>
          </td>
          <!-- By -->
          <td class="text-center">
            <span style="font-size:.65rem;color:#64748b"><?=e($t['done_by']??'&mdash;')?></span>
          </td>
          <!-- Delete &mdash; developer only -->
          <?php if(Auth::role()==='developer'):?>
          <td class="text-center no-print">
            <button onclick="deleteTxn(<?=$t['id']?>, '<?=$sym?><?=number_format($t['amount'],2)?>', '<?=e(addslashes($tc[2]))?>')"
                    class="btn btn-sm btn-outline-danger py-0 px-1" title="Delete transaction"
                    style="font-size:.65rem">
              <i class="bi bi-trash3"></i>
            </button>
          </td>
          <?php endif;?>
        </tr>
        <?php endforeach;?>
      </tbody>
      <?php if($txnCount > 0):?>
      <tfoot class="table-secondary fw-bold" style="font-size:.73rem">
        <tr>
          <td colspan="3" class="ps-3">TOTAL</td>
          <td class="text-end" style="color:#16a34a"><?=$sym?><?=number_format($totalIn,2)?></td>
          <td class="text-end" style="color:#dc2626"><?=$sym?><?=number_format($totalOut,2)?></td>
          <td class="text-end" style="color:<?=$acClr?>">
            <?=$sym?><?=number_format($account['current_balance'],2)?>
          </td>
          <td></td>
          <?php if(Auth::role()==='developer'):?><td class="no-print"></td><?php endif;?>
        </tr>
      </tfoot>
      <?php endif;?>
    </table>
  </div>
</div>

<!-- Developer Delete Transaction Modal -->
<?php if(Auth::role()==='developer'):?>
<div class="modal fade" id="deleteTxnModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered" style="max-width:400px">
    <div class="modal-content">
      <div class="modal-header" style="background:#dc2626;color:#fff">
        <h6 class="modal-title fw-bold"><i class="bi bi-trash3 me-2"></i>Delete Transaction</h6>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="p-3 rounded mb-3" style="background:#fef2f2;border:1px solid #fca5a5">
          <div class="fw-bold text-danger mb-1">Developer Only Action</div>
          <div class="small text-muted">
            Deleting a transaction will <strong>NOT</strong> auto-adjust the account balance.
            You must manually correct the balance via Deposit/Withdraw after deletion.
          </div>
        </div>
        <p class="mb-1 small">Transaction to delete:</p>
        <p class="fw-bold" id="deleteTxnInfo"></p>
      </div>
      <form method="POST" id="deleteTxnForm"
            action="<?=APP_URL?>/finance/transactions/delete/0">
        <?=Auth::csrfField()?>
        <div class="modal-footer justify-content-between">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-danger fw-bold">
            <i class="bi bi-trash3 me-1"></i>Delete Transaction
          </button>
        </div>
      </form>
    </div>
  </div>
</div>
<script>
function deleteTxn(id, amount, type) {
  document.getElementById('deleteTxnInfo').textContent = type + ' &mdash; ' + amount;
  document.getElementById('deleteTxnForm').action =
    '<?=APP_URL?>/finance/transactions/delete/' + id;
  new bootstrap.Modal(document.getElementById('deleteTxnModal')).show();
}
</script>
<?php endif;?>

<!-- ══════════════════════════════════════════════════ -->
<!-- MODALS                                              -->
<!-- ══════════════════════════════════════════════════ -->

<!-- Deposit / Withdraw -->
<div class="modal fade" id="txnModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered" style="max-width:430px">
    <div class="modal-content">
      <div class="modal-header" id="txnHeader">
        <h6 class="modal-title fw-bold" id="txnTitle"></h6>
        <button type="button" class="btn-close" id="txnBtnClose" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" action="<?=APP_URL?>/finance/accounts/<?=$account['id']?>/transaction">
        <?=Auth::csrfField()?>
        <input type="hidden" name="txn_type" id="txnTypeInput">
        <div class="modal-body">
          <div class="p-3 rounded mb-3 text-center"
               style="background:<?=$acBg?>;border:1.5px solid <?=$acClr?>33">
            <div style="font-size:.7rem;color:<?=$acClr?>;font-weight:600">
              <?=e($account['account_name'])?> &mdash; Current Balance
            </div>
            <div style="font-size:1.4rem;font-weight:900;color:<?=$acClr?>">
              <?=$sym?><?=number_format($account['current_balance'],2)?>
            </div>
          </div>
          <div class="mb-3">
            <label class="form-label small fw-semibold">Amount *</label>
            <div class="input-group">
              <span class="input-group-text"><?=$sym?></span>
              <input type="number" name="amount" class="form-control fw-bold fs-5"
                     step="0.01" min="0.01" required id="txnAmountInput"
                     placeholder="0.00">
            </div>
          </div>
          <div class="row g-2 mb-3">
            <div class="col-7">
              <label class="form-label small fw-semibold">Reference</label>
              <input type="text" name="reference" class="form-control" placeholder="Voucher no. etc.">
            </div>
            <div class="col-5">
              <label class="form-label small fw-semibold">Date</label>
              <input type="date" name="txn_date" class="form-control" value="<?=date('Y-m-d')?>">
            </div>
          </div>
          <div>
            <label class="form-label small fw-semibold">Note</label>
            <textarea name="note" class="form-control" rows="2"
                      placeholder="Optional description…"></textarea>
          </div>
        </div>
        <div class="modal-footer justify-content-between">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn fw-bold px-4" id="txnSubmitBtn">Confirm</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Transfer -->
<div class="modal fade" id="transferModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered" style="max-width:430px">
    <div class="modal-content">
      <div class="modal-header" style="background:#0891b2;color:#fff">
        <h6 class="modal-title fw-bold">
          <i class="bi bi-arrow-left-right me-2"></i>Transfer Funds
        </h6>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" action="<?=APP_URL?>/finance/accounts/<?=$account['id']?>/transfer">
        <?=Auth::csrfField()?>
        <div class="modal-body">
          <div class="p-3 rounded mb-3 text-center"
               style="background:#f0f9ff;border:1.5px solid #7dd3fc">
            <div style="font-size:.7rem;color:#0891b2;font-weight:600">Transferring from</div>
            <div style="font-size:1.1rem;font-weight:900;color:#0891b2">
              <?=e($account['account_name'])?>
            </div>
            <div style="font-size:.8rem;color:#0891b2">
              Balance: <?=$sym?><?=number_format($account['current_balance'],2)?>
            </div>
          </div>
          <div class="mb-3">
            <label class="form-label small fw-semibold">To Account *</label>
            <select name="to_account_id" class="form-select" required>
              <?php foreach($otherAccounts as $oa):?>
              <option value="<?=$oa['id']?>">
                <?=$oa['account_type']==='cash'?'':''?>
                <?=e($oa['account_name'])?>
                (<?=$sym?><?=number_format($oa['current_balance'],0)?>)
              </option>
              <?php endforeach;?>
            </select>
          </div>
          <div class="mb-3">
            <label class="form-label small fw-semibold">Amount *</label>
            <div class="input-group">
              <span class="input-group-text"><?=$sym?></span>
              <input type="number" name="amount" class="form-control fw-bold"
                     step="0.01" min="0.01" required placeholder="0.00">
            </div>
          </div>
          <div class="row g-2 mb-3">
            <div class="col-6">
              <label class="form-label small fw-semibold">Date</label>
              <input type="date" name="txn_date" class="form-control" value="<?=date('Y-m-d')?>">
            </div>
          </div>
          <div>
            <label class="form-label small fw-semibold">Note</label>
            <input type="text" name="note" class="form-control" placeholder="Optional">
          </div>
        </div>
        <div class="modal-footer justify-content-between">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn fw-bold px-4"
                  style="background:#0891b2;color:#fff">
            <i class="bi bi-arrow-left-right me-1"></i>Transfer
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
function openTxn(type) {
  document.getElementById('txnTypeInput').value = type;
  const header = document.getElementById('txnHeader');
  const title  = document.getElementById('txnTitle');
  const btn    = document.getElementById('txnSubmitBtn');
  const close  = document.getElementById('txnBtnClose');
  if (type === 'deposit') {
    header.style.cssText  = 'background:#16a34a;color:#fff';
    close.className       = 'btn-close btn-close-white';
    title.innerHTML       = '<i class="bi bi-plus-circle me-2"></i>Deposit Funds';
    btn.className         = 'btn btn-success fw-bold px-4';
    btn.innerHTML         = '<i class="bi bi-check-circle me-1"></i>Deposit';
  } else {
    header.style.cssText  = 'background:#dc2626;color:#fff';
    close.className       = 'btn-close btn-close-white';
    title.innerHTML       = '<i class="bi bi-dash-circle me-2"></i>Withdraw Funds';
    btn.className         = 'btn btn-danger fw-bold px-4';
    btn.innerHTML         = '<i class="bi bi-dash-circle me-1"></i>Withdraw';
  }
  const modal = new bootstrap.Modal(document.getElementById('txnModal'));
  modal.show();
  setTimeout(()=>document.getElementById('txnAmountInput').focus(), 400);
}
function openTransfer() {
  new bootstrap.Modal(document.getElementById('transferModal')).show();
}
</script>