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

$user = getUserById($_SESSION['user_id']);
if (!$user) {
    header('Location: logout.php');
    exit;
}

$allOrders = readJson(ORDERS_FILE);
$userOrdersAll = array_values(array_filter($allOrders, function ($o) use ($user) {
    return ($o['user_id'] ?? '') === $user['id'];
}));
usort($userOrdersAll, function ($a, $b) {
    return ($b['created_at_timestamp'] ?? 0) - ($a['created_at_timestamp'] ?? 0);
});

$totalPaid = 0;
$totalPending = 0;
foreach ($userOrdersAll as $o) {
    $amt = floatval($o['amount'] ?? 0);
    if ($o['status'] === 'success') $totalPaid += $amt;
    elseif ($o['status'] === 'pending') $totalPending += $amt;
}

$typeLabels = [
    'plan_purchase' => 'Plan Purchase',
    'api_order' => 'Custom API Key',
    'demo_test' => 'Demo Test',
];

$statusFilter = $_GET['status'] ?? '';
if ($statusFilter !== '') {
    $userOrders = array_values(array_filter($userOrdersAll, function ($o) use ($statusFilter) {
        return $o['status'] === $statusFilter;
    }));
} else {
    $userOrders = $userOrdersAll;
}

$pageTitle = 'Transactions';
$activeNav = 'transactions';
include __DIR__ . '/includes/user_header.php';
?>

<div class="page-head">
  <h1 class="page-title">Transactions</h1>
  <p class="page-sub">Every payment attempt on your account — success, pending and failed.</p>
</div>

<div class="stat-grid">
  <div class="stat-card primary">
    <div class="stat-label">Total transactions</div>
    <div class="stat-value" style="font-size:24px;"><?= count($userOrdersAll) ?></div>
  </div>
  <div class="stat-card">
    <div class="stat-label">Paid (success)</div>
    <div class="stat-value up">₹<?= number_format($totalPaid, 2) ?></div>
  </div>
  <div class="stat-card">
    <div class="stat-label">Pending amount</div>
    <div class="stat-value">₹<?= number_format($totalPending, 2) ?></div>
  </div>
</div>

<div class="card">
  <div class="justify-between flex flex-wrap items-center" style="gap:12px; margin-bottom:16px;">
    <h2 class="card-title">Transaction history</h2>
    <div class="flex items-center gap-8">
      <a href="transactions.php" class="filter-chip <?= $statusFilter === '' ? 'active' : '' ?>">All</a>
      <a href="transactions.php?status=success" class="filter-chip <?= $statusFilter === 'success' ? 'active' : '' ?>">Success</a>
      <a href="transactions.php?status=pending" class="filter-chip <?= $statusFilter === 'pending' ? 'active' : '' ?>">Pending</a>
      <a href="transactions.php?status=expired" class="filter-chip <?= $statusFilter === 'expired' ? 'active' : '' ?>">Expired</a>
    </div>
  </div>

  <div class="table-wrap">
    <table class="data-table">
      <tr>
        <th>Order ID</th>
        <th>Type</th>
        <th>Amount</th>
        <th>Status</th>
        <th>UTR</th>
        <th>Date</th>
      </tr>
      <?php if (empty($userOrders)): ?>
        <tr><td colspan="6" class="empty-row">No transactions found.</td></tr>
      <?php else: ?>
        <?php foreach ($userOrders as $o): ?>
          <tr>
            <td class="mono" style="font-size:12px;"><?= htmlspecialchars($o['order_id']) ?></td>
            <td><?= htmlspecialchars($typeLabels[$o['type'] ?? ''] ?? ucwords(str_replace('_', ' ', $o['type'] ?? 'Order'))) ?></td>
            <td style="font-weight:600;">₹<?= number_format(floatval($o['amount'] ?? 0), 2) ?></td>
            <td>
              <?php if ($o['status'] === 'success'): ?>
                <span class="badge badge-green">Paid</span>
              <?php elseif ($o['status'] === 'pending'): ?>
                <span class="badge badge-amber">Pending</span>
              <?php elseif ($o['status'] === 'expired'): ?>
                <span class="badge badge-gray">Expired</span>
              <?php else: ?>
                <span class="badge badge-red">Failed</span>
              <?php endif; ?>
            </td>
            <td class="mono" style="font-size:12px; color:var(--muted);"><?= htmlspecialchars($o['utr'] ?? '—') ?></td>
            <td style="font-size:12px;"><?= htmlspecialchars($o['created_at'] ?? '-') ?></td>
          </tr>
        <?php endforeach; ?>
      <?php endif; ?>
    </table>
  </div>
</div>

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