<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once 'includes/auth.php';
requireUserLogin();
$currentUser = currentUser($pdo);
$uid = (int)$_SESSION['user_id'];

// Filters
$status  = $_GET['status'] ?? '';
$type    = $_GET['type'] ?? '';
$search  = trim($_GET['search'] ?? '');
$from    = $_GET['from'] ?? '';
$to      = $_GET['to'] ?? '';
$page    = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;

$where = "WHERE t.user_id = ?"; $params = [$uid];
if ($status) { $where .= " AND t.status=?"; $params[] = $status; }
if ($type)   { $where .= " AND t.transaction_type=?"; $params[] = $type; }
if ($search) { $where .= " AND (t.description LIKE ? OR t.reference_number LIKE ? OR t.beneficiary_name LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; $params[] = "%$search%"; }
if ($from)   { $where .= " AND DATE(t.created_at) >= ?"; $params[] = $from; }
if ($to)     { $where .= " AND DATE(t.created_at) <= ?"; $params[] = $to; }

$countStmt = $pdo->prepare("SELECT COUNT(*) FROM transactions t $where");
$countStmt->execute($params); $total = (int)$countStmt->fetchColumn();
$pages = (int)ceil($total / $perPage);
$offset = ($page - 1) * $perPage;

$txStmt = $pdo->prepare("SELECT * FROM transactions t $where ORDER BY t.created_at DESC LIMIT $perPage OFFSET $offset");
$txStmt->execute($params); $transactions = $txStmt->fetchAll();

// Single transaction view for receipt
if (isset($_GET['receipt'])) {
    $rid = (int)$_GET['receipt'];
    $rec = $pdo->prepare("SELECT * FROM transactions WHERE id=? AND user_id=? LIMIT 1");
    $rec->execute([$rid, $uid]); $receipt = $rec->fetch();
}

$pageTitle = 'Transaction History';
?>
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $pageTitle ?> | <?= SITE_NAME ?></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link rel="stylesheet" href="/assets/css/style.css">
</head><body>
<?php include 'includes/header.php'; ?>
<div class="page-wrapper"><div class="container">
<div class="d-flex justify-content-between align-items-center mb-3">
  <div class="page-title mb-0"><i class="fa fa-list me-2 text-danger"></i>Transaction History</div>
  <div class="d-flex gap-2">
    <a href="/transactions.php?export=csv&<?= http_build_query(array_filter(compact('status','type','search','from','to'))) ?>" class="btn btn-sm btn-outline-success"><i class="fa fa-download me-1"></i>Export CSV</a>
    <a href="javascript:print()" class="btn btn-sm btn-outline-secondary"><i class="fa fa-print me-1"></i>Print</a>
  </div>
</div>

<!-- Filters -->
<div class="card mb-4">
  <div class="card-body">
    <form method="GET" class="row g-2 align-items-end">
      <div class="col-6 col-md-2">
        <label class="form-label small">Type</label>
        <select name="type" class="form-select form-select-sm">
          <option value="">All Types</option>
          <option value="credit" <?= $type==='credit'?'selected':'' ?>>Credit</option>
          <option value="debit" <?= $type==='debit'?'selected':'' ?>>Debit</option>
          <option value="transfer" <?= $type==='transfer'?'selected':'' ?>>Transfer</option>
        </select>
      </div>
      <div class="col-6 col-md-2">
        <label class="form-label small">Status</label>
        <select name="status" class="form-select form-select-sm">
          <option value="">All Statuses</option>
          <option value="completed" <?= $status==='completed'?'selected':'' ?>>Completed</option>
          <option value="pending" <?= $status==='pending'?'selected':'' ?>>Pending</option>
          <option value="failed" <?= $status==='failed'?'selected':'' ?>>Failed</option>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label small">From</label>
        <input type="date" name="from" class="form-control form-control-sm" value="<?= sanitize($from) ?>">
      </div>
      <div class="col-md-2">
        <label class="form-label small">To</label>
        <input type="date" name="to" class="form-control form-control-sm" value="<?= sanitize($to) ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label small">Search</label>
        <input type="text" name="search" class="form-control form-control-sm" placeholder="Ref, description..." value="<?= sanitize($search) ?>">
      </div>
      <div class="col-md-1">
        <button class="btn btn-primary btn-sm w-100"><i class="fa fa-search"></i></button>
      </div>
    </form>
  </div>
</div>

<!-- Table -->
<div class="card">
  <div class="card-header d-flex justify-content-between align-items-center">
    <span><?= $total ?> transaction<?= $total!=1?'s':'' ?> found</span>
    <span class="text-muted small">Balance: <strong><?= money((float)$currentUser['account_balance'],$currentUser['currency']) ?></strong></span>
  </div>
  <div class="table-responsive">
    <table class="table table-hover mb-0">
      <thead>
        <tr>
          <th>Date</th><th>Reference</th><th>Description</th><th>Beneficiary</th><th>Type</th><th>Amount</th><th>Status</th><th></th>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($transactions)): ?>
        <tr><td colspan="8" class="text-center py-4 text-muted">No transactions found.</td></tr>
        <?php else: foreach ($transactions as $t): $isCredit = $t['transaction_type']==='credit'; ?>
        <tr>
          <td><small><?= formatDate($t['created_at'],'M j Y') ?><br><span class="text-muted"><?= formatDate($t['created_at'],'g:i A') ?></span></small></td>
          <td><code class="small"><?= sanitize($t['reference_number']) ?></code></td>
          <td class="small"><?= sanitize(substr($t['description'],0,40)) ?></td>
          <td class="small"><?= $t['beneficiary_name'] ? sanitize($t['beneficiary_name']) : '—' ?></td>
          <td><?= statusBadge($t['transaction_type']) ?></td>
          <td class="fw-bold <?= $isCredit?'text-success':'text-danger' ?>">
            <?= ($isCredit?'+':'-').money((float)$t['amount'],$t['currency']) ?>
          </td>
          <td><?= statusBadge($t['status']) ?></td>
          <td><a href="?receipt=<?= $t['id'] ?>" class="btn btn-xs btn-outline-secondary" title="Receipt"><i class="fa fa-receipt"></i></a></td>
        </tr>
        <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
  <?php if ($pages > 1): ?>
  <div class="card-footer d-flex justify-content-between align-items-center">
    <small class="text-muted">Page <?= $page ?> of <?= $pages ?></small>
    <nav><ul class="pagination pagination-sm mb-0">
      <?php for ($i=1;$i<=$pages;$i++): ?>
      <li class="page-item <?= $i==$page?'active':'' ?>">
        <a class="page-link" href="?page=<?= $i ?>&<?= http_build_query(array_filter(compact('status','type','search','from','to'))) ?>"><?= $i ?></a>
      </li>
      <?php endfor; ?>
    </ul></nav>
  </div>
  <?php endif; ?>
</div>
</div></div>
<?php include 'includes/footer.php'; ?>

<?php if (!empty($receipt)): $r=$receipt; $isC=$r['transaction_type']==='credit'; ?>
<div class="modal fade show" id="receiptModal" tabindex="-1" style="display:block;background:rgba(0,0,0,.5);">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-<?= $isC?'success':'danger' ?> text-white">
        <h5 class="modal-title"><i class="fa fa-receipt me-2"></i>Transaction Receipt</h5>
        <a href="/transactions.php" class="btn-close btn-close-white"></a>
      </div>
      <div class="modal-body" id="receiptContent">
        <div class="text-center mb-3">
          <img src="/assets/img/logo.png" height="40" alt="<?= SITE_NAME ?>"><br>
          <h6 class="mt-2 mb-0"><?= SITE_NAME ?></h6>
          <small class="text-muted">Official Transaction Receipt</small>
        </div>
        <table class="table table-sm">
          <tr><th>Reference</th><td><?= sanitize($r['reference_number']) ?></td></tr>
          <tr><th>Date</th><td><?= formatDate($r['created_at']) ?></td></tr>
          <tr><th>Type</th><td><?= statusBadge($r['transaction_type']) ?></td></tr>
          <tr><th>Amount</th><td class="fw-bold <?= $isC?'text-success':'text-danger' ?>"><?= ($isC?'+':'-').money((float)$r['amount'],$r['currency']) ?></td></tr>
          <?php if ($r['fee'] > 0): ?><tr><th>Fee</th><td><?= money((float)$r['fee'],$r['currency']) ?></td></tr><?php endif; ?>
          <tr><th>Description</th><td><?= sanitize($r['description']) ?></td></tr>
          <?php if ($r['beneficiary_name']): ?>
          <tr><th>Beneficiary</th><td><?= sanitize($r['beneficiary_name']) ?></td></tr>
          <tr><th>Bene. Account</th><td><?= sanitize($r['beneficiary_account']??'') ?></td></tr>
          <tr><th>Bene. Bank</th><td><?= sanitize($r['beneficiary_bank']??'') ?></td></tr>
          <?php endif; ?>
          <tr><th>Status</th><td><?= statusBadge($r['status']) ?></td></tr>
        </table>
        <p class="text-center text-muted small mt-2">Thank you for banking with <?= SITE_NAME ?></p>
      </div>
      <div class="modal-footer">
        <button class="btn btn-outline-secondary" onclick="printReceipt()"><i class="fa fa-print me-1"></i>Print</button>
        <a href="/transactions.php" class="btn btn-primary">Close</a>
      </div>
    </div>
  </div>
</div>
<script>
function printReceipt() {
  const w = window.open('','_blank');
  w.document.write('<html><head><title>Receipt</title><link rel="stylesheet" href="/assets/css/style.css"></head><body>');
  w.document.write(document.getElementById('receiptContent').innerHTML);
  w.document.write('</body></html>');
  w.document.close(); w.print();
}
</script>
<?php endif; ?>
<?php
// CSV export
if (isset($_GET['export']) && $_GET['export']==='csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="transactions_'.date('Ymd').'.csv"');
    $out = fopen('php://output','w');
    fputcsv($out,['Date','Reference','Description','Beneficiary','Type','Amount','Currency','Fee','Status']);
    foreach ($transactions as $t) {
        fputcsv($out,[$t['created_at'],$t['reference_number'],$t['description'],$t['beneficiary_name']??'',$t['transaction_type'],$t['amount'],$t['currency'],$t['fee'],$t['status']]);
    }
    fclose($out); exit;
}
?>
</body></html>
