<?php
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();
requireAdmin();

$orders = readJson(ORDERS_FILE);
$users = readJson(USERS_FILE);
$usersById = [];
foreach ($users as $u) { $usersById[$u['id']] = $u; }

$totalOrders = count($orders);
$successCount = 0; $pendingCount = 0; $failedCount = 0;
$successAmt = 0; $pendingAmt = 0; $failedAmt = 0;

foreach ($orders as $o) {
    $amt = floatval($o['amount'] ?? 0);
    if (($o['status'] ?? '') === 'success') { $successCount++; $successAmt += $amt; }
    elseif (($o['status'] ?? '') === 'pending') { $pendingCount++; $pendingAmt += $amt; }
    else { $failedCount++; $failedAmt += $amt; }
}

$pageTitle = 'Transactions';
$pageSub = 'All payment transactions across every merchant and order type.';
include __DIR__ . '/../includes/admin_header.php';
?>

<div class="admin-wrap">
  <div class="stat-grid" style="margin-bottom:24px">
    <div class="stat-card primary">
      <div class="stat-label"><i class="fa-solid fa-receipt"></i> Total Transactions</div>
      <div class="stat-value"><?= number_format($totalOrders) ?></div>
    </div>
    <div class="stat-card">
      <div class="stat-label"><i class="fa-solid fa-circle-check"></i> Successful</div>
      <div class="stat-value"><?= number_format($successCount) ?></div>
      <div class="stat-desc" style="color:#34d399">₹<?= number_format($successAmt, 2) ?></div>
    </div>
    <div class="stat-card">
      <div class="stat-label"><i class="fa-solid fa-clock"></i> Pending</div>
      <div class="stat-value" style="color:var(--yellow)"><?= number_format($pendingCount) ?></div>
      <div class="stat-desc" style="color:#fbbf24">₹<?= number_format($pendingAmt, 2) ?></div>
    </div>
    <div class="stat-card">
      <div class="stat-label"><i class="fa-solid fa-circle-xmark"></i> Failed / Expired</div>
      <div class="stat-value" style="color:var(--red)"><?= number_format($failedCount) ?></div>
      <div class="stat-desc" style="color:#f87171">₹<?= number_format($failedAmt, 2) ?></div>
    </div>
  </div>

  <div class="card">
    <div style="display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap;margin-bottom:1.2rem">
      <h2 class="card-title" style="margin:0"><i class="fa-solid fa-list-check"></i> All Transactions</h2>
      <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap">
        <input type="text" id="txSearch" placeholder="Search Order ID, Email, UTR..." style="background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.1);border-radius:8px;padding:8px 14px;color:#f1f5f9;font-size:0.85rem;width:220px;outline:none" />
        <select id="txStatus" style="background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.1);border-radius:8px;padding:8px 14px;color:#f1f5f9;font-size:0.85rem;outline:none">
          <option value="">All Status</option>
          <option value="success">Success</option>
          <option value="pending">Pending</option>
          <option value="failed">Failed</option>
          <option value="expired">Expired</option>
        </select>
        <select id="txType" style="background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.1);border-radius:8px;padding:8px 14px;color:#f1f5f9;font-size:0.85rem;outline:none">
          <option value="">All Types</option>
          <option value="api_order">API Order</option>
          <option value="demo_test">Demo Test</option>
          <option value="plan_purchase">Plan Upgrade</option>
          <option value="payment_link">Payment Link</option>
        </select>
      </div>
    </div>

    <div class="table-card">
      <table class="data-table">
        <thead>
          <tr>
            <th>Order ID</th>
            <th>Merchant / User</th>
            <th>Type</th>
            <th>Amount</th>
            <th>Status</th>
            <th>UTR Ref</th>
            <th>Created (IST)</th>
          </tr>
        </thead>
        <tbody id="txBody">
          <tr><td colspan="7" style="text-align:center;color:var(--muted);padding:28px"><i class="fa-solid fa-spinner fa-spin"></i><br>Loading transactions...</td></tr>
        </tbody>
      </table>
    </div>

    <div style="display:flex;align-items:center;justify-content:space-between;margin-top:16px;flex-wrap:wrap;gap:10px">
      <span id="txInfo" style="font-size:0.82rem;color:var(--muted)"></span>
      <div id="txPages" style="display:flex;gap:6px;flex-wrap:wrap"></div>
    </div>
  </div>
</div>

<script>
const TYPE_LABELS = {api_order:'API Order',demo_test:'Demo Test',plan_purchase:'Plan Upgrade',reset_unlock:'Reset Key',custom_api_purchase:'Custom API',payment_link:'Payment Link'};
let currentPage = 1;

function txRow(o) {
  const type = TYPE_LABELS[o.type] || (o.type||'-').replace(/_/g,' ');
  const bc = {success:'success',pending:'pending',failed:'failed',expired:'failed'}[o.status] || 'pending';
  const st = {success:'Paid',pending:'Pending',failed:'Failed',expired:'Expired'}[o.status] || o.status;
  return '<tr><td><strong style="color:#f8fafc;font-family:monospace;font-size:0.82rem">'+o.order_id+'</strong></td><td>'+(o.user||'<span style="color:#64748b">System</span>')+'</td><td><span style="font-size:0.82rem;font-weight:600;color:#94a3b8">'+type+'</span></td><td><strong style="color:#3b82f6">₹'+parseFloat(o.amount).toFixed(2)+'</strong></td><td><span class="badge-status '+bc+'">'+st+'</span></td><td style="font-family:monospace;color:#cbd5e1;font-size:0.82rem">'+(o.utr||'-')+'</td><td style="font-size:0.82rem;color:#64748b">'+(o.created_at||'-')+'</td></tr>';
}

async function loadTx(page) {
  page = page || 1;
  const s = document.getElementById('txSearch').value;
  const st = document.getElementById('txStatus').value;
  const tp = document.getElementById('txType').value;
  const params = new URLSearchParams({page:page,search:s,status:st,type:tp});
  try {
    const res = await fetch('api_all_transactions.php?' + params);
    const data = await res.json();
    if (data.status !== 'success') return;
    currentPage = data.page;
    document.getElementById('txBody').innerHTML = data.transactions.map(txRow).join('') || '<tr><td colspan="7" style="text-align:center;color:var(--muted);padding:28px">No transactions found</td></tr>';
    document.getElementById('txInfo').textContent = 'Showing '+data.transactions.length+' of '+data.total+' transactions - Page '+data.page+' of '+data.total_pages;
    var pd = document.getElementById('txPages');
    pd.innerHTML = '';
    if (data.total_pages > 1) {
      if (data.page > 1) pd.innerHTML += '<button onclick="loadTx('+(data.page-1)+')" style="background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.1);border-radius:6px;padding:6px 12px;color:#f1f5f9;cursor:pointer;font-size:0.82rem">Prev</button>';
      for (var i = 1; i <= data.total_pages && i <= 7; i++) {
        pd.innerHTML += '<button onclick="loadTx('+i+')" style="background:'+(i===data.page?'#3b82f6':'rgba(255,255,255,0.06)')+';border:1px solid '+(i===data.page?'#3b82f6':'rgba(255,255,255,0.1)')+';border-radius:6px;padding:6px 12px;color:#fff;cursor:pointer;font-size:0.82rem">'+i+'</button>';
      }
      if (data.page < data.total_pages) pd.innerHTML += '<button onclick="loadTx('+(data.page+1)+')" style="background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.1);border-radius:6px;padding:6px 12px;color:#f1f5f9;cursor:pointer;font-size:0.82rem">Next</button>';
    }
  } catch(e) {}
}

document.getElementById('txSearch').addEventListener('input', function(){ clearTimeout(window._deb); window._deb = setTimeout(function(){loadTx(1)},300); });
document.getElementById('txStatus').addEventListener('change', function(){loadTx(1)});
document.getElementById('txType').addEventListener('change', function(){loadTx(1)});
loadTx(1);
</script>

<?php include __DIR__ . '/../includes/admin_footer.php'; ?>
