<?php
session_start();
if (!isset($_SESSION['admin_id']) && $_SESSION['role'] != 'admin') {
    header("Location: ../login.php");
    exit();
}
include '../../include/config.php';

$filter = $_GET['filter'] ?? 'all';
$status = $_GET['status'] ?? 'all';

$query = "SELECT t.*, 
          CASE WHEN t.user_id IN (SELECT patient_id FROM patients) THEN (SELECT CONCAT(first_name, ' ', last_name) FROM patients WHERE patient_id = t.user_id) ELSE 'Guest' END as user_name
          FROM transactions t WHERE 1=1";

if ($status != 'all') {
    $query .= " AND t.status = '$status'";
}
if ($filter == 'month') {
    $query .= " AND MONTH(t.created_at) = MONTH(NOW())";
}

$query .= " ORDER BY t.created_at DESC";

$transactions = $conn->query($query);

$page_title = 'All Transactions | Admin';
include '../../include/header.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>All Transactions</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
    <div class="d-flex justify-content-between mb-4">
        <h2>All Transactions</h2>
        <a href="index.php" class="btn btn-secondary">← Back to Dashboard</a>
    </div>
    
    <div class="card shadow rounded-4">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr><th>ID</th><th>User</th><th>Amount</th><th>Type</th><th>Reference</th><th>Status</th><th>Date</th><th>Action</th></tr>
                    </thead>
                    <tbody>
                        <?php while($tx = $transactions->fetch_assoc()): ?>
                        <tr>
                            <td><?= $tx['id'] ?></td>
                            <td><?= htmlspecialchars($tx['user_name'] ?? 'User ' . $tx['user_id']) ?></td>
                            <td class="fw-bold text-success">₦<?= number_format($tx['amount'], 2) ?></td>
                            <td><?= str_replace('_', ' ', ucfirst($tx['payment_type'] ?? 'N/A')) ?></td>
                            <td><code><?= substr($tx['tx_ref'] ?? '', 0, 15) ?>...</code></td>
                            <td>
                                <span class="badge bg-<?= $tx['status'] == 'completed' ? 'success' : 'warning' ?>">
                                    <?= ucfirst($tx['status']) ?>
                                </span>
                             </td
                            <td><?= date('M d, Y', strtotime($tx['created_at'])) ?></td
                            <td><a href="view_transaction.php?id=<?= $tx['id'] ?>" class="btn btn-sm btn-info">View</a></td
                          </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php include '../../include/footer.php'; ?>