<?php
include "auth.php";
include "db.php";
require_once('stripe-php/init.php'); // Stripe SDK

\Stripe\Stripe::setApiKey('sk_test_YourSecretKey'); // replace with your secret key

$username = $_SESSION['user'];

// Get user's payment links from DB
$stmt = $conn->prepare("SELECT stripe_link_id, title FROM payment_links WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

$linkIds = [];
$titles = [];

while ($row = $result->fetch_assoc()) {
    if (!empty($row['stripe_link_id'])) {
        $linkIds[] = $row['stripe_link_id'];
        $titles[$row['stripe_link_id']] = $row['title'];
    }
}

// Fetch Stripe Payment Link transactions
$allTransactions = [];

foreach ($linkIds as $linkId) {
    try {
        $paymentLink = \Stripe\PaymentLink::retrieve($linkId);
        $sessions = \Stripe\Checkout\Session::all([
            'limit' => 100,
            'payment_link' => $linkId,
        ]);

        foreach ($sessions->data as $session) {
            $allTransactions[] = [
                'link_id' => $linkId,
                'title' => $titles[$linkId] ?? 'N/A',
                'email' => $session->customer_details->email ?? 'Unknown',
                'amount_total' => $session->amount_total / 100,
                'currency' => strtoupper($session->currency),
                'status' => $session->payment_status,
                'created' => date("d-M-Y H:i:s", $session->created),
            ];
        }

    } catch (Exception $e) {
        // Log or skip failed link
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>ATG | Transactions</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="shortcut icon" href="uploads/favicon.png" />
</head>
<body>

  <div class="container-fluid">
    <div class="row">
      <!-- Sidebar -->
      <nav class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse pt-3">
        <div class="position-sticky">
             <!-- Company Logo -->
          <img src="uploads/logo.png" alt="Allied Tech Global" class="mx-auto d-block mb-3" style="max-height: 40px;">
          <br>
          <br>
          <ul class="nav flex-column">
            <li class="nav-item"><a class="nav-link" href="dashboard.php">Dashboard</a></li>
            <li class="nav-item"><a class="nav-link" href="create.php">Create Payment Link</a></li>
            <li class="nav-item"><a class="nav-link" href="list.php">Payment Links List</a></li>
            <li class="nav-item"><a class="nav-link" href="transactions.php">Transactions</a></li>
            <li class="nav-item"><a class="nav-link text-danger" href="logout.php">Logout</a></li>
          </ul>
        </div>
      </nav>

      <!-- Main content -->
      <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
        <h2>Welcome, <?= $_SESSION['user'] ?>!</h2>
        <br>
        <br>
        <br>
        <div class="container py-4">
				  <h2 class="mb-4">Transactions List</h2>

				  <?php if (empty($allTransactions)): ?>
				    <div class="alert alert-warning">No transactions found for your payment links.</div>
				  <?php else: ?>
				    <div class="table-responsive">
				      <table class="table table-bordered table-hover align-middle">
				        <thead class="table-light">
				          <tr>
				            <th>Link Title</th>
				            <th>Customer Email</th>
				            <th>Amount</th>
				            <th>Status</th>
				            <th>Date</th>
				          </tr>
				        </thead>
				        <tbody>
				          <?php foreach ($allTransactions as $txn): ?>
				            <tr>
				              <td><?= htmlspecialchars($txn['title']) ?></td>
				              <td><?= htmlspecialchars($txn['email']) ?></td>
				              <td>$<?= $txn['amount_total'] ?> <?= $txn['currency'] ?></td>
				              <td><?= ucfirst($txn['status']) ?></td>
				              <td><?= $txn['created'] ?></td>
				            </tr>
				          <?php endforeach; ?>
				        </tbody>
				      </table>
				    </div>
				  <?php endif; ?>
				</div>
      </main>
    </div>
  </div>


</body>
</html>
