<?php
session_start();
$page_title = 'Transactions';
$active_nav = 'wallet';
include("includes/header.php");

$uid = (int)$_SESSION['user_id'];

// All transactions, newest first
$all_txns = $conn->prepare("SELECT * FROM wallet_transactions WHERE user_id=? ORDER BY created_at DESC");
$all_txns->bind_param("i", $uid); $all_txns->execute();
$txn_rows = $all_txns->get_result()->fetch_all(MYSQLI_ASSOC);

// Totals
$cr = $conn->prepare("SELECT COALESCE(SUM(amount),0) t FROM wallet_transactions WHERE user_id=? AND type='credit' AND status='success'");
$cr->bind_param("i",$uid); $cr->execute();
$total_credited = $cr->get_result()->fetch_assoc()['t'];

$dr = $conn->prepare("SELECT COALESCE(SUM(amount),0) t FROM wallet_transactions WHERE user_id=? AND type='debit' AND status='success'");
$dr->bind_param("i",$uid); $dr->execute();
$total_debited = $dr->get_result()->fetch_assoc()['t'];

// Group into "Recent" (last 7 days) and "Earlier"
$now = time();
$groups = ['Recent Transactions' => [], 'Earlier' => []];
foreach ($txn_rows as $t) {
    $age = $now - strtotime($t['created_at']);
    $groups[$age <= 7 * 86400 ? 'Recent Transactions' : 'Earlier'][] = $t;
}
?>

<style>
.app-topbar { display: none; }
.main-content { padding-top: calc(env(safe-area-inset-top) + 6px); }
.tx-wrap { max-width: 600px; margin: 0 auto; }

.sub-topbar { display: flex; align-items: center; justify-content: space-between; padding: 4px 2px 18px; }
.sub-topbar-left { display: flex; align-items: center; gap: 12px; }
.sub-topbar .sub-back { width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: var(--primary); background: var(--primary-bg); flex-shrink: 0; }
.sub-topbar .sub-title { font-size: 1.15rem; font-weight: 800; letter-spacing: -.02em; color: var(--text); }
.sub-topbar .icon-btn { color: var(--primary); }

.tx-balance { position: relative; overflow: hidden; border-radius: 20px; padding: 22px 20px; margin-bottom: 16px; color: #fff;
  background: linear-gradient(120deg, #1d4ccb 0%, #225AE3 26%, #3d76f0 50%, #1a47b8 76%, #225AE3 100%);
  background-size: 280% 280%; animation: walletGradient 9s ease-in-out infinite;
  box-shadow: 0 10px 28px rgba(34,90,227,.3); }
@keyframes walletGradient { 0% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } 100% { background-position: 0% 50%; } }
@media (prefers-reduced-motion: reduce) { .tx-balance { animation: none; } }
.tx-balance::before { content: ''; position: absolute; right: -34px; top: -34px; width: 140px; height: 140px; border-radius: 50%; background: rgba(255,255,255,.1); pointer-events: none; }
.tx-balance::after { content: ''; position: absolute; right: 36px; top: 44px; width: 70px; height: 70px; border-radius: 50%; background: rgba(255,255,255,.07); pointer-events: none; }
.tx-balance .tb-top { display: flex; align-items: center; justify-content: space-between; position: relative; z-index: 1; margin-bottom: 8px; }
.tx-balance .tb-label { font-size: .84rem; opacity: .9; }
.tx-balance .tb-eye { background: rgba(255,255,255,.2); border: none; border-radius: 9px; width: 34px; height: 34px; display: flex; align-items: center; justify-content: center; color: #fff; cursor: pointer; flex-shrink: 0; }
.tx-balance .tb-eye:active { background: rgba(255,255,255,.34); }
.tx-balance .tb-amount { font-size: 2.1rem; font-weight: 800; letter-spacing: -.03em; line-height: 1; margin-bottom: 18px; position: relative; z-index: 1; word-break: break-word; }
.tx-add { position: relative; z-index: 1; display: flex; align-items: center; justify-content: center; gap: 8px; width: 100%; height: 52px; background: rgba(255,255,255,.96); color: var(--primary); border-radius: 14px; font-weight: 700; font-size: .95rem; box-shadow: 0 6px 18px rgba(0,0,0,.12); }
.tx-add:active { background: #fff; }

.tx-stats { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; margin-bottom: 22px; }
.tx-stat { background: #fff; border: 1px solid var(--border); border-radius: 16px; box-shadow: 0 4px 18px rgba(15,23,42,.06); padding: 16px; }
.tx-stat .ts-top { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
.tx-stat .ts-ic { width: 30px; height: 30px; border-radius: 9px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
.tx-stat .ts-ic.up { background: var(--success-bg); color: var(--success); }
.tx-stat .ts-ic.down { background: var(--error-bg); color: var(--error); }
.tx-stat .ts-label { font-size: .76rem; color: var(--text-muted); font-weight: 600; }
.tx-stat .ts-val { font-size: 1.15rem; font-weight: 800; letter-spacing: -.02em; word-break: break-word; }
.tx-stat .ts-val.up { color: var(--primary); }
.tx-stat .ts-val.down { color: var(--error); }

.tx-pills { display: flex; gap: 8px; margin-bottom: 18px; }
.tx-pill { padding: 9px 20px; border-radius: 30px; font-size: .85rem; font-weight: 700; border: 1.5px solid var(--border); background: #fff; color: var(--text-muted); cursor: pointer; font-family: var(--font); }
.tx-pill.active { background: var(--primary); color: #fff; border-color: var(--primary); }

.tx-group-label { font-size: .68rem; font-weight: 800; letter-spacing: .1em; text-transform: uppercase; color: var(--text-light); margin: 18px 4px 10px; }
.tx-card { background: #fff; border-radius: 16px; border: 1px solid var(--border); box-shadow: 0 4px 18px rgba(15,23,42,.06); overflow: hidden; }
.tx-row { display: flex; align-items: center; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--border); text-decoration: none; color: inherit; }
.tx-row:last-child { border-bottom: none; }
.tx-row:active { background: var(--bg); }
.tx-row .tr-chev { color: var(--border-dark); flex-shrink: 0; }
.tx-row .tr-ic { width: 42px; height: 42px; border-radius: 12px; background: var(--primary-bg); color: var(--primary); display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
/* meta column must be the only flexible element, with min-width:0 so its
   text children can shrink and truncate instead of pushing the amount out */
.tx-row .tr-meta { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; }
.tx-row .tr-title { display: block; max-width: 100%; font-weight: 700; font-size: .9rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.tx-row .tr-sub { display: block; font-size: .74rem; color: var(--text-muted); margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
/* amount column never shrinks, stays fully visible on one line */
.tx-row .tr-right { display: flex; flex-direction: column; align-items: flex-end; text-align: right; flex-shrink: 0; }
.tx-row .tr-amt { font-weight: 800; font-size: .92rem; white-space: nowrap; }
.tx-row .tr-amt.cr { color: var(--primary); }
.tx-row .tr-amt.dr { color: var(--text); }
.tx-row .tr-badge { font-size: .62rem; font-weight: 800; letter-spacing: .06em; margin-top: 3px; white-space: nowrap; }
.tx-row .tr-badge.cr { color: var(--primary); }
.tx-row .tr-badge.dr { color: var(--error); }

/* Narrow phones: tighten spacing so icon + text + amount + chevron all fit */
@media (max-width: 380px) {
  .tx-row { gap: 9px; padding: 13px 12px; }
  .tx-row .tr-ic { width: 38px; height: 38px; border-radius: 11px; }
  .tx-row .tr-amt { font-size: .88rem; }
}
@media (max-width: 320px) {
  .tx-row { gap: 7px; padding: 12px 10px; }
  .tx-row .tr-chev { display: none; }
}

.tx-empty { text-align: center; padding: 48px 20px; }
.tx-empty .ee-ic { width: 96px; height: 96px; border-radius: 50%; background: #fff; box-shadow: 0 6px 22px rgba(15,23,42,.07); display: flex; align-items: center; justify-content: center; margin: 0 auto 18px; color: var(--primary); }
.tx-empty h3 { font-size: 1.15rem; font-weight: 800; margin-bottom: 6px; }
.tx-empty p { font-size: .86rem; color: var(--text-muted); line-height: 1.5; max-width: 280px; margin: 0 auto; }
</style>

<div class="tx-wrap">

  <div class="sub-topbar">
    <div class="sub-topbar-left">
      <a href="dashboard.php" class="sub-back" aria-label="Back" onclick="return goBack(event)">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 12H5m0 0l7 7M5 12l7-7"/></svg>
      </a>
      <span class="sub-title">Transactions</span>
    </div>
    <a href="help_center.php" class="icon-btn" title="Help">
      <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 115.83 1c0 2-3 2-3 4"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
    </a>
  </div>

  <div class="tx-balance">
    <div class="tb-top">
      <span class="tb-label">Total Balance</span>
      <button class="tb-eye" type="button" onclick="toggleBalance()" title="Show/hide balance" aria-label="Show or hide balance">
        <svg id="eyeIcon" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
      </button>
    </div>
    <div class="tb-amount" id="walletBalance">₦<?php echo number_format($__balance, 2); ?></div>
    <a href="fund_wallet.php" class="tx-add">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v8M8 12h8"/></svg>
      Add Money
    </a>
  </div>

  <div class="tx-stats">
    <div class="tx-stat">
      <div class="ts-top">
        <span class="ts-ic up"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M12 19V5m0 0l-7 7m7-7l7 7"/></svg></span>
        <span class="ts-label">Total Funded</span>
      </div>
      <div class="ts-val up">₦<?php echo number_format($total_credited, 2); ?></div>
    </div>
    <div class="tx-stat">
      <div class="ts-top">
        <span class="ts-ic down"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M12 5v14m0 0l7-7m-7 7l-7-7"/></svg></span>
        <span class="ts-label">Total Spent</span>
      </div>
      <div class="ts-val down">₦<?php echo number_format($total_debited, 2); ?></div>
    </div>
  </div>

  <?php if (empty($txn_rows)): ?>
    <div class="tx-empty">
      <div class="ee-ic"><svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><line x1="6" y1="20" x2="6" y2="13"/><line x1="12" y1="20" x2="12" y2="8"/><line x1="18" y1="20" x2="18" y2="11"/></svg></div>
      <h3>No transactions found</h3>
      <p>We couldn't find any recent activity in your wallet history.</p>
    </div>
  <?php else: ?>
    <div class="tx-pills">
      <button class="tx-pill active" data-filter="all" onclick="filterTxn('all',this)">All</button>
      <button class="tx-pill" data-filter="credit" onclick="filterTxn('credit',this)">Credits</button>
      <button class="tx-pill" data-filter="debit" onclick="filterTxn('debit',this)">Debits</button>
    </div>

    <?php foreach ($groups as $gname => $rows): if (empty($rows)) continue; ?>
      <div class="tx-group-label js-group" data-group="<?php echo htmlspecialchars($gname); ?>"><?php echo htmlspecialchars($gname); ?></div>
      <div class="tx-card js-group-card" data-group="<?php echo htmlspecialchars($gname); ?>">
        <?php foreach ($rows as $t):
          $is_cr = $t['type'] === 'credit';
          $title = $t['description'] ?: ($is_cr ? 'Wallet Funding' : 'Wallet Payment');
          $sub   = date('M j', strtotime($t['created_at'])) . ' · ' . ($is_cr ? 'Funding' : 'Payment');
          $ipath = $is_cr ? 'M21 12V7H5a2 2 0 010-4h15a1 1 0 011 1v4M3 5v14a2 2 0 002 2h16v-5M18 12a2 2 0 000 4h4v-4z'
                          : 'M3 3h2l2.4 12.4a2 2 0 002 1.6h9.8a2 2 0 002-1.6L23 6H6';
        ?>
        <a class="tx-row" href="transaction_detail.php?id=<?php echo (int)$t['id']; ?>" data-type="<?php echo $t['type']; ?>">
          <span class="tr-ic"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="<?php echo $ipath; ?>"/><?php if(!$is_cr): ?><circle cx="9" cy="20" r="1"/><circle cx="18" cy="20" r="1"/><?php endif; ?></svg></span>
          <span class="tr-meta">
            <span class="tr-title"><?php echo htmlspecialchars($title); ?></span>
            <span class="tr-sub"><?php echo $sub; ?></span>
          </span>
          <span class="tr-right">
            <span class="tr-amt <?php echo $is_cr ? 'cr' : 'dr'; ?>"><?php echo $is_cr ? '+' : '- '; ?>₦<?php echo number_format($t['amount'], 2); ?></span>
            <div class="tr-badge <?php echo $is_cr ? 'cr' : 'dr'; ?>"><?php echo $is_cr ? 'CREDIT' : 'DEBIT'; ?></div>
          </span>
          <svg class="tr-chev" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="9 18 15 12 9 6"/></svg>
        </a>
        <?php endforeach; ?>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</div>

<script>
// ── Balance show/hide (persisted across pages/tabs via localStorage) ────
const _realBal = '₦<?php echo number_format($__balance, 2); ?>';
const _EYE_OPEN = '<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>';
const _EYE_OFF  = '<path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/>';
function _balHidden() { try { return localStorage.getItem('dabil_bal_hidden') === '1'; } catch (e) { return false; } }
function _applyBalance(hidden) {
  const amt = document.getElementById('walletBalance'); const ic = document.getElementById('eyeIcon');
  if (amt) amt.textContent = hidden ? '₦ ••••••' : _realBal;
  if (ic)  ic.innerHTML = hidden ? _EYE_OFF : _EYE_OPEN;
}
function toggleBalance() {
  const hidden = !_balHidden();
  try { localStorage.setItem('dabil_bal_hidden', hidden ? '1' : '0'); } catch (e) {}
  _applyBalance(hidden);
}
_applyBalance(_balHidden());

function filterTxn(type, btn){
  document.querySelectorAll('.tx-pill').forEach(p => p.classList.remove('active'));
  btn.classList.add('active');
  document.querySelectorAll('.tx-row').forEach(r => {
    r.style.display = (type === 'all' || r.dataset.type === type) ? 'flex' : 'none';
  });
  // hide a group + its label when it has no visible rows
  document.querySelectorAll('.js-group-card').forEach(card => {
    const visible = [...card.querySelectorAll('.tx-row')].some(r => r.style.display !== 'none');
    card.style.display = visible ? '' : 'none';
    const label = document.querySelector('.js-group[data-group="' + card.dataset.group + '"]');
    if (label) label.style.display = visible ? '' : 'none';
  });
}
</script>

<?php include("includes/footer.php"); ?>
