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

$type_filter = $_GET['type'] ?? 'all';
$search      = trim($_GET['search'] ?? '');
$date_from   = $_GET['date_from'] ?? '';
$date_to     = $_GET['date_to'] ?? '';

$query = "SELECT wt.*, u.name as user_name, u.email as user_email
          FROM wallet_transactions wt
          LEFT JOIN users u ON wt.user_id=u.id
          WHERE 1=1";
$params=[]; $types="";

if ($type_filter !== 'all') { $query.=" AND wt.type=?"; $params[]=$type_filter; $types.="s"; }
if ($search) {
    $query.=" AND (u.name LIKE ? OR u.email LIKE ? OR wt.reference LIKE ?)";
    $s="%$search%"; $params=array_merge($params,[$s,$s,$s]); $types.="sss";
}
if ($date_from) { $query.=" AND DATE(wt.created_at)>=?"; $params[]=$date_from; $types.="s"; }
if ($date_to)   { $query.=" AND DATE(wt.created_at)<=?"; $params[]=$date_to;   $types.="s"; }
$query.=" ORDER BY wt.created_at DESC";

$stmt=$conn->prepare($query);
if($params) $stmt->bind_param($types,...$params);
$stmt->execute();
$txns=$stmt->get_result();

// Totals
$totals = $conn->query("SELECT
    COALESCE(SUM(CASE WHEN type='credit' AND status='success' THEN amount ELSE 0 END),0) as total_credits,
    COALESCE(SUM(CASE WHEN type='debit'  AND status='success' THEN amount ELSE 0 END),0) as total_debits,
    COUNT(*) as total_count
    FROM wallet_transactions")->fetch_assoc();
?>

<div style="margin-bottom:28px">
  <h1 style="font-size:1.5rem;font-weight:800;letter-spacing:-.03em;margin-bottom:4px">Transactions</h1>
  <p style="color:var(--text-muted);font-size:.875rem">All wallet transactions across the platform</p>
</div>

<!-- Summary Cards -->
<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-bottom:28px">
  <div class="card" style="padding:20px;border-top:3px solid var(--success)">
    <div style="font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:10px">Total Credits</div>
    <div style="font-size:1.6rem;font-weight:800;color:var(--success)">₦<?php echo number_format($totals['total_credits'],0); ?></div>
  </div>
  <div class="card" style="padding:20px;border-top:3px solid var(--error)">
    <div style="font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:10px">Total Debits</div>
    <div style="font-size:1.6rem;font-weight:800;color:var(--error)">₦<?php echo number_format($totals['total_debits'],0); ?></div>
  </div>
  <div class="card" style="padding:20px;border-top:3px solid var(--primary)">
    <div style="font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:10px">Total Transactions</div>
    <div style="font-size:1.6rem;font-weight:800;color:var(--primary)"><?php echo number_format($totals['total_count']); ?></div>
  </div>
</div>

<!-- Filters -->
<div style="display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap;align-items:center">
  <?php foreach(['all'=>'All','credit'=>'Credits','debit'=>'Debits'] as $k=>$l): ?>
  <a href="?type=<?php echo $k; ?><?php echo $search?"&search=".urlencode($search):''; ?>"
     class="btn btn-sm <?php echo $type_filter===$k?'btn-primary':'btn-secondary'; ?>"><?php echo $l; ?></a>
  <?php endforeach; ?>

  <form method="GET" style="display:flex;gap:8px;margin-left:auto;flex-wrap:wrap;align-items:center">
    <input type="hidden" name="type" value="<?php echo htmlspecialchars($type_filter); ?>">
    <div style="position:relative">
      <svg style="position:absolute;left:11px;top:50%;transform:translateY(-50%);width:14px;height:14px;stroke:var(--text-light);fill:none" viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
      <input type="text" name="search" placeholder="Search user or ref…" value="<?php echo htmlspecialchars($search); ?>"
             style="height:38px;border:1.5px solid var(--border);border-radius:10px;background:var(--white);padding:0 12px 0 32px;font-size:.83rem;font-family:var(--font);outline:none;width:210px"
             onfocus="this.style.borderColor='var(--primary)'" onblur="this.style.borderColor='var(--border)'">
    </div>
    <input type="date" name="date_from" value="<?php echo $date_from; ?>"
           style="height:38px;border:1.5px solid var(--border);border-radius:10px;background:var(--white);padding:0 10px;font-size:.82rem;font-family:var(--font);outline:none">
    <input type="date" name="date_to" value="<?php echo $date_to; ?>"
           style="height:38px;border:1.5px solid var(--border);border-radius:10px;background:var(--white);padding:0 10px;font-size:.82rem;font-family:var(--font);outline:none">
    <button type="submit" class="btn btn-primary btn-sm">Filter</button>
    <a href="transactions.php" class="btn btn-secondary btn-sm">Reset</a>
  </form>
</div>

<div class="card">
  <?php if($txns->num_rows===0): ?>
    <div style="padding:60px;text-align:center;color:var(--text-muted)">
      <p style="font-weight:700;margin-bottom:6px">No transactions found</p>
    </div>
  <?php else: ?>
  <div style="overflow-x:auto">
  <table class="data-table">
    <thead><tr><th>User</th><th>Type</th><th>Amount</th><th>Reference</th><th>Description</th><th>Status</th><th>Date</th></tr></thead>
    <tbody>
    <?php while($t=$txns->fetch_assoc()):
      $is_credit=$t['type']==='credit';
      $tc=$is_credit?'var(--success)':'var(--error)';
      $sc=['success'=>'badge-success','pending'=>'badge-warning','failed'=>'badge-error'];
    ?>
      <tr>
        <td>
          <div style="font-weight:600;font-size:.84rem"><?php echo htmlspecialchars($t['user_name']??'—'); ?></div>
          <div style="font-size:.7rem;color:var(--text-muted)"><?php echo htmlspecialchars($t['user_email']??''); ?></div>
        </td>
        <td>
          <span style="font-size:.78rem;font-weight:700;color:<?php echo $tc; ?>;text-transform:uppercase;letter-spacing:.06em">
            <?php echo $is_credit?'↑ Credit':'↓ Debit'; ?>
          </span>
        </td>
        <td style="font-weight:800;color:<?php echo $tc; ?>">
          <?php echo $is_credit?'+':'-'; ?>₦<?php echo number_format($t['amount'],2); ?>
        </td>
        <td style="font-size:.72rem;color:var(--text-muted);max-width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
          <?php echo htmlspecialchars($t['reference']??'—'); ?>
        </td>
        <td style="font-size:.82rem;max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
          <?php echo htmlspecialchars($t['description']??'—'); ?>
        </td>
        <td><span class="badge <?php echo $sc[$t['status']]??'badge-muted'; ?>"><?php echo ucfirst($t['status']); ?></span></td>
        <td style="font-size:.78rem;color:var(--text-muted);white-space:nowrap"><?php echo date('M j, Y g:i A', strtotime($t['created_at'])); ?></td>
      </tr>
    <?php endwhile; ?>
    </tbody>
  </table>
  </div>
  <?php endif; ?>
</div>

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